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