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