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