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