updates.
[silc.git] / apps / silcd / protocol.c
1 /*
2
3   protocol.c
4
5   Author: Pekka Riikonen <priikone@poseidon.pspt.fi>
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
31 extern char *silc_version_string;
32
33 /*
34  * Key Exhange protocol functions
35  */
36
37 /* Packet sending callback. This function is provided as packet sending
38    routine to the Key Exchange functions. */
39
40 static void silc_server_protocol_ke_send_packet(SilcSKE ske,
41                                                 SilcBuffer packet,
42                                                 SilcPacketType type,
43                                                 void *context)
44 {
45   SilcProtocol protocol = (SilcProtocol)context;
46   SilcServerKEInternalContext *ctx = 
47     (SilcServerKEInternalContext *)protocol->context;
48   SilcServer server = (SilcServer)ctx->server;
49
50   /* Send the packet immediately */
51   silc_server_packet_send(server, ske->sock,
52                           type, 0, packet->data, packet->len, TRUE);
53 }
54
55 /* Sets the negotiated key material into use for particular connection. */
56
57 int silc_server_protocol_ke_set_keys(SilcSKE ske,
58                                      SilcSocketConnection sock,
59                                      SilcSKEKeyMaterial *keymat,
60                                      SilcCipher cipher,
61                                      SilcPKCS pkcs,
62                                      SilcHash hash,
63                                      SilcHmac hmac,
64                                      bool is_responder)
65 {
66   SilcUnknownEntry conn_data;
67   SilcIDListData idata;
68
69   SILC_LOG_DEBUG(("Setting new key into use"));
70
71   conn_data = silc_calloc(1, sizeof(*conn_data));
72   idata = (SilcIDListData)conn_data;
73
74   /* Allocate cipher to be used in the communication */
75   if (!silc_cipher_alloc(cipher->cipher->name, &idata->send_key)) {
76     silc_free(conn_data);
77     return FALSE;
78   }
79   if (!silc_cipher_alloc(cipher->cipher->name, &idata->receive_key)) {
80     silc_free(conn_data);
81     return FALSE;
82   }
83   
84   if (is_responder == TRUE) {
85     silc_cipher_set_key(idata->send_key, keymat->receive_enc_key, 
86                         keymat->enc_key_len);
87     silc_cipher_set_iv(idata->send_key, keymat->receive_iv);
88     silc_cipher_set_key(idata->receive_key, keymat->send_enc_key, 
89                         keymat->enc_key_len);
90     silc_cipher_set_iv(idata->receive_key, keymat->send_iv);
91   } else {
92     silc_cipher_set_key(idata->send_key, keymat->send_enc_key, 
93                         keymat->enc_key_len);
94     silc_cipher_set_iv(idata->send_key, keymat->send_iv);
95     silc_cipher_set_key(idata->receive_key, keymat->receive_enc_key, 
96                         keymat->enc_key_len);
97     silc_cipher_set_iv(idata->receive_key, keymat->receive_iv);
98   }
99
100   /* Note that for responder the initiator's sending key is receiving key */
101   idata->rekey = silc_calloc(1, sizeof(*idata->rekey));
102   idata->rekey->send_enc_key = 
103     silc_calloc(keymat->enc_key_len / 8,
104                 sizeof(*idata->rekey->send_enc_key));
105   memcpy(idata->rekey->send_enc_key, 
106          keymat->send_enc_key, keymat->enc_key_len / 8);
107   idata->rekey->enc_key_len = keymat->enc_key_len / 8;
108
109   if (ske->start_payload->flags & SILC_SKE_SP_FLAG_PFS)
110     idata->rekey->pfs = TRUE;
111
112   /* Save the remote host's public key */
113   silc_pkcs_public_key_decode(ske->ke1_payload->pk_data, 
114                               ske->ke1_payload->pk_len, &idata->public_key);
115
116   /* Save the hash */
117   if (!silc_hash_alloc(hash->hash->name, &idata->hash)) {
118     silc_cipher_free(idata->send_key);
119     silc_cipher_free(idata->receive_key);
120     silc_free(conn_data);
121     return FALSE;
122   }
123
124   /* Save HMAC key to be used in the communication. */
125   if (!silc_hmac_alloc(hmac->hmac->name, NULL, &idata->hmac)) {
126     silc_cipher_free(idata->send_key);
127     silc_cipher_free(idata->receive_key);
128     silc_hash_free(idata->hash);
129     silc_free(conn_data);
130     return FALSE;
131   }
132   silc_hmac_set_key(idata->hmac, keymat->hmac_key, keymat->hmac_key_len);
133
134   sock->user_data = (void *)conn_data;
135
136   return TRUE;
137 }
138
139 /* Check remote host version string */
140
141 SilcSKEStatus silc_ske_check_version(SilcSKE ske, unsigned char *version,
142                                      uint32 len)
143 {
144   SilcSKEStatus status = SILC_SKE_STATUS_OK;
145
146   SILC_LOG_INFO(("%s (%s) is version %s", ske->sock->hostname,
147                  ske->sock->ip, version));
148
149   /* Check for initial version string */
150   if (!strstr(version, "SILC-1.0-"))
151     status = SILC_SKE_STATUS_BAD_VERSION;
152
153   /* Check software version */
154
155   if (len < strlen(silc_version_string))
156     status = SILC_SKE_STATUS_BAD_VERSION;
157
158   /* XXX for now there is no other tests due to the abnormal version
159      string that is used */
160
161   return status;
162 }
163
164 /* Performs key exchange protocol. This is used for both initiator
165    and responder key exchange. This is performed always when accepting
166    new connection to the server. This may be called recursively. */
167
168 SILC_TASK_CALLBACK(silc_server_protocol_key_exchange)
169 {
170   SilcProtocol protocol = (SilcProtocol)context;
171   SilcServerKEInternalContext *ctx = 
172     (SilcServerKEInternalContext *)protocol->context;
173   SilcServer server = (SilcServer)ctx->server;
174   SilcSKEStatus status = 0;
175
176   SILC_LOG_DEBUG(("Start"));
177
178   if (protocol->state == SILC_PROTOCOL_STATE_UNKNOWN)
179     protocol->state = SILC_PROTOCOL_STATE_START;
180
181   SILC_LOG_DEBUG(("State=%d", protocol->state));
182
183   switch(protocol->state) {
184   case SILC_PROTOCOL_STATE_START:
185     {
186       /*
187        * Start protocol
188        */
189       SilcSKE ske;
190
191       /* Allocate Key Exchange object */
192       ske = silc_ske_alloc();
193       ctx->ske = ske;
194       ske->rng = server->rng;
195       
196       if (ctx->responder == TRUE) {
197         /* Start the key exchange by processing the received security
198            properties packet from initiator. */
199         status = silc_ske_responder_start(ske, ctx->rng, ctx->sock,
200                                           silc_version_string,
201                                           ctx->packet->buffer, FALSE,
202                                           NULL, NULL);
203       } else {
204         SilcSKEStartPayload *start_payload;
205
206         /* Assemble security properties. */
207         silc_ske_assemble_security_properties(ske, SILC_SKE_SP_FLAG_NONE, 
208                                               silc_version_string,
209                                               &start_payload);
210
211         /* Start the key exchange by sending our security properties
212            to the remote end. */
213         status = silc_ske_initiator_start(ske, ctx->rng, ctx->sock,
214                                           start_payload,
215                                           silc_server_protocol_ke_send_packet,
216                                           context);
217       }
218
219       if (status != SILC_SKE_STATUS_OK) {
220         SILC_LOG_WARNING(("Error (type %d) during Key Exchange protocol",
221                           status));
222         SILC_LOG_DEBUG(("Error (type %d) during Key Exchange protocol",
223                         status));
224
225         protocol->state = SILC_PROTOCOL_STATE_ERROR;
226         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 300000);
227         return;
228       }
229
230       /* Advance protocol state and call the next state if we are responder */
231       protocol->state++;
232       if (ctx->responder == TRUE)
233         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 100000);
234     }
235     break;
236   case 2:
237     {
238       /* 
239        * Phase 1 
240        */
241       if (ctx->responder == TRUE) {
242         /* Sends the selected security properties to the initiator. */
243         status = 
244           silc_ske_responder_phase_1(ctx->ske, 
245                                      ctx->ske->start_payload,
246                                      silc_server_protocol_ke_send_packet,
247                                      context);
248       } else {
249         /* Call Phase-1 function. This processes the Key Exchange Start
250            paylaod reply we just got from the responder. The callback
251            function will receive the processed payload where we will
252            save it. */
253         status = silc_ske_initiator_phase_1(ctx->ske, ctx->packet->buffer,
254                                             NULL, NULL);
255       }
256
257       if (status != SILC_SKE_STATUS_OK) {
258         SILC_LOG_WARNING(("Error (type %d) during Key Exchange protocol",
259                           status));
260         SILC_LOG_DEBUG(("Error (type %d) during Key Exchange protocol",
261                         status));
262
263         protocol->state = SILC_PROTOCOL_STATE_ERROR;
264         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 300000);
265         return;
266       }
267
268       /* Advance protocol state and call next state if we are initiator */
269       protocol->state++;
270       if (ctx->responder == FALSE)
271         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 100000);
272     }
273     break;
274   case 3:
275     {
276       /* 
277        * Phase 2 
278        */
279       if (ctx->responder == TRUE) {
280         /* Process the received Key Exchange 1 Payload packet from
281            the initiator. This also creates our parts of the Diffie
282            Hellman algorithm. */
283         status = silc_ske_responder_phase_2(ctx->ske, ctx->packet->buffer, 
284                                             NULL, NULL, NULL, NULL);
285       } else {
286         /* Call the Phase-2 function. This creates Diffie Hellman
287            key exchange parameters and sends our public part inside
288            Key Exhange 1 Payload to the responder. */
289         status = 
290           silc_ske_initiator_phase_2(ctx->ske,
291                                      server->public_key,
292                                      server->private_key,
293                                      silc_server_protocol_ke_send_packet,
294                                      context);
295       }
296
297       if (status != SILC_SKE_STATUS_OK) {
298         SILC_LOG_WARNING(("Error (type %d) during Key Exchange protocol",
299                           status));
300         SILC_LOG_DEBUG(("Error (type %d) during Key Exchange protocol",
301                         status));
302
303         protocol->state = SILC_PROTOCOL_STATE_ERROR;
304         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 300000);
305         return;
306       }
307
308       /* Advance protocol state and call the next state if we are responder */
309       protocol->state++;
310       if (ctx->responder == TRUE)
311         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 100000);
312     }
313     break;
314   case 4:
315     {
316       /* 
317        * Finish protocol
318        */
319       if (ctx->responder == TRUE) {
320         /* This creates the key exchange material and sends our
321            public parts to the initiator inside Key Exchange 2 Payload. */
322         status = 
323           silc_ske_responder_finish(ctx->ske, 
324                                     server->public_key, server->private_key,
325                                     SILC_SKE_PK_TYPE_SILC,
326                                     silc_server_protocol_ke_send_packet,
327                                     context);
328       } else {
329         /* Finish the protocol. This verifies the Key Exchange 2 payload
330            sent by responder. */
331         status = silc_ske_initiator_finish(ctx->ske, ctx->packet->buffer, 
332                                            NULL, NULL, NULL, NULL);
333       }
334
335       if (status != SILC_SKE_STATUS_OK) {
336         SILC_LOG_WARNING(("Error (type %d) during Key Exchange protocol",
337                           status));
338         SILC_LOG_DEBUG(("Error (type %d) during Key Exchange protocol",
339                         status));
340
341         protocol->state = SILC_PROTOCOL_STATE_ERROR;
342         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 300000);
343         return;
344       }
345
346       /* Send Ok to the other end. We will end the protocol as responder
347          sends Ok to us when we will take the new keys into use. */
348       if (ctx->responder == FALSE)
349         silc_ske_end(ctx->ske, silc_server_protocol_ke_send_packet, context);
350
351       /* End the protocol on the next round */
352       protocol->state = SILC_PROTOCOL_STATE_END;
353     }
354     break;
355
356   case SILC_PROTOCOL_STATE_END:
357     {
358       /* 
359        * End protocol
360        */
361       SilcSKEKeyMaterial *keymat;
362       int key_len = silc_cipher_get_key_len(ctx->ske->prop->cipher);
363       int hash_len = ctx->ske->prop->hash->hash->hash_len;
364
365       /* Process the key material */
366       keymat = silc_calloc(1, sizeof(*keymat));
367       status = silc_ske_process_key_material(ctx->ske, 16, key_len, hash_len,
368                                              keymat);
369       if (status != SILC_SKE_STATUS_OK) {
370         protocol->state = SILC_PROTOCOL_STATE_ERROR;
371         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 300000);
372         silc_ske_free_key_material(keymat);
373         return;
374       }
375       ctx->keymat = keymat;
376
377       /* Send Ok to the other end if we are responder. If we are initiator
378          we have sent this already. */
379       if (ctx->responder == TRUE)
380         silc_ske_end(ctx->ske, silc_server_protocol_ke_send_packet, context);
381
382       /* Unregister the timeout task since the protocol has ended. 
383          This was the timeout task to be executed if the protocol is
384          not completed fast enough. */
385       if (ctx->timeout_task)
386         silc_task_unregister(server->timeout_queue, ctx->timeout_task);
387
388       /* Call the final callback */
389       if (protocol->final_callback)
390         protocol->execute_final(server->timeout_queue, 0, protocol, fd);
391       else
392         silc_protocol_free(protocol);
393     }
394     break;
395
396   case SILC_PROTOCOL_STATE_ERROR:
397     /*
398      * Error occured
399      */
400
401     /* Send abort notification */
402     silc_ske_abort(ctx->ske, ctx->ske->status, 
403                    silc_server_protocol_ke_send_packet,
404                    context);
405
406     /* Unregister the timeout task since the protocol has ended. 
407        This was the timeout task to be executed if the protocol is
408        not completed fast enough. */
409     if (ctx->timeout_task)
410       silc_task_unregister(server->timeout_queue, ctx->timeout_task);
411
412     /* On error the final callback is always called. */
413     if (protocol->final_callback)
414       protocol->execute_final(server->timeout_queue, 0, protocol, fd);
415     else
416       silc_protocol_free(protocol);
417     break;
418
419   case SILC_PROTOCOL_STATE_FAILURE:
420     /*
421      * We have received failure from remote
422      */
423
424     /* Unregister the timeout task since the protocol has ended. 
425        This was the timeout task to be executed if the protocol is
426        not completed fast enough. */
427     if (ctx->timeout_task)
428       silc_task_unregister(server->timeout_queue, ctx->timeout_task);
429
430     /* On error the final callback is always called. */
431     if (protocol->final_callback)
432       protocol->execute_final(server->timeout_queue, 0, protocol, fd);
433     else
434       silc_protocol_free(protocol);
435     break;
436
437   case SILC_PROTOCOL_STATE_UNKNOWN:
438     break;
439   }
440 }
441
442 /*
443  * Connection Authentication protocol functions
444  */
445
446 static int 
447 silc_server_password_authentication(SilcServer server, char *auth1, 
448                                     char *auth2)
449 {
450   if (!auth1 || !auth2)
451     return FALSE;
452
453   if (!memcmp(auth1, auth2, strlen(auth1)))
454     return TRUE;
455
456   return FALSE;
457 }
458
459 static int
460 silc_server_public_key_authentication(SilcServer server,
461                                       SilcPublicKey pub_key,
462                                       unsigned char *sign,
463                                       uint32 sign_len,
464                                       SilcSKE ske)
465 {
466   SilcPKCS pkcs;
467   int len;
468   SilcBuffer auth;
469
470   if (!pub_key || !sign)
471     return FALSE;
472
473   silc_pkcs_alloc(pub_key->name, &pkcs);
474   if (!silc_pkcs_public_key_set(pkcs, pub_key)) {
475     silc_pkcs_free(pkcs);
476     return FALSE;
477   }
478
479   /* Make the authentication data. Protocol says it is HASH plus
480      KE Start Payload. */
481   len = ske->hash_len + ske->start_payload_copy->len;
482   auth = silc_buffer_alloc(len);
483   silc_buffer_pull_tail(auth, len);
484   silc_buffer_format(auth,
485                      SILC_STR_UI_XNSTRING(ske->hash, ske->hash_len),
486                      SILC_STR_UI_XNSTRING(ske->start_payload_copy->data,
487                                           ske->start_payload_copy->len),
488                      SILC_STR_END);
489
490   /* Verify signature */
491   if (silc_pkcs_verify(pkcs, sign, sign_len, auth->data, auth->len)) {
492     silc_pkcs_free(pkcs);
493     silc_buffer_free(auth);
494     return TRUE;
495   }
496
497   silc_pkcs_free(pkcs);
498   silc_buffer_free(auth);
499   return FALSE;
500 }
501
502 static int
503 silc_server_get_public_key_auth(SilcServer server,
504                                 SilcPublicKey pub_key,
505                                 unsigned char *auth_data,
506                                 uint32 *auth_data_len,
507                                 SilcSKE ske)
508 {
509   int len;
510   SilcPKCS pkcs;
511   SilcBuffer auth;
512
513   if (!pub_key)
514     return FALSE;
515
516   silc_pkcs_alloc(pub_key->name, &pkcs);
517   if (!silc_pkcs_public_key_set(pkcs, pub_key)) {
518     silc_pkcs_free(pkcs);
519     return FALSE;
520   }
521
522   /* Make the authentication data. Protocol says it is HASH plus
523      KE Start Payload. */
524   len = ske->hash_len + ske->start_payload_copy->len;
525   auth = silc_buffer_alloc(len);
526   silc_buffer_pull_tail(auth, len);
527   silc_buffer_format(auth,
528                      SILC_STR_UI_XNSTRING(ske->hash, ske->hash_len),
529                      SILC_STR_UI_XNSTRING(ske->start_payload_copy->data,
530                                           ske->start_payload_copy->len),
531                      SILC_STR_END);
532
533   if (silc_pkcs_sign(pkcs, auth->data, auth->len, auth_data, auth_data_len)) {
534     silc_pkcs_free(pkcs);
535     silc_buffer_free(auth);
536     return TRUE;
537   }
538
539   silc_pkcs_free(pkcs);
540   silc_buffer_free(auth);
541   return FALSE;
542 }
543
544 /* Performs connection authentication protocol. If responder, we 
545    authenticate the remote data received. If initiator, we will send
546    authentication data to the remote end. */
547
548 SILC_TASK_CALLBACK(silc_server_protocol_connection_auth)
549 {
550   SilcProtocol protocol = (SilcProtocol)context;
551   SilcServerConnAuthInternalContext *ctx = 
552     (SilcServerConnAuthInternalContext *)protocol->context;
553   SilcServer server = (SilcServer)ctx->server;
554
555   SILC_LOG_DEBUG(("Start"));
556
557   if (protocol->state == SILC_PROTOCOL_STATE_UNKNOWN)
558     protocol->state = SILC_PROTOCOL_STATE_START;
559
560   SILC_LOG_DEBUG(("State=%d", protocol->state));
561
562   switch(protocol->state) {
563   case SILC_PROTOCOL_STATE_START:
564     {
565       /* 
566        * Start protocol.
567        */
568
569       if (ctx->responder == TRUE) {
570         /*
571          * We are receiving party
572          */
573         int ret;
574         uint16 payload_len;
575         uint16 conn_type;
576         unsigned char *auth_data = NULL;
577
578         SILC_LOG_INFO(("Performing authentication protocol for %s (%s)",
579                        ctx->sock->hostname, ctx->sock->ip));
580
581         /* Parse the received authentication data packet. The received
582            payload is Connection Auth Payload. */
583         ret = silc_buffer_unformat(ctx->packet->buffer,
584                                    SILC_STR_UI_SHORT(&payload_len),
585                                    SILC_STR_UI_SHORT(&conn_type),
586                                    SILC_STR_END);
587         if (ret == -1) {
588           SILC_LOG_DEBUG(("Bad payload in authentication packet"));
589           protocol->state = SILC_PROTOCOL_STATE_ERROR;
590           protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 300000);
591           return;
592         }
593         
594         if (payload_len != ctx->packet->buffer->len) {
595           SILC_LOG_DEBUG(("Bad payload in authentication packet"));
596           protocol->state = SILC_PROTOCOL_STATE_ERROR;
597           protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 300000);
598           return;
599         }
600         
601         payload_len -= 4;
602         
603         if (conn_type < SILC_SOCKET_TYPE_CLIENT || 
604             conn_type > SILC_SOCKET_TYPE_ROUTER) {
605           SILC_LOG_ERROR(("Bad connection type %d", conn_type));
606           protocol->state = SILC_PROTOCOL_STATE_ERROR;
607           protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 300000);
608           return;
609         }
610         
611         if (payload_len > 0) {
612           /* Get authentication data */
613           silc_buffer_pull(ctx->packet->buffer, 4);
614           ret = silc_buffer_unformat(ctx->packet->buffer,
615                                      SILC_STR_UI_XNSTRING_ALLOC(&auth_data, 
616                                                                 payload_len),
617                                      SILC_STR_END);
618           if (ret == -1) {
619             SILC_LOG_DEBUG(("Bad payload in authentication packet"));
620             protocol->state = SILC_PROTOCOL_STATE_ERROR;
621             protocol->execute(server->timeout_queue, 0, 
622                               protocol, fd, 0, 300000);
623             return;
624           }
625         }
626
627         /* 
628          * Check the remote connection type and make sure that we have
629          * configured this connection. If we haven't allowed this connection
630          * the authentication must be failed.
631          */
632
633         SILC_LOG_DEBUG(("Remote connection type %d", conn_type));
634
635         /* Remote end is client */
636         if (conn_type == SILC_SOCKET_TYPE_CLIENT) {
637           SilcServerConfigSectionClientConnection *client = NULL;
638           client = silc_server_config_find_client_conn(server->config,
639                                                        ctx->sock->ip,
640                                                        ctx->sock->port);
641           if (!client)
642             client = silc_server_config_find_client_conn(server->config,
643                                                          ctx->sock->hostname,
644                                                          ctx->sock->port);
645           
646           if (client) {
647             switch(client->auth_meth) {
648             case SILC_AUTH_NONE:
649               /* No authentication required */
650               SILC_LOG_DEBUG(("No authentication required"));
651               break;
652               
653             case SILC_AUTH_PASSWORD:
654               /* Password authentication */
655               SILC_LOG_DEBUG(("Password authentication"));
656               ret = silc_server_password_authentication(server, auth_data,
657                                                         client->auth_data);
658
659               if (ret)
660                 break;
661
662               /* Authentication failed */
663               SILC_LOG_ERROR(("Authentication failed"));
664               SILC_LOG_DEBUG(("Authentication failed"));
665               silc_free(auth_data);
666               protocol->state = SILC_PROTOCOL_STATE_ERROR;
667               protocol->execute(server->timeout_queue, 0, 
668                                 protocol, fd, 0, 300000);
669               return;
670               break;
671               
672             case SILC_AUTH_PUBLIC_KEY:
673               /* Public key authentication */
674               SILC_LOG_DEBUG(("Public key authentication"));
675               ret = silc_server_public_key_authentication(server, 
676                                                           client->auth_data,
677                                                           auth_data,
678                                                           payload_len, 
679                                                           ctx->ske);
680
681               if (ret)
682                 break;
683
684               SILC_LOG_ERROR(("Authentication failed"));
685               SILC_LOG_DEBUG(("Authentication failed"));
686               silc_free(auth_data);
687               protocol->state = SILC_PROTOCOL_STATE_ERROR;
688               protocol->execute(server->timeout_queue, 0, 
689                                 protocol, fd, 0, 300000);
690               return;
691             }
692           } else {
693             SILC_LOG_DEBUG(("No configuration for remote connection"));
694             SILC_LOG_ERROR(("Remote connection not configured"));
695             SILC_LOG_ERROR(("Authentication failed"));
696             silc_free(auth_data);
697             protocol->state = SILC_PROTOCOL_STATE_ERROR;
698             protocol->execute(server->timeout_queue, 0, 
699                               protocol, fd, 0, 300000);
700             return;
701           }
702         }
703         
704         /* Remote end is server */
705         if (conn_type == SILC_SOCKET_TYPE_SERVER) {
706           SilcServerConfigSectionServerConnection *serv = NULL;
707           serv = silc_server_config_find_server_conn(server->config,
708                                                      ctx->sock->ip,
709                                                      ctx->sock->port);
710           if (!serv)
711             serv = silc_server_config_find_server_conn(server->config,
712                                                        ctx->sock->hostname,
713                                                        ctx->sock->port);
714
715           if (serv) {
716             switch(serv->auth_meth) {
717             case SILC_AUTH_NONE:
718               /* No authentication required */
719               SILC_LOG_DEBUG(("No authentication required"));
720               break;
721               
722             case SILC_AUTH_PASSWORD:
723               /* Password authentication */
724               SILC_LOG_DEBUG(("Password authentication"));
725               ret = silc_server_password_authentication(server, auth_data,
726                                                         serv->auth_data);
727
728               if (ret)
729                 break;
730               
731               /* Authentication failed */
732               SILC_LOG_ERROR(("Authentication failed"));
733               SILC_LOG_DEBUG(("Authentication failed"));
734               silc_free(auth_data);
735               protocol->state = SILC_PROTOCOL_STATE_ERROR;
736               protocol->execute(server->timeout_queue, 0, 
737                                 protocol, fd, 0, 300000);
738               return;
739               break;
740
741             case SILC_AUTH_PUBLIC_KEY:
742               /* Public key authentication */
743               SILC_LOG_DEBUG(("Public key authentication"));
744               ret = silc_server_public_key_authentication(server, 
745                                                           serv->auth_data,
746                                                           auth_data,
747                                                           payload_len, 
748                                                           ctx->ske);
749                                                           
750               if (ret)
751                 break;
752
753               SILC_LOG_ERROR(("Authentication failed"));
754               SILC_LOG_DEBUG(("Authentication failed"));
755               silc_free(auth_data);
756               protocol->state = SILC_PROTOCOL_STATE_ERROR;
757               protocol->execute(server->timeout_queue, 0, 
758                                 protocol, fd, 0, 300000);
759               return;
760             }
761           } else {
762             SILC_LOG_DEBUG(("No configuration for remote connection"));
763             SILC_LOG_ERROR(("Remote connection not configured"));
764             SILC_LOG_ERROR(("Authentication failed"));
765             protocol->state = SILC_PROTOCOL_STATE_ERROR;
766             protocol->execute(server->timeout_queue, 0, 
767                               protocol, fd, 0, 300000);
768             silc_free(auth_data);
769             return;
770           }
771         }
772         
773         /* Remote end is router */
774         if (conn_type == SILC_SOCKET_TYPE_ROUTER) {
775           SilcServerConfigSectionServerConnection *serv = NULL;
776           serv = silc_server_config_find_router_conn(server->config,
777                                                      ctx->sock->ip,
778                                                      ctx->sock->port);
779           if (!serv)
780             serv = silc_server_config_find_router_conn(server->config,
781                                                        ctx->sock->hostname,
782                                                        ctx->sock->port);
783           
784           if (serv) {
785             switch(serv->auth_meth) {
786             case SILC_AUTH_NONE:
787               /* No authentication required */
788               SILC_LOG_DEBUG(("No authentication required"));
789               break;
790               
791             case SILC_AUTH_PASSWORD:
792               /* Password authentication */
793               SILC_LOG_DEBUG(("Password authentication"));
794               ret = silc_server_password_authentication(server, auth_data,
795                                                         serv->auth_data);
796
797               if (ret)
798                 break;
799               
800               /* Authentication failed */
801               SILC_LOG_ERROR(("Authentication failed"));
802               SILC_LOG_DEBUG(("Authentication failed"));
803               silc_free(auth_data);
804               protocol->state = SILC_PROTOCOL_STATE_ERROR;
805               protocol->execute(server->timeout_queue, 0, 
806                                 protocol, fd, 0, 300000);
807               return;
808               break;
809               
810             case SILC_AUTH_PUBLIC_KEY:
811               /* Public key authentication */
812               SILC_LOG_DEBUG(("Public key authentication"));
813               ret = silc_server_public_key_authentication(server, 
814                                                           serv->auth_data,
815                                                           auth_data,
816                                                           payload_len, 
817                                                           ctx->ske);
818                                                           
819               if (ret)
820                 break;
821               
822               SILC_LOG_ERROR(("Authentication failed"));
823               SILC_LOG_DEBUG(("Authentication failed"));
824               silc_free(auth_data);
825               protocol->state = SILC_PROTOCOL_STATE_ERROR;
826               protocol->execute(server->timeout_queue, 0, 
827                                 protocol, fd, 0, 300000);
828               return;
829             }
830           } else {
831             SILC_LOG_DEBUG(("No configuration for remote connection"));
832             SILC_LOG_ERROR(("Remote connection not configured"));
833             SILC_LOG_ERROR(("Authentication failed"));
834             silc_free(auth_data);
835             protocol->state = SILC_PROTOCOL_STATE_ERROR;
836             protocol->execute(server->timeout_queue, 0, 
837                               protocol, fd, 0, 300000);
838             return;
839           }
840         }
841         
842         silc_free(auth_data);
843
844         /* Save connection type. This is later used to create the
845            ID for the connection. */
846         ctx->conn_type = conn_type;
847           
848         /* Advance protocol state. */
849         protocol->state = SILC_PROTOCOL_STATE_END;
850         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 0);
851
852       } else {
853         /* 
854          * We are initiator. We are authenticating ourselves to a
855          * remote server. We will send the authentication data to the
856          * other end for verify. 
857          */
858         SilcBuffer packet;
859         int payload_len = 0;
860         unsigned char *auth_data = NULL;
861         uint32 auth_data_len = 0;
862         
863         switch(ctx->auth_meth) {
864         case SILC_AUTH_NONE:
865           /* No authentication required */
866           break;
867           
868         case SILC_AUTH_PASSWORD:
869           /* Password authentication */
870           if (ctx->auth_data && ctx->auth_data_len) {
871             auth_data = strdup(ctx->auth_data);
872             auth_data_len = ctx->auth_data_len;
873             break;
874           }
875           break;
876           
877         case SILC_AUTH_PUBLIC_KEY:
878           {
879             unsigned char sign[1024];
880
881             /* Public key authentication */
882             silc_server_get_public_key_auth(server, ctx->auth_data,
883                                             sign, &auth_data_len,
884                                             ctx->ske);
885             auth_data = silc_calloc(auth_data_len, sizeof(*auth_data));
886             memcpy(auth_data, sign, auth_data_len);
887             break;
888           }
889         }
890         
891         payload_len = 4 + auth_data_len;
892         packet = silc_buffer_alloc(payload_len);
893         silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
894         silc_buffer_format(packet,
895                            SILC_STR_UI_SHORT(payload_len),
896                            SILC_STR_UI_SHORT(server->server_type 
897                                               == SILC_SERVER ?
898                                               SILC_SOCKET_TYPE_SERVER :
899                                               SILC_SOCKET_TYPE_ROUTER),
900                            SILC_STR_UI_XNSTRING(auth_data, auth_data_len),
901                            SILC_STR_END);
902         
903         /* Send the packet to server */
904         silc_server_packet_send(server, ctx->sock,
905                                 SILC_PACKET_CONNECTION_AUTH, 0, 
906                                 packet->data, packet->len, TRUE);
907         
908         if (auth_data) {
909           memset(auth_data, 0, auth_data_len);
910           silc_free(auth_data);
911         }
912         silc_buffer_free(packet);
913         
914         /* Next state is end of protocol */
915         protocol->state = SILC_PROTOCOL_STATE_END;
916       }
917     }
918     break;
919
920   case SILC_PROTOCOL_STATE_END:
921     {
922       /* 
923        * End protocol
924        */
925       unsigned char ok[4];
926
927       SILC_PUT32_MSB(SILC_AUTH_OK, ok);
928
929       /* Authentication successful */
930       silc_server_packet_send(server, ctx->sock, SILC_PACKET_SUCCESS,
931                               0, ok, 4, TRUE);
932
933       /* Unregister the timeout task since the protocol has ended. 
934          This was the timeout task to be executed if the protocol is
935          not completed fast enough. */
936       if (ctx->timeout_task)
937         silc_task_unregister(server->timeout_queue, ctx->timeout_task);
938
939       /* Protocol has ended, call the final callback */
940       if (protocol->final_callback)
941         protocol->execute_final(server->timeout_queue, 0, protocol, fd);
942       else
943         silc_protocol_free(protocol);
944     }
945     break;
946   case SILC_PROTOCOL_STATE_ERROR:
947     {
948       /*
949        * Error. Send notify to remote.
950        */
951       unsigned char error[4];
952
953       SILC_PUT32_MSB(SILC_AUTH_FAILED, error);
954
955       /* Authentication failed */
956       silc_server_packet_send(server, ctx->sock, SILC_PACKET_FAILURE,
957                               0, error, 4, TRUE);
958
959       /* Unregister the timeout task since the protocol has ended. 
960          This was the timeout task to be executed if the protocol is
961          not completed fast enough. */
962       if (ctx->timeout_task)
963         silc_task_unregister(server->timeout_queue, ctx->timeout_task);
964
965       /* On error the final callback is always called. */
966       if (protocol->final_callback)
967         protocol->execute_final(server->timeout_queue, 0, protocol, fd);
968       else
969         silc_protocol_free(protocol);
970     }
971     break;
972
973   case SILC_PROTOCOL_STATE_FAILURE:
974     /*
975      * We have received failure from remote
976      */
977
978     /* Unregister the timeout task since the protocol has ended. 
979        This was the timeout task to be executed if the protocol is
980        not completed fast enough. */
981     if (ctx->timeout_task)
982       silc_task_unregister(server->timeout_queue, ctx->timeout_task);
983
984     /* On error the final callback is always called. */
985     if (protocol->final_callback)
986       protocol->execute_final(server->timeout_queue, 0, protocol, fd);
987     else
988       silc_protocol_free(protocol);
989     break;
990
991   case SILC_PROTOCOL_STATE_UNKNOWN:
992     break;
993   }
994 }
995
996 /*
997  * Re-key protocol routines
998  */
999
1000 /* This function actually re-generates (when not using PFS) the keys and
1001    takes them into use. */
1002
1003 void silc_server_protocol_rekey_generate(SilcServer server,
1004                                          SilcServerRekeyInternalContext *ctx)
1005 {
1006   SilcIDListData idata = (SilcIDListData)ctx->sock->user_data;
1007   SilcSKEKeyMaterial *keymat;
1008   uint32 key_len = silc_cipher_get_key_len(idata->send_key);
1009   uint32 hash_len = idata->hash->hash->hash_len;
1010
1011   SILC_LOG_DEBUG(("Generating new session keys (no PFS)"));
1012
1013   /* Generate the new key */
1014   keymat = silc_calloc(1, sizeof(*keymat));
1015   silc_ske_process_key_material_data(idata->rekey->send_enc_key,
1016                                      idata->rekey->enc_key_len,
1017                                      16, key_len, hash_len, 
1018                                      idata->hash, keymat);
1019
1020   /* Set the keys into use */
1021
1022   if (ctx->responder == TRUE) {
1023     silc_cipher_set_key(idata->send_key, keymat->receive_enc_key, 
1024                         keymat->enc_key_len);
1025     silc_cipher_set_iv(idata->send_key, keymat->receive_iv);
1026     silc_cipher_set_key(idata->receive_key, keymat->send_enc_key, 
1027                         keymat->enc_key_len);
1028     silc_cipher_set_iv(idata->receive_key, keymat->send_iv);
1029   } else {
1030     silc_cipher_set_key(idata->send_key, keymat->send_enc_key, 
1031                         keymat->enc_key_len);
1032     silc_cipher_set_iv(idata->send_key, keymat->send_iv);
1033     silc_cipher_set_key(idata->receive_key, keymat->receive_enc_key, 
1034                         keymat->enc_key_len);
1035     silc_cipher_set_iv(idata->receive_key, keymat->receive_iv);
1036   }
1037
1038   silc_hmac_set_key(idata->hmac, keymat->hmac_key, keymat->hmac_key_len);
1039
1040   /* Save the current sending encryption key */
1041   memset(idata->rekey->send_enc_key, 0, idata->rekey->enc_key_len);
1042   silc_free(idata->rekey->send_enc_key);
1043   idata->rekey->send_enc_key = 
1044     silc_calloc(keymat->enc_key_len / 8,
1045                 sizeof(*idata->rekey->send_enc_key));
1046   memcpy(idata->rekey->send_enc_key, keymat->send_enc_key, 
1047          keymat->enc_key_len / 8);
1048   idata->rekey->enc_key_len = keymat->enc_key_len / 8;
1049
1050   silc_ske_free_key_material(keymat);
1051 }
1052
1053 /* Performs re-key as defined the SILC protocol specification. */
1054
1055 SILC_TASK_CALLBACK(silc_server_protocol_rekey)
1056 {
1057   SilcProtocol protocol = (SilcProtocol)context;
1058   SilcServerRekeyInternalContext *ctx = 
1059     (SilcServerRekeyInternalContext *)protocol->context;
1060   SilcServer server = (SilcServer)ctx->server;
1061
1062   SILC_LOG_DEBUG(("Start"));
1063
1064   if (protocol->state == SILC_PROTOCOL_STATE_UNKNOWN)
1065     protocol->state = SILC_PROTOCOL_STATE_START;
1066
1067   SILC_LOG_DEBUG(("State=%d", protocol->state));
1068
1069   switch(protocol->state) {
1070   case SILC_PROTOCOL_STATE_START:
1071     {
1072       /* 
1073        * Start protocol.
1074        */
1075
1076       if (ctx->responder == TRUE) {
1077         /*
1078          * We are receiving party
1079          */
1080
1081         if (ctx->pfs == TRUE) {
1082           /* 
1083            * Use Perfect Forward Secrecy, ie. negotiate the key material
1084            * using the SKE protocol.
1085            */
1086
1087         } else {
1088           /*
1089            * Do normal and simple re-key.
1090            */
1091
1092           /* Send the REKEY_DONE to indicate we will take new keys into use */
1093           silc_server_packet_send(server, ctx->sock, SILC_PACKET_REKEY_DONE,
1094                                   0, NULL, 0, TRUE);
1095
1096           /* The protocol ends in next stage. */
1097           protocol->state = SILC_PROTOCOL_STATE_END;
1098         }
1099       
1100       } else {
1101         /*
1102          * We are the initiator of this protocol
1103          */
1104
1105         if (ctx->pfs == TRUE) {
1106           /* 
1107            * Use Perfect Forward Secrecy, ie. negotiate the key material
1108            * using the SKE protocol.
1109            */
1110
1111         } else {
1112           /*
1113            * Do normal and simple re-key.
1114            */
1115
1116           /* Start the re-key by sending the REKEY packet */
1117           silc_server_packet_send(server, ctx->sock, SILC_PACKET_REKEY,
1118                                   0, NULL, 0, TRUE);
1119
1120           /* The protocol ends in next stage. */
1121           protocol->state = SILC_PROTOCOL_STATE_END;
1122         }
1123       }
1124
1125     }
1126     break;
1127
1128   case SILC_PROTOCOL_STATE_END:
1129     /* 
1130      * End protocol
1131      */
1132
1133     if (ctx->responder == TRUE) {
1134
1135       if (ctx->pfs == TRUE) {
1136         /*
1137          *
1138          */
1139         
1140       } else {
1141         /*
1142          * We must have received the REKEY_DONE from the initiator.
1143          */
1144
1145         if (ctx->packet->type != SILC_PACKET_REKEY_DONE) {
1146           /* Error in protocol */
1147           protocol->state = SILC_PROTOCOL_STATE_ERROR;
1148           protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 0);
1149         }
1150       }
1151
1152     } else {
1153
1154       if (ctx->pfs == TRUE) {
1155         /*
1156          *
1157          */
1158         
1159       } else {
1160         /*
1161          * We must have received the REKEY_DONE from the responder.
1162          */
1163
1164         if (ctx->packet->type != SILC_PACKET_REKEY_DONE) {
1165           /* Error in protocol */
1166           protocol->state = SILC_PROTOCOL_STATE_ERROR;
1167           protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 0);
1168         }
1169
1170         /* Send the REKEY_DONE to indicate we will take new keys into use 
1171            now. */ 
1172         silc_server_packet_send(server, ctx->sock, SILC_PACKET_REKEY_DONE,
1173                                 0, NULL, 0, TRUE);
1174       }
1175     }
1176
1177     /* Protocol has ended, call the final callback */
1178     if (protocol->final_callback)
1179       protocol->execute_final(server->timeout_queue, 0, protocol, fd);
1180     else
1181       silc_protocol_free(protocol);
1182     break;
1183
1184   case SILC_PROTOCOL_STATE_ERROR:
1185     /*
1186      * Error occured
1187      */
1188
1189     if (ctx->pfs == TRUE) {
1190       /* Send abort notification */
1191       silc_ske_abort(ctx->ske, ctx->ske->status, 
1192                      silc_server_protocol_ke_send_packet,
1193                      context);
1194     }
1195
1196     /* On error the final callback is always called. */
1197     if (protocol->final_callback)
1198       protocol->execute_final(server->timeout_queue, 0, protocol, fd);
1199     else
1200       silc_protocol_free(protocol);
1201     break;
1202
1203   case SILC_PROTOCOL_STATE_FAILURE:
1204     /*
1205      * We have received failure from remote
1206      */
1207
1208     /* On error the final callback is always called. */
1209     if (protocol->final_callback)
1210       protocol->execute_final(server->timeout_queue, 0, protocol, fd);
1211     else
1212       silc_protocol_free(protocol);
1213     break;
1214
1215   case SILC_PROTOCOL_STATE_UNKNOWN:
1216     break;
1217   }
1218
1219 }
1220
1221 /* Registers protocols used in server. */
1222
1223 void silc_server_protocols_register(void)
1224 {
1225   silc_protocol_register(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1226                          silc_server_protocol_connection_auth);
1227   silc_protocol_register(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1228                          silc_server_protocol_key_exchange);
1229   silc_protocol_register(SILC_PROTOCOL_SERVER_REKEY,
1230                          silc_server_protocol_rekey);
1231 }
1232
1233 /* Unregisters protocols */
1234
1235 void silc_server_protocols_unregister(void)
1236 {
1237   silc_protocol_unregister(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1238                            silc_server_protocol_connection_auth);
1239   silc_protocol_unregister(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1240                            silc_server_protocol_key_exchange);
1241   silc_protocol_unregister(SILC_PROTOCOL_SERVER_REKEY,
1242                            silc_server_protocol_rekey);
1243 }