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