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