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