updates.
[silc.git] / apps / silcd / protocol.c
1 /*
2
3   protocol.c
4
5   Author: Pekka Riikonen <priikone@poseidon.pspt.fi>
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   return TRUE;
284 }
285
286 /* Check remote host version string */
287
288 SilcSKEStatus silc_ske_check_version(SilcSKE ske, unsigned char *version,
289                                      uint32 len)
290 {
291   SilcSKEStatus status = SILC_SKE_STATUS_OK;
292   char *cp;
293   int maj = 0, min = 0, build = 0, maj2 = 0, min2 = 0, build2 = 0;
294
295   SILC_LOG_INFO(("%s (%s) is version %s", ske->sock->hostname,
296                  ske->sock->ip, version));
297
298   /* Check for initial version string */
299   if (!strstr(version, "SILC-1.0-"))
300     status = SILC_SKE_STATUS_BAD_VERSION;
301
302   /* Check software version */
303
304   cp = version + 9;
305   if (!cp)
306     status = SILC_SKE_STATUS_BAD_VERSION;
307
308   maj = atoi(cp);
309   cp = strchr(cp, '.');
310   if (cp) {
311     min = atoi(cp + 1);
312     cp++;
313   }
314   if (cp) {
315     cp = strchr(cp, '.');
316     if (cp)
317       build = atoi(cp + 1);
318   }
319
320   cp = silc_version_string + 9;
321   if (!cp)
322     status = SILC_SKE_STATUS_BAD_VERSION;
323
324   maj2 = atoi(cp);
325   cp = strchr(cp, '.');
326   if (cp) {
327     min2 = atoi(cp + 1);
328     cp++;
329   }
330   if (cp) {
331     cp = strchr(cp, '.');
332     if (cp)
333       build2 = atoi(cp + 1);
334   }
335
336   if (maj != maj2)
337     status = SILC_SKE_STATUS_BAD_VERSION;
338   if (min < min2)
339     status = SILC_SKE_STATUS_BAD_VERSION;
340
341   return status;
342 }
343
344 /* Callback that is called by the SKE to indicate that it is safe to
345    continue the execution of the protocol. This is used only if we are
346    initiator.  Is given as argument to the silc_ske_initiator_finish or
347    silc_ske_responder_phase_2 functions. This is called due to the fact
348    that the public key verification process is asynchronous and we must
349    not continue the protocl until the public key has been verified and
350    this callback is called. */
351
352 static void silc_server_protocol_ke_continue(SilcSKE ske, void *context)
353 {
354   SilcProtocol protocol = (SilcProtocol)context;
355   SilcServerKEInternalContext *ctx = 
356     (SilcServerKEInternalContext *)protocol->context;
357   SilcServer server = (SilcServer)ctx->server;
358
359   SILC_LOG_DEBUG(("Start"));
360
361   if (ske->status != SILC_SKE_STATUS_OK) {
362     SILC_LOG_WARNING(("Error (type %d) during Key Exchange protocol",
363                       ske->status));
364     SILC_LOG_DEBUG(("Error (type %d) during Key Exchange protocol",
365                     ske->status));
366     
367     protocol->state = SILC_PROTOCOL_STATE_ERROR;
368     silc_protocol_execute(protocol, server->timeout_queue, 0, 300000);
369     return;
370   }
371
372   /* Send Ok to the other end. We will end the protocol as responder
373      sends Ok to us when we will take the new keys into use. */
374   if (ctx->responder == FALSE) {
375     silc_ske_end(ctx->ske, silc_server_protocol_ke_send_packet, context);
376
377     /* End the protocol on the next round */
378     protocol->state = SILC_PROTOCOL_STATE_END;
379   }
380
381   /* Advance protocol state and call the next state if we are responder. 
382      This happens when this callback was sent to silc_ske_responder_phase_2
383      function. */
384   if (ctx->responder == TRUE) {
385     protocol->state++;
386     silc_protocol_execute(protocol, server->timeout_queue, 0, 100000);
387   }
388 }
389
390 /* Performs key exchange protocol. This is used for both initiator
391    and responder key exchange. This is performed always when accepting
392    new connection to the server. This may be called recursively. */
393
394 SILC_TASK_CALLBACK(silc_server_protocol_key_exchange)
395 {
396   SilcProtocol protocol = (SilcProtocol)context;
397   SilcServerKEInternalContext *ctx = 
398     (SilcServerKEInternalContext *)protocol->context;
399   SilcServer server = (SilcServer)ctx->server;
400   SilcSKEStatus status = SILC_SKE_STATUS_OK;
401
402   SILC_LOG_DEBUG(("Start"));
403
404   if (protocol->state == SILC_PROTOCOL_STATE_UNKNOWN)
405     protocol->state = SILC_PROTOCOL_STATE_START;
406
407   SILC_LOG_DEBUG(("State=%d", protocol->state));
408
409   switch(protocol->state) {
410   case SILC_PROTOCOL_STATE_START:
411     {
412       /*
413        * Start protocol
414        */
415       SilcSKE ske;
416
417       /* Allocate Key Exchange object */
418       ske = silc_ske_alloc();
419       ctx->ske = ske;
420       ske->rng = server->rng;
421       
422       if (ctx->responder == TRUE) {
423         /* Start the key exchange by processing the received security
424            properties packet from initiator. */
425         status = silc_ske_responder_start(ske, ctx->rng, ctx->sock,
426                                           silc_version_string,
427                                           ctx->packet->buffer, FALSE,
428                                           NULL, NULL);
429       } else {
430         SilcSKEStartPayload *start_payload;
431
432         /* Assemble security properties. */
433         silc_ske_assemble_security_properties(ske, SILC_SKE_SP_FLAG_NONE, 
434                                               silc_version_string,
435                                               &start_payload);
436
437         /* Start the key exchange by sending our security properties
438            to the remote end. */
439         status = silc_ske_initiator_start(ske, ctx->rng, ctx->sock,
440                                           start_payload,
441                                           silc_server_protocol_ke_send_packet,
442                                           context);
443       }
444
445       /* Return now if the procedure is pending. */
446       if (status == SILC_SKE_STATUS_PENDING)
447         return;
448
449       if (status != SILC_SKE_STATUS_OK) {
450         SILC_LOG_WARNING(("Error (type %d) during Key Exchange protocol",
451                           status));
452         SILC_LOG_DEBUG(("Error (type %d) during Key Exchange protocol",
453                         status));
454
455         protocol->state = SILC_PROTOCOL_STATE_ERROR;
456         silc_protocol_execute(protocol, server->timeout_queue, 0, 300000);
457         return;
458       }
459
460       /* Advance protocol state and call the next state if we are responder */
461       protocol->state++;
462       if (ctx->responder == TRUE)
463         silc_protocol_execute(protocol, server->timeout_queue, 0, 100000);
464     }
465     break;
466   case 2:
467     {
468       /* 
469        * Phase 1 
470        */
471       if (ctx->responder == TRUE) {
472         /* Sends the selected security properties to the initiator. */
473         status = 
474           silc_ske_responder_phase_1(ctx->ske, 
475                                      ctx->ske->start_payload,
476                                      silc_server_protocol_ke_send_packet,
477                                      context);
478       } else {
479         /* Call Phase-1 function. This processes the Key Exchange Start
480            paylaod reply we just got from the responder. The callback
481            function will receive the processed payload where we will
482            save it. */
483         status = silc_ske_initiator_phase_1(ctx->ske, ctx->packet->buffer,
484                                             NULL, NULL);
485       }
486
487       /* Return now if the procedure is pending. */
488       if (status == SILC_SKE_STATUS_PENDING)
489         return;
490
491       if (status != SILC_SKE_STATUS_OK) {
492         SILC_LOG_WARNING(("Error (type %d) during Key Exchange protocol",
493                           status));
494         SILC_LOG_DEBUG(("Error (type %d) during Key Exchange protocol",
495                         status));
496
497         protocol->state = SILC_PROTOCOL_STATE_ERROR;
498         silc_protocol_execute(protocol, server->timeout_queue, 0, 300000);
499         return;
500       }
501
502       /* Advance protocol state and call next state if we are initiator */
503       protocol->state++;
504       if (ctx->responder == FALSE)
505         silc_protocol_execute(protocol, server->timeout_queue, 0, 100000);
506     }
507     break;
508   case 3:
509     {
510       /* 
511        * Phase 2 
512        */
513       if (ctx->responder == TRUE) {
514         /* Process the received Key Exchange 1 Payload packet from
515            the initiator. This also creates our parts of the Diffie
516            Hellman algorithm. The silc_server_protocol_ke_continue
517            will be called after the public key has been verified. */
518         status = 
519           silc_ske_responder_phase_2(ctx->ske, ctx->packet->buffer, 
520                                      silc_server_protocol_ke_verify_key, 
521                                      context, 
522                                      silc_server_protocol_ke_continue, 
523                                      context);
524       } else {
525         /* Call the Phase-2 function. This creates Diffie Hellman
526            key exchange parameters and sends our public part inside
527            Key Exhange 1 Payload to the responder. */
528         status = 
529           silc_ske_initiator_phase_2(ctx->ske,
530                                      server->public_key,
531                                      server->private_key,
532                                      silc_server_protocol_ke_send_packet,
533                                      context);
534         protocol->state++;
535       }
536
537       /* Return now if the procedure is pending. */
538       if (status == SILC_SKE_STATUS_PENDING)
539         return;
540
541       if (status != SILC_SKE_STATUS_OK) {
542         SILC_LOG_WARNING(("Error (type %d) during Key Exchange protocol",
543                           status));
544         SILC_LOG_DEBUG(("Error (type %d) during Key Exchange protocol",
545                         status));
546
547         protocol->state = SILC_PROTOCOL_STATE_ERROR;
548         silc_protocol_execute(protocol, server->timeout_queue, 0, 300000);
549         return;
550       }
551     }
552     break;
553   case 4:
554     {
555       /* 
556        * Finish protocol
557        */
558       if (ctx->responder == TRUE) {
559         /* This creates the key exchange material and sends our
560            public parts to the initiator inside Key Exchange 2 Payload. */
561         status = 
562           silc_ske_responder_finish(ctx->ske, 
563                                     server->public_key, server->private_key,
564                                     SILC_SKE_PK_TYPE_SILC,
565                                     silc_server_protocol_ke_send_packet,
566                                     context);
567
568         /* End the protocol on the next round */
569         protocol->state = SILC_PROTOCOL_STATE_END;
570       } else {
571         /* Finish the protocol. This verifies the Key Exchange 2 payload
572            sent by responder. The silc_server_protocol_ke_continue will
573            be called after the public key has been verified. */
574         status = silc_ske_initiator_finish(ctx->ske, ctx->packet->buffer, 
575                                            silc_server_protocol_ke_verify_key,
576                                            context,
577                                            silc_server_protocol_ke_continue, 
578                                            context);
579       }
580
581       /* Return now if the procedure is pending. */
582       if (status == SILC_SKE_STATUS_PENDING)
583         return;
584
585       if (status != SILC_SKE_STATUS_OK) {
586         SILC_LOG_WARNING(("Error (type %d) during Key Exchange protocol",
587                           status));
588         SILC_LOG_DEBUG(("Error (type %d) during Key Exchange protocol",
589                         status));
590
591         protocol->state = SILC_PROTOCOL_STATE_ERROR;
592         silc_protocol_execute(protocol, server->timeout_queue, 0, 300000);
593         return;
594       }
595     }
596     break;
597
598   case SILC_PROTOCOL_STATE_END:
599     {
600       /* 
601        * End protocol
602        */
603       SilcSKEKeyMaterial *keymat;
604       int key_len = silc_cipher_get_key_len(ctx->ske->prop->cipher);
605       int hash_len = ctx->ske->prop->hash->hash->hash_len;
606
607       /* Process the key material */
608       keymat = silc_calloc(1, sizeof(*keymat));
609       status = silc_ske_process_key_material(ctx->ske, 16, key_len, hash_len,
610                                              keymat);
611       if (status != SILC_SKE_STATUS_OK) {
612         protocol->state = SILC_PROTOCOL_STATE_ERROR;
613         silc_protocol_execute(protocol, server->timeout_queue, 0, 300000);
614         silc_ske_free_key_material(keymat);
615         return;
616       }
617       ctx->keymat = keymat;
618
619       /* Send Ok to the other end if we are responder. If we are initiator
620          we have sent this already. */
621       if (ctx->responder == TRUE)
622         silc_ske_end(ctx->ske, silc_server_protocol_ke_send_packet, context);
623
624       /* Unregister the timeout task since the protocol has ended. 
625          This was the timeout task to be executed if the protocol is
626          not completed fast enough. */
627       if (ctx->timeout_task)
628         silc_task_unregister(server->timeout_queue, ctx->timeout_task);
629
630       /* Call the final callback */
631       if (protocol->final_callback)
632         silc_protocol_execute_final(protocol, server->timeout_queue);
633       else
634         silc_protocol_free(protocol);
635     }
636     break;
637
638   case SILC_PROTOCOL_STATE_ERROR:
639     /*
640      * Error occured
641      */
642
643     /* Send abort notification */
644     silc_ske_abort(ctx->ske, ctx->ske->status, 
645                    silc_server_protocol_ke_send_packet,
646                    context);
647
648     /* Unregister the timeout task since the protocol has ended. 
649        This was the timeout task to be executed if the protocol is
650        not completed fast enough. */
651     if (ctx->timeout_task)
652       silc_task_unregister(server->timeout_queue, ctx->timeout_task);
653
654     /* On error the final callback is always called. */
655     if (protocol->final_callback)
656       silc_protocol_execute_final(protocol, server->timeout_queue);
657     else
658       silc_protocol_free(protocol);
659     break;
660
661   case SILC_PROTOCOL_STATE_FAILURE:
662     /*
663      * We have received failure from remote
664      */
665
666     /* Unregister the timeout task since the protocol has ended. 
667        This was the timeout task to be executed if the protocol is
668        not completed fast enough. */
669     if (ctx->timeout_task)
670       silc_task_unregister(server->timeout_queue, ctx->timeout_task);
671
672     /* On error the final callback is always called. */
673     if (protocol->final_callback)
674       silc_protocol_execute_final(protocol, server->timeout_queue);
675     else
676       silc_protocol_free(protocol);
677     break;
678
679   case SILC_PROTOCOL_STATE_UNKNOWN:
680     break;
681   }
682 }
683
684 /*
685  * Connection Authentication protocol functions
686  */
687
688 static int 
689 silc_server_password_authentication(SilcServer server, char *auth1, 
690                                     char *auth2)
691 {
692   if (!auth1 || !auth2)
693     return FALSE;
694
695   if (!memcmp(auth1, auth2, strlen(auth1)))
696     return TRUE;
697
698   return FALSE;
699 }
700
701 static int
702 silc_server_public_key_authentication(SilcServer server,
703                                       SilcPublicKey pub_key,
704                                       unsigned char *sign,
705                                       uint32 sign_len,
706                                       SilcSKE ske)
707 {
708   SilcPKCS pkcs;
709   int len;
710   SilcBuffer auth;
711
712   if (!pub_key || !sign)
713     return FALSE;
714
715   silc_pkcs_alloc(pub_key->name, &pkcs);
716   if (!silc_pkcs_public_key_set(pkcs, pub_key)) {
717     silc_pkcs_free(pkcs);
718     return FALSE;
719   }
720
721   /* Make the authentication data. Protocol says it is HASH plus
722      KE Start Payload. */
723   len = ske->hash_len + ske->start_payload_copy->len;
724   auth = silc_buffer_alloc(len);
725   silc_buffer_pull_tail(auth, len);
726   silc_buffer_format(auth,
727                      SILC_STR_UI_XNSTRING(ske->hash, ske->hash_len),
728                      SILC_STR_UI_XNSTRING(ske->start_payload_copy->data,
729                                           ske->start_payload_copy->len),
730                      SILC_STR_END);
731
732   /* Verify signature */
733   if (silc_pkcs_verify(pkcs, sign, sign_len, auth->data, auth->len)) {
734     silc_pkcs_free(pkcs);
735     silc_buffer_free(auth);
736     return TRUE;
737   }
738
739   silc_pkcs_free(pkcs);
740   silc_buffer_free(auth);
741   return FALSE;
742 }
743
744 static int
745 silc_server_get_public_key_auth(SilcServer server,
746                                 SilcPublicKey pub_key,
747                                 unsigned char *auth_data,
748                                 uint32 *auth_data_len,
749                                 SilcSKE ske)
750 {
751   int len;
752   SilcPKCS pkcs;
753   SilcBuffer auth;
754
755   if (!pub_key)
756     return FALSE;
757
758   silc_pkcs_alloc(pub_key->name, &pkcs);
759   if (!silc_pkcs_public_key_set(pkcs, pub_key)) {
760     silc_pkcs_free(pkcs);
761     return FALSE;
762   }
763
764   /* Make the authentication data. Protocol says it is HASH plus
765      KE Start Payload. */
766   len = ske->hash_len + ske->start_payload_copy->len;
767   auth = silc_buffer_alloc(len);
768   silc_buffer_pull_tail(auth, len);
769   silc_buffer_format(auth,
770                      SILC_STR_UI_XNSTRING(ske->hash, ske->hash_len),
771                      SILC_STR_UI_XNSTRING(ske->start_payload_copy->data,
772                                           ske->start_payload_copy->len),
773                      SILC_STR_END);
774
775   if (silc_pkcs_sign(pkcs, auth->data, auth->len, auth_data, auth_data_len)) {
776     silc_pkcs_free(pkcs);
777     silc_buffer_free(auth);
778     return TRUE;
779   }
780
781   silc_pkcs_free(pkcs);
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->timeout_queue, 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->timeout_queue, 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->timeout_queue, 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->timeout_queue, 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->timeout_queue, 
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->timeout_queue, 
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->timeout_queue, 
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->timeout_queue, 
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->timeout_queue, 
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->timeout_queue, 
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->timeout_queue, 
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->timeout_queue, 
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->timeout_queue, 
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->timeout_queue, 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, ctx->auth_data,
1103                                             sign, &auth_data_len,
1104                                             ctx->ske);
1105             auth_data = silc_calloc(auth_data_len, sizeof(*auth_data));
1106             memcpy(auth_data, sign, auth_data_len);
1107             break;
1108           }
1109         }
1110         
1111         payload_len = 4 + auth_data_len;
1112         packet = silc_buffer_alloc(payload_len);
1113         silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1114         silc_buffer_format(packet,
1115                            SILC_STR_UI_SHORT(payload_len),
1116                            SILC_STR_UI_SHORT(server->server_type 
1117                                               == SILC_SERVER ?
1118                                               SILC_SOCKET_TYPE_SERVER :
1119                                               SILC_SOCKET_TYPE_ROUTER),
1120                            SILC_STR_UI_XNSTRING(auth_data, auth_data_len),
1121                            SILC_STR_END);
1122         
1123         /* Send the packet to server */
1124         silc_server_packet_send(server, ctx->sock,
1125                                 SILC_PACKET_CONNECTION_AUTH, 0, 
1126                                 packet->data, packet->len, TRUE);
1127         
1128         if (auth_data) {
1129           memset(auth_data, 0, auth_data_len);
1130           silc_free(auth_data);
1131         }
1132         silc_buffer_free(packet);
1133         
1134         /* Next state is end of protocol */
1135         protocol->state = SILC_PROTOCOL_STATE_END;
1136       }
1137     }
1138     break;
1139
1140   case SILC_PROTOCOL_STATE_END:
1141     {
1142       /* 
1143        * End protocol
1144        */
1145       unsigned char ok[4];
1146
1147       SILC_PUT32_MSB(SILC_AUTH_OK, ok);
1148
1149       /* Authentication successful */
1150       silc_server_packet_send(server, ctx->sock, SILC_PACKET_SUCCESS,
1151                               0, ok, 4, TRUE);
1152
1153       /* Unregister the timeout task since the protocol has ended. 
1154          This was the timeout task to be executed if the protocol is
1155          not completed fast enough. */
1156       if (ctx->timeout_task)
1157         silc_task_unregister(server->timeout_queue, ctx->timeout_task);
1158
1159       /* Protocol has ended, call the final callback */
1160       if (protocol->final_callback)
1161         silc_protocol_execute_final(protocol, server->timeout_queue);
1162       else
1163         silc_protocol_free(protocol);
1164     }
1165     break;
1166   case SILC_PROTOCOL_STATE_ERROR:
1167     {
1168       /*
1169        * Error. Send notify to remote.
1170        */
1171       unsigned char error[4];
1172
1173       SILC_PUT32_MSB(SILC_AUTH_FAILED, error);
1174
1175       /* Authentication failed */
1176       silc_server_packet_send(server, ctx->sock, SILC_PACKET_FAILURE,
1177                               0, error, 4, TRUE);
1178
1179       /* Unregister the timeout task since the protocol has ended. 
1180          This was the timeout task to be executed if the protocol is
1181          not completed fast enough. */
1182       if (ctx->timeout_task)
1183         silc_task_unregister(server->timeout_queue, ctx->timeout_task);
1184
1185       /* On error the final callback is always called. */
1186       if (protocol->final_callback)
1187         silc_protocol_execute_final(protocol, server->timeout_queue);
1188       else
1189         silc_protocol_free(protocol);
1190     }
1191     break;
1192
1193   case SILC_PROTOCOL_STATE_FAILURE:
1194     /*
1195      * We have received failure from remote
1196      */
1197
1198     /* Unregister the timeout task since the protocol has ended. 
1199        This was the timeout task to be executed if the protocol is
1200        not completed fast enough. */
1201     if (ctx->timeout_task)
1202       silc_task_unregister(server->timeout_queue, ctx->timeout_task);
1203
1204     /* On error the final callback is always called. */
1205     if (protocol->final_callback)
1206       silc_protocol_execute_final(protocol, server->timeout_queue);
1207     else
1208       silc_protocol_free(protocol);
1209     break;
1210
1211   case SILC_PROTOCOL_STATE_UNKNOWN:
1212     break;
1213   }
1214 }
1215
1216 /*
1217  * Re-key protocol routines
1218  */
1219
1220 /* Actually takes the new keys into use. */
1221
1222 static void 
1223 silc_server_protocol_rekey_validate(SilcServer server,
1224                                     SilcServerRekeyInternalContext *ctx,
1225                                     SilcIDListData idata,
1226                                     SilcSKEKeyMaterial *keymat,
1227                                     bool send)
1228 {
1229   if (ctx->responder == TRUE) {
1230     if (send) {
1231       silc_cipher_set_key(idata->send_key, keymat->receive_enc_key, 
1232                           keymat->enc_key_len);
1233       silc_cipher_set_iv(idata->send_key, keymat->receive_iv);
1234     } else {
1235       silc_cipher_set_key(idata->receive_key, keymat->send_enc_key, 
1236                           keymat->enc_key_len);
1237       silc_cipher_set_iv(idata->receive_key, keymat->send_iv);
1238     }
1239   } else {
1240     if (send) {
1241       silc_cipher_set_key(idata->send_key, keymat->send_enc_key, 
1242                           keymat->enc_key_len);
1243       silc_cipher_set_iv(idata->send_key, keymat->send_iv);
1244     } else {
1245       silc_cipher_set_key(idata->receive_key, keymat->receive_enc_key, 
1246                           keymat->enc_key_len);
1247       silc_cipher_set_iv(idata->receive_key, keymat->receive_iv);
1248     }
1249   }
1250
1251   if (send) {
1252     silc_hmac_alloc(idata->hmac_send->hmac->name, NULL, &idata->hmac_send);
1253     silc_hmac_set_key(idata->hmac_send, keymat->hmac_key, 
1254                       keymat->hmac_key_len);
1255   } else {
1256     silc_hmac_free(idata->hmac_receive);
1257     idata->hmac_receive = idata->hmac_send;
1258   }
1259
1260   /* Save the current sending encryption key */
1261   if (!send) {
1262     memset(idata->rekey->send_enc_key, 0, idata->rekey->enc_key_len);
1263     silc_free(idata->rekey->send_enc_key);
1264     idata->rekey->send_enc_key = 
1265       silc_calloc(keymat->enc_key_len / 8,
1266                   sizeof(*idata->rekey->send_enc_key));
1267     memcpy(idata->rekey->send_enc_key, keymat->send_enc_key, 
1268            keymat->enc_key_len / 8);
1269     idata->rekey->enc_key_len = keymat->enc_key_len / 8;
1270   }
1271 }
1272
1273 /* This function actually re-generates (when not using PFS) the keys and
1274    takes them into use. */
1275
1276 void silc_server_protocol_rekey_generate(SilcServer server,
1277                                          SilcServerRekeyInternalContext *ctx,
1278                                          bool send)
1279 {
1280   SilcIDListData idata = (SilcIDListData)ctx->sock->user_data;
1281   SilcSKEKeyMaterial *keymat;
1282   uint32 key_len = silc_cipher_get_key_len(idata->send_key);
1283   uint32 hash_len = idata->hash->hash->hash_len;
1284
1285   SILC_LOG_DEBUG(("Generating new %s session keys (no PFS)",
1286                   send ? "sending" : "receiving"));
1287
1288   /* Generate the new key */
1289   keymat = silc_calloc(1, sizeof(*keymat));
1290   silc_ske_process_key_material_data(idata->rekey->send_enc_key,
1291                                      idata->rekey->enc_key_len,
1292                                      16, key_len, hash_len, 
1293                                      idata->hash, keymat);
1294
1295   /* Set the keys into use */
1296   silc_server_protocol_rekey_validate(server, ctx, idata, keymat, send);
1297
1298   silc_ske_free_key_material(keymat);
1299 }
1300
1301 /* This function actually re-generates (with PFS) the keys and
1302    takes them into use. */
1303
1304 void 
1305 silc_server_protocol_rekey_generate_pfs(SilcServer server,
1306                                         SilcServerRekeyInternalContext *ctx,
1307                                         bool send)
1308 {
1309   SilcIDListData idata = (SilcIDListData)ctx->sock->user_data;
1310   SilcSKEKeyMaterial *keymat;
1311   uint32 key_len = silc_cipher_get_key_len(idata->send_key);
1312   uint32 hash_len = idata->hash->hash->hash_len;
1313   unsigned char *tmpbuf;
1314   uint32 klen;
1315
1316   SILC_LOG_DEBUG(("Generating new %s session keys (with PFS)",
1317                   send ? "sending" : "receiving"));
1318
1319   /* Encode KEY to binary data */
1320   tmpbuf = silc_mp_mp2bin(ctx->ske->KEY, 0, &klen);
1321
1322   /* Generate the new key */
1323   keymat = silc_calloc(1, sizeof(*keymat));
1324   silc_ske_process_key_material_data(tmpbuf, klen, 16, key_len, hash_len, 
1325                                      idata->hash, keymat);
1326
1327   /* Set the keys into use */
1328   silc_server_protocol_rekey_validate(server, ctx, idata, keymat, send);
1329
1330   memset(tmpbuf, 0, klen);
1331   silc_free(tmpbuf);
1332   silc_ske_free_key_material(keymat);
1333 }
1334
1335 /* Packet sending callback. This function is provided as packet sending
1336    routine to the Key Exchange functions. */
1337
1338 static void 
1339 silc_server_protocol_rekey_send_packet(SilcSKE ske,
1340                                        SilcBuffer packet,
1341                                        SilcPacketType type,
1342                                        void *context)
1343 {
1344   SilcProtocol protocol = (SilcProtocol)context;
1345   SilcServerRekeyInternalContext *ctx = 
1346     (SilcServerRekeyInternalContext *)protocol->context;
1347   SilcServer server = (SilcServer)ctx->server;
1348
1349   /* Send the packet immediately */
1350   silc_server_packet_send(server, ctx->sock,
1351                           type, 0, packet->data, packet->len, FALSE);
1352 }
1353
1354 /* Performs re-key as defined in the SILC protocol specification. */
1355
1356 SILC_TASK_CALLBACK(silc_server_protocol_rekey)
1357 {
1358   SilcProtocol protocol = (SilcProtocol)context;
1359   SilcServerRekeyInternalContext *ctx = 
1360     (SilcServerRekeyInternalContext *)protocol->context;
1361   SilcServer server = (SilcServer)ctx->server;
1362   SilcIDListData idata = (SilcIDListData)ctx->sock->user_data;
1363   SilcSKEStatus status;
1364
1365   SILC_LOG_DEBUG(("Start"));
1366
1367   if (protocol->state == SILC_PROTOCOL_STATE_UNKNOWN)
1368     protocol->state = SILC_PROTOCOL_STATE_START;
1369
1370   SILC_LOG_DEBUG(("State=%d", protocol->state));
1371
1372   switch(protocol->state) {
1373   case SILC_PROTOCOL_STATE_START:
1374     {
1375       /* 
1376        * Start protocol.
1377        */
1378
1379       if (ctx->responder == TRUE) {
1380         /*
1381          * We are receiving party
1382          */
1383
1384         if (ctx->pfs == TRUE) {
1385           /* 
1386            * Use Perfect Forward Secrecy, ie. negotiate the key material
1387            * using the SKE protocol.
1388            */
1389
1390           if (ctx->packet->type != SILC_PACKET_KEY_EXCHANGE_1) {
1391             /* Error in protocol */
1392             protocol->state = SILC_PROTOCOL_STATE_ERROR;
1393             silc_protocol_execute(protocol, server->timeout_queue, 0, 300000);
1394           }
1395
1396           ctx->ske = silc_ske_alloc();
1397           ctx->ske->rng = server->rng;
1398           ctx->ske->prop = silc_calloc(1, sizeof(*ctx->ske->prop));
1399           silc_ske_get_group_by_number(idata->rekey->ske_group,
1400                                        &ctx->ske->prop->group);
1401
1402           status = silc_ske_responder_phase_2(ctx->ske, ctx->packet->buffer,
1403                                               NULL, NULL, NULL, NULL);
1404           if (status != SILC_SKE_STATUS_OK) {
1405             SILC_LOG_WARNING(("Error (type %d) during Re-key (PFS)",
1406                               status));
1407             
1408             protocol->state = SILC_PROTOCOL_STATE_ERROR;
1409             silc_protocol_execute(protocol, server->timeout_queue, 0, 300000);
1410             return;
1411           }
1412
1413           /* Advance the protocol state */
1414           protocol->state++;
1415           silc_protocol_execute(protocol, server->timeout_queue, 0, 0);
1416         } else {
1417           /*
1418            * Do normal and simple re-key.
1419            */
1420
1421           /* Send the REKEY_DONE to indicate we will take new keys into use */
1422           silc_server_packet_send(server, ctx->sock, SILC_PACKET_REKEY_DONE,
1423                                   0, NULL, 0, FALSE);
1424
1425           /* After we send REKEY_DONE we must set the sending encryption
1426              key to the new key since all packets after this packet must
1427              encrypted with the new key. */
1428           silc_server_protocol_rekey_generate(server, ctx, TRUE);
1429
1430           /* The protocol ends in next stage. */
1431           protocol->state = SILC_PROTOCOL_STATE_END;
1432         }
1433       
1434       } else {
1435         /*
1436          * We are the initiator of this protocol
1437          */
1438
1439         /* Start the re-key by sending the REKEY packet */
1440         silc_server_packet_send(server, ctx->sock, SILC_PACKET_REKEY,
1441                                 0, NULL, 0, FALSE);
1442
1443         if (ctx->pfs == TRUE) {
1444           /* 
1445            * Use Perfect Forward Secrecy, ie. negotiate the key material
1446            * using the SKE protocol.
1447            */
1448           ctx->ske = silc_ske_alloc();
1449           ctx->ske->rng = server->rng;
1450           ctx->ske->prop = silc_calloc(1, sizeof(*ctx->ske->prop));
1451           silc_ske_get_group_by_number(idata->rekey->ske_group,
1452                                        &ctx->ske->prop->group);
1453
1454           status = 
1455             silc_ske_initiator_phase_2(ctx->ske, NULL, NULL,
1456                                        silc_server_protocol_rekey_send_packet,
1457                                        context);
1458
1459           if (status != SILC_SKE_STATUS_OK) {
1460             SILC_LOG_WARNING(("Error (type %d) during Re-key (PFS)",
1461                               status));
1462             
1463             protocol->state = SILC_PROTOCOL_STATE_ERROR;
1464             silc_protocol_execute(protocol, server->timeout_queue, 0, 300000);
1465             return;
1466           }
1467
1468           /* Advance the protocol state */
1469           protocol->state++;
1470         } else {
1471           /*
1472            * Do normal and simple re-key.
1473            */
1474
1475           /* Send the REKEY_DONE to indicate we will take new keys into use 
1476              now. */ 
1477           silc_server_packet_send(server, ctx->sock, SILC_PACKET_REKEY_DONE,
1478                                   0, NULL, 0, FALSE);
1479
1480           /* After we send REKEY_DONE we must set the sending encryption
1481              key to the new key since all packets after this packet must
1482              encrypted with the new key. */
1483           silc_server_protocol_rekey_generate(server, ctx, TRUE);
1484
1485           /* The protocol ends in next stage. */
1486           protocol->state = SILC_PROTOCOL_STATE_END;
1487         }
1488       }
1489     }
1490     break;
1491
1492   case 2:
1493     /*
1494      * Second state, used only when oding re-key with PFS.
1495      */
1496     if (ctx->responder == TRUE) {
1497       if (ctx->pfs == TRUE) {
1498         /*
1499          * Send our KE packe to the initiator now that we've processed
1500          * the initiator's KE packet.
1501          */
1502         status = 
1503           silc_ske_responder_finish(ctx->ske, NULL, NULL, 
1504                                     SILC_SKE_PK_TYPE_SILC,
1505                                     silc_server_protocol_rekey_send_packet,
1506                                     context);
1507
1508           if (status != SILC_SKE_STATUS_OK) {
1509             SILC_LOG_WARNING(("Error (type %d) during Re-key (PFS)",
1510                               status));
1511             
1512             protocol->state = SILC_PROTOCOL_STATE_ERROR;
1513             silc_protocol_execute(protocol, server->timeout_queue, 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->timeout_queue, 0, 300000);
1527         }
1528         
1529         status = silc_ske_initiator_finish(ctx->ske, ctx->packet->buffer,
1530                                            NULL, NULL, NULL, NULL);
1531         if (status != SILC_SKE_STATUS_OK) {
1532           SILC_LOG_WARNING(("Error (type %d) during Re-key (PFS)",
1533                             status));
1534           
1535           protocol->state = SILC_PROTOCOL_STATE_ERROR;
1536           silc_protocol_execute(protocol, server->timeout_queue, 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->timeout_queue, 0, 0);
1565     }
1566
1567     /* We received the REKEY_DONE packet and all packets after this is
1568        encrypted with the new key so set the decryption key to the new key */
1569     silc_server_protocol_rekey_generate(server, ctx, FALSE);
1570
1571     /* Protocol has ended, call the final callback */
1572     if (protocol->final_callback)
1573       silc_protocol_execute_final(protocol, server->timeout_queue);
1574     else
1575       silc_protocol_free(protocol);
1576     break;
1577
1578   case SILC_PROTOCOL_STATE_ERROR:
1579     /*
1580      * Error occured
1581      */
1582
1583     if (ctx->pfs == TRUE) {
1584       /* Send abort notification */
1585       silc_ske_abort(ctx->ske, ctx->ske->status, 
1586                      silc_server_protocol_ke_send_packet,
1587                      context);
1588     }
1589
1590     /* On error the final callback is always called. */
1591     if (protocol->final_callback)
1592       silc_protocol_execute_final(protocol, server->timeout_queue);
1593     else
1594       silc_protocol_free(protocol);
1595     break;
1596
1597   case SILC_PROTOCOL_STATE_FAILURE:
1598     /*
1599      * We have received failure from remote
1600      */
1601
1602     /* On error the final callback is always called. */
1603     if (protocol->final_callback)
1604       silc_protocol_execute_final(protocol, server->timeout_queue);
1605     else
1606       silc_protocol_free(protocol);
1607     break;
1608
1609   case SILC_PROTOCOL_STATE_UNKNOWN:
1610     break;
1611   }
1612
1613 }
1614
1615 /* Registers protocols used in server. */
1616
1617 void silc_server_protocols_register(void)
1618 {
1619   silc_protocol_register(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1620                          silc_server_protocol_connection_auth);
1621   silc_protocol_register(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1622                          silc_server_protocol_key_exchange);
1623   silc_protocol_register(SILC_PROTOCOL_SERVER_REKEY,
1624                          silc_server_protocol_rekey);
1625 }
1626
1627 /* Unregisters protocols */
1628
1629 void silc_server_protocols_unregister(void)
1630 {
1631   silc_protocol_unregister(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1632                            silc_server_protocol_connection_auth);
1633   silc_protocol_unregister(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1634                            silc_server_protocol_key_exchange);
1635   silc_protocol_unregister(SILC_PROTOCOL_SERVER_REKEY,
1636                            silc_server_protocol_rekey);
1637 }