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