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