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 static int 
434 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 static int
447 silc_server_public_key_authentication(SilcServer server,
448                                       SilcPublicKey pub_key,
449                                       unsigned char *sign,
450                                       unsigned int sign_len,
451                                       SilcSKE ske)
452 {
453   SilcPKCS pkcs;
454   int len;
455   SilcBuffer auth;
456
457   if (!pub_key || !sign)
458     return FALSE;
459
460   silc_pkcs_alloc(pub_key->name, &pkcs);
461   if (!silc_pkcs_public_key_set(pkcs, pub_key)) {
462     silc_pkcs_free(pkcs);
463     return FALSE;
464   }
465
466   /* Make the authentication data. Protocol says it is HASH plus
467      KE Start Payload. */
468   len = ske->hash_len + ske->start_payload_copy->len;
469   auth = silc_buffer_alloc(len);
470   silc_buffer_pull_tail(auth, len);
471   silc_buffer_format(auth,
472                      SILC_STR_UI_XNSTRING(ske->hash, ske->hash_len),
473                      SILC_STR_UI_XNSTRING(ske->start_payload_copy->data,
474                                           ske->start_payload_copy->len),
475                      SILC_STR_END);
476
477   /* Verify signature */
478   if (silc_pkcs_verify(pkcs, sign, sign_len, auth->data, auth->len)) {
479     silc_pkcs_free(pkcs);
480     silc_buffer_free(auth);
481     return TRUE;
482   }
483
484   silc_pkcs_free(pkcs);
485   silc_buffer_free(auth);
486   return FALSE;
487 }
488
489 static int
490 silc_server_get_public_key_auth(SilcServer server,
491                                 SilcPublicKey pub_key,
492                                 unsigned char *auth_data,
493                                 unsigned int *auth_data_len,
494                                 SilcSKE ske)
495 {
496   int len;
497   SilcPKCS pkcs;
498   SilcBuffer auth;
499
500   if (!pub_key)
501     return FALSE;
502
503   silc_pkcs_alloc(pub_key->name, &pkcs);
504   if (!silc_pkcs_public_key_set(pkcs, pub_key)) {
505     silc_pkcs_free(pkcs);
506     return FALSE;
507   }
508
509   /* Make the authentication data. Protocol says it is HASH plus
510      KE Start Payload. */
511   len = ske->hash_len + ske->start_payload_copy->len;
512   auth = silc_buffer_alloc(len);
513   silc_buffer_pull_tail(auth, len);
514   silc_buffer_format(auth,
515                      SILC_STR_UI_XNSTRING(ske->hash, ske->hash_len),
516                      SILC_STR_UI_XNSTRING(ske->start_payload_copy->data,
517                                           ske->start_payload_copy->len),
518                      SILC_STR_END);
519
520   if (silc_pkcs_sign(pkcs, auth->data, auth->len, auth_data, auth_data_len)) {
521     silc_pkcs_free(pkcs);
522     silc_buffer_free(auth);
523     return TRUE;
524   }
525
526   silc_pkcs_free(pkcs);
527   silc_buffer_free(auth);
528   return FALSE;
529 }
530
531 /* Performs connection authentication protocol. If responder, we 
532    authenticate the remote data received. If initiator, we will send
533    authentication data to the remote end. */
534
535 SILC_TASK_CALLBACK(silc_server_protocol_connection_auth)
536 {
537   SilcProtocol protocol = (SilcProtocol)context;
538   SilcServerConnAuthInternalContext *ctx = 
539     (SilcServerConnAuthInternalContext *)protocol->context;
540   SilcServer server = (SilcServer)ctx->server;
541
542   SILC_LOG_DEBUG(("Start"));
543
544   if (protocol->state == SILC_PROTOCOL_STATE_UNKNOWN)
545     protocol->state = SILC_PROTOCOL_STATE_START;
546
547   SILC_LOG_DEBUG(("State=%d", protocol->state));
548
549   switch(protocol->state) {
550   case SILC_PROTOCOL_STATE_START:
551     {
552       /* 
553        * Start protocol.
554        */
555
556       if (ctx->responder == TRUE) {
557         /*
558          * We are receiving party
559          */
560         int ret;
561         unsigned short payload_len;
562         unsigned short conn_type;
563         unsigned char *auth_data = NULL;
564
565         SILC_LOG_INFO(("Performing authentication protocol for %s (%s)",
566                        ctx->sock->hostname, ctx->sock->ip));
567
568         /* Parse the received authentication data packet. The received
569            payload is Connection Auth Payload. */
570         ret = silc_buffer_unformat(ctx->packet->buffer,
571                                    SILC_STR_UI_SHORT(&payload_len),
572                                    SILC_STR_UI_SHORT(&conn_type),
573                                    SILC_STR_END);
574         if (ret == -1) {
575           SILC_LOG_DEBUG(("Bad payload in authentication packet"));
576           protocol->state = SILC_PROTOCOL_STATE_ERROR;
577           protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 300000);
578           return;
579         }
580         
581         if (payload_len != ctx->packet->buffer->len) {
582           SILC_LOG_DEBUG(("Bad payload in authentication packet"));
583           protocol->state = SILC_PROTOCOL_STATE_ERROR;
584           protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 300000);
585           return;
586         }
587         
588         payload_len -= 4;
589         
590         if (conn_type < SILC_SOCKET_TYPE_CLIENT || 
591             conn_type > SILC_SOCKET_TYPE_ROUTER) {
592           SILC_LOG_ERROR(("Bad connection type %d", conn_type));
593           protocol->state = SILC_PROTOCOL_STATE_ERROR;
594           protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 300000);
595           return;
596         }
597         
598         if (payload_len > 0) {
599           /* Get authentication data */
600           silc_buffer_pull(ctx->packet->buffer, 4);
601           ret = silc_buffer_unformat(ctx->packet->buffer,
602                                      SILC_STR_UI_XNSTRING_ALLOC(&auth_data, 
603                                                                 payload_len),
604                                      SILC_STR_END);
605           if (ret == -1) {
606             SILC_LOG_DEBUG(("Bad payload in authentication packet"));
607             protocol->state = SILC_PROTOCOL_STATE_ERROR;
608             protocol->execute(server->timeout_queue, 0, 
609                               protocol, fd, 0, 300000);
610             return;
611           }
612         }
613
614         /* 
615          * Check the remote connection type and make sure that we have
616          * configured this connection. If we haven't allowed this connection
617          * the authentication must be failed.
618          */
619
620         SILC_LOG_DEBUG(("Remote connection type %d", conn_type));
621
622         /* Remote end is client */
623         if (conn_type == SILC_SOCKET_TYPE_CLIENT) {
624           SilcServerConfigSectionClientConnection *client = NULL;
625           client = silc_server_config_find_client_conn(server->config,
626                                                        ctx->sock->ip,
627                                                        ctx->sock->port);
628           if (!client)
629             client = silc_server_config_find_client_conn(server->config,
630                                                          ctx->sock->hostname,
631                                                          ctx->sock->port);
632           
633           if (client) {
634             switch(client->auth_meth) {
635             case SILC_AUTH_NONE:
636               /* No authentication required */
637               SILC_LOG_DEBUG(("No authentication required"));
638               break;
639               
640             case SILC_AUTH_PASSWORD:
641               /* Password authentication */
642               SILC_LOG_DEBUG(("Password authentication"));
643               ret = silc_server_password_authentication(server, auth_data,
644                                                         client->auth_data);
645
646               if (ret)
647                 break;
648
649               /* Authentication failed */
650               SILC_LOG_ERROR(("Authentication failed"));
651               SILC_LOG_DEBUG(("Authentication failed"));
652               silc_free(auth_data);
653               protocol->state = SILC_PROTOCOL_STATE_ERROR;
654               protocol->execute(server->timeout_queue, 0, 
655                                 protocol, fd, 0, 300000);
656               return;
657               break;
658               
659             case SILC_AUTH_PUBLIC_KEY:
660               /* Public key authentication */
661               SILC_LOG_DEBUG(("Public key authentication"));
662               ret = silc_server_public_key_authentication(server, 
663                                                           client->auth_data,
664                                                           auth_data,
665                                                           payload_len, 
666                                                           ctx->ske);
667
668               if (ret)
669                 break;
670
671               SILC_LOG_ERROR(("Authentication failed"));
672               SILC_LOG_DEBUG(("Authentication failed"));
673               silc_free(auth_data);
674               protocol->state = SILC_PROTOCOL_STATE_ERROR;
675               protocol->execute(server->timeout_queue, 0, 
676                                 protocol, fd, 0, 300000);
677               return;
678             }
679           } else {
680             SILC_LOG_DEBUG(("No configuration for remote connection"));
681             SILC_LOG_ERROR(("Remote connection not configured"));
682             SILC_LOG_ERROR(("Authentication failed"));
683             silc_free(auth_data);
684             protocol->state = SILC_PROTOCOL_STATE_ERROR;
685             protocol->execute(server->timeout_queue, 0, 
686                               protocol, fd, 0, 300000);
687             return;
688           }
689         }
690         
691         /* Remote end is server */
692         if (conn_type == SILC_SOCKET_TYPE_SERVER) {
693           SilcServerConfigSectionServerConnection *serv = NULL;
694           serv = silc_server_config_find_server_conn(server->config,
695                                                      ctx->sock->ip,
696                                                      ctx->sock->port);
697           if (!serv)
698             serv = silc_server_config_find_server_conn(server->config,
699                                                        ctx->sock->hostname,
700                                                        ctx->sock->port);
701
702           if (serv) {
703             switch(serv->auth_meth) {
704             case SILC_AUTH_NONE:
705               /* No authentication required */
706               SILC_LOG_DEBUG(("No authentication required"));
707               break;
708               
709             case SILC_AUTH_PASSWORD:
710               /* Password authentication */
711               SILC_LOG_DEBUG(("Password authentication"));
712               ret = silc_server_password_authentication(server, auth_data,
713                                                         serv->auth_data);
714
715               if (ret)
716                 break;
717               
718               /* Authentication failed */
719               SILC_LOG_ERROR(("Authentication failed"));
720               SILC_LOG_DEBUG(("Authentication failed"));
721               silc_free(auth_data);
722               protocol->state = SILC_PROTOCOL_STATE_ERROR;
723               protocol->execute(server->timeout_queue, 0, 
724                                 protocol, fd, 0, 300000);
725               return;
726               break;
727
728             case SILC_AUTH_PUBLIC_KEY:
729               /* Public key authentication */
730               SILC_LOG_DEBUG(("Public key authentication"));
731               ret = silc_server_public_key_authentication(server, 
732                                                           serv->auth_data,
733                                                           auth_data,
734                                                           payload_len, 
735                                                           ctx->ske);
736                                                           
737               if (ret)
738                 break;
739
740               SILC_LOG_ERROR(("Authentication failed"));
741               SILC_LOG_DEBUG(("Authentication failed"));
742               silc_free(auth_data);
743               protocol->state = SILC_PROTOCOL_STATE_ERROR;
744               protocol->execute(server->timeout_queue, 0, 
745                                 protocol, fd, 0, 300000);
746               return;
747             }
748           } else {
749             SILC_LOG_DEBUG(("No configuration for remote connection"));
750             SILC_LOG_ERROR(("Remote connection not configured"));
751             SILC_LOG_ERROR(("Authentication failed"));
752             protocol->state = SILC_PROTOCOL_STATE_ERROR;
753             protocol->execute(server->timeout_queue, 0, 
754                               protocol, fd, 0, 300000);
755             silc_free(auth_data);
756             return;
757           }
758         }
759         
760         /* Remote end is router */
761         if (conn_type == SILC_SOCKET_TYPE_ROUTER) {
762           SilcServerConfigSectionServerConnection *serv = NULL;
763           serv = silc_server_config_find_router_conn(server->config,
764                                                      ctx->sock->ip,
765                                                      ctx->sock->port);
766           if (!serv)
767             serv = silc_server_config_find_router_conn(server->config,
768                                                        ctx->sock->hostname,
769                                                        ctx->sock->port);
770           
771           if (serv) {
772             switch(serv->auth_meth) {
773             case SILC_AUTH_NONE:
774               /* No authentication required */
775               SILC_LOG_DEBUG(("No authentication required"));
776               break;
777               
778             case SILC_AUTH_PASSWORD:
779               /* Password authentication */
780               SILC_LOG_DEBUG(("Password authentication"));
781               ret = silc_server_password_authentication(server, auth_data,
782                                                         serv->auth_data);
783
784               if (ret)
785                 break;
786               
787               /* Authentication failed */
788               SILC_LOG_ERROR(("Authentication failed"));
789               SILC_LOG_DEBUG(("Authentication failed"));
790               silc_free(auth_data);
791               protocol->state = SILC_PROTOCOL_STATE_ERROR;
792               protocol->execute(server->timeout_queue, 0, 
793                                 protocol, fd, 0, 300000);
794               return;
795               break;
796               
797             case SILC_AUTH_PUBLIC_KEY:
798               /* Public key authentication */
799               SILC_LOG_DEBUG(("Public key authentication"));
800               ret = silc_server_public_key_authentication(server, 
801                                                           serv->auth_data,
802                                                           auth_data,
803                                                           payload_len, 
804                                                           ctx->ske);
805                                                           
806               if (ret)
807                 break;
808               
809               SILC_LOG_ERROR(("Authentication failed"));
810               SILC_LOG_DEBUG(("Authentication failed"));
811               silc_free(auth_data);
812               protocol->state = SILC_PROTOCOL_STATE_ERROR;
813               protocol->execute(server->timeout_queue, 0, 
814                                 protocol, fd, 0, 300000);
815               return;
816             }
817           } else {
818             SILC_LOG_DEBUG(("No configuration for remote connection"));
819             SILC_LOG_ERROR(("Remote connection not configured"));
820             SILC_LOG_ERROR(("Authentication failed"));
821             silc_free(auth_data);
822             protocol->state = SILC_PROTOCOL_STATE_ERROR;
823             protocol->execute(server->timeout_queue, 0, 
824                               protocol, fd, 0, 300000);
825             return;
826           }
827         }
828         
829         silc_free(auth_data);
830
831         /* Save connection type. This is later used to create the
832            ID for the connection. */
833         ctx->conn_type = conn_type;
834           
835         /* Advance protocol state. */
836         protocol->state = SILC_PROTOCOL_STATE_END;
837         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 0);
838
839       } else {
840         /* 
841          * We are initiator. We are authenticating ourselves to a
842          * remote server. We will send the authentication data to the
843          * other end for verify. 
844          */
845         SilcBuffer packet;
846         int payload_len = 0;
847         unsigned char *auth_data = NULL;
848         unsigned int auth_data_len = 0;
849         
850         switch(ctx->auth_meth) {
851         case SILC_AUTH_NONE:
852           /* No authentication required */
853           break;
854           
855         case SILC_AUTH_PASSWORD:
856           /* Password authentication */
857           if (ctx->auth_data && ctx->auth_data_len) {
858             auth_data = strdup(ctx->auth_data);
859             auth_data_len = ctx->auth_data_len;
860             break;
861           }
862           break;
863           
864         case SILC_AUTH_PUBLIC_KEY:
865           {
866             unsigned char sign[1024];
867
868             /* Public key authentication */
869             silc_server_get_public_key_auth(server, ctx->auth_data,
870                                             sign, &auth_data_len,
871                                             ctx->ske);
872             break;
873           }
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 }