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