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