Fixed silc_server_packet_broadcast to sen correct broadcast
[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 - 2000 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 static void silc_server_protocol_ke_set_keys(SilcSKE ske,
58                                              SilcSocketConnection sock,
59                                              SilcSKEKeyMaterial *keymat,
60                                              SilcCipher cipher,
61                                              SilcPKCS pkcs,
62                                              SilcHash hash,
63                                              int is_responder)
64 {
65   SilcUnknownEntry conn_data;
66   SilcIDListData idata;
67   SilcHash nhash;
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   silc_cipher_alloc(cipher->cipher->name, &idata->send_key);
76   silc_cipher_alloc(cipher->cipher->name, &idata->receive_key);
77   
78   if (is_responder == TRUE) {
79     idata->send_key->cipher->set_key(idata->send_key->context, 
80                                      keymat->receive_enc_key, 
81                                      keymat->enc_key_len);
82     idata->send_key->set_iv(idata->send_key, keymat->receive_iv);
83     idata->receive_key->cipher->set_key(idata->receive_key->context, 
84                                         keymat->send_enc_key, 
85                                         keymat->enc_key_len);
86     idata->receive_key->set_iv(idata->receive_key, keymat->send_iv);
87     
88   } else {
89     idata->send_key->cipher->set_key(idata->send_key->context, 
90                                      keymat->send_enc_key, 
91                                      keymat->enc_key_len);
92     idata->send_key->set_iv(idata->send_key, keymat->send_iv);
93     idata->receive_key->cipher->set_key(idata->receive_key->context, 
94                                         keymat->receive_enc_key, 
95                                         keymat->enc_key_len);
96     idata->receive_key->set_iv(idata->receive_key, keymat->receive_iv);
97   }
98
99   /* Allocate PKCS to be used */
100 #if 0
101   /* XXX Do we ever need to allocate PKCS for the connection??
102      If yes, we need to change KE protocol to get the initiators
103      public key. */
104   silc_pkcs_alloc(pkcs->pkcs->name, &idata->pkcs);
105   idata->public_key = silc_pkcs_public_key_alloc(XXX);
106   silc_pkcs_set_public_key(idata->pkcs, ske->ke2_payload->pk_data, 
107                            ske->ke2_payload->pk_len);
108 #endif
109
110   /* Save HMAC key to be used in the communication. */
111   silc_hash_alloc(hash->hash->name, &nhash);
112   silc_hmac_alloc(nhash, &idata->hmac);
113   silc_hmac_set_key(idata->hmac, keymat->hmac_key, keymat->hmac_key_len);
114
115   sock->user_data = (void *)conn_data;
116 }
117
118 /* XXX TODO */
119
120 SilcSKEStatus silc_ske_check_version(SilcSKE ske, unsigned char *version,
121                                      unsigned int len)
122 {
123   return SILC_SKE_STATUS_OK;
124 }
125
126 /* Performs key exchange protocol. This is used for both initiator
127    and responder key exchange. This is performed always when accepting
128    new connection to the server. This may be called recursively. */
129
130 SILC_TASK_CALLBACK(silc_server_protocol_key_exchange)
131 {
132   SilcProtocol protocol = (SilcProtocol)context;
133   SilcServerKEInternalContext *ctx = 
134     (SilcServerKEInternalContext *)protocol->context;
135   SilcServer server = (SilcServer)ctx->server;
136   SilcSKEStatus status = 0;
137
138   SILC_LOG_DEBUG(("Start"));
139
140   if (protocol->state == SILC_PROTOCOL_STATE_UNKNOWN)
141     protocol->state = SILC_PROTOCOL_STATE_START;
142
143   SILC_LOG_DEBUG(("State=%d", protocol->state));
144
145   switch(protocol->state) {
146   case SILC_PROTOCOL_STATE_START:
147     {
148       /*
149        * Start protocol
150        */
151       SilcSKE ske;
152
153       /* Allocate Key Exchange object */
154       ske = silc_ske_alloc();
155       ctx->ske = ske;
156       ske->rng = server->rng;
157       
158       if (ctx->responder == TRUE) {
159         /* Start the key exchange by processing the received security
160            properties packet from initiator. */
161         status = silc_ske_responder_start(ske, ctx->rng, ctx->sock,
162                                           silc_version_string,
163                                           ctx->packet->buffer, NULL, NULL);
164       } else {
165         SilcSKEStartPayload *start_payload;
166
167         /* Assemble security properties. */
168         silc_ske_assemble_security_properties(ske, SILC_SKE_SP_FLAG_NONE, 
169                                               silc_version_string,
170                                               &start_payload);
171
172         /* Start the key exchange by sending our security properties
173            to the remote end. */
174         status = silc_ske_initiator_start(ske, ctx->rng, ctx->sock,
175                                           start_payload,
176                                           silc_server_protocol_ke_send_packet,
177                                           context);
178       }
179
180       if (status != SILC_SKE_STATUS_OK) {
181         SILC_LOG_WARNING(("Error (type %d) during Key Exchange protocol",
182                           status));
183         SILC_LOG_DEBUG(("Error (type %d) during Key Exchange protocol",
184                         status));
185
186         protocol->state = SILC_PROTOCOL_STATE_ERROR;
187         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 300000);
188         return;
189       }
190
191       /* Advance protocol state and call the next state if we are responder */
192       protocol->state++;
193       if (ctx->responder == TRUE)
194         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 100000);
195     }
196     break;
197   case 2:
198     {
199       /* 
200        * Phase 1 
201        */
202       if (ctx->responder == TRUE) {
203         /* Sends the selected security properties to the initiator. */
204         status = 
205           silc_ske_responder_phase_1(ctx->ske, 
206                                      ctx->ske->start_payload,
207                                      silc_server_protocol_ke_send_packet,
208                                      context);
209       } else {
210         /* Call Phase-1 function. This processes the Key Exchange Start
211            paylaod reply we just got from the responder. The callback
212            function will receive the processed payload where we will
213            save it. */
214         status = silc_ske_initiator_phase_1(ctx->ske, ctx->packet->buffer,
215                                             NULL, NULL);
216       }
217
218       if (status != SILC_SKE_STATUS_OK) {
219         SILC_LOG_WARNING(("Error (type %d) during Key Exchange protocol",
220                           status));
221         SILC_LOG_DEBUG(("Error (type %d) during Key Exchange protocol",
222                         status));
223
224         protocol->state = SILC_PROTOCOL_STATE_ERROR;
225         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 300000);
226         return;
227       }
228
229       /* Advance protocol state and call next state if we are initiator */
230       protocol->state++;
231       if (ctx->responder == FALSE)
232         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 100000);
233     }
234     break;
235   case 3:
236     {
237       /* 
238        * Phase 2 
239        */
240       if (ctx->responder == TRUE) {
241         /* Process the received Key Exchange 1 Payload packet from
242            the initiator. This also creates our parts of the Diffie
243            Hellman algorithm. */
244         status = silc_ske_responder_phase_2(ctx->ske, ctx->packet->buffer, 
245                                             NULL, NULL);
246       } else {
247         /* Call the Phase-2 function. This creates Diffie Hellman
248            key exchange parameters and sends our public part inside
249            Key Exhange 1 Payload to the responder. */
250         status = 
251           silc_ske_initiator_phase_2(ctx->ske,
252                                      server->public_key,
253                                      silc_server_protocol_ke_send_packet,
254                                      context);
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 the next state if we are responder */
269       protocol->state++;
270       if (ctx->responder == TRUE)
271         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 100000);
272     }
273     break;
274   case 4:
275     {
276       /* 
277        * Finish protocol
278        */
279       if (ctx->responder == TRUE) {
280         /* This creates the key exchange material and sends our
281            public parts to the initiator inside Key Exchange 2 Payload. */
282         status = 
283           silc_ske_responder_finish(ctx->ske, 
284                                     server->public_key, server->private_key,
285                                     SILC_SKE_PK_TYPE_SILC,
286                                     silc_server_protocol_ke_send_packet,
287                                     context);
288       } else {
289         /* Finish the protocol. This verifies the Key Exchange 2 payload
290            sent by responder. */
291         status = silc_ske_initiator_finish(ctx->ske, ctx->packet->buffer, 
292                                            NULL, NULL, NULL, NULL);
293       }
294
295       if (status != SILC_SKE_STATUS_OK) {
296         SILC_LOG_WARNING(("Error (type %d) during Key Exchange protocol",
297                           status));
298         SILC_LOG_DEBUG(("Error (type %d) during Key Exchange protocol",
299                         status));
300
301         protocol->state = SILC_PROTOCOL_STATE_ERROR;
302         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 300000);
303         return;
304       }
305
306       /* Send Ok to the other end. We will end the protocol as responder
307          sends Ok to us when we will take the new keys into use. */
308       if (ctx->responder == FALSE)
309         silc_ske_end(ctx->ske, silc_server_protocol_ke_send_packet, context);
310
311       /* End the protocol on the next round */
312       protocol->state = SILC_PROTOCOL_STATE_END;
313     }
314     break;
315
316   case SILC_PROTOCOL_STATE_END:
317     {
318       /* 
319        * End protocol
320        */
321       SilcSKEKeyMaterial *keymat;
322
323       /* Send Ok to the other end if we are responder. If we are 
324          initiator we have sent this already. */
325       if (ctx->responder == TRUE)
326         silc_ske_end(ctx->ske, silc_server_protocol_ke_send_packet, context);
327
328       /* Process the key material */
329       keymat = silc_calloc(1, sizeof(*keymat));
330       silc_ske_process_key_material(ctx->ske, 16, (16 * 8), 16, keymat);
331
332       /* Take the new keys into use. */
333       silc_server_protocol_ke_set_keys(ctx->ske, ctx->sock, keymat,
334                                        ctx->ske->prop->cipher,
335                                        ctx->ske->prop->pkcs,
336                                        ctx->ske->prop->hash,
337                                        ctx->responder);
338
339       /* Unregister the timeout task since the protocol has ended. 
340          This was the timeout task to be executed if the protocol is
341          not completed fast enough. */
342       if (ctx->timeout_task)
343         silc_task_unregister(server->timeout_queue, ctx->timeout_task);
344
345       /* Call the final callback */
346       if (protocol->final_callback)
347         protocol->execute_final(server->timeout_queue, 0, protocol, fd);
348       else
349         silc_protocol_free(protocol);
350     }
351     break;
352
353   case SILC_PROTOCOL_STATE_ERROR:
354     /*
355      * Error occured
356      */
357
358     /* Send abort notification */
359     silc_ske_abort(ctx->ske, ctx->ske->status, 
360                    silc_server_protocol_ke_send_packet,
361                    context);
362
363     /* Unregister the timeout task since the protocol has ended. 
364        This was the timeout task to be executed if the protocol is
365        not completed fast enough. */
366     if (ctx->timeout_task)
367       silc_task_unregister(server->timeout_queue, ctx->timeout_task);
368
369     /* On error the final callback is always called. */
370     if (protocol->final_callback)
371       protocol->execute_final(server->timeout_queue, 0, protocol, fd);
372     else
373       silc_protocol_free(protocol);
374     break;
375
376   case SILC_PROTOCOL_STATE_FAILURE:
377     /*
378      * We have received failure from remote
379      */
380
381     /* Unregister the timeout task since the protocol has ended. 
382        This was the timeout task to be executed if the protocol is
383        not completed fast enough. */
384     if (ctx->timeout_task)
385       silc_task_unregister(server->timeout_queue, ctx->timeout_task);
386
387     /* On error the final callback is always called. */
388     if (protocol->final_callback)
389       protocol->execute_final(server->timeout_queue, 0, protocol, fd);
390     else
391       silc_protocol_free(protocol);
392     break;
393
394   case SILC_PROTOCOL_STATE_UNKNOWN:
395     break;
396   }
397 }
398
399 /*
400  * Connection Authentication protocol functions
401  */
402
403 /* XXX move these to somehwere else */
404
405 int silc_server_password_authentication(SilcServer server, char *auth1, 
406                                         char *auth2)
407 {
408   if (!auth1 || !auth2)
409     return FALSE;
410
411   if (!memcmp(auth1, auth2, strlen(auth1)))
412     return TRUE;
413
414   return FALSE;
415 }
416
417 int silc_server_public_key_authentication(SilcServer server,
418                                           char *pkfile,
419                                           unsigned char *sign,
420                                           unsigned int sign_len,
421                                           SilcSKE ske)
422 {
423   SilcPublicKey pub_key;
424   SilcPKCS pkcs;
425   int len;
426   SilcBuffer auth;
427
428   if (!pkfile || !sign)
429     return FALSE;
430
431   /* Load public key from file */
432   if (!silc_pkcs_load_public_key(pkfile, &pub_key, SILC_PKCS_FILE_PEM))
433     if (!silc_pkcs_load_public_key(pkfile, &pub_key, SILC_PKCS_FILE_BIN))
434       return FALSE;
435
436   silc_pkcs_alloc(pub_key->name, &pkcs);
437   if (!silc_pkcs_public_key_set(pkcs, pub_key)) {
438     silc_pkcs_free(pkcs);
439     return FALSE;
440   }
441
442   /* Make the authentication data. Protocol says it is HASH plus
443      KE Start Payload. */
444   len = ske->hash_len + ske->start_payload_copy->len;
445   auth = silc_buffer_alloc(len);
446   silc_buffer_pull_tail(auth, len);
447   silc_buffer_format(auth,
448                      SILC_STR_UI_XNSTRING(ske->hash, ske->hash_len),
449                      SILC_STR_UI_XNSTRING(ske->start_payload_copy->data,
450                                           ske->start_payload_copy->len),
451                      SILC_STR_END);
452
453   /* Verify signature */
454   if (pkcs->pkcs->verify(pkcs->context, sign, sign_len,
455                          auth->data, auth->len))
456     {
457       silc_pkcs_free(pkcs);
458       silc_pkcs_public_key_free(pub_key);
459       silc_buffer_free(auth);
460       return TRUE;
461     }
462
463   silc_pkcs_free(pkcs);
464   silc_pkcs_public_key_free(pub_key);
465   silc_buffer_free(auth);
466   return FALSE;
467 }
468
469 /* Performs connection authentication protocol. If responder, we 
470    authenticate the remote data received. If initiator, we will send
471    authentication data to the remote end. */
472
473 SILC_TASK_CALLBACK(silc_server_protocol_connection_auth)
474 {
475   SilcProtocol protocol = (SilcProtocol)context;
476   SilcServerConnAuthInternalContext *ctx = 
477     (SilcServerConnAuthInternalContext *)protocol->context;
478   SilcServer server = (SilcServer)ctx->server;
479
480   SILC_LOG_DEBUG(("Start"));
481
482   if (protocol->state == SILC_PROTOCOL_STATE_UNKNOWN)
483     protocol->state = SILC_PROTOCOL_STATE_START;
484
485   SILC_LOG_DEBUG(("State=%d", protocol->state));
486
487   switch(protocol->state) {
488   case SILC_PROTOCOL_STATE_START:
489     {
490       /* 
491        * Start protocol.
492        */
493
494       if (ctx->responder == TRUE) {
495         /*
496          * We are receiving party
497          */
498         int ret;
499         unsigned short payload_len;
500         unsigned short conn_type;
501         unsigned char *auth_data;
502
503         SILC_LOG_INFO(("Performing authentication protocol for %s",
504                        ctx->sock->hostname ? ctx->sock->hostname :
505                        ctx->sock->ip));
506
507         /* Parse the received authentication data packet. The received
508            payload is Connection Auth Payload. */
509         silc_buffer_unformat(ctx->packet->buffer,
510                              SILC_STR_UI_SHORT(&payload_len),
511                              SILC_STR_UI_SHORT(&conn_type),
512                              SILC_STR_END);
513         
514         if (payload_len != ctx->packet->buffer->len) {
515           SILC_LOG_ERROR(("Bad payload in authentication packet"));
516           SILC_LOG_DEBUG(("Bad payload in authentication packet"));
517           protocol->state = SILC_PROTOCOL_STATE_ERROR;
518           protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 300000);
519           return;
520         }
521         
522         payload_len -= 4;
523         
524         if (conn_type < SILC_SOCKET_TYPE_CLIENT || 
525             conn_type > SILC_SOCKET_TYPE_ROUTER) {
526           SILC_LOG_ERROR(("Bad connection type %d", conn_type));
527           SILC_LOG_DEBUG(("Bad connection type %d", conn_type));
528           protocol->state = SILC_PROTOCOL_STATE_ERROR;
529           protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 300000);
530           return;
531         }
532         
533         if (payload_len > 0) {
534           /* Get authentication data */
535           silc_buffer_pull(ctx->packet->buffer, 4);
536           silc_buffer_unformat(ctx->packet->buffer,
537                                SILC_STR_UI_XNSTRING_ALLOC(&auth_data, 
538                                                           payload_len),
539                                SILC_STR_END);
540         } else {
541           auth_data = NULL;
542         }
543
544         /* 
545          * Check the remote connection type and make sure that we have
546          * configured this connection. If we haven't allowed this connection
547          * the authentication must be failed.
548          */
549
550         SILC_LOG_DEBUG(("Remote connection type %d", conn_type));
551
552         /* Remote end is client */
553         if (conn_type == SILC_SOCKET_TYPE_CLIENT) {
554           SilcConfigServerSectionClientConnection *client = NULL;
555           client = 
556             silc_config_server_find_client_conn(server->config,
557                                                 ctx->sock->ip,
558                                                 ctx->sock->port);
559           if (!client)
560             client = 
561               silc_config_server_find_client_conn(server->config,
562                                                   ctx->sock->hostname,
563                                                   ctx->sock->port);
564           
565           if (client) {
566             switch(client->auth_meth) {
567             case SILC_PROTOCOL_CONN_AUTH_NONE:
568               /* No authentication required */
569               SILC_LOG_DEBUG(("No authentication required"));
570               break;
571               
572             case SILC_PROTOCOL_CONN_AUTH_PASSWORD:
573               /* Password authentication */
574               SILC_LOG_DEBUG(("Password authentication"));
575               ret = silc_server_password_authentication(server, auth_data,
576                                                         client->auth_data);
577
578               if (ret) {
579                 memset(auth_data, 0, payload_len);
580                 silc_free(auth_data);
581                 auth_data = NULL;
582                 break;
583               }
584
585               /* Authentication failed */
586               SILC_LOG_ERROR(("Authentication failed"));
587               SILC_LOG_DEBUG(("Authentication failed"));
588               protocol->state = SILC_PROTOCOL_STATE_ERROR;
589               protocol->execute(server->timeout_queue, 0, 
590                                 protocol, fd, 0, 300000);
591               return;
592               break;
593               
594             case SILC_PROTOCOL_CONN_AUTH_PUBLIC_KEY:
595               /* Public key authentication */
596               SILC_LOG_DEBUG(("Public key authentication"));
597               ret = silc_server_public_key_authentication(server, 
598                                                           client->auth_data,
599                                                           auth_data,
600                                                           payload_len, 
601                                                           ctx->ske);
602                                                           
603               if (ret) {
604                 memset(auth_data, 0, payload_len);
605                 silc_free(auth_data);
606                 auth_data = NULL;
607                 break;
608               }
609
610               SILC_LOG_ERROR(("Authentication failed"));
611               SILC_LOG_DEBUG(("Authentication failed"));
612               protocol->state = SILC_PROTOCOL_STATE_ERROR;
613               protocol->execute(server->timeout_queue, 0, 
614                                 protocol, fd, 0, 300000);
615               return;
616             }
617           } else {
618             SILC_LOG_DEBUG(("No configuration for remote connection"));
619             SILC_LOG_ERROR(("Remote connection not configured"));
620             SILC_LOG_ERROR(("Authentication failed"));
621             memset(auth_data, 0, payload_len);
622             silc_free(auth_data);
623             auth_data = NULL;
624             protocol->state = SILC_PROTOCOL_STATE_ERROR;
625             protocol->execute(server->timeout_queue, 0, 
626                               protocol, fd, 0, 300000);
627             return;
628           }
629         }
630         
631         /* Remote end is server */
632         if (conn_type == SILC_SOCKET_TYPE_SERVER) {
633           SilcConfigServerSectionServerConnection *serv = NULL;
634           serv = 
635             silc_config_server_find_server_conn(server->config,
636                                                 ctx->sock->ip,
637                                                 ctx->sock->port);
638           if (!serv)
639             serv = 
640               silc_config_server_find_server_conn(server->config,
641                                                   ctx->sock->hostname,
642                                                   ctx->sock->port);
643           
644           if (serv) {
645             switch(serv->auth_meth) {
646             case SILC_PROTOCOL_CONN_AUTH_NONE:
647               /* No authentication required */
648               SILC_LOG_DEBUG(("No authentication required"));
649               break;
650               
651             case SILC_PROTOCOL_CONN_AUTH_PASSWORD:
652               /* Password authentication */
653               SILC_LOG_DEBUG(("Password authentication"));
654               ret = silc_server_password_authentication(server, auth_data,
655                                                         serv->auth_data);
656
657               if (ret) {
658                 memset(auth_data, 0, payload_len);
659                 silc_free(auth_data);
660                 auth_data = NULL;
661                 break;
662               }
663               
664               /* Authentication failed */
665               SILC_LOG_ERROR(("Authentication failed"));
666               SILC_LOG_DEBUG(("Authentication failed"));
667               protocol->state = SILC_PROTOCOL_STATE_ERROR;
668               protocol->execute(server->timeout_queue, 0, 
669                                 protocol, fd, 0, 300000);
670               return;
671               break;
672               
673             case SILC_PROTOCOL_CONN_AUTH_PUBLIC_KEY:
674               /* Public key authentication */
675               SILC_LOG_DEBUG(("Public key authentication"));
676               ret = silc_server_public_key_authentication(server, 
677                                                           serv->auth_data,
678                                                           auth_data,
679                                                           payload_len, 
680                                                           ctx->ske);
681                                                           
682               if (ret) {
683                 memset(auth_data, 0, payload_len);
684                 silc_free(auth_data);
685                 auth_data = NULL;
686                 break;
687               }
688
689               SILC_LOG_ERROR(("Authentication failed"));
690               SILC_LOG_DEBUG(("Authentication failed"));
691               protocol->state = SILC_PROTOCOL_STATE_ERROR;
692               protocol->execute(server->timeout_queue, 0, 
693                                 protocol, fd, 0, 300000);
694               return;
695             }
696           } else {
697             SILC_LOG_DEBUG(("No configuration for remote connection"));
698             SILC_LOG_ERROR(("Remote connection not configured"));
699             SILC_LOG_ERROR(("Authentication failed"));
700             memset(auth_data, 0, payload_len);
701             silc_free(auth_data);
702             auth_data = NULL;
703             protocol->state = SILC_PROTOCOL_STATE_ERROR;
704             protocol->execute(server->timeout_queue, 0, 
705                               protocol, fd, 0, 300000);
706             return;
707           }
708         }
709         
710         /* Remote end is router */
711         if (conn_type == SILC_SOCKET_TYPE_ROUTER) {
712           SilcConfigServerSectionServerConnection *serv = NULL;
713           serv = 
714             silc_config_server_find_router_conn(server->config,
715                                                 ctx->sock->ip,
716                                                 ctx->sock->port);
717           if (!serv)
718             serv = 
719               silc_config_server_find_router_conn(server->config,
720                                                   ctx->sock->hostname,
721                                                   ctx->sock->port);
722           
723           if (serv) {
724             switch(serv->auth_meth) {
725             case SILC_PROTOCOL_CONN_AUTH_NONE:
726               /* No authentication required */
727               SILC_LOG_DEBUG(("No authentication required"));
728               break;
729               
730             case SILC_PROTOCOL_CONN_AUTH_PASSWORD:
731               /* Password authentication */
732               SILC_LOG_DEBUG(("Password authentication"));
733               ret = silc_server_password_authentication(server, auth_data,
734                                                         serv->auth_data);
735
736               if (ret) {
737                 memset(auth_data, 0, payload_len);
738                 silc_free(auth_data);
739                 auth_data = NULL;
740                 break;
741               }
742               
743               /* Authentication failed */
744               SILC_LOG_ERROR(("Authentication failed"));
745               SILC_LOG_DEBUG(("Authentication failed"));
746               protocol->state = SILC_PROTOCOL_STATE_ERROR;
747               protocol->execute(server->timeout_queue, 0, 
748                                 protocol, fd, 0, 300000);
749               return;
750               break;
751               
752             case SILC_PROTOCOL_CONN_AUTH_PUBLIC_KEY:
753               /* Public key authentication */
754               SILC_LOG_DEBUG(("Public key authentication"));
755               ret = silc_server_public_key_authentication(server, 
756                                                           serv->auth_data,
757                                                           auth_data,
758                                                           payload_len, 
759                                                           ctx->ske);
760                                                           
761               if (ret) {
762                 memset(auth_data, 0, payload_len);
763                 silc_free(auth_data);
764                 auth_data = NULL;
765                 break;
766               }
767
768               SILC_LOG_ERROR(("Authentication failed"));
769               SILC_LOG_DEBUG(("Authentication failed"));
770               protocol->state = SILC_PROTOCOL_STATE_ERROR;
771               protocol->execute(server->timeout_queue, 0, 
772                                 protocol, fd, 0, 300000);
773               return;
774             }
775           } else {
776             SILC_LOG_DEBUG(("No configuration for remote connection"));
777             SILC_LOG_ERROR(("Remote connection not configured"));
778             SILC_LOG_ERROR(("Authentication failed"));
779             memset(auth_data, 0, payload_len);
780             silc_free(auth_data);
781             auth_data = NULL;
782             protocol->state = SILC_PROTOCOL_STATE_ERROR;
783             protocol->execute(server->timeout_queue, 0, 
784                               protocol, fd, 0, 300000);
785             return;
786           }
787         }
788         
789         if (auth_data) {
790           memset(auth_data, 0, payload_len);
791           silc_free(auth_data);
792         }
793         
794         /* Save connection type. This is later used to create the
795            ID for the connection. */
796         ctx->conn_type = conn_type;
797           
798         /* Advance protocol state. */
799         protocol->state = SILC_PROTOCOL_STATE_END;
800         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 0);
801
802       } else {
803         /* 
804          * We are initiator. We are authenticating ourselves to a
805          * remote server. We will send the authentication data to the
806          * other end for verify. 
807          */
808         SilcBuffer packet;
809         int payload_len = 0;
810         unsigned char *auth_data = NULL;
811         unsigned int auth_data_len = 0;
812         
813         switch(ctx->auth_meth) {
814         case SILC_PROTOCOL_CONN_AUTH_NONE:
815           /* No authentication required */
816           break;
817           
818         case SILC_PROTOCOL_CONN_AUTH_PASSWORD:
819           /* Password authentication */
820           if (ctx->auth_data && ctx->auth_data_len) {
821             auth_data = ctx->auth_data;
822             auth_data_len = ctx->auth_data_len;
823             break;
824           }
825
826           /* No authentication data exits. Ask interactively from user. */
827           /* XXX */
828
829           break;
830           
831         case SILC_PROTOCOL_CONN_AUTH_PUBLIC_KEY:
832           /* Public key authentication */
833           /* XXX TODO */
834           break;
835         }
836         
837         payload_len = 4 + auth_data_len;
838         packet = silc_buffer_alloc(payload_len);
839         silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
840         silc_buffer_format(packet,
841                            SILC_STR_UI_SHORT(payload_len),
842                            SILC_STR_UI_SHORT(server->server_type 
843                                               == SILC_SERVER ?
844                                               SILC_SOCKET_TYPE_SERVER :
845                                               SILC_SOCKET_TYPE_ROUTER),
846                            SILC_STR_UI_XNSTRING(auth_data, auth_data_len),
847                            SILC_STR_END);
848         
849         /* Send the packet to server */
850         silc_server_packet_send(server, ctx->sock,
851                                 SILC_PACKET_CONNECTION_AUTH, 0, 
852                                 packet->data, packet->len, TRUE);
853         
854         if (auth_data) {
855           memset(auth_data, 0, auth_data_len);
856           silc_free(auth_data);
857         }
858         silc_buffer_free(packet);
859         
860         /* Next state is end of protocol */
861         protocol->state = SILC_PROTOCOL_STATE_END;
862       }
863     }
864     break;
865
866   case SILC_PROTOCOL_STATE_END:
867     {
868       /* 
869        * End protocol
870        */
871       unsigned char ok[4];
872
873       SILC_PUT32_MSB(SILC_CONN_AUTH_OK, ok);
874
875       /* Authentication failed */
876       silc_server_packet_send(server, ctx->sock, SILC_PACKET_FAILURE,
877                               0, ok, 4, TRUE);
878
879       /* Unregister the timeout task since the protocol has ended. 
880          This was the timeout task to be executed if the protocol is
881          not completed fast enough. */
882       if (ctx->timeout_task)
883         silc_task_unregister(server->timeout_queue, ctx->timeout_task);
884
885       /* Protocol has ended, call the final callback */
886       if (protocol->final_callback)
887         protocol->execute_final(server->timeout_queue, 0, protocol, fd);
888       else
889         silc_protocol_free(protocol);
890     }
891     break;
892   case SILC_PROTOCOL_STATE_ERROR:
893     {
894       /*
895        * Error. Send notify to remote.
896        */
897       unsigned char error[4];
898
899       SILC_PUT32_MSB(SILC_CONN_AUTH_FAILED, error);
900
901       /* Authentication failed */
902       silc_server_packet_send(server, ctx->sock, SILC_PACKET_FAILURE,
903                               0, error, 4, TRUE);
904
905       /* Unregister the timeout task since the protocol has ended. 
906          This was the timeout task to be executed if the protocol is
907          not completed fast enough. */
908       if (ctx->timeout_task)
909         silc_task_unregister(server->timeout_queue, ctx->timeout_task);
910
911       /* On error the final callback is always called. */
912       if (protocol->final_callback)
913         protocol->execute_final(server->timeout_queue, 0, protocol, fd);
914       else
915         silc_protocol_free(protocol);
916     }
917     break;
918
919   case SILC_PROTOCOL_STATE_FAILURE:
920     /*
921      * We have received failure from remote
922      */
923
924     /* Unregister the timeout task since the protocol has ended. 
925        This was the timeout task to be executed if the protocol is
926        not completed fast enough. */
927     if (ctx->timeout_task)
928       silc_task_unregister(server->timeout_queue, ctx->timeout_task);
929
930     /* On error the final callback is always called. */
931     if (protocol->final_callback)
932       protocol->execute_final(server->timeout_queue, 0, protocol, fd);
933     else
934       silc_protocol_free(protocol);
935     break;
936
937   case SILC_PROTOCOL_STATE_UNKNOWN:
938     break;
939   }
940 }
941
942 /* Registers protocols used in server. */
943
944 void silc_server_protocols_register(void)
945 {
946   silc_protocol_register(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
947                          silc_server_protocol_connection_auth);
948   silc_protocol_register(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
949                          silc_server_protocol_key_exchange);
950 }
951
952 /* Unregisters protocols */
953
954 void silc_server_protocols_unregister(void)
955 {
956   silc_protocol_unregister(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
957                            silc_server_protocol_connection_auth);
958   silc_protocol_unregister(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
959                            silc_server_protocol_key_exchange);
960 }