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