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