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