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