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