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