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