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