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