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