updates.
[silc.git] / apps / silcd / protocol.c
1 /*
2
3   protocol.c
4
5   Author: Pekka Riikonen <priikone@poseidon.pspt.fi>
6
7   Copyright (C) 1997 - 2001 Pekka Riikonen
8
9   This program is free software; you can redistribute it and/or modify
10   it under the terms of the GNU General Public License as published by
11   the Free Software Foundation; either version 2 of the License, or
12   (at your option) any later version.
13   
14   This program is distributed in the hope that it will be useful,
15   but WITHOUT ANY WARRANTY; without even the implied warranty of
16   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17   GNU General Public License for more details.
18
19 */
20 /*
21  * Server side of the protocols.
22  */
23 /* $Id$ */
24
25 #include "serverincludes.h"
26 #include "server_internal.h"
27
28 SILC_TASK_CALLBACK(silc_server_protocol_connection_auth);
29 SILC_TASK_CALLBACK(silc_server_protocol_key_exchange);
30 SILC_TASK_CALLBACK(silc_server_protocol_rekey);
31
32 extern char *silc_version_string;
33
34 /*
35  * Key Exhange protocol functions
36  */
37
38 /* Packet sending callback. This function is provided as packet sending
39    routine to the Key Exchange functions. */
40
41 static void silc_server_protocol_ke_send_packet(SilcSKE ske,
42                                                 SilcBuffer packet,
43                                                 SilcPacketType type,
44                                                 void *context)
45 {
46   SilcProtocol protocol = (SilcProtocol)context;
47   SilcServerKEInternalContext *ctx = 
48     (SilcServerKEInternalContext *)protocol->context;
49   SilcServer server = (SilcServer)ctx->server;
50
51   /* Send the packet immediately */
52   silc_server_packet_send(server, ske->sock,
53                           type, 0, packet->data, packet->len, TRUE);
54 }
55
56 /* Sets the negotiated key material into use for particular connection. */
57
58 int silc_server_protocol_ke_set_keys(SilcSKE ske,
59                                      SilcSocketConnection sock,
60                                      SilcSKEKeyMaterial *keymat,
61                                      SilcCipher cipher,
62                                      SilcPKCS pkcs,
63                                      SilcHash hash,
64                                      SilcHmac hmac,
65                                      SilcSKEDiffieHellmanGroup group,
66                                      bool is_responder)
67 {
68   SilcUnknownEntry conn_data;
69   SilcIDListData idata;
70
71   SILC_LOG_DEBUG(("Setting new key into use"));
72
73   conn_data = silc_calloc(1, sizeof(*conn_data));
74   idata = (SilcIDListData)conn_data;
75
76   /* Allocate cipher to be used in the communication */
77   if (!silc_cipher_alloc(cipher->cipher->name, &idata->send_key)) {
78     silc_free(conn_data);
79     return FALSE;
80   }
81   if (!silc_cipher_alloc(cipher->cipher->name, &idata->receive_key)) {
82     silc_free(conn_data);
83     return FALSE;
84   }
85   
86   if (is_responder == TRUE) {
87     silc_cipher_set_key(idata->send_key, keymat->receive_enc_key, 
88                         keymat->enc_key_len);
89     silc_cipher_set_iv(idata->send_key, keymat->receive_iv);
90     silc_cipher_set_key(idata->receive_key, keymat->send_enc_key, 
91                         keymat->enc_key_len);
92     silc_cipher_set_iv(idata->receive_key, keymat->send_iv);
93   } else {
94     silc_cipher_set_key(idata->send_key, keymat->send_enc_key, 
95                         keymat->enc_key_len);
96     silc_cipher_set_iv(idata->send_key, keymat->send_iv);
97     silc_cipher_set_key(idata->receive_key, keymat->receive_enc_key, 
98                         keymat->enc_key_len);
99     silc_cipher_set_iv(idata->receive_key, keymat->receive_iv);
100   }
101
102   idata->rekey = silc_calloc(1, sizeof(*idata->rekey));
103   idata->rekey->send_enc_key = 
104     silc_calloc(keymat->enc_key_len / 8,
105                 sizeof(*idata->rekey->send_enc_key));
106   memcpy(idata->rekey->send_enc_key, 
107          keymat->send_enc_key, keymat->enc_key_len / 8);
108   idata->rekey->enc_key_len = keymat->enc_key_len / 8;
109
110   if (ske->start_payload->flags & SILC_SKE_SP_FLAG_PFS)
111     idata->rekey->pfs = TRUE;
112   idata->rekey->ske_group = silc_ske_group_get_number(group);
113
114   /* Save the remote host's public key */
115   silc_pkcs_public_key_decode(ske->ke1_payload->pk_data, 
116                               ske->ke1_payload->pk_len, &idata->public_key);
117
118   /* Save the hash */
119   if (!silc_hash_alloc(hash->hash->name, &idata->hash)) {
120     silc_cipher_free(idata->send_key);
121     silc_cipher_free(idata->receive_key);
122     silc_free(conn_data);
123     return FALSE;
124   }
125
126   /* Save HMAC key to be used in the communication. */
127   if (!silc_hmac_alloc(hmac->hmac->name, NULL, &idata->hmac_send)) {
128     silc_cipher_free(idata->send_key);
129     silc_cipher_free(idata->receive_key);
130     silc_hash_free(idata->hash);
131     silc_free(conn_data);
132     return FALSE;
133   }
134   silc_hmac_set_key(idata->hmac_send, keymat->hmac_key, keymat->hmac_key_len);
135   idata->hmac_receive = idata->hmac_send;
136
137   sock->user_data = (void *)conn_data;
138
139   return TRUE;
140 }
141
142 /* Check remote host version string */
143
144 SilcSKEStatus silc_ske_check_version(SilcSKE ske, unsigned char *version,
145                                      uint32 len)
146 {
147   SilcSKEStatus status = SILC_SKE_STATUS_OK;
148   char *cp;
149   int maj = 0, min = 0, build = 0, maj2 = 0, min2 = 0, build2 = 0;
150
151   SILC_LOG_INFO(("%s (%s) is version %s", ske->sock->hostname,
152                  ske->sock->ip, version));
153
154   /* Check for initial version string */
155   if (!strstr(version, "SILC-1.0-"))
156     status = SILC_SKE_STATUS_BAD_VERSION;
157
158   /* Check software version */
159
160   cp = version + 9;
161   if (!cp)
162     status = SILC_SKE_STATUS_BAD_VERSION;
163
164   maj = atoi(cp);
165   cp = strchr(cp, '.');
166   if (cp) {
167     min = atoi(cp + 1);
168     cp++;
169   }
170   if (cp) {
171     cp = strchr(cp, '.');
172     if (cp)
173       build = atoi(cp + 1);
174   }
175
176   cp = silc_version_string + 9;
177   if (!cp)
178     status = SILC_SKE_STATUS_BAD_VERSION;
179
180   maj2 = atoi(cp);
181   cp = strchr(cp, '.');
182   if (cp) {
183     min2 = atoi(cp + 1);
184     cp++;
185   }
186   if (cp) {
187     cp = strchr(cp, '.');
188     if (cp)
189       build2 = atoi(cp + 1);
190   }
191
192   if (maj != maj2)
193     status = SILC_SKE_STATUS_BAD_VERSION;
194   if (min < min2)
195     status = SILC_SKE_STATUS_BAD_VERSION;
196
197   return status;
198 }
199
200 /* Callback that is called by the SKE to indicate that it is safe to
201    continue the execution of the protocol. This is used only if we are
202    initiator.  Is given as argument to the silc_ske_initiator_finish
203    function. This is called due to the fact that the public key verification
204    process is asynchronous and we must not continue the protocl until
205    the public key has been verified and this callback is called. */
206
207 static void silc_server_protocol_ke_finish(SilcSKE ske, void *context)
208 {
209   SilcProtocol protocol = (SilcProtocol)context;
210   SilcServerKEInternalContext *ctx = 
211     (SilcServerKEInternalContext *)protocol->context;
212   SilcServer server = (SilcServer)ctx->server;
213
214   SILC_LOG_DEBUG(("Start"));
215
216   if (ske->status != SILC_SKE_STATUS_OK) {
217     SILC_LOG_WARNING(("Error (type %d) during Key Exchange protocol",
218                       ske->status));
219     SILC_LOG_DEBUG(("Error (type %d) during Key Exchange protocol",
220                     ske->status));
221     
222     protocol->state = SILC_PROTOCOL_STATE_ERROR;
223     protocol->execute(server->timeout_queue, 0, protocol, 0, 0, 300000);
224     return;
225   }
226
227   /* Send Ok to the other end. We will end the protocol as responder
228      sends Ok to us when we will take the new keys into use. */
229   if (ctx->responder == FALSE)
230     silc_ske_end(ctx->ske, silc_server_protocol_ke_send_packet, context);
231
232   /* End the protocol on the next round */
233   protocol->state = SILC_PROTOCOL_STATE_END;
234 }
235
236 /* Performs key exchange protocol. This is used for both initiator
237    and responder key exchange. This is performed always when accepting
238    new connection to the server. This may be called recursively. */
239
240 SILC_TASK_CALLBACK(silc_server_protocol_key_exchange)
241 {
242   SilcProtocol protocol = (SilcProtocol)context;
243   SilcServerKEInternalContext *ctx = 
244     (SilcServerKEInternalContext *)protocol->context;
245   SilcServer server = (SilcServer)ctx->server;
246   SilcSKEStatus status = SILC_SKE_STATUS_OK;
247
248   SILC_LOG_DEBUG(("Start"));
249
250   if (protocol->state == SILC_PROTOCOL_STATE_UNKNOWN)
251     protocol->state = SILC_PROTOCOL_STATE_START;
252
253   SILC_LOG_DEBUG(("State=%d", protocol->state));
254
255   switch(protocol->state) {
256   case SILC_PROTOCOL_STATE_START:
257     {
258       /*
259        * Start protocol
260        */
261       SilcSKE ske;
262
263       /* Allocate Key Exchange object */
264       ske = silc_ske_alloc();
265       ctx->ske = ske;
266       ske->rng = server->rng;
267       
268       if (ctx->responder == TRUE) {
269         /* Start the key exchange by processing the received security
270            properties packet from initiator. */
271         status = silc_ske_responder_start(ske, ctx->rng, ctx->sock,
272                                           silc_version_string,
273                                           ctx->packet->buffer, FALSE,
274                                           NULL, NULL);
275       } else {
276         SilcSKEStartPayload *start_payload;
277
278         /* Assemble security properties. */
279         silc_ske_assemble_security_properties(ske, SILC_SKE_SP_FLAG_NONE, 
280                                               silc_version_string,
281                                               &start_payload);
282
283         /* Start the key exchange by sending our security properties
284            to the remote end. */
285         status = silc_ske_initiator_start(ske, ctx->rng, ctx->sock,
286                                           start_payload,
287                                           silc_server_protocol_ke_send_packet,
288                                           context);
289       }
290
291       /* Return now if the procedure is pending. */
292       if (status == SILC_SKE_STATUS_PENDING)
293         return;
294
295       if (status != SILC_SKE_STATUS_OK) {
296         SILC_LOG_WARNING(("Error (type %d) during Key Exchange protocol",
297                           status));
298         SILC_LOG_DEBUG(("Error (type %d) during Key Exchange protocol",
299                         status));
300
301         protocol->state = SILC_PROTOCOL_STATE_ERROR;
302         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 300000);
303         return;
304       }
305
306       /* Advance protocol state and call the next state if we are responder */
307       protocol->state++;
308       if (ctx->responder == TRUE)
309         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 100000);
310     }
311     break;
312   case 2:
313     {
314       /* 
315        * Phase 1 
316        */
317       if (ctx->responder == TRUE) {
318         /* Sends the selected security properties to the initiator. */
319         status = 
320           silc_ske_responder_phase_1(ctx->ske, 
321                                      ctx->ske->start_payload,
322                                      silc_server_protocol_ke_send_packet,
323                                      context);
324       } else {
325         /* Call Phase-1 function. This processes the Key Exchange Start
326            paylaod reply we just got from the responder. The callback
327            function will receive the processed payload where we will
328            save it. */
329         status = silc_ske_initiator_phase_1(ctx->ske, ctx->packet->buffer,
330                                             NULL, NULL);
331       }
332
333       /* Return now if the procedure is pending. */
334       if (status == SILC_SKE_STATUS_PENDING)
335         return;
336
337       if (status != SILC_SKE_STATUS_OK) {
338         SILC_LOG_WARNING(("Error (type %d) during Key Exchange protocol",
339                           status));
340         SILC_LOG_DEBUG(("Error (type %d) during Key Exchange protocol",
341                         status));
342
343         protocol->state = SILC_PROTOCOL_STATE_ERROR;
344         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 300000);
345         return;
346       }
347
348       /* Advance protocol state and call next state if we are initiator */
349       protocol->state++;
350       if (ctx->responder == FALSE)
351         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 100000);
352     }
353     break;
354   case 3:
355     {
356       /* 
357        * Phase 2 
358        */
359       if (ctx->responder == TRUE) {
360         /* Process the received Key Exchange 1 Payload packet from
361            the initiator. This also creates our parts of the Diffie
362            Hellman algorithm. */
363         /* XXX TODO: If mutual authentication flag is set then the
364            verify_key callback should be set to verify the remote ends
365            public key!! */
366         /* XXX TODO: when the verify_key is set then the `callback'
367            must be set as well as the verify_key is asynchronous
368            (take a look to silc_ske_initiator_finish for example. */
369         status = silc_ske_responder_phase_2(ctx->ske, ctx->packet->buffer, 
370                                             NULL, NULL, NULL, NULL);
371       } else {
372         /* Call the Phase-2 function. This creates Diffie Hellman
373            key exchange parameters and sends our public part inside
374            Key Exhange 1 Payload to the responder. */
375         status = 
376           silc_ske_initiator_phase_2(ctx->ske,
377                                      server->public_key,
378                                      server->private_key,
379                                      silc_server_protocol_ke_send_packet,
380                                      context);
381       }
382
383       /* Return now if the procedure is pending. */
384       if (status == SILC_SKE_STATUS_PENDING)
385         return;
386
387       if (status != SILC_SKE_STATUS_OK) {
388         SILC_LOG_WARNING(("Error (type %d) during Key Exchange protocol",
389                           status));
390         SILC_LOG_DEBUG(("Error (type %d) during Key Exchange protocol",
391                         status));
392
393         protocol->state = SILC_PROTOCOL_STATE_ERROR;
394         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 300000);
395         return;
396       }
397
398       /* Advance protocol state and call the next state if we are responder */
399       protocol->state++;
400       if (ctx->responder == TRUE)
401         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 100000);
402     }
403     break;
404   case 4:
405     {
406       /* 
407        * Finish protocol
408        */
409       if (ctx->responder == TRUE) {
410         /* This creates the key exchange material and sends our
411            public parts to the initiator inside Key Exchange 2 Payload. */
412         status = 
413           silc_ske_responder_finish(ctx->ske, 
414                                     server->public_key, server->private_key,
415                                     SILC_SKE_PK_TYPE_SILC,
416                                     silc_server_protocol_ke_send_packet,
417                                     context);
418
419         /* End the protocol on the next round */
420         protocol->state = SILC_PROTOCOL_STATE_END;
421       } else {
422         /* Finish the protocol. This verifies the Key Exchange 2 payload
423            sent by responder. */
424         /* XXX TODO: the verify_key callback is not set!!! */
425         status = silc_ske_initiator_finish(ctx->ske, ctx->packet->buffer, 
426                                            NULL, NULL, 
427                                            silc_server_protocol_ke_finish, 
428                                            context);
429       }
430
431       /* Return now if the procedure is pending. */
432       if (status == SILC_SKE_STATUS_PENDING)
433         return;
434
435       if (status != SILC_SKE_STATUS_OK) {
436         SILC_LOG_WARNING(("Error (type %d) during Key Exchange protocol",
437                           status));
438         SILC_LOG_DEBUG(("Error (type %d) during Key Exchange protocol",
439                         status));
440
441         protocol->state = SILC_PROTOCOL_STATE_ERROR;
442         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 300000);
443         return;
444       }
445     }
446     break;
447
448   case SILC_PROTOCOL_STATE_END:
449     {
450       /* 
451        * End protocol
452        */
453       SilcSKEKeyMaterial *keymat;
454       int key_len = silc_cipher_get_key_len(ctx->ske->prop->cipher);
455       int hash_len = ctx->ske->prop->hash->hash->hash_len;
456
457       /* Process the key material */
458       keymat = silc_calloc(1, sizeof(*keymat));
459       status = silc_ske_process_key_material(ctx->ske, 16, key_len, hash_len,
460                                              keymat);
461       if (status != SILC_SKE_STATUS_OK) {
462         protocol->state = SILC_PROTOCOL_STATE_ERROR;
463         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 300000);
464         silc_ske_free_key_material(keymat);
465         return;
466       }
467       ctx->keymat = keymat;
468
469       /* Send Ok to the other end if we are responder. If we are initiator
470          we have sent this already. */
471       if (ctx->responder == TRUE)
472         silc_ske_end(ctx->ske, silc_server_protocol_ke_send_packet, context);
473
474       /* Unregister the timeout task since the protocol has ended. 
475          This was the timeout task to be executed if the protocol is
476          not completed fast enough. */
477       if (ctx->timeout_task)
478         silc_task_unregister(server->timeout_queue, ctx->timeout_task);
479
480       /* Call the final callback */
481       if (protocol->final_callback)
482         protocol->execute_final(server->timeout_queue, 0, protocol, fd);
483       else
484         silc_protocol_free(protocol);
485     }
486     break;
487
488   case SILC_PROTOCOL_STATE_ERROR:
489     /*
490      * Error occured
491      */
492
493     /* Send abort notification */
494     silc_ske_abort(ctx->ske, ctx->ske->status, 
495                    silc_server_protocol_ke_send_packet,
496                    context);
497
498     /* Unregister the timeout task since the protocol has ended. 
499        This was the timeout task to be executed if the protocol is
500        not completed fast enough. */
501     if (ctx->timeout_task)
502       silc_task_unregister(server->timeout_queue, ctx->timeout_task);
503
504     /* On error the final callback is always called. */
505     if (protocol->final_callback)
506       protocol->execute_final(server->timeout_queue, 0, protocol, fd);
507     else
508       silc_protocol_free(protocol);
509     break;
510
511   case SILC_PROTOCOL_STATE_FAILURE:
512     /*
513      * We have received failure from remote
514      */
515
516     /* Unregister the timeout task since the protocol has ended. 
517        This was the timeout task to be executed if the protocol is
518        not completed fast enough. */
519     if (ctx->timeout_task)
520       silc_task_unregister(server->timeout_queue, ctx->timeout_task);
521
522     /* On error the final callback is always called. */
523     if (protocol->final_callback)
524       protocol->execute_final(server->timeout_queue, 0, protocol, fd);
525     else
526       silc_protocol_free(protocol);
527     break;
528
529   case SILC_PROTOCOL_STATE_UNKNOWN:
530     break;
531   }
532 }
533
534 /*
535  * Connection Authentication protocol functions
536  */
537
538 static int 
539 silc_server_password_authentication(SilcServer server, char *auth1, 
540                                     char *auth2)
541 {
542   if (!auth1 || !auth2)
543     return FALSE;
544
545   if (!memcmp(auth1, auth2, strlen(auth1)))
546     return TRUE;
547
548   return FALSE;
549 }
550
551 static int
552 silc_server_public_key_authentication(SilcServer server,
553                                       SilcPublicKey pub_key,
554                                       unsigned char *sign,
555                                       uint32 sign_len,
556                                       SilcSKE ske)
557 {
558   SilcPKCS pkcs;
559   int len;
560   SilcBuffer auth;
561
562   if (!pub_key || !sign)
563     return FALSE;
564
565   silc_pkcs_alloc(pub_key->name, &pkcs);
566   if (!silc_pkcs_public_key_set(pkcs, pub_key)) {
567     silc_pkcs_free(pkcs);
568     return FALSE;
569   }
570
571   /* Make the authentication data. Protocol says it is HASH plus
572      KE Start Payload. */
573   len = ske->hash_len + ske->start_payload_copy->len;
574   auth = silc_buffer_alloc(len);
575   silc_buffer_pull_tail(auth, len);
576   silc_buffer_format(auth,
577                      SILC_STR_UI_XNSTRING(ske->hash, ske->hash_len),
578                      SILC_STR_UI_XNSTRING(ske->start_payload_copy->data,
579                                           ske->start_payload_copy->len),
580                      SILC_STR_END);
581
582   /* Verify signature */
583   if (silc_pkcs_verify(pkcs, sign, sign_len, auth->data, auth->len)) {
584     silc_pkcs_free(pkcs);
585     silc_buffer_free(auth);
586     return TRUE;
587   }
588
589   silc_pkcs_free(pkcs);
590   silc_buffer_free(auth);
591   return FALSE;
592 }
593
594 static int
595 silc_server_get_public_key_auth(SilcServer server,
596                                 SilcPublicKey pub_key,
597                                 unsigned char *auth_data,
598                                 uint32 *auth_data_len,
599                                 SilcSKE ske)
600 {
601   int len;
602   SilcPKCS pkcs;
603   SilcBuffer auth;
604
605   if (!pub_key)
606     return FALSE;
607
608   silc_pkcs_alloc(pub_key->name, &pkcs);
609   if (!silc_pkcs_public_key_set(pkcs, pub_key)) {
610     silc_pkcs_free(pkcs);
611     return FALSE;
612   }
613
614   /* Make the authentication data. Protocol says it is HASH plus
615      KE Start Payload. */
616   len = ske->hash_len + ske->start_payload_copy->len;
617   auth = silc_buffer_alloc(len);
618   silc_buffer_pull_tail(auth, len);
619   silc_buffer_format(auth,
620                      SILC_STR_UI_XNSTRING(ske->hash, ske->hash_len),
621                      SILC_STR_UI_XNSTRING(ske->start_payload_copy->data,
622                                           ske->start_payload_copy->len),
623                      SILC_STR_END);
624
625   if (silc_pkcs_sign(pkcs, auth->data, auth->len, auth_data, auth_data_len)) {
626     silc_pkcs_free(pkcs);
627     silc_buffer_free(auth);
628     return TRUE;
629   }
630
631   silc_pkcs_free(pkcs);
632   silc_buffer_free(auth);
633   return FALSE;
634 }
635
636 /* Performs connection authentication protocol. If responder, we 
637    authenticate the remote data received. If initiator, we will send
638    authentication data to the remote end. */
639
640 SILC_TASK_CALLBACK(silc_server_protocol_connection_auth)
641 {
642   SilcProtocol protocol = (SilcProtocol)context;
643   SilcServerConnAuthInternalContext *ctx = 
644     (SilcServerConnAuthInternalContext *)protocol->context;
645   SilcServer server = (SilcServer)ctx->server;
646
647   SILC_LOG_DEBUG(("Start"));
648
649   if (protocol->state == SILC_PROTOCOL_STATE_UNKNOWN)
650     protocol->state = SILC_PROTOCOL_STATE_START;
651
652   SILC_LOG_DEBUG(("State=%d", protocol->state));
653
654   switch(protocol->state) {
655   case SILC_PROTOCOL_STATE_START:
656     {
657       /* 
658        * Start protocol.
659        */
660
661       if (ctx->responder == TRUE) {
662         /*
663          * We are receiving party
664          */
665         int ret;
666         uint16 payload_len;
667         uint16 conn_type;
668         unsigned char *auth_data = NULL;
669
670         SILC_LOG_INFO(("Performing authentication protocol for %s (%s)",
671                        ctx->sock->hostname, ctx->sock->ip));
672
673         /* Parse the received authentication data packet. The received
674            payload is Connection Auth Payload. */
675         ret = silc_buffer_unformat(ctx->packet->buffer,
676                                    SILC_STR_UI_SHORT(&payload_len),
677                                    SILC_STR_UI_SHORT(&conn_type),
678                                    SILC_STR_END);
679         if (ret == -1) {
680           SILC_LOG_DEBUG(("Bad payload in authentication packet"));
681           protocol->state = SILC_PROTOCOL_STATE_ERROR;
682           protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 300000);
683           return;
684         }
685         
686         if (payload_len != ctx->packet->buffer->len) {
687           SILC_LOG_DEBUG(("Bad payload in authentication packet"));
688           protocol->state = SILC_PROTOCOL_STATE_ERROR;
689           protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 300000);
690           return;
691         }
692         
693         payload_len -= 4;
694         
695         if (conn_type < SILC_SOCKET_TYPE_CLIENT || 
696             conn_type > SILC_SOCKET_TYPE_ROUTER) {
697           SILC_LOG_ERROR(("Bad connection type %d", conn_type));
698           protocol->state = SILC_PROTOCOL_STATE_ERROR;
699           protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 300000);
700           return;
701         }
702         
703         if (payload_len > 0) {
704           /* Get authentication data */
705           silc_buffer_pull(ctx->packet->buffer, 4);
706           ret = silc_buffer_unformat(ctx->packet->buffer,
707                                      SILC_STR_UI_XNSTRING_ALLOC(&auth_data, 
708                                                                 payload_len),
709                                      SILC_STR_END);
710           if (ret == -1) {
711             SILC_LOG_DEBUG(("Bad payload in authentication packet"));
712             protocol->state = SILC_PROTOCOL_STATE_ERROR;
713             protocol->execute(server->timeout_queue, 0, 
714                               protocol, fd, 0, 300000);
715             return;
716           }
717         }
718
719         /* 
720          * Check the remote connection type and make sure that we have
721          * configured this connection. If we haven't allowed this connection
722          * the authentication must be failed.
723          */
724
725         SILC_LOG_DEBUG(("Remote connection type %d", conn_type));
726
727         /* Remote end is client */
728         if (conn_type == SILC_SOCKET_TYPE_CLIENT) {
729           SilcServerConfigSectionClientConnection *client = ctx->cconfig;
730           
731           if (client) {
732             switch(client->auth_meth) {
733             case SILC_AUTH_NONE:
734               /* No authentication required */
735               SILC_LOG_DEBUG(("No authentication required"));
736               break;
737               
738             case SILC_AUTH_PASSWORD:
739               /* Password authentication */
740               SILC_LOG_DEBUG(("Password authentication"));
741               ret = silc_server_password_authentication(server, auth_data,
742                                                         client->auth_data);
743
744               if (ret)
745                 break;
746
747               /* Authentication failed */
748               SILC_LOG_ERROR(("Authentication failed"));
749               SILC_LOG_DEBUG(("Authentication failed"));
750               silc_free(auth_data);
751               protocol->state = SILC_PROTOCOL_STATE_ERROR;
752               protocol->execute(server->timeout_queue, 0, 
753                                 protocol, fd, 0, 300000);
754               return;
755               break;
756               
757             case SILC_AUTH_PUBLIC_KEY:
758               /* Public key authentication */
759               SILC_LOG_DEBUG(("Public key authentication"));
760               ret = silc_server_public_key_authentication(server, 
761                                                           client->auth_data,
762                                                           auth_data,
763                                                           payload_len, 
764                                                           ctx->ske);
765
766               if (ret)
767                 break;
768
769               SILC_LOG_ERROR(("Authentication failed"));
770               SILC_LOG_DEBUG(("Authentication failed"));
771               silc_free(auth_data);
772               protocol->state = SILC_PROTOCOL_STATE_ERROR;
773               protocol->execute(server->timeout_queue, 0, 
774                                 protocol, fd, 0, 300000);
775               return;
776             }
777           } else {
778             SILC_LOG_DEBUG(("No configuration for remote connection"));
779             SILC_LOG_ERROR(("Remote connection not configured"));
780             SILC_LOG_ERROR(("Authentication failed"));
781             silc_free(auth_data);
782             protocol->state = SILC_PROTOCOL_STATE_ERROR;
783             protocol->execute(server->timeout_queue, 0, 
784                               protocol, fd, 0, 300000);
785             return;
786           }
787         }
788         
789         /* Remote end is server */
790         if (conn_type == SILC_SOCKET_TYPE_SERVER) {
791           SilcServerConfigSectionServerConnection *serv = ctx->sconfig;
792           
793           if (serv) {
794             switch(serv->auth_meth) {
795             case SILC_AUTH_NONE:
796               /* No authentication required */
797               SILC_LOG_DEBUG(("No authentication required"));
798               break;
799               
800             case SILC_AUTH_PASSWORD:
801               /* Password authentication */
802               SILC_LOG_DEBUG(("Password authentication"));
803               ret = silc_server_password_authentication(server, auth_data,
804                                                         serv->auth_data);
805
806               if (ret)
807                 break;
808               
809               /* Authentication failed */
810               SILC_LOG_ERROR(("Authentication failed"));
811               SILC_LOG_DEBUG(("Authentication failed"));
812               silc_free(auth_data);
813               protocol->state = SILC_PROTOCOL_STATE_ERROR;
814               protocol->execute(server->timeout_queue, 0, 
815                                 protocol, fd, 0, 300000);
816               return;
817               break;
818
819             case SILC_AUTH_PUBLIC_KEY:
820               /* Public key authentication */
821               SILC_LOG_DEBUG(("Public key authentication"));
822               ret = silc_server_public_key_authentication(server, 
823                                                           serv->auth_data,
824                                                           auth_data,
825                                                           payload_len, 
826                                                           ctx->ske);
827                                                           
828               if (ret)
829                 break;
830
831               SILC_LOG_ERROR(("Authentication failed"));
832               SILC_LOG_DEBUG(("Authentication failed"));
833               silc_free(auth_data);
834               protocol->state = SILC_PROTOCOL_STATE_ERROR;
835               protocol->execute(server->timeout_queue, 0, 
836                                 protocol, fd, 0, 300000);
837               return;
838             }
839           } else {
840             SILC_LOG_DEBUG(("No configuration for remote connection"));
841             SILC_LOG_ERROR(("Remote connection not configured"));
842             SILC_LOG_ERROR(("Authentication failed"));
843             protocol->state = SILC_PROTOCOL_STATE_ERROR;
844             protocol->execute(server->timeout_queue, 0, 
845                               protocol, fd, 0, 300000);
846             silc_free(auth_data);
847             return;
848           }
849         }
850         
851         /* Remote end is router */
852         if (conn_type == SILC_SOCKET_TYPE_ROUTER) {
853           SilcServerConfigSectionServerConnection *serv = ctx->rconfig;
854
855           if (serv) {
856             switch(serv->auth_meth) {
857             case SILC_AUTH_NONE:
858               /* No authentication required */
859               SILC_LOG_DEBUG(("No authentication required"));
860               break;
861               
862             case SILC_AUTH_PASSWORD:
863               /* Password authentication */
864               SILC_LOG_DEBUG(("Password authentication"));
865               ret = silc_server_password_authentication(server, auth_data,
866                                                         serv->auth_data);
867
868               if (ret)
869                 break;
870               
871               /* Authentication failed */
872               SILC_LOG_ERROR(("Authentication failed"));
873               SILC_LOG_DEBUG(("Authentication failed"));
874               silc_free(auth_data);
875               protocol->state = SILC_PROTOCOL_STATE_ERROR;
876               protocol->execute(server->timeout_queue, 0, 
877                                 protocol, fd, 0, 300000);
878               return;
879               break;
880               
881             case SILC_AUTH_PUBLIC_KEY:
882               /* Public key authentication */
883               SILC_LOG_DEBUG(("Public key authentication"));
884               ret = silc_server_public_key_authentication(server, 
885                                                           serv->auth_data,
886                                                           auth_data,
887                                                           payload_len, 
888                                                           ctx->ske);
889                                                           
890               if (ret)
891                 break;
892               
893               SILC_LOG_ERROR(("Authentication failed"));
894               SILC_LOG_DEBUG(("Authentication failed"));
895               silc_free(auth_data);
896               protocol->state = SILC_PROTOCOL_STATE_ERROR;
897               protocol->execute(server->timeout_queue, 0, 
898                                 protocol, fd, 0, 300000);
899               return;
900             }
901           } else {
902             SILC_LOG_DEBUG(("No configuration for remote connection"));
903             SILC_LOG_ERROR(("Remote connection not configured"));
904             SILC_LOG_ERROR(("Authentication failed"));
905             silc_free(auth_data);
906             protocol->state = SILC_PROTOCOL_STATE_ERROR;
907             protocol->execute(server->timeout_queue, 0, 
908                               protocol, fd, 0, 300000);
909             return;
910           }
911         }
912         
913         silc_free(auth_data);
914
915         /* Save connection type. This is later used to create the
916            ID for the connection. */
917         ctx->conn_type = conn_type;
918           
919         /* Advance protocol state. */
920         protocol->state = SILC_PROTOCOL_STATE_END;
921         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 0);
922
923       } else {
924         /* 
925          * We are initiator. We are authenticating ourselves to a
926          * remote server. We will send the authentication data to the
927          * other end for verify. 
928          */
929         SilcBuffer packet;
930         int payload_len = 0;
931         unsigned char *auth_data = NULL;
932         uint32 auth_data_len = 0;
933         
934         switch(ctx->auth_meth) {
935         case SILC_AUTH_NONE:
936           /* No authentication required */
937           break;
938           
939         case SILC_AUTH_PASSWORD:
940           /* Password authentication */
941           if (ctx->auth_data && ctx->auth_data_len) {
942             auth_data = strdup(ctx->auth_data);
943             auth_data_len = ctx->auth_data_len;
944             break;
945           }
946           break;
947           
948         case SILC_AUTH_PUBLIC_KEY:
949           {
950             unsigned char sign[1024];
951
952             /* Public key authentication */
953             silc_server_get_public_key_auth(server, ctx->auth_data,
954                                             sign, &auth_data_len,
955                                             ctx->ske);
956             auth_data = silc_calloc(auth_data_len, sizeof(*auth_data));
957             memcpy(auth_data, sign, auth_data_len);
958             break;
959           }
960         }
961         
962         payload_len = 4 + auth_data_len;
963         packet = silc_buffer_alloc(payload_len);
964         silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
965         silc_buffer_format(packet,
966                            SILC_STR_UI_SHORT(payload_len),
967                            SILC_STR_UI_SHORT(server->server_type 
968                                               == SILC_SERVER ?
969                                               SILC_SOCKET_TYPE_SERVER :
970                                               SILC_SOCKET_TYPE_ROUTER),
971                            SILC_STR_UI_XNSTRING(auth_data, auth_data_len),
972                            SILC_STR_END);
973         
974         /* Send the packet to server */
975         silc_server_packet_send(server, ctx->sock,
976                                 SILC_PACKET_CONNECTION_AUTH, 0, 
977                                 packet->data, packet->len, TRUE);
978         
979         if (auth_data) {
980           memset(auth_data, 0, auth_data_len);
981           silc_free(auth_data);
982         }
983         silc_buffer_free(packet);
984         
985         /* Next state is end of protocol */
986         protocol->state = SILC_PROTOCOL_STATE_END;
987       }
988     }
989     break;
990
991   case SILC_PROTOCOL_STATE_END:
992     {
993       /* 
994        * End protocol
995        */
996       unsigned char ok[4];
997
998       SILC_PUT32_MSB(SILC_AUTH_OK, ok);
999
1000       /* Authentication successful */
1001       silc_server_packet_send(server, ctx->sock, SILC_PACKET_SUCCESS,
1002                               0, ok, 4, TRUE);
1003
1004       /* Unregister the timeout task since the protocol has ended. 
1005          This was the timeout task to be executed if the protocol is
1006          not completed fast enough. */
1007       if (ctx->timeout_task)
1008         silc_task_unregister(server->timeout_queue, ctx->timeout_task);
1009
1010       /* Protocol has ended, call the final callback */
1011       if (protocol->final_callback)
1012         protocol->execute_final(server->timeout_queue, 0, protocol, fd);
1013       else
1014         silc_protocol_free(protocol);
1015     }
1016     break;
1017   case SILC_PROTOCOL_STATE_ERROR:
1018     {
1019       /*
1020        * Error. Send notify to remote.
1021        */
1022       unsigned char error[4];
1023
1024       SILC_PUT32_MSB(SILC_AUTH_FAILED, error);
1025
1026       /* Authentication failed */
1027       silc_server_packet_send(server, ctx->sock, SILC_PACKET_FAILURE,
1028                               0, error, 4, TRUE);
1029
1030       /* Unregister the timeout task since the protocol has ended. 
1031          This was the timeout task to be executed if the protocol is
1032          not completed fast enough. */
1033       if (ctx->timeout_task)
1034         silc_task_unregister(server->timeout_queue, ctx->timeout_task);
1035
1036       /* On error the final callback is always called. */
1037       if (protocol->final_callback)
1038         protocol->execute_final(server->timeout_queue, 0, protocol, fd);
1039       else
1040         silc_protocol_free(protocol);
1041     }
1042     break;
1043
1044   case SILC_PROTOCOL_STATE_FAILURE:
1045     /*
1046      * We have received failure from remote
1047      */
1048
1049     /* Unregister the timeout task since the protocol has ended. 
1050        This was the timeout task to be executed if the protocol is
1051        not completed fast enough. */
1052     if (ctx->timeout_task)
1053       silc_task_unregister(server->timeout_queue, ctx->timeout_task);
1054
1055     /* On error the final callback is always called. */
1056     if (protocol->final_callback)
1057       protocol->execute_final(server->timeout_queue, 0, protocol, fd);
1058     else
1059       silc_protocol_free(protocol);
1060     break;
1061
1062   case SILC_PROTOCOL_STATE_UNKNOWN:
1063     break;
1064   }
1065 }
1066
1067 /*
1068  * Re-key protocol routines
1069  */
1070
1071 /* Actually takes the new keys into use. */
1072
1073 static void 
1074 silc_server_protocol_rekey_validate(SilcServer server,
1075                                     SilcServerRekeyInternalContext *ctx,
1076                                     SilcIDListData idata,
1077                                     SilcSKEKeyMaterial *keymat,
1078                                     bool send)
1079 {
1080   if (ctx->responder == TRUE) {
1081     if (send) {
1082       silc_cipher_set_key(idata->send_key, keymat->receive_enc_key, 
1083                           keymat->enc_key_len);
1084       silc_cipher_set_iv(idata->send_key, keymat->receive_iv);
1085     } else {
1086       silc_cipher_set_key(idata->receive_key, keymat->send_enc_key, 
1087                           keymat->enc_key_len);
1088       silc_cipher_set_iv(idata->receive_key, keymat->send_iv);
1089     }
1090   } else {
1091     if (send) {
1092       silc_cipher_set_key(idata->send_key, keymat->send_enc_key, 
1093                           keymat->enc_key_len);
1094       silc_cipher_set_iv(idata->send_key, keymat->send_iv);
1095     } else {
1096       silc_cipher_set_key(idata->receive_key, keymat->receive_enc_key, 
1097                           keymat->enc_key_len);
1098       silc_cipher_set_iv(idata->receive_key, keymat->receive_iv);
1099     }
1100   }
1101
1102   if (send) {
1103     silc_hmac_alloc(idata->hmac_send->hmac->name, NULL, &idata->hmac_send);
1104     silc_hmac_set_key(idata->hmac_send, keymat->hmac_key, 
1105                       keymat->hmac_key_len);
1106   } else {
1107     silc_hmac_free(idata->hmac_receive);
1108     idata->hmac_receive = idata->hmac_send;
1109   }
1110
1111   /* Save the current sending encryption key */
1112   if (!send) {
1113     memset(idata->rekey->send_enc_key, 0, idata->rekey->enc_key_len);
1114     silc_free(idata->rekey->send_enc_key);
1115     idata->rekey->send_enc_key = 
1116       silc_calloc(keymat->enc_key_len / 8,
1117                   sizeof(*idata->rekey->send_enc_key));
1118     memcpy(idata->rekey->send_enc_key, keymat->send_enc_key, 
1119            keymat->enc_key_len / 8);
1120     idata->rekey->enc_key_len = keymat->enc_key_len / 8;
1121   }
1122 }
1123
1124 /* This function actually re-generates (when not using PFS) the keys and
1125    takes them into use. */
1126
1127 void silc_server_protocol_rekey_generate(SilcServer server,
1128                                          SilcServerRekeyInternalContext *ctx,
1129                                          bool send)
1130 {
1131   SilcIDListData idata = (SilcIDListData)ctx->sock->user_data;
1132   SilcSKEKeyMaterial *keymat;
1133   uint32 key_len = silc_cipher_get_key_len(idata->send_key);
1134   uint32 hash_len = idata->hash->hash->hash_len;
1135
1136   SILC_LOG_DEBUG(("Generating new %s session keys (no PFS)",
1137                   send ? "sending" : "receiving"));
1138
1139   /* Generate the new key */
1140   keymat = silc_calloc(1, sizeof(*keymat));
1141   silc_ske_process_key_material_data(idata->rekey->send_enc_key,
1142                                      idata->rekey->enc_key_len,
1143                                      16, key_len, hash_len, 
1144                                      idata->hash, keymat);
1145
1146   /* Set the keys into use */
1147   silc_server_protocol_rekey_validate(server, ctx, idata, keymat, send);
1148
1149   silc_ske_free_key_material(keymat);
1150 }
1151
1152 /* This function actually re-generates (with PFS) the keys and
1153    takes them into use. */
1154
1155 void 
1156 silc_server_protocol_rekey_generate_pfs(SilcServer server,
1157                                         SilcServerRekeyInternalContext *ctx,
1158                                         bool send)
1159 {
1160   SilcIDListData idata = (SilcIDListData)ctx->sock->user_data;
1161   SilcSKEKeyMaterial *keymat;
1162   uint32 key_len = silc_cipher_get_key_len(idata->send_key);
1163   uint32 hash_len = idata->hash->hash->hash_len;
1164   unsigned char *tmpbuf;
1165   uint32 klen;
1166
1167   SILC_LOG_DEBUG(("Generating new %s session keys (with PFS)",
1168                   send ? "sending" : "receiving"));
1169
1170   /* Encode KEY to binary data */
1171   tmpbuf = silc_mp_mp2bin(ctx->ske->KEY, 0, &klen);
1172
1173   /* Generate the new key */
1174   keymat = silc_calloc(1, sizeof(*keymat));
1175   silc_ske_process_key_material_data(tmpbuf, klen, 16, key_len, hash_len, 
1176                                      idata->hash, keymat);
1177
1178   /* Set the keys into use */
1179   silc_server_protocol_rekey_validate(server, ctx, idata, keymat, send);
1180
1181   memset(tmpbuf, 0, klen);
1182   silc_free(tmpbuf);
1183   silc_ske_free_key_material(keymat);
1184 }
1185
1186 /* Packet sending callback. This function is provided as packet sending
1187    routine to the Key Exchange functions. */
1188
1189 static void 
1190 silc_server_protocol_rekey_send_packet(SilcSKE ske,
1191                                        SilcBuffer packet,
1192                                        SilcPacketType type,
1193                                        void *context)
1194 {
1195   SilcProtocol protocol = (SilcProtocol)context;
1196   SilcServerRekeyInternalContext *ctx = 
1197     (SilcServerRekeyInternalContext *)protocol->context;
1198   SilcServer server = (SilcServer)ctx->server;
1199
1200   /* Send the packet immediately */
1201   silc_server_packet_send(server, ctx->sock,
1202                           type, 0, packet->data, packet->len, FALSE);
1203 }
1204
1205 /* Performs re-key as defined in the SILC protocol specification. */
1206
1207 SILC_TASK_CALLBACK(silc_server_protocol_rekey)
1208 {
1209   SilcProtocol protocol = (SilcProtocol)context;
1210   SilcServerRekeyInternalContext *ctx = 
1211     (SilcServerRekeyInternalContext *)protocol->context;
1212   SilcServer server = (SilcServer)ctx->server;
1213   SilcIDListData idata = (SilcIDListData)ctx->sock->user_data;
1214   SilcSKEStatus status;
1215
1216   SILC_LOG_DEBUG(("Start"));
1217
1218   if (protocol->state == SILC_PROTOCOL_STATE_UNKNOWN)
1219     protocol->state = SILC_PROTOCOL_STATE_START;
1220
1221   SILC_LOG_DEBUG(("State=%d", protocol->state));
1222
1223   switch(protocol->state) {
1224   case SILC_PROTOCOL_STATE_START:
1225     {
1226       /* 
1227        * Start protocol.
1228        */
1229
1230       if (ctx->responder == TRUE) {
1231         /*
1232          * We are receiving party
1233          */
1234
1235         if (ctx->pfs == TRUE) {
1236           /* 
1237            * Use Perfect Forward Secrecy, ie. negotiate the key material
1238            * using the SKE protocol.
1239            */
1240
1241           if (ctx->packet->type != SILC_PACKET_KEY_EXCHANGE_1) {
1242             /* Error in protocol */
1243             protocol->state = SILC_PROTOCOL_STATE_ERROR;
1244             protocol->execute(server->timeout_queue, 0, protocol, fd, 
1245                               0, 300000);
1246           }
1247
1248           ctx->ske = silc_ske_alloc();
1249           ctx->ske->rng = server->rng;
1250           ctx->ske->prop = silc_calloc(1, sizeof(*ctx->ske->prop));
1251           silc_ske_get_group_by_number(idata->rekey->ske_group,
1252                                        &ctx->ske->prop->group);
1253
1254           status = silc_ske_responder_phase_2(ctx->ske, ctx->packet->buffer,
1255                                               NULL, NULL, NULL, NULL);
1256           if (status != SILC_SKE_STATUS_OK) {
1257             SILC_LOG_WARNING(("Error (type %d) during Re-key (PFS)",
1258                               status));
1259             
1260             protocol->state = SILC_PROTOCOL_STATE_ERROR;
1261             protocol->execute(server->timeout_queue, 0, 
1262                               protocol, fd, 0, 300000);
1263             return;
1264           }
1265
1266           /* Advance the protocol state */
1267           protocol->state++;
1268           protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 0);
1269         } else {
1270           /*
1271            * Do normal and simple re-key.
1272            */
1273
1274           /* Send the REKEY_DONE to indicate we will take new keys into use */
1275           silc_server_packet_send(server, ctx->sock, SILC_PACKET_REKEY_DONE,
1276                                   0, NULL, 0, FALSE);
1277
1278           /* After we send REKEY_DONE we must set the sending encryption
1279              key to the new key since all packets after this packet must
1280              encrypted with the new key. */
1281           silc_server_protocol_rekey_generate(server, ctx, TRUE);
1282
1283           /* The protocol ends in next stage. */
1284           protocol->state = SILC_PROTOCOL_STATE_END;
1285         }
1286       
1287       } else {
1288         /*
1289          * We are the initiator of this protocol
1290          */
1291
1292         /* Start the re-key by sending the REKEY packet */
1293         silc_server_packet_send(server, ctx->sock, SILC_PACKET_REKEY,
1294                                 0, NULL, 0, FALSE);
1295
1296         if (ctx->pfs == TRUE) {
1297           /* 
1298            * Use Perfect Forward Secrecy, ie. negotiate the key material
1299            * using the SKE protocol.
1300            */
1301           ctx->ske = silc_ske_alloc();
1302           ctx->ske->rng = server->rng;
1303           ctx->ske->prop = silc_calloc(1, sizeof(*ctx->ske->prop));
1304           silc_ske_get_group_by_number(idata->rekey->ske_group,
1305                                        &ctx->ske->prop->group);
1306
1307           status = 
1308             silc_ske_initiator_phase_2(ctx->ske, NULL, NULL,
1309                                        silc_server_protocol_rekey_send_packet,
1310                                        context);
1311
1312           if (status != SILC_SKE_STATUS_OK) {
1313             SILC_LOG_WARNING(("Error (type %d) during Re-key (PFS)",
1314                               status));
1315             
1316             protocol->state = SILC_PROTOCOL_STATE_ERROR;
1317             protocol->execute(server->timeout_queue, 0, 
1318                               protocol, fd, 0, 300000);
1319             return;
1320           }
1321
1322           /* Advance the protocol state */
1323           protocol->state++;
1324         } else {
1325           /*
1326            * Do normal and simple re-key.
1327            */
1328
1329           /* Send the REKEY_DONE to indicate we will take new keys into use 
1330              now. */ 
1331           silc_server_packet_send(server, ctx->sock, SILC_PACKET_REKEY_DONE,
1332                                   0, NULL, 0, FALSE);
1333
1334           /* After we send REKEY_DONE we must set the sending encryption
1335              key to the new key since all packets after this packet must
1336              encrypted with the new key. */
1337           silc_server_protocol_rekey_generate(server, ctx, TRUE);
1338
1339           /* The protocol ends in next stage. */
1340           protocol->state = SILC_PROTOCOL_STATE_END;
1341         }
1342       }
1343     }
1344     break;
1345
1346   case 2:
1347     /*
1348      * Second state, used only when oding re-key with PFS.
1349      */
1350     if (ctx->responder == TRUE) {
1351       if (ctx->pfs == TRUE) {
1352         /*
1353          * Send our KE packe to the initiator now that we've processed
1354          * the initiator's KE packet.
1355          */
1356         status = 
1357           silc_ske_responder_finish(ctx->ske, NULL, NULL, 
1358                                     SILC_SKE_PK_TYPE_SILC,
1359                                     silc_server_protocol_rekey_send_packet,
1360                                     context);
1361
1362           if (status != SILC_SKE_STATUS_OK) {
1363             SILC_LOG_WARNING(("Error (type %d) during Re-key (PFS)",
1364                               status));
1365             
1366             protocol->state = SILC_PROTOCOL_STATE_ERROR;
1367             protocol->execute(server->timeout_queue, 0, 
1368                               protocol, fd, 0, 300000);
1369             return;
1370           }
1371       }
1372
1373     } else {
1374       if (ctx->pfs == TRUE) {
1375         /*
1376          * The packet type must be KE packet
1377          */
1378         if (ctx->packet->type != SILC_PACKET_KEY_EXCHANGE_2) {
1379           /* Error in protocol */
1380           protocol->state = SILC_PROTOCOL_STATE_ERROR;
1381           protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 300000);
1382         }
1383         
1384         status = silc_ske_initiator_finish(ctx->ske, ctx->packet->buffer,
1385                                            NULL, NULL, NULL, NULL);
1386         if (status != SILC_SKE_STATUS_OK) {
1387           SILC_LOG_WARNING(("Error (type %d) during Re-key (PFS)",
1388                             status));
1389           
1390           protocol->state = SILC_PROTOCOL_STATE_ERROR;
1391           protocol->execute(server->timeout_queue, 0, 
1392                             protocol, fd, 0, 300000);
1393           return;
1394         }
1395       }
1396     }
1397
1398     /* Send the REKEY_DONE to indicate we will take new keys into use 
1399        now. */ 
1400     silc_server_packet_send(server, ctx->sock, SILC_PACKET_REKEY_DONE,
1401                             0, NULL, 0, FALSE);
1402     
1403     /* After we send REKEY_DONE we must set the sending encryption
1404        key to the new key since all packets after this packet must
1405        encrypted with the new key. */
1406     silc_server_protocol_rekey_generate_pfs(server, ctx, TRUE);
1407
1408     /* The protocol ends in next stage. */
1409     protocol->state = SILC_PROTOCOL_STATE_END;
1410     break;
1411
1412   case SILC_PROTOCOL_STATE_END:
1413     /* 
1414      * End protocol
1415      */
1416
1417     if (ctx->packet->type != SILC_PACKET_REKEY_DONE) {
1418       /* Error in protocol */
1419       protocol->state = SILC_PROTOCOL_STATE_ERROR;
1420       protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 0);
1421     }
1422
1423     /* We received the REKEY_DONE packet and all packets after this is
1424        encrypted with the new key so set the decryption key to the new key */
1425     silc_server_protocol_rekey_generate(server, ctx, FALSE);
1426
1427     /* Protocol has ended, call the final callback */
1428     if (protocol->final_callback)
1429       protocol->execute_final(server->timeout_queue, 0, protocol, fd);
1430     else
1431       silc_protocol_free(protocol);
1432     break;
1433
1434   case SILC_PROTOCOL_STATE_ERROR:
1435     /*
1436      * Error occured
1437      */
1438
1439     if (ctx->pfs == TRUE) {
1440       /* Send abort notification */
1441       silc_ske_abort(ctx->ske, ctx->ske->status, 
1442                      silc_server_protocol_ke_send_packet,
1443                      context);
1444     }
1445
1446     /* On error the final callback is always called. */
1447     if (protocol->final_callback)
1448       protocol->execute_final(server->timeout_queue, 0, protocol, fd);
1449     else
1450       silc_protocol_free(protocol);
1451     break;
1452
1453   case SILC_PROTOCOL_STATE_FAILURE:
1454     /*
1455      * We have received failure from remote
1456      */
1457
1458     /* On error the final callback is always called. */
1459     if (protocol->final_callback)
1460       protocol->execute_final(server->timeout_queue, 0, protocol, fd);
1461     else
1462       silc_protocol_free(protocol);
1463     break;
1464
1465   case SILC_PROTOCOL_STATE_UNKNOWN:
1466     break;
1467   }
1468
1469 }
1470
1471 /* Registers protocols used in server. */
1472
1473 void silc_server_protocols_register(void)
1474 {
1475   silc_protocol_register(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1476                          silc_server_protocol_connection_auth);
1477   silc_protocol_register(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1478                          silc_server_protocol_key_exchange);
1479   silc_protocol_register(SILC_PROTOCOL_SERVER_REKEY,
1480                          silc_server_protocol_rekey);
1481 }
1482
1483 /* Unregisters protocols */
1484
1485 void silc_server_protocols_unregister(void)
1486 {
1487   silc_protocol_unregister(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1488                            silc_server_protocol_connection_auth);
1489   silc_protocol_unregister(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1490                            silc_server_protocol_key_exchange);
1491   silc_protocol_unregister(SILC_PROTOCOL_SERVER_REKEY,
1492                            silc_server_protocol_rekey);
1493 }