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                                      bool 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   if (ske->start_payload->flags & SILC_SKE_SP_FLAG_PFS)
75     idata->pfs = TRUE;
76
77   /* Allocate cipher to be used in the communication */
78   if (!silc_cipher_alloc(cipher->cipher->name, &idata->send_key)) {
79     silc_free(conn_data);
80     return FALSE;
81   }
82   if (!silc_cipher_alloc(cipher->cipher->name, &idata->receive_key)) {
83     silc_free(conn_data);
84     return FALSE;
85   }
86   
87   if (is_responder == TRUE) {
88     silc_cipher_set_key(idata->send_key, keymat->receive_enc_key, 
89                         keymat->enc_key_len);
90     silc_cipher_set_iv(idata->send_key, keymat->receive_iv);
91     silc_cipher_set_key(idata->receive_key, keymat->send_enc_key, 
92                         keymat->enc_key_len);
93     silc_cipher_set_iv(idata->receive_key, keymat->send_iv);
94   } else {
95     silc_cipher_set_key(idata->send_key, keymat->send_enc_key, 
96                         keymat->enc_key_len);
97     silc_cipher_set_iv(idata->send_key, keymat->send_iv);
98     silc_cipher_set_key(idata->receive_key, keymat->receive_enc_key, 
99                         keymat->enc_key_len);
100     silc_cipher_set_iv(idata->receive_key, keymat->receive_iv);
101   }
102
103   /* Note that for responder the initiator's sending key is receiving key */
104   idata->send_enc_key = silc_calloc(keymat->enc_key_len / 8,
105                                     sizeof(*idata->send_enc_key));
106   memcpy(idata->send_enc_key, keymat->send_enc_key, keymat->enc_key_len / 8);
107   idata->enc_key_len = keymat->enc_key_len / 8;
108
109   /* Save the remote host's public key */
110   silc_pkcs_public_key_decode(ske->ke1_payload->pk_data, 
111                               ske->ke1_payload->pk_len, &idata->public_key);
112
113   /* Save the hash */
114   if (!silc_hash_alloc(hash->hash->name, &idata->hash)) {
115     silc_cipher_free(idata->send_key);
116     silc_cipher_free(idata->receive_key);
117     silc_free(conn_data);
118     return FALSE;
119   }
120
121   /* Save HMAC key to be used in the communication. */
122   if (!silc_hmac_alloc(hmac->hmac->name, NULL, &idata->hmac)) {
123     silc_cipher_free(idata->send_key);
124     silc_cipher_free(idata->receive_key);
125     silc_hash_free(idata->hash);
126     silc_free(conn_data);
127     return FALSE;
128   }
129   silc_hmac_set_key(idata->hmac, keymat->hmac_key, keymat->hmac_key_len);
130
131   sock->user_data = (void *)conn_data;
132
133   return TRUE;
134 }
135
136 /* Check remote host version string */
137
138 SilcSKEStatus silc_ske_check_version(SilcSKE ske, unsigned char *version,
139                                      uint32 len)
140 {
141   SilcSKEStatus status = SILC_SKE_STATUS_OK;
142
143   SILC_LOG_INFO(("%s (%s) is version %s", ske->sock->hostname,
144                  ske->sock->ip, version));
145
146   /* Check for initial version string */
147   if (!strstr(version, "SILC-1.0-"))
148     status = SILC_SKE_STATUS_BAD_VERSION;
149
150   /* Check software version */
151
152   if (len < strlen(silc_version_string))
153     status = SILC_SKE_STATUS_BAD_VERSION;
154
155   /* XXX for now there is no other tests due to the abnormal version
156      string that is used */
157
158   return status;
159 }
160
161 /* Performs key exchange protocol. This is used for both initiator
162    and responder key exchange. This is performed always when accepting
163    new connection to the server. This may be called recursively. */
164
165 SILC_TASK_CALLBACK(silc_server_protocol_key_exchange)
166 {
167   SilcProtocol protocol = (SilcProtocol)context;
168   SilcServerKEInternalContext *ctx = 
169     (SilcServerKEInternalContext *)protocol->context;
170   SilcServer server = (SilcServer)ctx->server;
171   SilcSKEStatus status = 0;
172
173   SILC_LOG_DEBUG(("Start"));
174
175   if (protocol->state == SILC_PROTOCOL_STATE_UNKNOWN)
176     protocol->state = SILC_PROTOCOL_STATE_START;
177
178   SILC_LOG_DEBUG(("State=%d", protocol->state));
179
180   switch(protocol->state) {
181   case SILC_PROTOCOL_STATE_START:
182     {
183       /*
184        * Start protocol
185        */
186       SilcSKE ske;
187
188       /* Allocate Key Exchange object */
189       ske = silc_ske_alloc();
190       ctx->ske = ske;
191       ske->rng = server->rng;
192       
193       if (ctx->responder == TRUE) {
194         /* Start the key exchange by processing the received security
195            properties packet from initiator. */
196         status = silc_ske_responder_start(ske, ctx->rng, ctx->sock,
197                                           silc_version_string,
198                                           ctx->packet->buffer, FALSE,
199                                           NULL, NULL);
200       } else {
201         SilcSKEStartPayload *start_payload;
202
203         /* Assemble security properties. */
204         silc_ske_assemble_security_properties(ske, SILC_SKE_SP_FLAG_NONE, 
205                                               silc_version_string,
206                                               &start_payload);
207
208         /* Start the key exchange by sending our security properties
209            to the remote end. */
210         status = silc_ske_initiator_start(ske, ctx->rng, ctx->sock,
211                                           start_payload,
212                                           silc_server_protocol_ke_send_packet,
213                                           context);
214       }
215
216       if (status != SILC_SKE_STATUS_OK) {
217         SILC_LOG_WARNING(("Error (type %d) during Key Exchange protocol",
218                           status));
219         SILC_LOG_DEBUG(("Error (type %d) during Key Exchange protocol",
220                         status));
221
222         protocol->state = SILC_PROTOCOL_STATE_ERROR;
223         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 300000);
224         return;
225       }
226
227       /* Advance protocol state and call the next state if we are responder */
228       protocol->state++;
229       if (ctx->responder == TRUE)
230         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 100000);
231     }
232     break;
233   case 2:
234     {
235       /* 
236        * Phase 1 
237        */
238       if (ctx->responder == TRUE) {
239         /* Sends the selected security properties to the initiator. */
240         status = 
241           silc_ske_responder_phase_1(ctx->ske, 
242                                      ctx->ske->start_payload,
243                                      silc_server_protocol_ke_send_packet,
244                                      context);
245       } else {
246         /* Call Phase-1 function. This processes the Key Exchange Start
247            paylaod reply we just got from the responder. The callback
248            function will receive the processed payload where we will
249            save it. */
250         status = silc_ske_initiator_phase_1(ctx->ske, ctx->packet->buffer,
251                                             NULL, NULL);
252       }
253
254       if (status != SILC_SKE_STATUS_OK) {
255         SILC_LOG_WARNING(("Error (type %d) during Key Exchange protocol",
256                           status));
257         SILC_LOG_DEBUG(("Error (type %d) during Key Exchange protocol",
258                         status));
259
260         protocol->state = SILC_PROTOCOL_STATE_ERROR;
261         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 300000);
262         return;
263       }
264
265       /* Advance protocol state and call next state if we are initiator */
266       protocol->state++;
267       if (ctx->responder == FALSE)
268         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 100000);
269     }
270     break;
271   case 3:
272     {
273       /* 
274        * Phase 2 
275        */
276       if (ctx->responder == TRUE) {
277         /* Process the received Key Exchange 1 Payload packet from
278            the initiator. This also creates our parts of the Diffie
279            Hellman algorithm. */
280         status = silc_ske_responder_phase_2(ctx->ske, ctx->packet->buffer, 
281                                             NULL, NULL, NULL, NULL);
282       } else {
283         /* Call the Phase-2 function. This creates Diffie Hellman
284            key exchange parameters and sends our public part inside
285            Key Exhange 1 Payload to the responder. */
286         status = 
287           silc_ske_initiator_phase_2(ctx->ske,
288                                      server->public_key,
289                                      server->private_key,
290                                      silc_server_protocol_ke_send_packet,
291                                      context);
292       }
293
294       if (status != SILC_SKE_STATUS_OK) {
295         SILC_LOG_WARNING(("Error (type %d) during Key Exchange protocol",
296                           status));
297         SILC_LOG_DEBUG(("Error (type %d) during Key Exchange protocol",
298                         status));
299
300         protocol->state = SILC_PROTOCOL_STATE_ERROR;
301         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 300000);
302         return;
303       }
304
305       /* Advance protocol state and call the next state if we are responder */
306       protocol->state++;
307       if (ctx->responder == TRUE)
308         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 100000);
309     }
310     break;
311   case 4:
312     {
313       /* 
314        * Finish protocol
315        */
316       if (ctx->responder == TRUE) {
317         /* This creates the key exchange material and sends our
318            public parts to the initiator inside Key Exchange 2 Payload. */
319         status = 
320           silc_ske_responder_finish(ctx->ske, 
321                                     server->public_key, server->private_key,
322                                     SILC_SKE_PK_TYPE_SILC,
323                                     silc_server_protocol_ke_send_packet,
324                                     context);
325       } else {
326         /* Finish the protocol. This verifies the Key Exchange 2 payload
327            sent by responder. */
328         status = silc_ske_initiator_finish(ctx->ske, ctx->packet->buffer, 
329                                            NULL, NULL, NULL, NULL);
330       }
331
332       if (status != SILC_SKE_STATUS_OK) {
333         SILC_LOG_WARNING(("Error (type %d) during Key Exchange protocol",
334                           status));
335         SILC_LOG_DEBUG(("Error (type %d) during Key Exchange protocol",
336                         status));
337
338         protocol->state = SILC_PROTOCOL_STATE_ERROR;
339         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 300000);
340         return;
341       }
342
343       /* Send Ok to the other end. We will end the protocol as responder
344          sends Ok to us when we will take the new keys into use. */
345       if (ctx->responder == FALSE)
346         silc_ske_end(ctx->ske, silc_server_protocol_ke_send_packet, context);
347
348       /* End the protocol on the next round */
349       protocol->state = SILC_PROTOCOL_STATE_END;
350     }
351     break;
352
353   case SILC_PROTOCOL_STATE_END:
354     {
355       /* 
356        * End protocol
357        */
358       SilcSKEKeyMaterial *keymat;
359       int key_len = silc_cipher_get_key_len(ctx->ske->prop->cipher);
360       int hash_len = ctx->ske->prop->hash->hash->hash_len;
361
362       /* Process the key material */
363       keymat = silc_calloc(1, sizeof(*keymat));
364       status = silc_ske_process_key_material(ctx->ske, 16, key_len, hash_len,
365                                              keymat);
366       if (status != SILC_SKE_STATUS_OK) {
367         protocol->state = SILC_PROTOCOL_STATE_ERROR;
368         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 300000);
369         silc_ske_free_key_material(keymat);
370         return;
371       }
372       ctx->keymat = keymat;
373
374       /* Send Ok to the other end if we are responder. If we are initiator
375          we have sent this already. */
376       if (ctx->responder == TRUE)
377         silc_ske_end(ctx->ske, silc_server_protocol_ke_send_packet, context);
378
379       /* Unregister the timeout task since the protocol has ended. 
380          This was the timeout task to be executed if the protocol is
381          not completed fast enough. */
382       if (ctx->timeout_task)
383         silc_task_unregister(server->timeout_queue, ctx->timeout_task);
384
385       /* Call the final callback */
386       if (protocol->final_callback)
387         protocol->execute_final(server->timeout_queue, 0, protocol, fd);
388       else
389         silc_protocol_free(protocol);
390     }
391     break;
392
393   case SILC_PROTOCOL_STATE_ERROR:
394     /*
395      * Error occured
396      */
397
398     /* Send abort notification */
399     silc_ske_abort(ctx->ske, ctx->ske->status, 
400                    silc_server_protocol_ke_send_packet,
401                    context);
402
403     /* Unregister the timeout task since the protocol has ended. 
404        This was the timeout task to be executed if the protocol is
405        not completed fast enough. */
406     if (ctx->timeout_task)
407       silc_task_unregister(server->timeout_queue, ctx->timeout_task);
408
409     /* On error the final callback is always called. */
410     if (protocol->final_callback)
411       protocol->execute_final(server->timeout_queue, 0, protocol, fd);
412     else
413       silc_protocol_free(protocol);
414     break;
415
416   case SILC_PROTOCOL_STATE_FAILURE:
417     /*
418      * We have received failure from remote
419      */
420
421     /* Unregister the timeout task since the protocol has ended. 
422        This was the timeout task to be executed if the protocol is
423        not completed fast enough. */
424     if (ctx->timeout_task)
425       silc_task_unregister(server->timeout_queue, ctx->timeout_task);
426
427     /* On error the final callback is always called. */
428     if (protocol->final_callback)
429       protocol->execute_final(server->timeout_queue, 0, protocol, fd);
430     else
431       silc_protocol_free(protocol);
432     break;
433
434   case SILC_PROTOCOL_STATE_UNKNOWN:
435     break;
436   }
437 }
438
439 /*
440  * Connection Authentication protocol functions
441  */
442
443 static int 
444 silc_server_password_authentication(SilcServer server, char *auth1, 
445                                     char *auth2)
446 {
447   if (!auth1 || !auth2)
448     return FALSE;
449
450   if (!memcmp(auth1, auth2, strlen(auth1)))
451     return TRUE;
452
453   return FALSE;
454 }
455
456 static int
457 silc_server_public_key_authentication(SilcServer server,
458                                       SilcPublicKey pub_key,
459                                       unsigned char *sign,
460                                       uint32 sign_len,
461                                       SilcSKE ske)
462 {
463   SilcPKCS pkcs;
464   int len;
465   SilcBuffer auth;
466
467   if (!pub_key || !sign)
468     return FALSE;
469
470   silc_pkcs_alloc(pub_key->name, &pkcs);
471   if (!silc_pkcs_public_key_set(pkcs, pub_key)) {
472     silc_pkcs_free(pkcs);
473     return FALSE;
474   }
475
476   /* Make the authentication data. Protocol says it is HASH plus
477      KE Start Payload. */
478   len = ske->hash_len + ske->start_payload_copy->len;
479   auth = silc_buffer_alloc(len);
480   silc_buffer_pull_tail(auth, len);
481   silc_buffer_format(auth,
482                      SILC_STR_UI_XNSTRING(ske->hash, ske->hash_len),
483                      SILC_STR_UI_XNSTRING(ske->start_payload_copy->data,
484                                           ske->start_payload_copy->len),
485                      SILC_STR_END);
486
487   /* Verify signature */
488   if (silc_pkcs_verify(pkcs, sign, sign_len, auth->data, auth->len)) {
489     silc_pkcs_free(pkcs);
490     silc_buffer_free(auth);
491     return TRUE;
492   }
493
494   silc_pkcs_free(pkcs);
495   silc_buffer_free(auth);
496   return FALSE;
497 }
498
499 static int
500 silc_server_get_public_key_auth(SilcServer server,
501                                 SilcPublicKey pub_key,
502                                 unsigned char *auth_data,
503                                 uint32 *auth_data_len,
504                                 SilcSKE ske)
505 {
506   int len;
507   SilcPKCS pkcs;
508   SilcBuffer auth;
509
510   if (!pub_key)
511     return FALSE;
512
513   silc_pkcs_alloc(pub_key->name, &pkcs);
514   if (!silc_pkcs_public_key_set(pkcs, pub_key)) {
515     silc_pkcs_free(pkcs);
516     return FALSE;
517   }
518
519   /* Make the authentication data. Protocol says it is HASH plus
520      KE Start Payload. */
521   len = ske->hash_len + ske->start_payload_copy->len;
522   auth = silc_buffer_alloc(len);
523   silc_buffer_pull_tail(auth, len);
524   silc_buffer_format(auth,
525                      SILC_STR_UI_XNSTRING(ske->hash, ske->hash_len),
526                      SILC_STR_UI_XNSTRING(ske->start_payload_copy->data,
527                                           ske->start_payload_copy->len),
528                      SILC_STR_END);
529
530   if (silc_pkcs_sign(pkcs, auth->data, auth->len, auth_data, auth_data_len)) {
531     silc_pkcs_free(pkcs);
532     silc_buffer_free(auth);
533     return TRUE;
534   }
535
536   silc_pkcs_free(pkcs);
537   silc_buffer_free(auth);
538   return FALSE;
539 }
540
541 /* Performs connection authentication protocol. If responder, we 
542    authenticate the remote data received. If initiator, we will send
543    authentication data to the remote end. */
544
545 SILC_TASK_CALLBACK(silc_server_protocol_connection_auth)
546 {
547   SilcProtocol protocol = (SilcProtocol)context;
548   SilcServerConnAuthInternalContext *ctx = 
549     (SilcServerConnAuthInternalContext *)protocol->context;
550   SilcServer server = (SilcServer)ctx->server;
551
552   SILC_LOG_DEBUG(("Start"));
553
554   if (protocol->state == SILC_PROTOCOL_STATE_UNKNOWN)
555     protocol->state = SILC_PROTOCOL_STATE_START;
556
557   SILC_LOG_DEBUG(("State=%d", protocol->state));
558
559   switch(protocol->state) {
560   case SILC_PROTOCOL_STATE_START:
561     {
562       /* 
563        * Start protocol.
564        */
565
566       if (ctx->responder == TRUE) {
567         /*
568          * We are receiving party
569          */
570         int ret;
571         uint16 payload_len;
572         uint16 conn_type;
573         unsigned char *auth_data = NULL;
574
575         SILC_LOG_INFO(("Performing authentication protocol for %s (%s)",
576                        ctx->sock->hostname, ctx->sock->ip));
577
578         /* Parse the received authentication data packet. The received
579            payload is Connection Auth Payload. */
580         ret = silc_buffer_unformat(ctx->packet->buffer,
581                                    SILC_STR_UI_SHORT(&payload_len),
582                                    SILC_STR_UI_SHORT(&conn_type),
583                                    SILC_STR_END);
584         if (ret == -1) {
585           SILC_LOG_DEBUG(("Bad payload in authentication packet"));
586           protocol->state = SILC_PROTOCOL_STATE_ERROR;
587           protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 300000);
588           return;
589         }
590         
591         if (payload_len != ctx->packet->buffer->len) {
592           SILC_LOG_DEBUG(("Bad payload in authentication packet"));
593           protocol->state = SILC_PROTOCOL_STATE_ERROR;
594           protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 300000);
595           return;
596         }
597         
598         payload_len -= 4;
599         
600         if (conn_type < SILC_SOCKET_TYPE_CLIENT || 
601             conn_type > SILC_SOCKET_TYPE_ROUTER) {
602           SILC_LOG_ERROR(("Bad connection type %d", conn_type));
603           protocol->state = SILC_PROTOCOL_STATE_ERROR;
604           protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 300000);
605           return;
606         }
607         
608         if (payload_len > 0) {
609           /* Get authentication data */
610           silc_buffer_pull(ctx->packet->buffer, 4);
611           ret = silc_buffer_unformat(ctx->packet->buffer,
612                                      SILC_STR_UI_XNSTRING_ALLOC(&auth_data, 
613                                                                 payload_len),
614                                      SILC_STR_END);
615           if (ret == -1) {
616             SILC_LOG_DEBUG(("Bad payload in authentication packet"));
617             protocol->state = SILC_PROTOCOL_STATE_ERROR;
618             protocol->execute(server->timeout_queue, 0, 
619                               protocol, fd, 0, 300000);
620             return;
621           }
622         }
623
624         /* 
625          * Check the remote connection type and make sure that we have
626          * configured this connection. If we haven't allowed this connection
627          * the authentication must be failed.
628          */
629
630         SILC_LOG_DEBUG(("Remote connection type %d", conn_type));
631
632         /* Remote end is client */
633         if (conn_type == SILC_SOCKET_TYPE_CLIENT) {
634           SilcServerConfigSectionClientConnection *client = NULL;
635           client = silc_server_config_find_client_conn(server->config,
636                                                        ctx->sock->ip,
637                                                        ctx->sock->port);
638           if (!client)
639             client = silc_server_config_find_client_conn(server->config,
640                                                          ctx->sock->hostname,
641                                                          ctx->sock->port);
642           
643           if (client) {
644             switch(client->auth_meth) {
645             case SILC_AUTH_NONE:
646               /* No authentication required */
647               SILC_LOG_DEBUG(("No authentication required"));
648               break;
649               
650             case SILC_AUTH_PASSWORD:
651               /* Password authentication */
652               SILC_LOG_DEBUG(("Password authentication"));
653               ret = silc_server_password_authentication(server, auth_data,
654                                                         client->auth_data);
655
656               if (ret)
657                 break;
658
659               /* Authentication failed */
660               SILC_LOG_ERROR(("Authentication failed"));
661               SILC_LOG_DEBUG(("Authentication failed"));
662               silc_free(auth_data);
663               protocol->state = SILC_PROTOCOL_STATE_ERROR;
664               protocol->execute(server->timeout_queue, 0, 
665                                 protocol, fd, 0, 300000);
666               return;
667               break;
668               
669             case SILC_AUTH_PUBLIC_KEY:
670               /* Public key authentication */
671               SILC_LOG_DEBUG(("Public key authentication"));
672               ret = silc_server_public_key_authentication(server, 
673                                                           client->auth_data,
674                                                           auth_data,
675                                                           payload_len, 
676                                                           ctx->ske);
677
678               if (ret)
679                 break;
680
681               SILC_LOG_ERROR(("Authentication failed"));
682               SILC_LOG_DEBUG(("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           } else {
690             SILC_LOG_DEBUG(("No configuration for remote connection"));
691             SILC_LOG_ERROR(("Remote connection not configured"));
692             SILC_LOG_ERROR(("Authentication failed"));
693             silc_free(auth_data);
694             protocol->state = SILC_PROTOCOL_STATE_ERROR;
695             protocol->execute(server->timeout_queue, 0, 
696                               protocol, fd, 0, 300000);
697             return;
698           }
699         }
700         
701         /* Remote end is server */
702         if (conn_type == SILC_SOCKET_TYPE_SERVER) {
703           SilcServerConfigSectionServerConnection *serv = NULL;
704           serv = silc_server_config_find_server_conn(server->config,
705                                                      ctx->sock->ip,
706                                                      ctx->sock->port);
707           if (!serv)
708             serv = silc_server_config_find_server_conn(server->config,
709                                                        ctx->sock->hostname,
710                                                        ctx->sock->port);
711
712           if (serv) {
713             switch(serv->auth_meth) {
714             case SILC_AUTH_NONE:
715               /* No authentication required */
716               SILC_LOG_DEBUG(("No authentication required"));
717               break;
718               
719             case SILC_AUTH_PASSWORD:
720               /* Password authentication */
721               SILC_LOG_DEBUG(("Password authentication"));
722               ret = silc_server_password_authentication(server, auth_data,
723                                                         serv->auth_data);
724
725               if (ret)
726                 break;
727               
728               /* Authentication failed */
729               SILC_LOG_ERROR(("Authentication failed"));
730               SILC_LOG_DEBUG(("Authentication failed"));
731               silc_free(auth_data);
732               protocol->state = SILC_PROTOCOL_STATE_ERROR;
733               protocol->execute(server->timeout_queue, 0, 
734                                 protocol, fd, 0, 300000);
735               return;
736               break;
737
738             case SILC_AUTH_PUBLIC_KEY:
739               /* Public key authentication */
740               SILC_LOG_DEBUG(("Public key authentication"));
741               ret = silc_server_public_key_authentication(server, 
742                                                           serv->auth_data,
743                                                           auth_data,
744                                                           payload_len, 
745                                                           ctx->ske);
746                                                           
747               if (ret)
748                 break;
749
750               SILC_LOG_ERROR(("Authentication failed"));
751               SILC_LOG_DEBUG(("Authentication failed"));
752               silc_free(auth_data);
753               protocol->state = SILC_PROTOCOL_STATE_ERROR;
754               protocol->execute(server->timeout_queue, 0, 
755                                 protocol, fd, 0, 300000);
756               return;
757             }
758           } else {
759             SILC_LOG_DEBUG(("No configuration for remote connection"));
760             SILC_LOG_ERROR(("Remote connection not configured"));
761             SILC_LOG_ERROR(("Authentication failed"));
762             protocol->state = SILC_PROTOCOL_STATE_ERROR;
763             protocol->execute(server->timeout_queue, 0, 
764                               protocol, fd, 0, 300000);
765             silc_free(auth_data);
766             return;
767           }
768         }
769         
770         /* Remote end is router */
771         if (conn_type == SILC_SOCKET_TYPE_ROUTER) {
772           SilcServerConfigSectionServerConnection *serv = NULL;
773           serv = silc_server_config_find_router_conn(server->config,
774                                                      ctx->sock->ip,
775                                                      ctx->sock->port);
776           if (!serv)
777             serv = silc_server_config_find_router_conn(server->config,
778                                                        ctx->sock->hostname,
779                                                        ctx->sock->port);
780           
781           if (serv) {
782             switch(serv->auth_meth) {
783             case SILC_AUTH_NONE:
784               /* No authentication required */
785               SILC_LOG_DEBUG(("No authentication required"));
786               break;
787               
788             case SILC_AUTH_PASSWORD:
789               /* Password authentication */
790               SILC_LOG_DEBUG(("Password authentication"));
791               ret = silc_server_password_authentication(server, auth_data,
792                                                         serv->auth_data);
793
794               if (ret)
795                 break;
796               
797               /* Authentication failed */
798               SILC_LOG_ERROR(("Authentication failed"));
799               SILC_LOG_DEBUG(("Authentication failed"));
800               silc_free(auth_data);
801               protocol->state = SILC_PROTOCOL_STATE_ERROR;
802               protocol->execute(server->timeout_queue, 0, 
803                                 protocol, fd, 0, 300000);
804               return;
805               break;
806               
807             case SILC_AUTH_PUBLIC_KEY:
808               /* Public key authentication */
809               SILC_LOG_DEBUG(("Public key authentication"));
810               ret = silc_server_public_key_authentication(server, 
811                                                           serv->auth_data,
812                                                           auth_data,
813                                                           payload_len, 
814                                                           ctx->ske);
815                                                           
816               if (ret)
817                 break;
818               
819               SILC_LOG_ERROR(("Authentication failed"));
820               SILC_LOG_DEBUG(("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           } else {
828             SILC_LOG_DEBUG(("No configuration for remote connection"));
829             SILC_LOG_ERROR(("Remote connection not configured"));
830             SILC_LOG_ERROR(("Authentication failed"));
831             silc_free(auth_data);
832             protocol->state = SILC_PROTOCOL_STATE_ERROR;
833             protocol->execute(server->timeout_queue, 0, 
834                               protocol, fd, 0, 300000);
835             return;
836           }
837         }
838         
839         silc_free(auth_data);
840
841         /* Save connection type. This is later used to create the
842            ID for the connection. */
843         ctx->conn_type = conn_type;
844           
845         /* Advance protocol state. */
846         protocol->state = SILC_PROTOCOL_STATE_END;
847         protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 0);
848
849       } else {
850         /* 
851          * We are initiator. We are authenticating ourselves to a
852          * remote server. We will send the authentication data to the
853          * other end for verify. 
854          */
855         SilcBuffer packet;
856         int payload_len = 0;
857         unsigned char *auth_data = NULL;
858         uint32 auth_data_len = 0;
859         
860         switch(ctx->auth_meth) {
861         case SILC_AUTH_NONE:
862           /* No authentication required */
863           break;
864           
865         case SILC_AUTH_PASSWORD:
866           /* Password authentication */
867           if (ctx->auth_data && ctx->auth_data_len) {
868             auth_data = strdup(ctx->auth_data);
869             auth_data_len = ctx->auth_data_len;
870             break;
871           }
872           break;
873           
874         case SILC_AUTH_PUBLIC_KEY:
875           {
876             unsigned char sign[1024];
877
878             /* Public key authentication */
879             silc_server_get_public_key_auth(server, ctx->auth_data,
880                                             sign, &auth_data_len,
881                                             ctx->ske);
882             auth_data = silc_calloc(auth_data_len, sizeof(*auth_data));
883             memcpy(auth_data, sign, auth_data_len);
884             break;
885           }
886         }
887         
888         payload_len = 4 + auth_data_len;
889         packet = silc_buffer_alloc(payload_len);
890         silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
891         silc_buffer_format(packet,
892                            SILC_STR_UI_SHORT(payload_len),
893                            SILC_STR_UI_SHORT(server->server_type 
894                                               == SILC_SERVER ?
895                                               SILC_SOCKET_TYPE_SERVER :
896                                               SILC_SOCKET_TYPE_ROUTER),
897                            SILC_STR_UI_XNSTRING(auth_data, auth_data_len),
898                            SILC_STR_END);
899         
900         /* Send the packet to server */
901         silc_server_packet_send(server, ctx->sock,
902                                 SILC_PACKET_CONNECTION_AUTH, 0, 
903                                 packet->data, packet->len, TRUE);
904         
905         if (auth_data) {
906           memset(auth_data, 0, auth_data_len);
907           silc_free(auth_data);
908         }
909         silc_buffer_free(packet);
910         
911         /* Next state is end of protocol */
912         protocol->state = SILC_PROTOCOL_STATE_END;
913       }
914     }
915     break;
916
917   case SILC_PROTOCOL_STATE_END:
918     {
919       /* 
920        * End protocol
921        */
922       unsigned char ok[4];
923
924       SILC_PUT32_MSB(SILC_AUTH_OK, ok);
925
926       /* Authentication successful */
927       silc_server_packet_send(server, ctx->sock, SILC_PACKET_SUCCESS,
928                               0, ok, 4, TRUE);
929
930       /* Unregister the timeout task since the protocol has ended. 
931          This was the timeout task to be executed if the protocol is
932          not completed fast enough. */
933       if (ctx->timeout_task)
934         silc_task_unregister(server->timeout_queue, ctx->timeout_task);
935
936       /* Protocol has ended, call the final callback */
937       if (protocol->final_callback)
938         protocol->execute_final(server->timeout_queue, 0, protocol, fd);
939       else
940         silc_protocol_free(protocol);
941     }
942     break;
943   case SILC_PROTOCOL_STATE_ERROR:
944     {
945       /*
946        * Error. Send notify to remote.
947        */
948       unsigned char error[4];
949
950       SILC_PUT32_MSB(SILC_AUTH_FAILED, error);
951
952       /* Authentication failed */
953       silc_server_packet_send(server, ctx->sock, SILC_PACKET_FAILURE,
954                               0, error, 4, TRUE);
955
956       /* Unregister the timeout task since the protocol has ended. 
957          This was the timeout task to be executed if the protocol is
958          not completed fast enough. */
959       if (ctx->timeout_task)
960         silc_task_unregister(server->timeout_queue, ctx->timeout_task);
961
962       /* On error the final callback is always called. */
963       if (protocol->final_callback)
964         protocol->execute_final(server->timeout_queue, 0, protocol, fd);
965       else
966         silc_protocol_free(protocol);
967     }
968     break;
969
970   case SILC_PROTOCOL_STATE_FAILURE:
971     /*
972      * We have received failure from remote
973      */
974
975     /* Unregister the timeout task since the protocol has ended. 
976        This was the timeout task to be executed if the protocol is
977        not completed fast enough. */
978     if (ctx->timeout_task)
979       silc_task_unregister(server->timeout_queue, ctx->timeout_task);
980
981     /* On error the final callback is always called. */
982     if (protocol->final_callback)
983       protocol->execute_final(server->timeout_queue, 0, protocol, fd);
984     else
985       silc_protocol_free(protocol);
986     break;
987
988   case SILC_PROTOCOL_STATE_UNKNOWN:
989     break;
990   }
991 }
992
993 /*
994  * Re-key protocol routines
995  */
996
997 /* This function actually re-generates (when not using PFS) the keys and
998    takes them into use. */
999
1000 void silc_server_protocol_rekey_generate(SilcServer server,
1001                                          SilcServerRekeyInternalContext *ctx)
1002 {
1003   SilcIDListData idata = (SilcIDListData)ctx->sock->user_data;
1004   SilcSKEKeyMaterial *keymat;
1005   uint32 key_len = silc_cipher_get_key_len(idata->send_key);
1006   uint32 hash_len = idata->hash->hash->hash_len;
1007
1008   SILC_LOG_DEBUG(("Generating new session keys (no PFS)"));
1009
1010   /* Generate the new key */
1011   keymat = silc_calloc(1, sizeof(*keymat));
1012   silc_ske_process_key_material_data(idata->send_enc_key,
1013                                      idata->enc_key_len,
1014                                      16, key_len, hash_len, 
1015                                      idata->hash, keymat);
1016
1017   /* Set the keys into use */
1018
1019   if (ctx->responder == TRUE) {
1020     silc_cipher_set_key(idata->send_key, keymat->receive_enc_key, 
1021                         keymat->enc_key_len);
1022     silc_cipher_set_iv(idata->send_key, keymat->receive_iv);
1023     silc_cipher_set_key(idata->receive_key, keymat->send_enc_key, 
1024                         keymat->enc_key_len);
1025     silc_cipher_set_iv(idata->receive_key, keymat->send_iv);
1026   } else {
1027     silc_cipher_set_key(idata->send_key, keymat->send_enc_key, 
1028                         keymat->enc_key_len);
1029     silc_cipher_set_iv(idata->send_key, keymat->send_iv);
1030     silc_cipher_set_key(idata->receive_key, keymat->receive_enc_key, 
1031                         keymat->enc_key_len);
1032     silc_cipher_set_iv(idata->receive_key, keymat->receive_iv);
1033   }
1034
1035   silc_hmac_set_key(idata->hmac, keymat->hmac_key, keymat->hmac_key_len);
1036
1037   /* Save the current sending encryption key */
1038   memset(idata->send_enc_key, 0, idata->enc_key_len);
1039   silc_free(idata->send_enc_key);
1040   idata->send_enc_key = silc_calloc(keymat->enc_key_len / 8,
1041                                     sizeof(*idata->send_enc_key));
1042   memcpy(idata->send_enc_key, keymat->send_enc_key, keymat->enc_key_len / 8);
1043   idata->enc_key_len = keymat->enc_key_len / 8;
1044
1045   silc_ske_free_key_material(keymat);
1046 }
1047
1048 /* Performs re-key as defined the SILC protocol specification. */
1049
1050 SILC_TASK_CALLBACK(silc_server_protocol_rekey)
1051 {
1052   SilcProtocol protocol = (SilcProtocol)context;
1053   SilcServerRekeyInternalContext *ctx = 
1054     (SilcServerRekeyInternalContext *)protocol->context;
1055   SilcServer server = (SilcServer)ctx->server;
1056
1057   SILC_LOG_DEBUG(("Start"));
1058
1059   if (protocol->state == SILC_PROTOCOL_STATE_UNKNOWN)
1060     protocol->state = SILC_PROTOCOL_STATE_START;
1061
1062   SILC_LOG_DEBUG(("State=%d", protocol->state));
1063
1064   switch(protocol->state) {
1065   case SILC_PROTOCOL_STATE_START:
1066     {
1067       /* 
1068        * Start protocol.
1069        */
1070
1071       if (ctx->responder == TRUE) {
1072         /*
1073          * We are receiving party
1074          */
1075
1076         if (ctx->pfs == TRUE) {
1077           /* 
1078            * Use Perfect Forward Secrecy, ie. negotiate the key material
1079            * using the SKE protocol.
1080            */
1081
1082         } else {
1083           /*
1084            * Do normal and simple re-key.
1085            */
1086
1087           /* Send the REKEY_DONE to indicate we will take new keys into use */
1088           silc_server_packet_send(server, ctx->sock, SILC_PACKET_REKEY_DONE,
1089                                   0, NULL, 0, TRUE);
1090
1091           /* The protocol ends in next stage. */
1092           protocol->state = SILC_PROTOCOL_STATE_END;
1093         }
1094       
1095       } else {
1096         /*
1097          * We are the initiator of this protocol
1098          */
1099
1100         if (ctx->pfs == TRUE) {
1101           /* 
1102            * Use Perfect Forward Secrecy, ie. negotiate the key material
1103            * using the SKE protocol.
1104            */
1105
1106         } else {
1107           /*
1108            * Do normal and simple re-key.
1109            */
1110
1111           /* Start the re-key by sending the REKEY packet */
1112           silc_server_packet_send(server, ctx->sock, SILC_PACKET_REKEY,
1113                                   0, NULL, 0, TRUE);
1114
1115           /* The protocol ends in next stage. */
1116           protocol->state = SILC_PROTOCOL_STATE_END;
1117         }
1118       }
1119
1120     }
1121     break;
1122
1123   case SILC_PROTOCOL_STATE_END:
1124     /* 
1125      * End protocol
1126      */
1127
1128     if (ctx->responder == TRUE) {
1129
1130       if (ctx->pfs == TRUE) {
1131         /*
1132          *
1133          */
1134         
1135       } else {
1136         /*
1137          * We must have received the REKEY_DONE from the initiator.
1138          */
1139
1140         if (ctx->packet->type != SILC_PACKET_REKEY_DONE) {
1141           /* Error in protocol */
1142           protocol->state = SILC_PROTOCOL_STATE_ERROR;
1143           protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 0);
1144         }
1145       }
1146
1147     } else {
1148
1149       if (ctx->pfs == TRUE) {
1150         /*
1151          *
1152          */
1153         
1154       } else {
1155         /*
1156          * We must have received the REKEY_DONE from the responder.
1157          */
1158
1159         if (ctx->packet->type != SILC_PACKET_REKEY_DONE) {
1160           /* Error in protocol */
1161           protocol->state = SILC_PROTOCOL_STATE_ERROR;
1162           protocol->execute(server->timeout_queue, 0, protocol, fd, 0, 0);
1163         }
1164
1165         /* Send the REKEY_DONE to indicate we will take new keys into use 
1166            now. */ 
1167         silc_server_packet_send(server, ctx->sock, SILC_PACKET_REKEY_DONE,
1168                                 0, NULL, 0, TRUE);
1169       }
1170     }
1171
1172     /* Protocol has ended, call the final callback */
1173     if (protocol->final_callback)
1174       protocol->execute_final(server->timeout_queue, 0, protocol, fd);
1175     else
1176       silc_protocol_free(protocol);
1177     break;
1178
1179   case SILC_PROTOCOL_STATE_ERROR:
1180     /*
1181      * Error occured
1182      */
1183
1184     if (ctx->pfs == TRUE) {
1185       /* Send abort notification */
1186       silc_ske_abort(ctx->ske, ctx->ske->status, 
1187                      silc_server_protocol_ke_send_packet,
1188                      context);
1189     }
1190
1191     /* On error the final callback is always called. */
1192     if (protocol->final_callback)
1193       protocol->execute_final(server->timeout_queue, 0, protocol, fd);
1194     else
1195       silc_protocol_free(protocol);
1196     break;
1197
1198   case SILC_PROTOCOL_STATE_FAILURE:
1199     /*
1200      * We have received failure from remote
1201      */
1202
1203     /* On error the final callback is always called. */
1204     if (protocol->final_callback)
1205       protocol->execute_final(server->timeout_queue, 0, protocol, fd);
1206     else
1207       silc_protocol_free(protocol);
1208     break;
1209
1210   case SILC_PROTOCOL_STATE_UNKNOWN:
1211     break;
1212   }
1213
1214 }
1215
1216 /* Registers protocols used in server. */
1217
1218 void silc_server_protocols_register(void)
1219 {
1220   silc_protocol_register(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1221                          silc_server_protocol_connection_auth);
1222   silc_protocol_register(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1223                          silc_server_protocol_key_exchange);
1224   silc_protocol_register(SILC_PROTOCOL_SERVER_REKEY,
1225                          silc_server_protocol_rekey);
1226 }
1227
1228 /* Unregisters protocols */
1229
1230 void silc_server_protocols_unregister(void)
1231 {
1232   silc_protocol_unregister(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1233                            silc_server_protocol_connection_auth);
1234   silc_protocol_unregister(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1235                            silc_server_protocol_key_exchange);
1236   silc_protocol_unregister(SILC_PROTOCOL_SERVER_REKEY,
1237                            silc_server_protocol_rekey);
1238 }