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