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