Check for NULL ske when aborting in error case.
[silc.git] / apps / silcd / protocol.c
1 /*
2
3   protocol.c
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 1997 - 2006 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     if (ctx->ske)
697       silc_ske_abort(ctx->ske, ctx->ske->status);
698
699     /* Unregister the timeout task since the protocol has ended.
700        This was the timeout task to be executed if the protocol is
701        not completed fast enough. */
702     if (ctx->timeout_task)
703       silc_schedule_task_del(server->schedule, ctx->timeout_task);
704
705     /* Assure that after calling final callback there cannot be pending
706        executions for this protocol anymore. This just unregisters any
707        timeout callbacks for this protocol. */
708     silc_protocol_cancel(protocol, server->schedule);
709
710     /* On error the final callback is always called. */
711     if (protocol->final_callback)
712       silc_protocol_execute_final(protocol, server->schedule);
713     else
714       silc_protocol_free(protocol);
715     break;
716
717   case SILC_PROTOCOL_STATE_FAILURE:
718     /*
719      * We have received failure from remote
720      */
721
722     /* Unregister the timeout task since the protocol has ended.
723        This was the timeout task to be executed if the protocol is
724        not completed fast enough. */
725     if (ctx->timeout_task)
726       silc_schedule_task_del(server->schedule, ctx->timeout_task);
727
728     /* Assure that after calling final callback there cannot be pending
729        executions for this protocol anymore. This just unregisters any
730        timeout callbacks for this protocol. */
731     silc_protocol_cancel(protocol, server->schedule);
732
733     /* On error the final callback is always called. */
734     if (protocol->final_callback)
735       silc_protocol_execute_final(protocol, server->schedule);
736     else
737       silc_protocol_free(protocol);
738     break;
739
740   case SILC_PROTOCOL_STATE_UNKNOWN:
741     break;
742   }
743 }
744
745 /*
746  * Connection Authentication protocol functions
747  */
748
749 static int
750 silc_server_password_authentication(SilcServer server, char *local_auth,
751                                     char *remote_auth)
752 {
753   if (!remote_auth || !local_auth || strlen(local_auth) != strlen(remote_auth))
754     return FALSE;
755
756   if (!memcmp(remote_auth, local_auth, strlen(local_auth)))
757     return TRUE;
758
759   return FALSE;
760 }
761
762 static int
763 silc_server_public_key_authentication(SilcServer server,
764                                       SilcPublicKey pub_key,
765                                       unsigned char *sign,
766                                       SilcUInt32 sign_len,
767                                       SilcSKE ske)
768 {
769   SilcPKCS pkcs;
770   int len;
771   SilcBuffer auth;
772
773   if (!pub_key || !sign)
774     return FALSE;
775
776   silc_pkcs_alloc(pub_key->name, &pkcs);
777   if (!silc_pkcs_public_key_set(pkcs, pub_key)) {
778     silc_pkcs_free(pkcs);
779     return FALSE;
780   }
781
782   /* Make the authentication data. Protocol says it is HASH plus
783      KE Start Payload. */
784   len = ske->hash_len + ske->start_payload_copy->len;
785   auth = silc_buffer_alloc(len);
786   silc_buffer_pull_tail(auth, len);
787   silc_buffer_format(auth,
788                      SILC_STR_UI_XNSTRING(ske->hash, ske->hash_len),
789                      SILC_STR_UI_XNSTRING(ske->start_payload_copy->data,
790                                           ske->start_payload_copy->len),
791                      SILC_STR_END);
792
793   /* Verify signature */
794   if (silc_pkcs_verify_with_hash(pkcs, ske->prop->hash, sign, sign_len,
795                                  auth->data, auth->len)) {
796     silc_pkcs_free(pkcs);
797     silc_buffer_free(auth);
798     return TRUE;
799   }
800
801   silc_pkcs_free(pkcs);
802   silc_buffer_free(auth);
803   return FALSE;
804 }
805
806 static int
807 silc_server_get_public_key_auth(SilcServer server,
808                                 unsigned char **auth_data,
809                                 SilcUInt32 *auth_data_len,
810                                 SilcSKE ske)
811 {
812   int len;
813   SilcPKCS pkcs;
814   SilcBuffer auth;
815
816   pkcs = server->pkcs;
817
818   /* Make the authentication data. Protocol says it is HASH plus
819      KE Start Payload. */
820   len = ske->hash_len + ske->start_payload_copy->len;
821   auth = silc_buffer_alloc(len);
822   silc_buffer_pull_tail(auth, len);
823   silc_buffer_format(auth,
824                      SILC_STR_UI_XNSTRING(ske->hash, ske->hash_len),
825                      SILC_STR_UI_XNSTRING(ske->start_payload_copy->data,
826                                           ske->start_payload_copy->len),
827                      SILC_STR_END);
828
829   *auth_data = silc_calloc((silc_pkcs_get_key_len(pkcs) / 8) + 1,
830                            sizeof(**auth_data));
831   if (silc_pkcs_sign_with_hash(pkcs, ske->prop->hash, auth->data,
832                                auth->len, *auth_data, auth_data_len)) {
833     silc_buffer_free(auth);
834     return TRUE;
835   }
836
837   SILC_LOG_ERROR(("Error computing signature"));
838
839   silc_free(*auth_data);
840   silc_buffer_free(auth);
841   return FALSE;
842 }
843
844 /* Function that actually performs the authentication to the remote. This
845    supports both passphrase and public key authentication. */
846
847 static bool
848 silc_server_get_authentication(SilcServerConnAuthInternalContext *ctx,
849                                char *local_passphrase,
850                                SilcHashTable local_publickeys,
851                                unsigned char *remote_auth,
852                                SilcUInt32 remote_auth_len)
853 {
854   SilcServer server = (SilcServer)ctx->server;
855   SilcSKE ske = ctx->ske;
856   bool result = FALSE;
857
858   /* If we don't have authentication data set at all we do not require
859      authentication at all */
860   if (!local_passphrase && (!local_publickeys ||
861                             !silc_hash_table_count(local_publickeys))) {
862     SILC_LOG_DEBUG(("No authentication required"));
863     return TRUE;
864   }
865
866   /* If both passphrase and public key is provided then we'll try both of
867      them and see which one of them authenticates.  If only one of them is
868      set, then try only that. */
869
870   /* Try first passphrase (as it is faster to check) */
871   if (local_passphrase) {
872     SILC_LOG_DEBUG(("Password authentication"));
873     result = silc_server_password_authentication(server, local_passphrase,
874                                                  remote_auth);
875   }
876
877   /* Try public key authenetication */
878   if (!result && local_publickeys) {
879     SilcPublicKey cached_key;
880     SilcPublicKey remote_key =
881       ((SilcIDListData)ctx->sock->user_data)->public_key;
882
883     SILC_LOG_DEBUG(("Public key authentication"));
884
885     /* Find the public key to be used in authentication */
886     cached_key = silc_server_find_public_key(server, local_publickeys,
887                                              remote_key);
888     if (!cached_key)
889       return FALSE;
890
891     result = silc_server_public_key_authentication(server, cached_key,
892                                                    remote_auth,
893                                                    remote_auth_len, ske);
894   }
895
896   SILC_LOG_DEBUG(("Authentication %s", result ? "successful" : "failed"));
897
898   return result;
899 }
900
901 /* Performs connection authentication protocol. If responder, we
902    authenticate the remote data received. If initiator, we will send
903    authentication data to the remote end. */
904
905 SILC_TASK_CALLBACK(silc_server_protocol_connection_auth)
906 {
907   SilcProtocol protocol = (SilcProtocol)context;
908   SilcServerConnAuthInternalContext *ctx =
909     (SilcServerConnAuthInternalContext *)protocol->context;
910   SilcServer server = (SilcServer)ctx->server;
911
912   if (protocol->state == SILC_PROTOCOL_STATE_UNKNOWN)
913     protocol->state = SILC_PROTOCOL_STATE_START;
914
915   SILC_LOG_DEBUG(("Current protocol state %d", protocol->state));
916
917   switch(protocol->state) {
918   case SILC_PROTOCOL_STATE_START:
919     {
920       /*
921        * Start protocol.
922        */
923
924       if (ctx->responder == TRUE) {
925         /*
926          * We are receiving party
927          */
928         int ret;
929         SilcUInt16 payload_len;
930         SilcUInt16 conn_type;
931         unsigned char *auth_data = NULL;
932
933         SILC_LOG_INFO(("Performing authentication protocol for %s (%s)",
934                        ctx->sock->hostname, ctx->sock->ip));
935
936         if (!ctx->packet) {
937           SILC_LOG_ERROR(("Bad authentication protocol request"));
938           protocol->state = SILC_PROTOCOL_STATE_ERROR;
939           silc_protocol_execute(protocol, server->schedule, 0, 300000);
940           return;
941         }
942
943         /* Parse the received authentication data packet. The received
944            payload is Connection Auth Payload. */
945         ret = silc_buffer_unformat(ctx->packet->buffer,
946                                    SILC_STR_UI_SHORT(&payload_len),
947                                    SILC_STR_UI_SHORT(&conn_type),
948                                    SILC_STR_END);
949         if (ret == -1) {
950           SILC_LOG_ERROR(("Bad payload in authentication packet"));
951           protocol->state = SILC_PROTOCOL_STATE_ERROR;
952           silc_protocol_execute(protocol, server->schedule, 0, 300000);
953           return;
954         }
955
956         if (payload_len != ctx->packet->buffer->len) {
957           SILC_LOG_ERROR(("Bad payload length in authentication packet"));
958           protocol->state = SILC_PROTOCOL_STATE_ERROR;
959           silc_protocol_execute(protocol, server->schedule, 0, 300000);
960           return;
961         }
962
963         payload_len -= 4;
964
965         if (conn_type < SILC_SOCKET_TYPE_CLIENT ||
966             conn_type > SILC_SOCKET_TYPE_ROUTER) {
967           SILC_LOG_ERROR(("Bad connection type (%d) in authentication packet",
968                           conn_type));
969           protocol->state = SILC_PROTOCOL_STATE_ERROR;
970           silc_protocol_execute(protocol, server->schedule, 0, 300000);
971           return;
972         }
973
974         if (payload_len > 0) {
975           /* Get authentication data */
976           silc_buffer_pull(ctx->packet->buffer, 4);
977           ret = silc_buffer_unformat(ctx->packet->buffer,
978                                      SILC_STR_UI_XNSTRING_ALLOC(&auth_data,
979                                                                 payload_len),
980                                      SILC_STR_END);
981           if (ret == -1) {
982             SILC_LOG_DEBUG(("Bad payload in authentication payload"));
983             protocol->state = SILC_PROTOCOL_STATE_ERROR;
984             silc_protocol_execute(protocol, server->schedule, 0, 300000);
985             return;
986           }
987         }
988
989         /*
990          * Check the remote connection type and make sure that we have
991          * configured this connection. If we haven't allowed this connection
992          * the authentication must be failed.
993          */
994
995         SILC_LOG_DEBUG(("Remote connection type %d", conn_type));
996
997         /* Remote end is client */
998         if (conn_type == SILC_SOCKET_TYPE_CLIENT) {
999           SilcServerConfigClient *client = ctx->cconfig.ref_ptr;
1000
1001           if (client) {
1002             ret = silc_server_get_authentication(ctx, client->passphrase,
1003                                                  client->publickeys,
1004                                                  auth_data, payload_len);
1005             if (!ret) {
1006               /* Authentication failed */
1007               SILC_LOG_ERROR(("Authentication failed"));
1008               silc_free(auth_data);
1009               protocol->state = SILC_PROTOCOL_STATE_ERROR;
1010               silc_protocol_execute(protocol, server->schedule, 0, 300000);
1011               return;
1012             }
1013           } else {
1014             SILC_LOG_ERROR(("Remote client connection not configured"));
1015             SILC_LOG_ERROR(("Authentication failed"));
1016             silc_free(auth_data);
1017             protocol->state = SILC_PROTOCOL_STATE_ERROR;
1018             silc_protocol_execute(protocol, server->schedule,
1019                                   0, 300000);
1020             return;
1021           }
1022         }
1023
1024         /* Remote end is server */
1025         if (conn_type == SILC_SOCKET_TYPE_SERVER) {
1026           SilcServerConfigServer *serv = ctx->sconfig.ref_ptr;
1027
1028           if (serv) {
1029             ret = silc_server_get_authentication(ctx, serv->passphrase,
1030                                                  serv->publickeys,
1031                                                  auth_data, payload_len);
1032             if (!ret) {
1033               /* Authentication failed */
1034               SILC_LOG_ERROR(("Authentication failed"));
1035               silc_free(auth_data);
1036               protocol->state = SILC_PROTOCOL_STATE_ERROR;
1037               silc_protocol_execute(protocol, server->schedule, 0, 300000);
1038               return;
1039             }
1040           } else {
1041             SILC_LOG_ERROR(("Remote server connection not configured"));
1042             SILC_LOG_ERROR(("Authentication failed"));
1043             protocol->state = SILC_PROTOCOL_STATE_ERROR;
1044             silc_protocol_execute(protocol, server->schedule,
1045                                   0, 300000);
1046             silc_free(auth_data);
1047             return;
1048           }
1049         }
1050
1051         /* Remote end is router */
1052         if (conn_type == SILC_SOCKET_TYPE_ROUTER) {
1053           SilcServerConfigRouter *serv = ctx->rconfig.ref_ptr;
1054
1055           if (serv) {
1056             ret = silc_server_get_authentication(ctx, serv->passphrase,
1057                                                  serv->publickeys,
1058                                                  auth_data, payload_len);
1059             if (!ret) {
1060               /* Authentication failed */
1061               SILC_LOG_ERROR(("Authentication failed"));
1062               silc_free(auth_data);
1063               protocol->state = SILC_PROTOCOL_STATE_ERROR;
1064               silc_protocol_execute(protocol, server->schedule, 0, 300000);
1065               return;
1066             }
1067           } else {
1068             SILC_LOG_ERROR(("Remote router connection not configured"));
1069             SILC_LOG_ERROR(("Authentication failed"));
1070             silc_free(auth_data);
1071             protocol->state = SILC_PROTOCOL_STATE_ERROR;
1072             silc_protocol_execute(protocol, server->schedule,
1073                                   0, 300000);
1074             return;
1075           }
1076         }
1077
1078         silc_free(auth_data);
1079
1080         /* Save connection type. This is later used to create the
1081            ID for the connection. */
1082         ctx->conn_type = conn_type;
1083
1084         /* Advance protocol state. */
1085         protocol->state = SILC_PROTOCOL_STATE_END;
1086         silc_protocol_execute(protocol, server->schedule, 0, 0);
1087
1088       } else {
1089         /*
1090          * We are initiator. We are authenticating ourselves to a
1091          * remote server. We will send the authentication data to the
1092          * other end for verify.
1093          */
1094         SilcBuffer packet;
1095         int payload_len = 0;
1096         unsigned char *auth_data = NULL;
1097         SilcUInt32 auth_data_len = 0;
1098
1099         switch(ctx->auth_meth) {
1100         case SILC_AUTH_NONE:
1101           /* No authentication required */
1102           break;
1103
1104         case SILC_AUTH_PASSWORD:
1105           /* Password authentication */
1106           if (ctx->auth_data && ctx->auth_data_len) {
1107             auth_data = strdup(ctx->auth_data);
1108             auth_data_len = ctx->auth_data_len;
1109             break;
1110           }
1111           break;
1112
1113         case SILC_AUTH_PUBLIC_KEY:
1114           {
1115             /* Public key authentication */
1116             silc_server_get_public_key_auth(server, &auth_data, &auth_data_len,
1117                                             ctx->ske);
1118             break;
1119           }
1120         }
1121
1122         payload_len = 4 + auth_data_len;
1123         packet = silc_buffer_alloc(payload_len);
1124         silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1125         silc_buffer_format(packet,
1126                            SILC_STR_UI_SHORT(payload_len),
1127                            SILC_STR_UI_SHORT(server->server_type
1128                                               == SILC_SERVER ?
1129                                               SILC_SOCKET_TYPE_SERVER :
1130                                               SILC_SOCKET_TYPE_ROUTER),
1131                            SILC_STR_UI_XNSTRING(auth_data, auth_data_len),
1132                            SILC_STR_END);
1133
1134         /* Send the packet to server */
1135         silc_server_packet_send(server, ctx->sock,
1136                                 SILC_PACKET_CONNECTION_AUTH, 0,
1137                                 packet->data, packet->len, TRUE);
1138
1139         if (auth_data) {
1140           memset(auth_data, 0, auth_data_len);
1141           silc_free(auth_data);
1142         }
1143         silc_buffer_free(packet);
1144
1145         /* Next state is end of protocol */
1146         protocol->state = SILC_PROTOCOL_STATE_END;
1147       }
1148     }
1149     break;
1150
1151   case SILC_PROTOCOL_STATE_END:
1152     {
1153       /*
1154        * End protocol
1155        */
1156       unsigned char ok[4];
1157
1158       SILC_PUT32_MSB(SILC_AUTH_OK, ok);
1159
1160       /* Authentication successful */
1161       silc_server_packet_send(server, ctx->sock, SILC_PACKET_SUCCESS,
1162                               0, ok, 4, TRUE);
1163
1164       /* Unregister the timeout task since the protocol has ended.
1165          This was the timeout task to be executed if the protocol is
1166          not completed fast enough. */
1167       if (ctx->timeout_task)
1168         silc_schedule_task_del(server->schedule, ctx->timeout_task);
1169
1170       /* Assure that after calling final callback there cannot be pending
1171          executions for this protocol anymore. This just unregisters any
1172          timeout callbacks for this protocol. */
1173       silc_protocol_cancel(protocol, server->schedule);
1174
1175       /* Protocol has ended, call the final callback */
1176       if (protocol->final_callback)
1177         silc_protocol_execute_final(protocol, server->schedule);
1178       else
1179         silc_protocol_free(protocol);
1180     }
1181     break;
1182   case SILC_PROTOCOL_STATE_ERROR:
1183     {
1184       /*
1185        * Error. Send notify to remote.
1186        */
1187       unsigned char error[4];
1188
1189       /* Authentication failed */
1190       SILC_PUT32_MSB(SILC_AUTH_FAILED, error);
1191       silc_server_packet_send(server, ctx->sock, SILC_PACKET_FAILURE,
1192                               0, error, 4, TRUE);
1193
1194       /* Unregister the timeout task since the protocol has ended.
1195          This was the timeout task to be executed if the protocol is
1196          not completed fast enough. */
1197       if (ctx->timeout_task)
1198         silc_schedule_task_del(server->schedule, ctx->timeout_task);
1199
1200       /* Assure that after calling final callback there cannot be pending
1201          executions for this protocol anymore. This just unregisters any
1202          timeout callbacks for this protocol. */
1203       silc_protocol_cancel(protocol, server->schedule);
1204
1205       /* On error the final callback is always called. */
1206       if (protocol->final_callback)
1207         silc_protocol_execute_final(protocol, server->schedule);
1208       else
1209         silc_protocol_free(protocol);
1210     }
1211     break;
1212
1213   case SILC_PROTOCOL_STATE_FAILURE:
1214     /*
1215      * We have received failure from remote
1216      */
1217
1218     SILC_LOG_ERROR(("Received Authentication Failure"));
1219
1220     /* Unregister the timeout task since the protocol has ended.
1221        This was the timeout task to be executed if the protocol is
1222        not completed fast enough. */
1223     if (ctx->timeout_task)
1224       silc_schedule_task_del(server->schedule, ctx->timeout_task);
1225
1226     /* Assure that after calling final callback there cannot be pending
1227        executions for this protocol anymore. This just unregisters any
1228        timeout callbacks for this protocol. */
1229     silc_protocol_cancel(protocol, server->schedule);
1230
1231     /* On error the final callback is always called. */
1232     if (protocol->final_callback)
1233       silc_protocol_execute_final(protocol, server->schedule);
1234     else
1235       silc_protocol_free(protocol);
1236     break;
1237
1238   case SILC_PROTOCOL_STATE_UNKNOWN:
1239     break;
1240   }
1241 }
1242
1243 /*
1244  * Re-key protocol routines
1245  */
1246
1247 /* Actually takes the new keys into use. */
1248
1249 static void
1250 silc_server_protocol_rekey_validate(SilcServer server,
1251                                     SilcServerRekeyInternalContext *ctx,
1252                                     SilcIDListData idata,
1253                                     SilcSKEKeyMaterial *keymat,
1254                                     bool send)
1255 {
1256   if (ctx->responder == TRUE) {
1257     if (send) {
1258       silc_cipher_set_key(idata->send_key, keymat->receive_enc_key,
1259                           keymat->enc_key_len);
1260       silc_cipher_set_iv(idata->send_key, keymat->receive_iv);
1261       silc_hmac_set_key(idata->hmac_send, keymat->receive_hmac_key,
1262                         keymat->hmac_key_len);
1263     } else {
1264       silc_cipher_set_key(idata->receive_key, keymat->send_enc_key,
1265                           keymat->enc_key_len);
1266       silc_cipher_set_iv(idata->receive_key, keymat->send_iv);
1267       silc_hmac_set_key(idata->hmac_receive, keymat->send_hmac_key,
1268                         keymat->hmac_key_len);
1269     }
1270   } else {
1271     if (send) {
1272       silc_cipher_set_key(idata->send_key, keymat->send_enc_key,
1273                           keymat->enc_key_len);
1274       silc_cipher_set_iv(idata->send_key, keymat->send_iv);
1275       silc_hmac_set_key(idata->hmac_send, keymat->send_hmac_key,
1276                         keymat->hmac_key_len);
1277     } else {
1278       silc_cipher_set_key(idata->receive_key, keymat->receive_enc_key,
1279                           keymat->enc_key_len);
1280       silc_cipher_set_iv(idata->receive_key, keymat->receive_iv);
1281       silc_hmac_set_key(idata->hmac_receive, keymat->receive_hmac_key,
1282                         keymat->hmac_key_len);
1283     }
1284   }
1285
1286   /* Save the current sending encryption key */
1287   if (!send) {
1288     memset(idata->rekey->send_enc_key, 0, idata->rekey->enc_key_len);
1289     silc_free(idata->rekey->send_enc_key);
1290     idata->rekey->send_enc_key = silc_memdup(keymat->send_enc_key,
1291                                              keymat->enc_key_len / 8);
1292     idata->rekey->enc_key_len = keymat->enc_key_len / 8;
1293   }
1294 }
1295
1296 /* This function actually re-generates (when not using PFS) the keys and
1297    takes them into use. */
1298
1299 void silc_server_protocol_rekey_generate(SilcServer server,
1300                                          SilcServerRekeyInternalContext *ctx,
1301                                          bool send)
1302 {
1303   SilcIDListData idata = (SilcIDListData)ctx->sock->user_data;
1304   SilcSKEKeyMaterial *keymat;
1305   SilcUInt32 key_len = silc_cipher_get_key_len(idata->send_key);
1306   SilcUInt32 hash_len = silc_hash_len(idata->hash);
1307
1308   SILC_LOG_DEBUG(("Generating new %s session keys (no PFS)",
1309                   send ? "sending" : "receiving"));
1310
1311   /* Generate the new key */
1312   keymat = silc_calloc(1, sizeof(*keymat));
1313   silc_ske_process_key_material_data(idata->rekey->send_enc_key,
1314                                      idata->rekey->enc_key_len,
1315                                      16, key_len, hash_len,
1316                                      idata->hash, keymat);
1317
1318   /* Set the keys into use */
1319   silc_server_protocol_rekey_validate(server, ctx, idata, keymat, send);
1320
1321   silc_ske_free_key_material(keymat);
1322 }
1323
1324 /* This function actually re-generates (with PFS) the keys and
1325    takes them into use. */
1326
1327 void
1328 silc_server_protocol_rekey_generate_pfs(SilcServer server,
1329                                         SilcServerRekeyInternalContext *ctx,
1330                                         bool send)
1331 {
1332   SilcIDListData idata = (SilcIDListData)ctx->sock->user_data;
1333   SilcSKEKeyMaterial *keymat;
1334   SilcUInt32 key_len = silc_cipher_get_key_len(idata->send_key);
1335   SilcUInt32 hash_len = silc_hash_len(idata->hash);
1336   unsigned char *tmpbuf;
1337   SilcUInt32 klen;
1338
1339   SILC_LOG_DEBUG(("Generating new %s session keys (with PFS)",
1340                   send ? "sending" : "receiving"));
1341
1342   /* Encode KEY to binary data */
1343   tmpbuf = silc_mp_mp2bin(ctx->ske->KEY, 0, &klen);
1344
1345   /* Generate the new key */
1346   keymat = silc_calloc(1, sizeof(*keymat));
1347   silc_ske_process_key_material_data(tmpbuf, klen, 16, key_len, hash_len,
1348                                      idata->hash, keymat);
1349
1350   /* Set the keys into use */
1351   silc_server_protocol_rekey_validate(server, ctx, idata, keymat, send);
1352
1353   memset(tmpbuf, 0, klen);
1354   silc_free(tmpbuf);
1355   silc_ske_free_key_material(keymat);
1356 }
1357
1358 /* Packet sending callback. This function is provided as packet sending
1359    routine to the Key Exchange functions. */
1360
1361 static void
1362 silc_server_protocol_rekey_send_packet(SilcSKE ske,
1363                                        SilcBuffer packet,
1364                                        SilcPacketType type,
1365                                        void *context)
1366 {
1367   SilcProtocol protocol = (SilcProtocol)context;
1368   SilcServerRekeyInternalContext *ctx =
1369     (SilcServerRekeyInternalContext *)protocol->context;
1370   SilcServer server = (SilcServer)ctx->server;
1371
1372   /* Send the packet immediately */
1373   silc_server_packet_send(server, ctx->sock,
1374                           type, 0, packet->data, packet->len, FALSE);
1375 }
1376
1377 /* Performs re-key as defined in the SILC protocol specification. */
1378
1379 SILC_TASK_CALLBACK(silc_server_protocol_rekey)
1380 {
1381   SilcProtocol protocol = (SilcProtocol)context;
1382   SilcServerRekeyInternalContext *ctx =
1383     (SilcServerRekeyInternalContext *)protocol->context;
1384   SilcServer server = (SilcServer)ctx->server;
1385   SilcIDListData idata = (SilcIDListData)ctx->sock->user_data;
1386   SilcSKEStatus status;
1387
1388   if (protocol->state == SILC_PROTOCOL_STATE_UNKNOWN)
1389     protocol->state = SILC_PROTOCOL_STATE_START;
1390
1391   SILC_LOG_DEBUG(("Current protocol state %d", protocol->state));
1392
1393   switch(protocol->state) {
1394   case SILC_PROTOCOL_STATE_START:
1395     {
1396       /*
1397        * Start protocol.
1398        */
1399
1400       if (ctx->responder == TRUE) {
1401         /*
1402          * We are receiving party
1403          */
1404
1405         if (ctx->pfs == TRUE) {
1406           /*
1407            * Use Perfect Forward Secrecy, ie. negotiate the key material
1408            * using the SKE protocol.
1409            */
1410
1411           if (!ctx->packet) {
1412             SILC_LOG_ERROR(("Error during Re-key, with %s (%s)",
1413                             ctx->sock->hostname, ctx->sock->ip));
1414             protocol->state = SILC_PROTOCOL_STATE_ERROR;
1415             silc_protocol_execute(protocol, server->schedule, 0, 300000);
1416             return;
1417           }
1418
1419           if (ctx->packet->type != SILC_PACKET_KEY_EXCHANGE_1) {
1420             SILC_LOG_ERROR(("Error during Re-key (R PFS): re-key state is "
1421                             "incorrect (received %d, expected %d packet), "
1422                             "with %s (%s)", ctx->packet->type,
1423                             SILC_PACKET_KEY_EXCHANGE_1, ctx->sock->hostname,
1424                             ctx->sock->ip));
1425             protocol->state = SILC_PROTOCOL_STATE_ERROR;
1426             silc_protocol_execute(protocol, server->schedule, 0, 300000);
1427             return;
1428           }
1429
1430           ctx->ske = silc_ske_alloc(server->rng, server);
1431           ctx->ske->prop = silc_calloc(1, sizeof(*ctx->ske->prop));
1432           silc_ske_group_get_by_number(idata->rekey->ske_group,
1433                                        &ctx->ske->prop->group);
1434
1435           silc_ske_set_callbacks(ctx->ske,
1436                                  silc_server_protocol_rekey_send_packet,
1437                                  NULL, NULL, NULL, silc_ske_check_version,
1438                                  context);
1439
1440           status = silc_ske_responder_phase_2(ctx->ske, ctx->packet->buffer);
1441           if (status != SILC_SKE_STATUS_OK) {
1442             SILC_LOG_ERROR(("Error (%s) during Re-key (R PFS), with %s (%s)",
1443                             silc_ske_map_status(status), ctx->sock->hostname,
1444                             ctx->sock->ip));
1445             protocol->state = SILC_PROTOCOL_STATE_ERROR;
1446             silc_protocol_execute(protocol, server->schedule, 0, 300000);
1447             return;
1448           }
1449
1450           /* Advance the protocol state */
1451           protocol->state++;
1452           silc_protocol_execute(protocol, server->schedule, 0, 0);
1453         } else {
1454           /*
1455            * Do normal and simple re-key.
1456            */
1457
1458           /* Send the REKEY_DONE to indicate we will take new keys into use */
1459           silc_server_packet_queue_purge(server, ctx->sock);
1460           silc_server_packet_send(server, ctx->sock, SILC_PACKET_REKEY_DONE,
1461                                   0, NULL, 0, FALSE);
1462
1463           /* After we send REKEY_DONE we must set the sending encryption
1464              key to the new key since all packets after this packet must
1465              encrypted with the new key. */
1466           silc_server_protocol_rekey_generate(server, ctx, TRUE);
1467           silc_server_packet_queue_purge(server, ctx->sock);
1468
1469           /* The protocol ends in next stage. */
1470           protocol->state = SILC_PROTOCOL_STATE_END;
1471         }
1472
1473       } else {
1474         /*
1475          * We are the initiator of this protocol
1476          */
1477
1478         /* Start the re-key by sending the REKEY packet */
1479         silc_server_packet_send(server, ctx->sock, SILC_PACKET_REKEY,
1480                                 0, NULL, 0, FALSE);
1481
1482         if (ctx->pfs == TRUE) {
1483           /*
1484            * Use Perfect Forward Secrecy, ie. negotiate the key material
1485            * using the SKE protocol.
1486            */
1487           ctx->ske = silc_ske_alloc(server->rng, server);
1488           ctx->ske->prop = silc_calloc(1, sizeof(*ctx->ske->prop));
1489           silc_ske_group_get_by_number(idata->rekey->ske_group,
1490                                        &ctx->ske->prop->group);
1491
1492           silc_ske_set_callbacks(ctx->ske,
1493                                  silc_server_protocol_rekey_send_packet,
1494                                  NULL, NULL, NULL, silc_ske_check_version,
1495                                  context);
1496
1497           status = silc_ske_initiator_phase_2(ctx->ske, NULL, NULL, 0);
1498           if (status != SILC_SKE_STATUS_OK) {
1499             SILC_LOG_ERROR(("Error (%s) during Re-key (I PFS), with %s (%s)",
1500                             silc_ske_map_status(status), ctx->sock->hostname,
1501                             ctx->sock->ip));
1502             protocol->state = SILC_PROTOCOL_STATE_ERROR;
1503             silc_protocol_execute(protocol, server->schedule, 0, 300000);
1504             return;
1505           }
1506
1507           /* Advance the protocol state */
1508           protocol->state++;
1509         } else {
1510           /*
1511            * Do normal and simple re-key.
1512            */
1513
1514           /* Send the REKEY_DONE to indicate we will take new keys into use
1515              now. */
1516           silc_server_packet_queue_purge(server, ctx->sock);
1517           silc_server_packet_send(server, ctx->sock, SILC_PACKET_REKEY_DONE,
1518                                   0, NULL, 0, FALSE);
1519
1520           /* After we send REKEY_DONE we must set the sending encryption
1521              key to the new key since all packets after this packet must
1522              encrypted with the new key. */
1523           silc_server_protocol_rekey_generate(server, ctx, TRUE);
1524           silc_server_packet_queue_purge(server, ctx->sock);
1525
1526           /* The protocol ends in next stage. */
1527           protocol->state = SILC_PROTOCOL_STATE_END;
1528         }
1529       }
1530     }
1531     break;
1532
1533   case 2:
1534     /*
1535      * Second state, used only when doing re-key with PFS.
1536      */
1537     if (ctx->responder == TRUE) {
1538       if (ctx->pfs == TRUE) {
1539         /*
1540          * Send our KE packet to the initiator now that we've processed
1541          * the initiator's KE packet.
1542          */
1543         status = silc_ske_responder_finish(ctx->ske, NULL, NULL,
1544                                            SILC_SKE_PK_TYPE_SILC);
1545         if (status != SILC_SKE_STATUS_OK) {
1546           SILC_LOG_ERROR(("Error (%s) during Re-key (R PFS), with %s (%s)",
1547                           silc_ske_map_status(status), ctx->sock->hostname,
1548                           ctx->sock->ip));
1549           protocol->state = SILC_PROTOCOL_STATE_ERROR;
1550           silc_protocol_execute(protocol, server->schedule, 0, 300000);
1551           return;
1552         }
1553       }
1554
1555     } else {
1556       if (ctx->pfs == TRUE) {
1557         /*
1558          * The packet type must be KE packet
1559          */
1560         if (!ctx->packet) {
1561           SILC_LOG_ERROR(("Error during Re-key, with %s (%s)",
1562                           ctx->sock->hostname, ctx->sock->ip));
1563           protocol->state = SILC_PROTOCOL_STATE_ERROR;
1564           silc_protocol_execute(protocol, server->schedule, 0, 300000);
1565           return;
1566         }
1567
1568         if (ctx->packet->type != SILC_PACKET_KEY_EXCHANGE_2) {
1569           SILC_LOG_ERROR(("Error during Re-key (I PFS): re-key state is "
1570                           "incorrect (received %d, expected %d packet), "
1571                           "with %s (%s)", ctx->packet->type,
1572                           SILC_PACKET_KEY_EXCHANGE_2, ctx->sock->hostname,
1573                           ctx->sock->ip));
1574           protocol->state = SILC_PROTOCOL_STATE_ERROR;
1575           silc_protocol_execute(protocol, server->schedule, 0, 300000);
1576           return;
1577         }
1578
1579         status = silc_ske_initiator_finish(ctx->ske, ctx->packet->buffer);
1580         if (status != SILC_SKE_STATUS_OK) {
1581           SILC_LOG_ERROR(("Error (%s) during Re-key (I PFS), with %s (%s)",
1582                           silc_ske_map_status(status), ctx->sock->hostname,
1583                           ctx->sock->ip));
1584           protocol->state = SILC_PROTOCOL_STATE_ERROR;
1585           silc_protocol_execute(protocol, server->schedule, 0, 300000);
1586           return;
1587         }
1588       }
1589     }
1590
1591     /* Send the REKEY_DONE to indicate we will take new keys into use
1592        now. */
1593     silc_server_packet_queue_purge(server, ctx->sock);
1594     silc_server_packet_send(server, ctx->sock, SILC_PACKET_REKEY_DONE,
1595                             0, NULL, 0, FALSE);
1596
1597     /* After we send REKEY_DONE we must set the sending encryption
1598        key to the new key since all packets after this packet must
1599        encrypted with the new key. */
1600     silc_server_protocol_rekey_generate_pfs(server, ctx, TRUE);
1601     silc_server_packet_queue_purge(server, ctx->sock);
1602
1603     /* The protocol ends in next stage. */
1604     protocol->state = SILC_PROTOCOL_STATE_END;
1605     break;
1606
1607   case SILC_PROTOCOL_STATE_END:
1608     /*
1609      * End protocol
1610      */
1611
1612     if (!ctx->packet) {
1613       SILC_LOG_ERROR(("Error during Re-key, with %s (%s)",
1614                      ctx->sock->hostname, ctx->sock->ip));
1615       protocol->state = SILC_PROTOCOL_STATE_ERROR;
1616       silc_protocol_execute(protocol, server->schedule, 0, 300000);
1617       return;
1618     }
1619
1620     if (ctx->packet->type != SILC_PACKET_REKEY_DONE) {
1621       SILC_LOG_ERROR(("Error during Re-key (%s PFS): re-key state is "
1622                       "incorrect (received %d, expected %d packet), "
1623                       "with %s (%s)", ctx->responder ? "R" : "I",
1624                       ctx->packet->type, SILC_PACKET_REKEY_DONE,
1625                       ctx->sock->hostname, ctx->sock->ip));
1626       protocol->state = SILC_PROTOCOL_STATE_ERROR;
1627       silc_protocol_execute(protocol, server->schedule, 0, 300000);
1628       return;
1629     }
1630
1631     /* We received the REKEY_DONE packet and all packets after this is
1632        encrypted with the new key so set the decryption key to the new key */
1633     if (ctx->pfs == TRUE)
1634       silc_server_protocol_rekey_generate_pfs(server, ctx, FALSE);
1635     else
1636       silc_server_protocol_rekey_generate(server, ctx, FALSE);
1637     silc_server_packet_queue_purge(server, ctx->sock);
1638
1639     /* Assure that after calling final callback there cannot be pending
1640        executions for this protocol anymore. This just unregisters any
1641        timeout callbacks for this protocol. */
1642     silc_protocol_cancel(protocol, server->schedule);
1643
1644     /* Protocol has ended, call the final callback */
1645     if (protocol->final_callback)
1646       silc_protocol_execute_final(protocol, server->schedule);
1647     else
1648       silc_protocol_free(protocol);
1649     break;
1650
1651   case SILC_PROTOCOL_STATE_ERROR:
1652     /*
1653      * Error occured
1654      */
1655
1656     if (ctx->pfs == TRUE && ctx->ske)
1657       /* Send abort notification */
1658       silc_ske_abort(ctx->ske, ctx->ske->status);
1659
1660     /* Assure that after calling final callback there cannot be pending
1661        executions for this protocol anymore. This just unregisters any
1662        timeout callbacks for this protocol. */
1663     silc_protocol_cancel(protocol, server->schedule);
1664
1665     /* On error the final callback is always called. */
1666     if (protocol->final_callback)
1667       silc_protocol_execute_final(protocol, server->schedule);
1668     else
1669       silc_protocol_free(protocol);
1670     break;
1671
1672   case SILC_PROTOCOL_STATE_FAILURE:
1673     /*
1674      * We have received failure from remote
1675      */
1676
1677     SILC_LOG_ERROR(("Error during Re-Key: received Failure"));
1678
1679     /* Assure that after calling final callback there cannot be pending
1680        executions for this protocol anymore. This just unregisters any
1681        timeout callbacks for this protocol. */
1682     silc_protocol_cancel(protocol, server->schedule);
1683
1684     /* On error the final callback is always called. */
1685     if (protocol->final_callback)
1686       silc_protocol_execute_final(protocol, server->schedule);
1687     else
1688       silc_protocol_free(protocol);
1689     break;
1690
1691   case SILC_PROTOCOL_STATE_UNKNOWN:
1692     break;
1693   }
1694
1695 }
1696
1697 /* Registers protocols used in server. */
1698
1699 void silc_server_protocols_register(void)
1700 {
1701   silc_protocol_register(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1702                          silc_server_protocol_connection_auth);
1703   silc_protocol_register(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1704                          silc_server_protocol_key_exchange);
1705   silc_protocol_register(SILC_PROTOCOL_SERVER_REKEY,
1706                          silc_server_protocol_rekey);
1707   silc_protocol_register(SILC_PROTOCOL_SERVER_BACKUP,
1708                          silc_server_protocol_backup);
1709 }
1710
1711 /* Unregisters protocols */
1712
1713 void silc_server_protocols_unregister(void)
1714 {
1715   silc_protocol_unregister(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1716                            silc_server_protocol_connection_auth);
1717   silc_protocol_unregister(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1718                            silc_server_protocol_key_exchange);
1719   silc_protocol_unregister(SILC_PROTOCOL_SERVER_REKEY,
1720                            silc_server_protocol_rekey);
1721   silc_protocol_unregister(SILC_PROTOCOL_SERVER_BACKUP,
1722                            silc_server_protocol_backup);
1723 }