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