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