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