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