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