Only send key_changed if it was previously requested.
[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.89 2001/05/24 21:52:26 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 cp
1072   return send_request(cl, "%d %s", PING, salt);
1073 }
1074
1075 int ping_h(connection_t *cl)
1076 {
1077 cp
1078   return send_pong(cl);
1079 }
1080
1081 int send_pong(connection_t *cl)
1082 {
1083   char salt[SALTLEN*2+1];
1084 cp
1085   RAND_bytes(salt, SALTLEN);
1086   bin2hex(salt, salt, SALTLEN);
1087 cp
1088   return send_request(cl, "%d %s", PONG, salt);
1089 }
1090
1091 int pong_h(connection_t *cl)
1092 {
1093 cp
1094   cl->status.pinged = 0;
1095 cp
1096   return 0;
1097 }
1098
1099 /* Key exchange */
1100
1101 int send_key_changed(connection_t *from, connection_t *cl)
1102 {
1103   connection_t *p;
1104   avl_node_t *node;
1105 cp
1106   /* Only send this message if some other daemon requested our key previously.
1107      This reduces unnecessary key_changed broadcasts.
1108   */
1109
1110   if(mykeyused)
1111     {
1112       for(node = connection_tree->head; node; node = node->next)
1113         {
1114           p = (connection_t *)node->data;
1115           if(p != cl && p->status.meta && p->status.active)
1116             if(!(p->options & OPTION_INDIRECT) || from == myself)
1117               send_request(p, "%d %s", KEY_CHANGED, from->name);
1118         }
1119     mykeyused = 0;
1120   }
1121 cp
1122   return 0;
1123 }
1124
1125 int key_changed_h(connection_t *cl)
1126 {
1127   char from_id[MAX_STRING_SIZE];
1128   connection_t *from;
1129 cp
1130   if(sscanf(cl->buffer, "%*d "MAX_STRING, from_id) != 1)
1131     {
1132       syslog(LOG_ERR, _("Got bad KEY_CHANGED from %s (%s)"),
1133              cl->name, cl->hostname);
1134       return -1;
1135     }
1136
1137   if(!(from = lookup_id(from_id)))
1138     {
1139       syslog(LOG_ERR, _("Got KEY_CHANGED from %s (%s) origin %s which does not exist in our connection list"),
1140              cl->name, cl->hostname, from_id);
1141       return -1;
1142     }
1143
1144   from->status.validkey = 0;
1145   from->status.waitingforkey = 0;
1146
1147   if(!(from->options | cl->options | myself->options) & OPTION_INDIRECT)
1148     send_key_changed(from, cl);
1149 cp
1150   return 0;
1151 }
1152
1153 int send_req_key(connection_t *from, connection_t *to)
1154 {
1155 cp
1156   return send_request(to->nexthop, "%d %s %s", REQ_KEY,
1157                       from->name, to->name);
1158 }
1159
1160 int req_key_h(connection_t *cl)
1161 {
1162   char from_id[MAX_STRING_SIZE];
1163   char to_id[MAX_STRING_SIZE];
1164   connection_t *from, *to;
1165   char pktkey[129];
1166 cp
1167   if(sscanf(cl->buffer, "%*d "MAX_STRING" "MAX_STRING, from_id, to_id) != 2)
1168     {
1169        syslog(LOG_ERR, _("Got bad REQ_KEY from %s (%s)"),
1170               cl->name, cl->hostname);
1171        return -1;
1172     }
1173
1174   if(!(from = lookup_id(from_id)))
1175     {
1176       syslog(LOG_ERR, _("Got REQ_KEY from %s (%s) origin %s which does not exist in our connection list"),
1177              cl->name, cl->hostname, from_id);
1178       return -1;
1179     }
1180
1181   /* Check if this key request is for us */
1182
1183   if(!strcmp(to_id, myself->name))      /* Yes, send our own key back */
1184     {
1185       bin2hex(myself->cipher_pktkey, pktkey, myself->cipher_pktkeylength);
1186       pktkey[myself->cipher_pktkeylength*2] = '\0';
1187       send_ans_key(myself, from, pktkey);
1188       mykeyused = 1;
1189     }
1190   else
1191     {
1192       if(!(to = lookup_id(to_id)))
1193         {
1194           syslog(LOG_ERR, _("Got REQ_KEY from %s (%s) destination %s which does not exist in our connection list"),
1195                  cl->name, cl->hostname, to_id);
1196           return -1;
1197         }
1198         
1199       if(to->status.validkey)   /* Proxy keys */
1200         {
1201           bin2hex(to->cipher_pktkey, pktkey, to->cipher_pktkeylength);
1202           pktkey[to->cipher_pktkeylength*2] = '\0';
1203           send_ans_key(to, from, pktkey);
1204         }
1205       else
1206         send_req_key(from, to);
1207     }
1208
1209 cp
1210   return 0;
1211 }
1212
1213 int send_ans_key(connection_t *from, connection_t *to, char *pktkey)
1214 {
1215 cp
1216   return send_request(to->nexthop, "%d %s %s %s", ANS_KEY,
1217                       from->name, to->name, pktkey);
1218 }
1219
1220 int ans_key_h(connection_t *cl)
1221 {
1222   char from_id[MAX_STRING_SIZE];
1223   char to_id[MAX_STRING_SIZE];
1224   char pktkey[MAX_STRING_SIZE];
1225   int keylength;
1226   connection_t *from, *to;
1227 cp
1228   if(sscanf(cl->buffer, "%*d "MAX_STRING" "MAX_STRING" "MAX_STRING, from_id, to_id, pktkey) != 3)
1229     {
1230        syslog(LOG_ERR, _("Got bad ANS_KEY from %s (%s)"),
1231               cl->name, cl->hostname);
1232        return -1;
1233     }
1234
1235   if(!(from = lookup_id(from_id)))
1236     {
1237       syslog(LOG_ERR, _("Got ANS_KEY from %s (%s) origin %s which does not exist in our connection list"),
1238              cl->name, cl->hostname, from_id);
1239       return -1;
1240     }
1241
1242   /* Check correctness of packet key */
1243
1244   keylength = strlen(pktkey);
1245
1246   if(keylength != from->cipher_pktkeylength*2)
1247     {
1248       syslog(LOG_ERR, _("Got bad ANS_KEY from %s (%s) origin %s: invalid key length"),
1249              cl->name, cl->hostname, from->name);
1250       return -1;
1251     }
1252
1253   /* Forward it if necessary */
1254
1255   if(strcmp(to_id, myself->name))
1256     {
1257       if(!(to = lookup_id(to_id)))
1258         {
1259           syslog(LOG_ERR, _("Got ANS_KEY from %s (%s) destination %s which does not exist in our connection list"),
1260                  cl->name, cl->hostname, to_id);
1261           return -1;
1262         }
1263       send_ans_key(from, to, pktkey);
1264     }
1265
1266   /* Update our copy of the origin's packet key */
1267
1268   if(from->cipher_pktkey)
1269     free(from->cipher_pktkey);
1270
1271   from->cipher_pktkey = xstrdup(pktkey);
1272   keylength /= 2;
1273   hex2bin(from->cipher_pktkey, from->cipher_pktkey, keylength);
1274   from->cipher_pktkey[keylength] = '\0';
1275
1276   from->status.validkey = 1;
1277   from->status.waitingforkey = 0;
1278   
1279   flush_queue(from);
1280 cp
1281   return 0;
1282 }
1283
1284 int send_tcppacket(connection_t *cl, vpn_packet_t *packet)
1285 {
1286   int x;
1287 cp  
1288   x = send_request(cl->nexthop, "%d %hd", PACKET, packet->len);
1289
1290   if(x)
1291     return x;
1292   
1293   return send_meta(cl->nexthop, packet->data, packet->len);  
1294 }
1295
1296 int tcppacket_h(connection_t *cl)
1297 {
1298   vpn_packet_t packet;
1299   char *p;
1300   int todo, x;
1301 cp  
1302   if(sscanf(cl->buffer, "%*d %hd", &packet.len) != 1)
1303     {
1304       syslog(LOG_ERR, _("Got bad PACKET from %s (%s)"), cl->name, cl->hostname);
1305       return -1;
1306     }
1307
1308   /* Evil hack. */
1309
1310   p = packet.data;
1311   todo = packet.len;
1312
1313   while(todo)
1314     {
1315       x = read(cl->meta_socket, p, todo);
1316
1317       if(x<=0)
1318         {
1319           if(x==0)
1320             syslog(LOG_NOTICE, _("Connection closed by %s (%s)"), cl->name, cl->hostname);
1321           else
1322             if(errno==EINTR || errno==EAGAIN)   /* FIXME: select() or poll() or reimplement this evil hack */
1323               continue;
1324             else
1325               syslog(LOG_ERR, _("Error during reception of PACKET from %s (%s): %m"), cl->name, cl->hostname);
1326
1327           return -1;
1328         }
1329       
1330       todo -= x;
1331       p += x;
1332     }
1333
1334   receive_packet(cl, &packet);
1335 cp
1336   return 0;
1337 }
1338
1339 /* Jumptable for the request handlers */
1340
1341 int (*request_handlers[])(connection_t*) = {
1342   id_h, metakey_h, challenge_h, chal_reply_h,
1343   status_h, error_h, termreq_h,
1344   ping_h, pong_h,
1345   add_host_h, del_host_h,
1346   add_subnet_h, del_subnet_h,
1347   key_changed_h, req_key_h, ans_key_h,
1348   tcppacket_h,
1349 };
1350
1351 /* Request names */
1352
1353 char (*request_name[]) = {
1354   "ID", "METAKEY", "CHALLENGE", "CHAL_REPLY",
1355   "STATUS", "ERROR", "TERMREQ",
1356   "PING", "PONG",
1357   "ADD_HOST", "DEL_HOST",
1358   "ADD_SUBNET", "DEL_SUBNET",
1359   "KEY_CHANGED", "REQ_KEY", "ANS_KEY",
1360   "PACKET",
1361 };
1362
1363 /* Status strings */
1364
1365 char (*status_text[]) = {
1366   "Warning",
1367 };
1368
1369 /* Error strings */
1370
1371 char (*error_text[]) = {
1372   "Error",
1373 };