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