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