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