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