cf5cd6773c3e6aa57f58be0dcae2dfbf6db14149
[tinc] / src / protocol.c
1 /*
2     protocol.c -- handle the meta-protocol
3     Copyright (C) 1999-2001 Ivo Timmermans <itimmermans@bigfoot.com>,
4                   2000,2001 Guus Sliepen <guus@sliepen.warande.net>
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20     $Id: protocol.c,v 1.28.4.92 2001/06/05 16:09:55 guus Exp $
21 */
22
23 #include "config.h"
24
25 #include <sys/types.h>
26
27 #include <stdlib.h>
28 #include <string.h>
29 #include <syslog.h>
30 #include <sys/socket.h>
31 #include <unistd.h>
32 #include <stdio.h>
33 #include <stdarg.h>
34 #include <errno.h>
35
36 #include <utils.h>
37 #include <xalloc.h>
38 #include <avl_tree.h>
39 #include <list.h>
40
41 #include <netinet/in.h>
42
43 #ifdef HAVE_OPENSSL_SHA_H
44 # include <openssl/sha.h>
45 #else
46 # include <sha.h>
47 #endif
48
49 #ifdef HAVE_OPENSSL_RAND_H
50 # include <openssl/rand.h>
51 #else
52 # include <rand.h>
53 #endif
54
55 #ifdef HAVE_OPENSSL_EVP_H
56 # include <openssl/evp.h>
57 #else
58 # include <evp.h>
59 #endif
60
61
62 #include "conf.h"
63 #include "net.h"
64 #include "netutl.h"
65 #include "protocol.h"
66 #include "meta.h"
67 #include "connection.h"
68
69 #include "system.h"
70
71 int mykeyused = 0;
72
73 int check_id(char *id)
74 {
75   int i;
76
77   for (i = 0; i < strlen(id); i++)
78     if(!isalnum(id[i]) && id[i] != '_')
79       return -1;
80   
81   return 0;
82 }
83
84 /* Generic request routines - takes care of logging and error
85    detection as well */
86
87 int send_request(connection_t *cl, const char *format, ...)
88 {
89   va_list args;
90   char buffer[MAXBUFSIZE];
91   int len, request;
92
93 cp
94   /* Use vsnprintf instead of vasprintf: faster, no memory
95      fragmentation, cleanup is automatic, and there is a limit on the
96      input buffer anyway */
97
98   va_start(args, format);
99   len = vsnprintf(buffer, MAXBUFSIZE, format, args);
100   request = va_arg(args, int);
101   va_end(args);
102
103   if(len < 0 || len > MAXBUFSIZE-1)
104     {
105       syslog(LOG_ERR, _("Output buffer overflow while sending %s to %s (%s)"), request_name[request], cl->name, cl->hostname);
106       return -1;
107     }
108
109   if(debug_lvl >= DEBUG_PROTOCOL)
110     {
111       if(debug_lvl >= DEBUG_META)
112         syslog(LOG_DEBUG, _("Sending %s to %s (%s): %s"), request_name[request], cl->name, cl->hostname, buffer);
113       else
114         syslog(LOG_DEBUG, _("Sending %s to %s (%s)"), request_name[request], cl->name, cl->hostname);
115     }
116
117   buffer[len++] = '\n';
118 cp
119   return send_meta(cl, buffer, len);
120 }
121
122 int receive_request(connection_t *cl)
123 {
124   int request;
125 cp
126   if(sscanf(cl->buffer, "%d", &request) == 1)
127     {
128       if((request < 0) || (request >= LAST) || (request_handlers[request] == NULL))
129         {
130           if(debug_lvl >= DEBUG_META)
131             syslog(LOG_DEBUG, _("Unknown request from %s (%s): %s"),
132                    cl->name, cl->hostname, cl->buffer);
133           else
134             syslog(LOG_ERR, _("Unknown request from %s (%s)"),
135                    cl->name, cl->hostname);
136                    
137           return -1;
138         }
139       else
140         {
141           if(debug_lvl >= DEBUG_PROTOCOL)
142             {
143               if(debug_lvl >= DEBUG_META)
144                 syslog(LOG_DEBUG, _("Got %s from %s (%s): %s"),
145                        request_name[request], cl->name, cl->hostname, cl->buffer);
146               else
147                 syslog(LOG_DEBUG, _("Got %s from %s (%s)"),
148                        request_name[request], cl->name, cl->hostname);
149             }
150         }
151
152       if((cl->allow_request != ALL) && (cl->allow_request != request))
153         {
154           syslog(LOG_ERR, _("Unauthorized request from %s (%s)"), cl->name, cl->hostname);
155           return -1;
156         }
157
158       if(request_handlers[request](cl))
159         /* Something went wrong. Probably scriptkiddies. Terminate. */
160         {
161           syslog(LOG_ERR, _("Error while processing %s from %s (%s)"),
162                  request_name[request], cl->name, cl->hostname);
163           return -1;
164         }
165     }
166   else
167     {
168       syslog(LOG_ERR, _("Bogus data received from %s (%s)"),
169              cl->name, cl->hostname);
170       return -1;
171     }
172 cp
173   return 0;
174 }
175
176 /* The authentication protocol is described in detail in doc/SECURITY2,
177    the rest will be described in doc/PROTOCOL. */
178
179 int send_id(connection_t *cl)
180 {
181 cp
182   return send_request(cl, "%d %s %d %lx %hd", ID, myself->name, myself->protocol_version, myself->options, myself->port);
183 }
184
185 int id_h(connection_t *cl)
186 {
187   connection_t *old;
188   unsigned short int port;
189   char name[MAX_STRING_SIZE];
190   avl_node_t *node;
191 cp
192   if(sscanf(cl->buffer, "%*d "MAX_STRING" %d %lx %hd", name, &cl->protocol_version, &cl->options, &port) != 4)
193     {
194        syslog(LOG_ERR, _("Got bad ID from %s"), cl->hostname);
195        return -1;
196     }
197
198   /* Check if version matches */
199
200   if(cl->protocol_version != myself->protocol_version)
201     {
202       syslog(LOG_ERR, _("Peer %s (%s) uses incompatible version %d"),
203              cl->name, cl->hostname, cl->protocol_version);
204       return -1;
205     }
206
207   /* Check if identity is a valid name */
208
209   if(check_id(name))
210     {
211       syslog(LOG_ERR, _("Peer %s uses invalid identity name"), cl->hostname);
212       return -1;
213     }
214   
215   /* Copy string to cl */
216   
217   if(cl->name)
218     free(cl->name);
219     
220   cl->name = xstrdup(name);
221
222   /* Load information about peer */
223
224   if(read_host_config(cl))
225     {
226       syslog(LOG_ERR, _("Peer %s had unknown identity (%s)"), cl->hostname, cl->name);
227       return -1;
228     }
229
230   /* First check if the host we connected to is already in our
231      connection list. If so, we are probably making a loop, which
232      is not desirable.
233    */
234
235   if(cl->status.outgoing)
236     {
237       if((old = lookup_id(cl->name)))
238         {
239           if(debug_lvl >= DEBUG_CONNECTIONS)
240             syslog(LOG_NOTICE, _("Uplink %s (%s) is already in our connection list"), cl->name, cl->hostname);
241           cl->status.outgoing = 0;
242           old->status.outgoing = 1;
243           terminate_connection(cl);
244           return 0;
245         }
246     }
247     
248   /* Now we can add the name to the id tree */
249   
250   id_add(cl);
251
252   /* And uhr... cl->port just changed so we have to unlink it from the connection tree and re-insert... */
253   
254   node = avl_unlink(connection_tree, cl);
255   cl->port = port;
256   avl_insert_node(connection_tree, node);
257
258   /* Read in the public key, so that we can send a metakey */
259
260   if(read_rsa_public_key(cl))
261     return -1;
262
263   cl->allow_request = METAKEY;
264 cp
265   return send_metakey(cl);
266 }
267
268 int ack_h(connection_t *cl)
269 {
270   config_t const *cfg;
271   connection_t *old, *p;
272   subnet_t *subnet;
273   avl_node_t *node, *node2;
274 cp
275   /* Okay, before we active the connection, we check if there is another entry
276      in the connection list with the same name. If so, it presumably is an
277      old connection that has timed out but we don't know it yet.
278    */
279
280   while((old = lookup_id(cl->name)))
281     {
282       if(debug_lvl >= DEBUG_CONNECTIONS)
283         syslog(LOG_NOTICE, _("Removing old entry for %s at %s in favour of new connection from %s"),
284         cl->name, old->hostname, cl->hostname);
285
286       terminate_connection(old);
287     }
288
289   /* Activate this connection */
290
291   cl->allow_request = ALL;
292   cl->status.active = 1;
293   cl->nexthop = cl;
294   cl->cipher_pkttype = EVP_bf_cbc();
295   cl->cipher_pktkeylength = cl->cipher_pkttype->key_len + cl->cipher_pkttype->iv_len;
296
297   if(debug_lvl >= DEBUG_CONNECTIONS)
298     syslog(LOG_NOTICE, _("Connection with %s (%s) activated"), cl->name, cl->hostname);
299
300 cp
301   /* Check some options */
302   
303   if((cfg = get_config_val(cl->config, config_indirectdata)))
304     {
305       if(cfg->data.val == stupid_true)
306         cl->options |= OPTION_INDIRECT;
307     }
308
309   if((cfg = get_config_val(cl->config, config_tcponly)))
310     {
311       if(cfg->data.val == stupid_true)
312         cl->options |= OPTION_TCPONLY;
313     }
314
315   /* Send him our subnets */
316   
317   for(node = myself->subnet_tree->head; node; node = node->next)
318     {
319       subnet = (subnet_t *)node->data;
320       send_add_subnet(cl, subnet);
321     }
322
323   /* And send him all the hosts and their subnets we know... */
324   
325   for(node = connection_tree->head; node; node = node->next)
326     {
327       p = (connection_t *)node->data;
328       
329       if(p != cl && p->status.active)
330         {
331           /* Notify others of this connection */
332
333           if(p->status.meta)
334             send_add_host(p, cl);
335
336           /* Notify new connection of everything we know */
337
338           send_add_host(cl, p);
339
340           for(node2 = p->subnet_tree->head; node2; node2 = node2->next)
341             {
342               subnet = (subnet_t *)node2->data;
343               send_add_subnet(cl, subnet);
344             }
345         }
346     }  
347 cp
348   return 0;
349 }
350
351 int send_challenge(connection_t *cl)
352 {
353   char *buffer;
354   int len, x;
355 cp
356   /* CHECKME: what is most reasonable value for len? */
357
358   len = RSA_size(cl->rsa_key);
359
360   /* Allocate buffers for the challenge */
361
362   buffer = xmalloc(len*2+1);
363
364   if(cl->hischallenge)
365     free(cl->hischallenge);
366     
367   cl->hischallenge = xmalloc(len);
368 cp
369   /* Copy random data to the buffer */
370
371   RAND_bytes(cl->hischallenge, len);
372
373 cp
374   /* Convert to hex */
375
376   bin2hex(cl->hischallenge, buffer, len);
377   buffer[len*2] = '\0';
378
379 cp
380   /* Send the challenge */
381
382   x = send_request(cl, "%d %s", CHALLENGE, buffer);
383   free(buffer);
384 cp
385   return x;
386 }
387
388 int challenge_h(connection_t *cl)
389 {
390   char buffer[MAX_STRING_SIZE];
391   int len;
392 cp
393   if(sscanf(cl->buffer, "%*d "MAX_STRING, buffer) != 1)
394     {
395        syslog(LOG_ERR, _("Got bad CHALLENGE from %s (%s)"), cl->name, cl->hostname);
396        return -1;
397     }
398
399   len = RSA_size(myself->rsa_key);
400
401   /* Check if the length of the challenge is all right */
402
403   if(strlen(buffer) != len*2)
404     {
405       syslog(LOG_ERR, _("Intruder: wrong challenge length from %s (%s)"), cl->name, cl->hostname);
406       return -1;
407     }
408
409   /* Allocate buffers for the challenge */
410
411   if(!cl->mychallenge)
412     cl->mychallenge = xmalloc(len);
413
414   /* Convert the challenge from hexadecimal back to binary */
415
416   hex2bin(buffer,cl->mychallenge,len);
417
418   cl->allow_request = CHAL_REPLY;
419
420   /* Rest is done by send_chal_reply() */
421 cp
422   return send_chal_reply(cl);
423 }
424
425 int send_chal_reply(connection_t *cl)
426 {
427   char hash[SHA_DIGEST_LENGTH*2+1];
428 cp
429   if(!cl->mychallenge)
430     {
431       syslog(LOG_ERR, _("Trying to send CHAL_REPLY to %s (%s) without a valid CHALLENGE"), cl->name, cl->hostname);
432       return -1;
433     }
434      
435   /* Calculate the hash from the challenge we received */
436
437   SHA1(cl->mychallenge, RSA_size(myself->rsa_key), hash);
438
439   /* Convert the hash to a hexadecimal formatted string */
440
441   bin2hex(hash,hash,SHA_DIGEST_LENGTH);
442   hash[SHA_DIGEST_LENGTH*2] = '\0';
443
444   /* Send the reply */
445
446 cp
447   return send_request(cl, "%d %s", CHAL_REPLY, hash);
448 }
449
450 int chal_reply_h(connection_t *cl)
451 {
452   char hishash[MAX_STRING_SIZE];
453   char myhash[SHA_DIGEST_LENGTH];
454 cp
455   if(sscanf(cl->buffer, "%*d "MAX_STRING, hishash) != 1)
456     {
457        syslog(LOG_ERR, _("Got bad CHAL_REPLY from %s (%s)"), cl->name, cl->hostname);
458        return -1;
459     }
460
461   /* Check if the length of the hash is all right */
462
463   if(strlen(hishash) != SHA_DIGEST_LENGTH*2)
464     {
465       syslog(LOG_ERR, _("Intruder: wrong challenge reply length from %s (%s)"), cl->name, cl->hostname);
466       return -1;
467     }
468
469   /* Convert the hash to binary format */
470
471   hex2bin(hishash, hishash, SHA_DIGEST_LENGTH);
472
473   /* Calculate the hash from the challenge we sent */
474
475   SHA1(cl->hischallenge, RSA_size(cl->rsa_key), myhash);
476
477   /* Verify the incoming hash with the calculated hash */
478
479   if(memcmp(hishash, myhash, SHA_DIGEST_LENGTH))
480     {
481       syslog(LOG_ERR, _("Intruder: wrong challenge reply from %s (%s)"), cl->name, cl->hostname);
482       if(debug_lvl >= DEBUG_SCARY_THINGS)
483         {
484           bin2hex(myhash, hishash, SHA_DIGEST_LENGTH);
485           hishash[SHA_DIGEST_LENGTH*2] = '\0';
486           syslog(LOG_DEBUG, _("Expected challenge reply: %s"), hishash);
487         }
488       return -1;
489     }
490
491   /* Identity has now been positively verified.
492      ack_h() handles the rest from now on.
493    */
494 cp
495   return ack_h(cl);
496 }
497
498 int send_metakey(connection_t *cl)
499 {
500   char *buffer;
501   int len, x;
502 cp
503   len = RSA_size(cl->rsa_key);
504
505   /* Allocate buffers for the meta key */
506
507   buffer = xmalloc(len*2+1);
508
509   if(!cl->cipher_outkey)
510     cl->cipher_outkey = xmalloc(len);
511     
512   if(!cl->cipher_outctx)
513     cl->cipher_outctx = xmalloc(sizeof(*cl->cipher_outctx));
514 cp
515   /* Copy random data to the buffer */
516
517   RAND_bytes(cl->cipher_outkey, len);
518
519   /* The message we send must be smaller than the modulus of the RSA key.
520      By definition, for a key of k bits, the following formula holds:
521      
522        2^(k-1) <= modulus < 2^(k)
523      
524      Where ^ means "to the power of", not "xor".
525      This means that to be sure, we must choose our message < 2^(k-1).
526      This can be done by setting the most significant bit to zero.
527   */
528   
529   cl->cipher_outkey[0] &= 0x7F;
530   
531   if(debug_lvl >= DEBUG_SCARY_THINGS)
532     {
533       bin2hex(cl->cipher_outkey, buffer, len);
534       buffer[len*2] = '\0';
535       syslog(LOG_DEBUG, _("Generated random meta key (unencrypted): %s"), buffer);
536     }
537
538   /* Encrypt the random data
539   
540      We do not use one of the PKCS padding schemes here.
541      This is allowed, because we encrypt a totally random string
542      with a length equal to that of the modulus of the RSA key.
543   */
544   
545   if(RSA_public_encrypt(len, cl->cipher_outkey, buffer, cl->rsa_key, RSA_NO_PADDING) != len)
546     {
547       syslog(LOG_ERR, _("Error during encryption of meta key for %s (%s)"), cl->name, cl->hostname);
548       free(buffer);
549       return -1;
550     }
551 cp
552   /* Convert the encrypted random data to a hexadecimal formatted string */
553
554   bin2hex(buffer, buffer, len);
555   buffer[len*2] = '\0';
556
557   /* Send the meta key */
558
559   x = send_request(cl, "%d %s", METAKEY, buffer);
560   free(buffer);
561
562   /* Further outgoing requests are encrypted with the key we just generated */
563
564   EVP_EncryptInit(cl->cipher_outctx, EVP_bf_cfb(),
565                   cl->cipher_outkey + len - EVP_bf_cfb()->key_len,
566                   cl->cipher_outkey + len - EVP_bf_cfb()->key_len - EVP_bf_cfb()->iv_len);
567
568   cl->status.encryptout = 1;
569 cp
570   return x;
571 }
572
573 int metakey_h(connection_t *cl)
574 {
575   char buffer[MAX_STRING_SIZE];
576   int len;
577 cp
578   if(sscanf(cl->buffer, "%*d "MAX_STRING, buffer) != 1)
579     {
580        syslog(LOG_ERR, _("Got bad METAKEY from %s (%s)"), cl->name, cl->hostname);
581        return -1;
582     }
583
584   len = RSA_size(myself->rsa_key);
585
586   /* Check if the length of the meta key is all right */
587
588   if(strlen(buffer) != len*2)
589     {
590       syslog(LOG_ERR, _("Intruder: wrong meta key length from %s (%s)"), cl->name, cl->hostname);
591       return -1;
592     }
593
594   /* Allocate buffers for the meta key */
595
596   if(!cl->cipher_inkey)
597     cl->cipher_inkey = xmalloc(len);
598
599   if(!cl->cipher_inctx)
600     cl->cipher_inctx = xmalloc(sizeof(*cl->cipher_inctx));
601
602   /* Convert the challenge from hexadecimal back to binary */
603
604   hex2bin(buffer,buffer,len);
605
606   /* Decrypt the meta key */
607   
608   if(RSA_private_decrypt(len, buffer, cl->cipher_inkey, myself->rsa_key, RSA_NO_PADDING) != len)        /* See challenge() */
609     {
610       syslog(LOG_ERR, _("Error during encryption of meta key for %s (%s)"), cl->name, cl->hostname);
611       return -1;
612     }
613
614   if(debug_lvl >= DEBUG_SCARY_THINGS)
615     {
616       bin2hex(cl->cipher_inkey, buffer, len);
617       buffer[len*2] = '\0';
618       syslog(LOG_DEBUG, _("Received random meta key (unencrypted): %s"), buffer);
619     }
620
621   /* All incoming requests will now be encrypted. */
622
623   EVP_DecryptInit(cl->cipher_inctx, EVP_bf_cfb(),
624                   cl->cipher_inkey + len - EVP_bf_cfb()->key_len,
625                   cl->cipher_inkey + len - EVP_bf_cfb()->key_len - EVP_bf_cfb()->iv_len);
626   
627   cl->status.decryptin = 1;
628
629   cl->allow_request = CHALLENGE;
630 cp
631   return send_challenge(cl);
632 }
633
634 /* Address and subnet information exchange */
635
636 int send_add_subnet(connection_t *cl, subnet_t *subnet)
637 {
638   int x;
639   char *netstr;
640   char *owner;
641 cp
642   if((cl->options | myself->options | subnet->owner->options) & OPTION_INDIRECT)
643     owner = myself->name;
644   else
645     owner = subnet->owner->name;
646
647   x = send_request(cl, "%d %s %s", ADD_SUBNET,
648                       owner, netstr = net2str(subnet));
649   free(netstr);
650 cp
651   return x;
652 }
653
654 int add_subnet_h(connection_t *cl)
655 {
656   char subnetstr[MAX_STRING_SIZE];
657   char name[MAX_STRING_SIZE];
658   connection_t *owner, *p;
659   subnet_t *subnet;
660   avl_node_t *node;
661 cp
662   if(sscanf(cl->buffer, "%*d "MAX_STRING" "MAX_STRING, name, subnetstr) != 2)
663     {
664       syslog(LOG_ERR, _("Got bad ADD_SUBNET from %s (%s)"), cl->name, cl->hostname);
665       return -1;
666     }
667
668   /* Check if owner name is a valid */
669
670   if(check_id(name))
671     {
672       syslog(LOG_ERR, _("Got bad ADD_SUBNET from %s (%s): invalid identity name"), cl->name, cl->hostname);
673       return -1;
674     }
675
676   /* Check if subnet string is valid */
677
678   if(!(subnet = str2net(subnetstr)))
679     {
680       syslog(LOG_ERR, _("Got bad ADD_SUBNET from %s (%s): invalid subnet string"), cl->name, cl->hostname);
681       return -1;
682     }
683
684   /* Check if somebody tries to add a subnet of ourself */
685
686   if(!strcmp(name, myself->name))
687     {
688       syslog(LOG_ERR, _("Warning: got ADD_SUBNET from %s (%s) for ourself, restarting"),
689              cl->name, cl->hostname);
690       sighup = 1;
691       return 0;
692     }
693
694   /* Check if the owner of the new subnet is in the connection list */
695
696   if(!(owner = lookup_id(name)))
697     {
698       syslog(LOG_ERR, _("Got ADD_SUBNET for %s from %s (%s) which is not in our connection list"),
699              name, cl->name, cl->hostname);
700       return -1;
701     }
702
703   /* If everything is correct, add the subnet to the list of the owner */
704
705   subnet_add(owner, subnet);
706
707   /* Tell the rest */
708   
709   for(node = connection_tree->head; node; node = node->next)
710     {
711       p = (connection_t *)node->data;
712       if(p->status.meta && p->status.active && p!= cl)
713         send_add_subnet(p, subnet);
714     }
715 cp
716   return 0;
717 }
718
719 int send_del_subnet(connection_t *cl, subnet_t *subnet)
720 {
721   int x;
722   char *netstr;
723   char *owner;
724 cp
725   if(cl->options & OPTION_INDIRECT)
726     owner = myself->name;
727   else
728     owner = subnet->owner->name;
729
730   x = send_request(cl, "%d %s %s", DEL_SUBNET, owner, netstr = net2str(subnet));
731   free(netstr);
732 cp
733   return x;
734 }
735
736 int del_subnet_h(connection_t *cl)
737 {
738   char subnetstr[MAX_STRING_SIZE];
739   char name[MAX_STRING_SIZE];
740   connection_t *owner, *p;
741   subnet_t *subnet;
742   avl_node_t *node;
743 cp
744   if(sscanf(cl->buffer, "%*d "MAX_STRING" "MAX_STRING, name, subnetstr) != 3)
745     {
746       syslog(LOG_ERR, _("Got bad DEL_SUBNET from %s (%s)"), cl->name, cl->hostname);
747       return -1;
748     }
749
750   /* Check if owner name is a valid */
751
752   if(check_id(name))
753     {
754       syslog(LOG_ERR, _("Got bad DEL_SUBNET from %s (%s): invalid identity name"), cl->name, cl->hostname);
755       return -1;
756     }
757
758   /* Check if subnet string is valid */
759
760   if(!(subnet = str2net(subnetstr)))
761     {
762       syslog(LOG_ERR, _("Got bad DEL_SUBNET from %s (%s): invalid subnet string"), cl->name, cl->hostname);
763       return -1;
764     }
765
766   free(subnetstr);
767   
768   /* Check if somebody tries to add a subnet of ourself */
769
770   if(!strcmp(name, myself->name))
771     {
772       syslog(LOG_ERR, _("Warning: got DEL_SUBNET from %s (%s) for ourself, restarting"),
773              cl->name, cl->hostname);
774       sighup = 1;
775       return 0;
776     }
777
778   /* Check if the owner of the new subnet is in the connection list */
779
780   if(!(owner = lookup_id(name)))
781     {
782       syslog(LOG_ERR, _("Got DEL_SUBNET for %s from %s (%s) which is not in our connection list"),
783              name, cl->name, cl->hostname);
784       return -1;
785     }
786
787   /* If everything is correct, delete the subnet from the list of the owner */
788
789   subnet_del(subnet);
790
791   /* Tell the rest */
792   
793   for(node = connection_tree->head; node; node = node->next)
794     {
795       p = (connection_t *)node->data;
796       if(p->status.meta && p->status.active && p!= cl)
797         send_del_subnet(p, subnet);
798     }
799 cp
800   return 0;
801 }
802
803 /* New and closed connections notification */
804
805 int send_add_host(connection_t *cl, connection_t *other)
806 {
807 cp
808   if(!((cl->options | myself->options | other->options) & OPTION_INDIRECT))
809     return send_request(cl, "%d %s %lx:%d %lx", ADD_HOST,
810                       other->name, other->address, other->port, other->options);
811   else
812     return 0;
813 }
814
815 int add_host_h(connection_t *cl)
816 {
817   connection_t *old, *new, *p;
818   char name[MAX_STRING_SIZE];
819   avl_node_t *node;
820 cp
821   new = new_connection();
822
823   if(sscanf(cl->buffer, "%*d "MAX_STRING" %lx:%hd %lx", name, &new->address, &new->port, &new->options) != 4)
824     {
825        syslog(LOG_ERR, _("Got bad ADD_HOST from %s (%s)"), cl->name, cl->hostname);
826        return -1;
827     }
828
829   /* Check if identity is a valid name */
830
831   if(check_id(name))
832     {
833       syslog(LOG_ERR, _("Got bad ADD_HOST from %s (%s): invalid identity name"), cl->name, cl->hostname);
834       free_connection(new);
835       return -1;
836     }
837
838   /* Check if somebody tries to add ourself */
839
840   if(!strcmp(name, myself->name))
841     {
842       syslog(LOG_ERR, _("Warning: got ADD_HOST from %s (%s) for ourself, restarting"), cl->name, cl->hostname);
843       sighup = 1;
844       free_connection(new);
845       return 0;
846     }
847     
848   /* Fill in more of the new connection structure */
849
850   new->hostname = hostlookup(htonl(new->address));
851
852   /* Check if the new host already exists in the connnection list */
853
854   if((old = lookup_id(name)))
855     {
856       if((new->address == old->address) && (new->port == old->port))
857         {
858           if(debug_lvl >= DEBUG_CONNECTIONS)
859             syslog(LOG_NOTICE, _("Got duplicate ADD_HOST for %s (%s) from %s (%s)"),
860                    old->name, old->hostname, name, new->hostname);
861           free_connection(new);
862           return 0;
863         }
864       else
865         {
866           if(debug_lvl >= DEBUG_CONNECTIONS)
867             syslog(LOG_NOTICE, _("Removing old entry for %s (%s) in favour of new connection"),
868                    old->name, old->hostname);
869
870           terminate_connection(old);
871         }
872     }
873
874   /* Hook it up into the connection */
875
876   new->name = xstrdup(name);
877   connection_add(new);
878   id_add(new);
879
880   /* Tell the rest about the new host */
881
882   for(node = connection_tree->head; node; node = node->next)
883     {
884       p = (connection_t *)node->data;
885       if(p->status.meta && p->status.active && p!=cl)
886         send_add_host(p, new);
887     }
888
889   /* Fill in rest of connection structure */
890
891   new->nexthop = cl;
892   new->status.active = 1;
893   new->cipher_pkttype = EVP_bf_cbc();
894   new->cipher_pktkeylength = cl->cipher_pkttype->key_len + cl->cipher_pkttype->iv_len;
895 cp
896   return 0;
897 }
898
899 int send_del_host(connection_t *cl, connection_t *other)
900 {
901 cp
902   if(!((cl->options | myself->options) & OPTION_INDIRECT))
903     return send_request(cl, "%d %s %lx:%d %lx", DEL_HOST,
904                       other->name, other->address, other->port, other->options);
905   else
906     return 0;
907 }
908
909 int del_host_h(connection_t *cl)
910 {
911   char name[MAX_STRING_SIZE];
912   ipv4_t address;
913   port_t port;
914   long int options;
915   connection_t *old, *p;
916   avl_node_t *node;
917 cp
918   if(sscanf(cl->buffer, "%*d "MAX_STRING" %lx:%hd %lx", name, &address, &port, &options) != 4)
919     {
920       syslog(LOG_ERR, _("Got bad DEL_HOST from %s (%s)"),
921              cl->name, cl->hostname);
922       return -1;
923     }
924
925   /* Check if identity is a valid name */
926
927   if(check_id(name))
928     {
929       syslog(LOG_ERR, _("Got bad DEL_HOST from %s (%s): invalid identity name"), cl->name, cl->hostname);
930       return -1;
931     }
932
933   /* Check if somebody tries to delete ourself */
934
935   if(!strcmp(name, myself->name))
936     {
937       syslog(LOG_ERR, _("Warning: got DEL_HOST from %s (%s) for ourself, restarting"),
938              cl->name, cl->hostname);
939       sighup = 1;
940       return 0;
941     }
942
943   /* Check if the new host already exists in the connnection list */
944
945   if(!(old = lookup_id(name)))
946     {
947       syslog(LOG_ERR, _("Got DEL_HOST from %s (%s) for %s which is not in our connection list"),
948              name, cl->name, cl->hostname);
949       return -1;
950     }
951   
952   /* Check if the rest matches */
953   
954   if(address!=old->address || port!=old->port || options!=old->options || cl!=old->nexthop)
955     {
956       syslog(LOG_WARNING, _("Got DEL_HOST from %s (%s) for %s which doesn't match"), cl->name, cl->hostname, old->name);
957       return 0;
958     }
959
960   /* Ok, since EVERYTHING seems to check out all right, delete it */
961
962   old->status.active = 0;
963   terminate_connection(old);
964
965   /* Tell the rest about the new host */
966
967   for(node = connection_tree->head; node; node = node->next)
968     {
969       p = (connection_t *)node->data;
970       if(p->status.meta && p->status.active && p!=cl)
971         send_del_host(p, old);
972     }
973 cp
974   return 0;
975 }
976
977 /* Status and error notification routines */
978
979 int send_status(connection_t *cl, int statusno, char *statusstring)
980 {
981 cp
982   if(!statusstring)
983     statusstring = status_text[statusno];
984 cp
985   return send_request(cl, "%d %d %s", STATUS, statusno, statusstring);
986 }
987
988 int status_h(connection_t *cl)
989 {
990   int statusno;
991   char statusstring[MAX_STRING_SIZE];
992 cp
993   if(sscanf(cl->buffer, "%*d %d "MAX_STRING, &statusno, statusstring) != 2)
994     {
995        syslog(LOG_ERR, _("Got bad STATUS from %s (%s)"),
996               cl->name, cl->hostname);
997        return -1;
998     }
999
1000   if(debug_lvl >= DEBUG_STATUS)
1001     {
1002       syslog(LOG_NOTICE, _("Status message from %s (%s): %s: %s"),
1003              cl->name, cl->hostname, status_text[statusno], statusstring);
1004     }
1005
1006 cp
1007   return 0;
1008 }
1009
1010 int send_error(connection_t *cl, int err, char *errstring)
1011 {
1012 cp
1013   if(!errstring)
1014     errstring = strerror(err);
1015   return send_request(cl, "%d %d %s", ERROR, err, errstring);
1016 }
1017
1018 int error_h(connection_t *cl)
1019 {
1020   int err;
1021   char errorstring[MAX_STRING_SIZE];
1022 cp
1023   if(sscanf(cl->buffer, "%*d %d "MAX_STRING, &err, errorstring) != 2)
1024     {
1025        syslog(LOG_ERR, _("Got bad ERROR from %s (%s)"),
1026               cl->name, cl->hostname);
1027        return -1;
1028     }
1029
1030   if(debug_lvl >= DEBUG_ERROR)
1031     {
1032       syslog(LOG_NOTICE, _("Error message from %s (%s): %s: %s"),
1033              cl->name, cl->hostname, strerror(err), errorstring);
1034     }
1035
1036   terminate_connection(cl);
1037 cp
1038   return 0;
1039 }
1040
1041 int send_termreq(connection_t *cl)
1042 {
1043 cp
1044   return send_request(cl, "%d", TERMREQ);
1045 }
1046
1047 int termreq_h(connection_t *cl)
1048 {
1049 cp
1050   terminate_connection(cl);
1051 cp
1052   return 0;
1053 }
1054
1055 int send_ping(connection_t *cl)
1056 {
1057   char salt[SALTLEN*2+1];
1058 cp
1059   cl->status.pinged = 1;
1060   cl->last_ping_time = time(NULL);
1061   RAND_bytes(salt, SALTLEN);
1062   bin2hex(salt, salt, SALTLEN);
1063   salt[SALTLEN*2] = '\0';
1064 cp
1065   return send_request(cl, "%d %s", PING, salt);
1066 }
1067
1068 int ping_h(connection_t *cl)
1069 {
1070 cp
1071   return send_pong(cl);
1072 }
1073
1074 int send_pong(connection_t *cl)
1075 {
1076   char salt[SALTLEN*2+1];
1077 cp
1078   RAND_bytes(salt, SALTLEN);
1079   bin2hex(salt, salt, SALTLEN);
1080   salt[SALTLEN*2] = '\0';
1081 cp
1082   return send_request(cl, "%d %s", PONG, salt);
1083 }
1084
1085 int pong_h(connection_t *cl)
1086 {
1087 cp
1088   cl->status.pinged = 0;
1089 cp
1090   return 0;
1091 }
1092
1093 /* Key exchange */
1094
1095 int send_key_changed(connection_t *from, connection_t *cl)
1096 {
1097   connection_t *p;
1098   avl_node_t *node;
1099 cp
1100   /* Only send this message if some other daemon requested our key previously.
1101      This reduces unnecessary key_changed broadcasts.
1102   */
1103
1104   if(mykeyused)
1105     {
1106       for(node = connection_tree->head; node; node = node->next)
1107         {
1108           p = (connection_t *)node->data;
1109           if(p != cl && p->status.meta && p->status.active)
1110             if(!(p->options & OPTION_INDIRECT) || from == myself)
1111               send_request(p, "%d %s", KEY_CHANGED, from->name);
1112         }
1113     mykeyused = 0;
1114   }
1115 cp
1116   return 0;
1117 }
1118
1119 int key_changed_h(connection_t *cl)
1120 {
1121   char from_id[MAX_STRING_SIZE];
1122   connection_t *from;
1123 cp
1124   if(sscanf(cl->buffer, "%*d "MAX_STRING, from_id) != 1)
1125     {
1126       syslog(LOG_ERR, _("Got bad KEY_CHANGED from %s (%s)"),
1127              cl->name, cl->hostname);
1128       return -1;
1129     }
1130
1131   if(!(from = lookup_id(from_id)))
1132     {
1133       syslog(LOG_ERR, _("Got KEY_CHANGED from %s (%s) origin %s which does not exist in our connection list"),
1134              cl->name, cl->hostname, from_id);
1135       return -1;
1136     }
1137
1138   from->status.validkey = 0;
1139   from->status.waitingforkey = 0;
1140
1141   if(!(from->options | cl->options | myself->options) & OPTION_INDIRECT)
1142     send_key_changed(from, cl);
1143 cp
1144   return 0;
1145 }
1146
1147 int send_req_key(connection_t *from, connection_t *to)
1148 {
1149 cp
1150   return send_request(to->nexthop, "%d %s %s", REQ_KEY,
1151                       from->name, to->name);
1152 }
1153
1154 int req_key_h(connection_t *cl)
1155 {
1156   char from_id[MAX_STRING_SIZE];
1157   char to_id[MAX_STRING_SIZE];
1158   connection_t *from, *to;
1159   char pktkey[129];
1160 cp
1161   if(sscanf(cl->buffer, "%*d "MAX_STRING" "MAX_STRING, from_id, to_id) != 2)
1162     {
1163        syslog(LOG_ERR, _("Got bad REQ_KEY from %s (%s)"),
1164               cl->name, cl->hostname);
1165        return -1;
1166     }
1167
1168   if(!(from = lookup_id(from_id)))
1169     {
1170       syslog(LOG_ERR, _("Got REQ_KEY from %s (%s) origin %s which does not exist in our connection list"),
1171              cl->name, cl->hostname, from_id);
1172       return -1;
1173     }
1174
1175   /* Check if this key request is for us */
1176
1177   if(!strcmp(to_id, myself->name))      /* Yes, send our own key back */
1178     {
1179       bin2hex(myself->cipher_pktkey, pktkey, myself->cipher_pktkeylength);
1180       pktkey[myself->cipher_pktkeylength*2] = '\0';
1181       send_ans_key(myself, from, pktkey);
1182       mykeyused = 1;
1183     }
1184   else
1185     {
1186       if(!(to = lookup_id(to_id)))
1187         {
1188           syslog(LOG_ERR, _("Got REQ_KEY from %s (%s) destination %s which does not exist in our connection list"),
1189                  cl->name, cl->hostname, to_id);
1190           return -1;
1191         }
1192         
1193       if(to->status.validkey)   /* Proxy keys */
1194         {
1195           bin2hex(to->cipher_pktkey, pktkey, to->cipher_pktkeylength);
1196           pktkey[to->cipher_pktkeylength*2] = '\0';
1197           send_ans_key(to, from, pktkey);
1198         }
1199       else
1200         send_req_key(from, to);
1201     }
1202
1203 cp
1204   return 0;
1205 }
1206
1207 int send_ans_key(connection_t *from, connection_t *to, char *pktkey)
1208 {
1209 cp
1210   return send_request(to->nexthop, "%d %s %s %s", ANS_KEY,
1211                       from->name, to->name, pktkey);
1212 }
1213
1214 int ans_key_h(connection_t *cl)
1215 {
1216   char from_id[MAX_STRING_SIZE];
1217   char to_id[MAX_STRING_SIZE];
1218   char pktkey[MAX_STRING_SIZE];
1219   int keylength;
1220   connection_t *from, *to;
1221 cp
1222   if(sscanf(cl->buffer, "%*d "MAX_STRING" "MAX_STRING" "MAX_STRING, from_id, to_id, pktkey) != 3)
1223     {
1224        syslog(LOG_ERR, _("Got bad ANS_KEY from %s (%s)"),
1225               cl->name, cl->hostname);
1226        return -1;
1227     }
1228
1229   if(!(from = lookup_id(from_id)))
1230     {
1231       syslog(LOG_ERR, _("Got ANS_KEY from %s (%s) origin %s which does not exist in our connection list"),
1232              cl->name, cl->hostname, from_id);
1233       return -1;
1234     }
1235
1236   /* Check correctness of packet key */
1237
1238   keylength = strlen(pktkey);
1239
1240   if(keylength != from->cipher_pktkeylength*2)
1241     {
1242       syslog(LOG_ERR, _("Got bad ANS_KEY from %s (%s) origin %s: invalid key length"),
1243              cl->name, cl->hostname, from->name);
1244       return -1;
1245     }
1246
1247   /* Forward it if necessary */
1248
1249   if(strcmp(to_id, myself->name))
1250     {
1251       if(!(to = lookup_id(to_id)))
1252         {
1253           syslog(LOG_ERR, _("Got ANS_KEY from %s (%s) destination %s which does not exist in our connection list"),
1254                  cl->name, cl->hostname, to_id);
1255           return -1;
1256         }
1257       send_ans_key(from, to, pktkey);
1258     }
1259
1260   /* Update our copy of the origin's packet key */
1261
1262   if(from->cipher_pktkey)
1263     free(from->cipher_pktkey);
1264
1265   from->cipher_pktkey = xstrdup(pktkey);
1266   keylength /= 2;
1267   hex2bin(from->cipher_pktkey, from->cipher_pktkey, keylength);
1268   from->cipher_pktkey[keylength] = '\0';
1269
1270   from->status.validkey = 1;
1271   from->status.waitingforkey = 0;
1272   
1273   flush_queue(from);
1274 cp
1275   return 0;
1276 }
1277
1278 int send_tcppacket(connection_t *cl, vpn_packet_t *packet)
1279 {
1280   int x;
1281 cp  
1282   /* Evil hack. */
1283
1284   x = send_request(cl->nexthop, "%d %hd", PACKET, packet->len);
1285
1286   if(x)
1287     return x;
1288 cp
1289   return send_meta(cl, packet->data, packet->len);
1290 }
1291
1292 int tcppacket_h(connection_t *cl)
1293 {
1294   short int len;
1295 cp  
1296   if(sscanf(cl->buffer, "%*d %hd", &len) != 1)
1297     {
1298       syslog(LOG_ERR, _("Got bad PACKET from %s (%s)"), cl->name, cl->hostname);
1299       return -1;
1300     }
1301
1302   /* Set reqlen to len, this will tell receive_meta() that a tcppacket is coming. */
1303
1304   cl->tcplen = len;
1305 cp
1306   return 0;
1307 }
1308
1309 /* Jumptable for the request handlers */
1310
1311 int (*request_handlers[])(connection_t*) = {
1312   id_h, metakey_h, challenge_h, chal_reply_h,
1313   status_h, error_h, termreq_h,
1314   ping_h, pong_h,
1315   add_host_h, del_host_h,
1316   add_subnet_h, del_subnet_h,
1317   key_changed_h, req_key_h, ans_key_h,
1318   tcppacket_h,
1319 };
1320
1321 /* Request names */
1322
1323 char (*request_name[]) = {
1324   "ID", "METAKEY", "CHALLENGE", "CHAL_REPLY",
1325   "STATUS", "ERROR", "TERMREQ",
1326   "PING", "PONG",
1327   "ADD_HOST", "DEL_HOST",
1328   "ADD_SUBNET", "DEL_SUBNET",
1329   "KEY_CHANGED", "REQ_KEY", "ANS_KEY",
1330   "PACKET",
1331 };
1332
1333 /* Status strings */
1334
1335 char (*status_text[]) = {
1336   "Warning",
1337 };
1338
1339 /* Error strings */
1340
1341 char (*error_text[]) = {
1342   "Error",
1343 };