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