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