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