52300632ad2286b923b60a7fa0d417d4e9d84c3a
[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.90 2001/05/25 08:36:11 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   len++;
110
111   if(debug_lvl >= DEBUG_PROTOCOL)
112     syslog(LOG_DEBUG, _("Sending %s to %s (%s)"), request_name[request], cl->name, cl->hostname);
113
114 cp
115   return send_meta(cl, buffer, len);
116 }
117
118 int receive_request(connection_t *cl)
119 {
120   int request;
121 cp  
122   if(sscanf(cl->buffer, "%d", &request) == 1)
123     {
124       if((request < 0) || (request >= LAST) || (request_handlers[request] == NULL))
125         {
126           syslog(LOG_ERR, _("Unknown request from %s (%s)"),
127                  cl->name, cl->hostname);
128           return -1;
129         }
130       else
131         {
132           if(debug_lvl >= DEBUG_PROTOCOL)
133             syslog(LOG_DEBUG, _("Got %s from %s (%s)"),
134                    request_name[request], cl->name, cl->hostname);
135         }
136
137       if((cl->allow_request != ALL) && (cl->allow_request != request))
138         {
139           syslog(LOG_ERR, _("Unauthorized request from %s (%s)"), cl->name, cl->hostname);
140           return -1;
141         }
142
143       if(request_handlers[request](cl))
144         /* Something went wrong. Probably scriptkiddies. Terminate. */
145         {
146           syslog(LOG_ERR, _("Error while processing %s from %s (%s)"),
147                  request_name[request], cl->name, cl->hostname);
148           return -1;
149         }
150     }
151   else
152     {
153       syslog(LOG_ERR, _("Bogus data received from %s (%s)"),
154              cl->name, cl->hostname);
155       return -1;
156     }
157 cp
158   return 0;
159 }
160
161 /* Connection protocol:
162
163    Client               Server
164    send_id(u)
165                         send_challenge(R)
166    send_chal_reply(H)
167                         send_id(u)
168    send_challenge(R)
169                         send_chal_reply(H)
170    ---------------------------------------
171    send_metakey(R)
172                         send_metakey(R)
173    ---------------------------------------
174    send_ack(u)
175                         send_ack(u)
176    ---------------------------------------
177    Other requests(E)...
178
179    (u) Unencrypted,
180    (R) RSA,
181    (H) SHA1,
182    (E) Encrypted with symmetric cipher.
183
184    Part of the challenge is directly used to set the symmetric cipher
185    key and the initial vector.  Since a man-in-the-middle cannot
186    decrypt the RSA challenges, this means that he cannot get or forge
187    the key for the symmetric cipher.
188 */
189
190 int send_id(connection_t *cl)
191 {
192 cp
193   return send_request(cl, "%d %s %d %lx %hd", ID, myself->name, myself->protocol_version, myself->options, myself->port);
194 }
195
196 int id_h(connection_t *cl)
197 {
198   connection_t *old;
199   unsigned short int port;
200   char name[MAX_STRING_SIZE];
201   avl_node_t *node;
202 cp
203   if(sscanf(cl->buffer, "%*d "MAX_STRING" %d %lx %hd", name, &cl->protocol_version, &cl->options, &port) != 4)
204     {
205        syslog(LOG_ERR, _("Got bad ID from %s"), cl->hostname);
206        return -1;
207     }
208
209   /* Check if version matches */
210
211   if(cl->protocol_version != myself->protocol_version)
212     {
213       syslog(LOG_ERR, _("Peer %s (%s) uses incompatible version %d"),
214              cl->name, cl->hostname, cl->protocol_version);
215       return -1;
216     }
217
218   /* Check if identity is a valid name */
219
220   if(check_id(name))
221     {
222       syslog(LOG_ERR, _("Peer %s uses invalid identity name"), cl->hostname);
223       return -1;
224     }
225   
226   /* Copy string to cl */
227   
228   cl->name = xstrdup(name);
229
230   /* Load information about peer */
231
232   if(read_host_config(cl))
233     {
234       syslog(LOG_ERR, _("Peer %s had unknown identity (%s)"), cl->hostname, cl->name);
235       return -1;
236     }
237
238   /* First check if the host we connected to is already in our
239      connection list. If so, we are probably making a loop, which
240      is not desirable.
241    */
242
243   if(cl->status.outgoing)
244     {
245       if((old = lookup_id(cl->name)))
246         {
247           if(debug_lvl >= DEBUG_CONNECTIONS)
248             syslog(LOG_NOTICE, _("Uplink %s (%s) is already in our connection list"), cl->name, cl->hostname);
249           cl->status.outgoing = 0;
250           old->status.outgoing = 1;
251           terminate_connection(cl);
252           return 0;
253         }
254     }
255     
256   /* Now we can add the name to the id tree */
257   
258   id_add(cl);
259
260   /* And uhr... cl->port just changed so we have to unlink it from the connection tree and re-insert... */
261   
262   node = avl_unlink(connection_tree, cl);
263   cl->port = port;
264   avl_insert_node(connection_tree, node);
265
266   /* Read in the public key, so that we can send a metakey */
267
268   if(read_rsa_public_key(cl))
269     return -1;
270
271   cl->allow_request = METAKEY;
272 cp
273   return send_metakey(cl);
274 }
275
276 int ack_h(connection_t *cl)
277 {
278   config_t const *cfg;
279   connection_t *old, *p;
280   subnet_t *subnet;
281   avl_node_t *node, *node2;
282 cp
283   /* Okay, before we active the connection, we check if there is another entry
284      in the connection list with the same name. If so, it presumably is an
285      old connection that has timed out but we don't know it yet.
286    */
287
288   while((old = lookup_id(cl->name)))
289     {
290       if(debug_lvl >= DEBUG_CONNECTIONS)
291         syslog(LOG_NOTICE, _("Removing old entry for %s at %s in favour of new connection from %s"),
292         cl->name, old->hostname, cl->hostname);
293
294       terminate_connection(old);
295     }
296
297   /* Activate this connection */
298
299   cl->allow_request = ALL;
300   cl->status.active = 1;
301   cl->nexthop = cl;
302   cl->cipher_pkttype = EVP_bf_cbc();
303   cl->cipher_pktkeylength = cl->cipher_pkttype->key_len + cl->cipher_pkttype->iv_len;
304
305   if(debug_lvl >= DEBUG_CONNECTIONS)
306     syslog(LOG_NOTICE, _("Connection with %s (%s) activated"), cl->name, cl->hostname);
307
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(mykeyused)
1113     {
1114       for(node = connection_tree->head; node; node = node->next)
1115         {
1116           p = (connection_t *)node->data;
1117           if(p != cl && p->status.meta && p->status.active)
1118             if(!(p->options & OPTION_INDIRECT) || from == myself)
1119               send_request(p, "%d %s", KEY_CHANGED, from->name);
1120         }
1121     mykeyused = 0;
1122   }
1123 cp
1124   return 0;
1125 }
1126
1127 int key_changed_h(connection_t *cl)
1128 {
1129   char from_id[MAX_STRING_SIZE];
1130   connection_t *from;
1131 cp
1132   if(sscanf(cl->buffer, "%*d "MAX_STRING, from_id) != 1)
1133     {
1134       syslog(LOG_ERR, _("Got bad KEY_CHANGED from %s (%s)"),
1135              cl->name, cl->hostname);
1136       return -1;
1137     }
1138
1139   if(!(from = lookup_id(from_id)))
1140     {
1141       syslog(LOG_ERR, _("Got KEY_CHANGED from %s (%s) origin %s which does not exist in our connection list"),
1142              cl->name, cl->hostname, from_id);
1143       return -1;
1144     }
1145
1146   from->status.validkey = 0;
1147   from->status.waitingforkey = 0;
1148
1149   if(!(from->options | cl->options | myself->options) & OPTION_INDIRECT)
1150     send_key_changed(from, cl);
1151 cp
1152   return 0;
1153 }
1154
1155 int send_req_key(connection_t *from, connection_t *to)
1156 {
1157 cp
1158   return send_request(to->nexthop, "%d %s %s", REQ_KEY,
1159                       from->name, to->name);
1160 }
1161
1162 int req_key_h(connection_t *cl)
1163 {
1164   char from_id[MAX_STRING_SIZE];
1165   char to_id[MAX_STRING_SIZE];
1166   connection_t *from, *to;
1167   char pktkey[129];
1168 cp
1169   if(sscanf(cl->buffer, "%*d "MAX_STRING" "MAX_STRING, from_id, to_id) != 2)
1170     {
1171        syslog(LOG_ERR, _("Got bad REQ_KEY from %s (%s)"),
1172               cl->name, cl->hostname);
1173        return -1;
1174     }
1175
1176   if(!(from = lookup_id(from_id)))
1177     {
1178       syslog(LOG_ERR, _("Got REQ_KEY from %s (%s) origin %s which does not exist in our connection list"),
1179              cl->name, cl->hostname, from_id);
1180       return -1;
1181     }
1182
1183   /* Check if this key request is for us */
1184
1185   if(!strcmp(to_id, myself->name))      /* Yes, send our own key back */
1186     {
1187       bin2hex(myself->cipher_pktkey, pktkey, myself->cipher_pktkeylength);
1188       pktkey[myself->cipher_pktkeylength*2] = '\0';
1189       send_ans_key(myself, from, pktkey);
1190       mykeyused = 1;
1191     }
1192   else
1193     {
1194       if(!(to = lookup_id(to_id)))
1195         {
1196           syslog(LOG_ERR, _("Got REQ_KEY from %s (%s) destination %s which does not exist in our connection list"),
1197                  cl->name, cl->hostname, to_id);
1198           return -1;
1199         }
1200         
1201       if(to->status.validkey)   /* Proxy keys */
1202         {
1203           bin2hex(to->cipher_pktkey, pktkey, to->cipher_pktkeylength);
1204           pktkey[to->cipher_pktkeylength*2] = '\0';
1205           send_ans_key(to, from, pktkey);
1206         }
1207       else
1208         send_req_key(from, to);
1209     }
1210
1211 cp
1212   return 0;
1213 }
1214
1215 int send_ans_key(connection_t *from, connection_t *to, char *pktkey)
1216 {
1217 cp
1218   return send_request(to->nexthop, "%d %s %s %s", ANS_KEY,
1219                       from->name, to->name, pktkey);
1220 }
1221
1222 int ans_key_h(connection_t *cl)
1223 {
1224   char from_id[MAX_STRING_SIZE];
1225   char to_id[MAX_STRING_SIZE];
1226   char pktkey[MAX_STRING_SIZE];
1227   int keylength;
1228   connection_t *from, *to;
1229 cp
1230   if(sscanf(cl->buffer, "%*d "MAX_STRING" "MAX_STRING" "MAX_STRING, from_id, to_id, pktkey) != 3)
1231     {
1232        syslog(LOG_ERR, _("Got bad ANS_KEY from %s (%s)"),
1233               cl->name, cl->hostname);
1234        return -1;
1235     }
1236
1237   if(!(from = lookup_id(from_id)))
1238     {
1239       syslog(LOG_ERR, _("Got ANS_KEY from %s (%s) origin %s which does not exist in our connection list"),
1240              cl->name, cl->hostname, from_id);
1241       return -1;
1242     }
1243
1244   /* Check correctness of packet key */
1245
1246   keylength = strlen(pktkey);
1247
1248   if(keylength != from->cipher_pktkeylength*2)
1249     {
1250       syslog(LOG_ERR, _("Got bad ANS_KEY from %s (%s) origin %s: invalid key length"),
1251              cl->name, cl->hostname, from->name);
1252       return -1;
1253     }
1254
1255   /* Forward it if necessary */
1256
1257   if(strcmp(to_id, myself->name))
1258     {
1259       if(!(to = lookup_id(to_id)))
1260         {
1261           syslog(LOG_ERR, _("Got ANS_KEY from %s (%s) destination %s which does not exist in our connection list"),
1262                  cl->name, cl->hostname, to_id);
1263           return -1;
1264         }
1265       send_ans_key(from, to, pktkey);
1266     }
1267
1268   /* Update our copy of the origin's packet key */
1269
1270   if(from->cipher_pktkey)
1271     free(from->cipher_pktkey);
1272
1273   from->cipher_pktkey = xstrdup(pktkey);
1274   keylength /= 2;
1275   hex2bin(from->cipher_pktkey, from->cipher_pktkey, keylength);
1276   from->cipher_pktkey[keylength] = '\0';
1277
1278   from->status.validkey = 1;
1279   from->status.waitingforkey = 0;
1280   
1281   flush_queue(from);
1282 cp
1283   return 0;
1284 }
1285
1286 int send_tcppacket(connection_t *cl, vpn_packet_t *packet)
1287 {
1288   int x;
1289 cp  
1290   x = send_request(cl->nexthop, "%d %hd", PACKET, packet->len);
1291
1292   if(x)
1293     return x;
1294   
1295   return send_meta(cl->nexthop, packet->data, packet->len);  
1296 }
1297
1298 int tcppacket_h(connection_t *cl)
1299 {
1300   vpn_packet_t packet;
1301   char *p;
1302   int todo, x;
1303 cp  
1304   if(sscanf(cl->buffer, "%*d %hd", &packet.len) != 1)
1305     {
1306       syslog(LOG_ERR, _("Got bad PACKET from %s (%s)"), cl->name, cl->hostname);
1307       return -1;
1308     }
1309
1310   /* Evil hack. */
1311
1312   p = packet.data;
1313   todo = packet.len;
1314
1315   while(todo)
1316     {
1317       x = read(cl->meta_socket, p, todo);
1318
1319       if(x<=0)
1320         {
1321           if(x==0)
1322             syslog(LOG_NOTICE, _("Connection closed by %s (%s)"), cl->name, cl->hostname);
1323           else
1324             if(errno==EINTR || errno==EAGAIN)   /* FIXME: select() or poll() or reimplement this evil hack */
1325               continue;
1326             else
1327               syslog(LOG_ERR, _("Error during reception of PACKET from %s (%s): %m"), cl->name, cl->hostname);
1328
1329           return -1;
1330         }
1331       
1332       todo -= x;
1333       p += x;
1334     }
1335
1336   receive_packet(cl, &packet);
1337 cp
1338   return 0;
1339 }
1340
1341 /* Jumptable for the request handlers */
1342
1343 int (*request_handlers[])(connection_t*) = {
1344   id_h, metakey_h, challenge_h, chal_reply_h,
1345   status_h, error_h, termreq_h,
1346   ping_h, pong_h,
1347   add_host_h, del_host_h,
1348   add_subnet_h, del_subnet_h,
1349   key_changed_h, req_key_h, ans_key_h,
1350   tcppacket_h,
1351 };
1352
1353 /* Request names */
1354
1355 char (*request_name[]) = {
1356   "ID", "METAKEY", "CHALLENGE", "CHAL_REPLY",
1357   "STATUS", "ERROR", "TERMREQ",
1358   "PING", "PONG",
1359   "ADD_HOST", "DEL_HOST",
1360   "ADD_SUBNET", "DEL_SUBNET",
1361   "KEY_CHANGED", "REQ_KEY", "ANS_KEY",
1362   "PACKET",
1363 };
1364
1365 /* Status strings */
1366
1367 char (*status_text[]) = {
1368   "Warning",
1369 };
1370
1371 /* Error strings */
1372
1373 char (*error_text[]) = {
1374   "Error",
1375 };