22a956151f03a520e49f10ffbe6d7af9e068f61d
[tinc] / src / net_setup.c
1 /*
2     net_setup.c -- Setup.
3     Copyright (C) 1998-2005 Ivo Timmermans,
4                   2000-2006 Guus Sliepen <guus@tinc-vpn.org>
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$
21 */
22
23 #include "system.h"
24
25 #include <openssl/pem.h>
26 #include <openssl/rsa.h>
27 #include <openssl/rand.h>
28 #include <openssl/err.h>
29 #include <openssl/evp.h>
30
31 #include "avl_tree.h"
32 #include "conf.h"
33 #include "connection.h"
34 #include "device.h"
35 #include "graph.h"
36 #include "logger.h"
37 #include "net.h"
38 #include "netutl.h"
39 #include "process.h"
40 #include "protocol.h"
41 #include "route.h"
42 #include "subnet.h"
43 #include "utils.h"
44 #include "xalloc.h"
45
46 char *myport;
47 static struct event device_ev;
48
49 bool read_rsa_public_key(connection_t *c)
50 {
51         FILE *fp;
52         char *fname;
53         char *key;
54
55         cp();
56
57         if(!c->rsa_key) {
58                 c->rsa_key = RSA_new();
59 //              RSA_blinding_on(c->rsa_key, NULL);
60         }
61
62         /* First, check for simple PublicKey statement */
63
64         if(get_config_string(lookup_config(c->config_tree, "PublicKey"), &key)) {
65                 BN_hex2bn(&c->rsa_key->n, key);
66                 BN_hex2bn(&c->rsa_key->e, "FFFF");
67                 free(key);
68                 return true;
69         }
70
71         /* Else, check for PublicKeyFile statement and read it */
72
73         if(get_config_string(lookup_config(c->config_tree, "PublicKeyFile"), &fname)) {
74                 fp = fopen(fname, "r");
75
76                 if(!fp) {
77                         logger(LOG_ERR, _("Error reading RSA public key file `%s': %s"),
78                                    fname, strerror(errno));
79                         free(fname);
80                         return false;
81                 }
82
83                 free(fname);
84                 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
85                 fclose(fp);
86
87                 if(c->rsa_key)
88                         return true;            /* Woohoo. */
89
90                 /* If it fails, try PEM_read_RSA_PUBKEY. */
91                 fp = fopen(fname, "r");
92
93                 if(!fp) {
94                         logger(LOG_ERR, _("Error reading RSA public key file `%s': %s"),
95                                    fname, strerror(errno));
96                         free(fname);
97                         return false;
98                 }
99
100                 free(fname);
101                 c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
102                 fclose(fp);
103
104                 if(c->rsa_key) {
105 //                              RSA_blinding_on(c->rsa_key, NULL);
106                         return true;
107                 }
108
109                 logger(LOG_ERR, _("Reading RSA public key file `%s' failed: %s"),
110                            fname, strerror(errno));
111                 return false;
112         }
113
114         /* Else, check if a harnessed public key is in the config file */
115
116         asprintf(&fname, "%s/hosts/%s", confbase, c->name);
117         fp = fopen(fname, "r");
118
119         if(fp) {
120                 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
121                 fclose(fp);
122         }
123
124         free(fname);
125
126         if(c->rsa_key)
127                 return true;
128
129         /* Try again with PEM_read_RSA_PUBKEY. */
130
131         asprintf(&fname, "%s/hosts/%s", confbase, c->name);
132         fp = fopen(fname, "r");
133
134         if(fp) {
135                 c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
136 //              RSA_blinding_on(c->rsa_key, NULL);
137                 fclose(fp);
138         }
139
140         free(fname);
141
142         if(c->rsa_key)
143                 return true;
144
145         logger(LOG_ERR, _("No public key for %s specified!"), c->name);
146
147         return false;
148 }
149
150 bool read_rsa_private_key(void)
151 {
152         FILE *fp;
153         char *fname, *key, *pubkey;
154         struct stat s;
155
156         cp();
157
158         if(get_config_string(lookup_config(config_tree, "PrivateKey"), &key)) {
159                 if(!get_config_string(lookup_config(myself->connection->config_tree, "PublicKey"), &pubkey)) {
160                         logger(LOG_ERR, _("PrivateKey used but no PublicKey found!"));
161                         return false;
162                 }
163                 myself->connection->rsa_key = RSA_new();
164 //              RSA_blinding_on(myself->connection->rsa_key, NULL);
165                 BN_hex2bn(&myself->connection->rsa_key->d, key);
166                 BN_hex2bn(&myself->connection->rsa_key->n, pubkey);
167                 BN_hex2bn(&myself->connection->rsa_key->e, "FFFF");
168                 free(key);
169                 free(pubkey);
170                 return true;
171         }
172
173         if(!get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname))
174                 asprintf(&fname, "%s/rsa_key.priv", confbase);
175
176         fp = fopen(fname, "r");
177
178         if(!fp) {
179                 logger(LOG_ERR, _("Error reading RSA private key file `%s': %s"),
180                            fname, strerror(errno));
181                 free(fname);
182                 return false;
183         }
184
185 #if !defined(HAVE_MINGW) && !defined(HAVE_CYGWIN)
186         if(fstat(fileno(fp), &s)) {
187                 logger(LOG_ERR, _("Could not stat RSA private key file `%s': %s'"),
188                                 fname, strerror(errno));
189                 free(fname);
190                 return false;
191         }
192
193         if(s.st_mode & ~0100700)
194                 logger(LOG_WARNING, _("Warning: insecure file permissions for RSA private key file `%s'!"), fname);
195 #endif
196
197         myself->connection->rsa_key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
198         fclose(fp);
199
200         if(!myself->connection->rsa_key) {
201                 logger(LOG_ERR, _("Reading RSA private key file `%s' failed: %s"),
202                            fname, strerror(errno));
203                 free(fname);
204                 return false;
205         }
206
207         free(fname);
208         return true;
209 }
210
211 static struct event keyexpire_event;
212
213 static void keyexpire_handler(int fd, short events, void *data) {
214         regenerate_key();
215 }
216
217 void regenerate_key() {
218         RAND_pseudo_bytes((unsigned char *)myself->key, myself->keylength);
219
220         if(timeout_initialized(&keyexpire_event)) {
221                 ifdebug(STATUS) logger(LOG_INFO, _("Regenerating symmetric key"));
222                 event_del(&keyexpire_event);
223                 send_key_changed(broadcast, myself);
224         } else {
225                 timeout_set(&keyexpire_event, keyexpire_handler, NULL);
226         }
227
228         event_add(&keyexpire_event, &(struct timeval){keylifetime, 0});
229
230         if(myself->cipher) {
231                 EVP_CIPHER_CTX_init(&packet_ctx);
232                 if(!EVP_DecryptInit_ex(&packet_ctx, myself->cipher, NULL, (unsigned char *)myself->key, (unsigned char *)myself->key + myself->cipher->key_len)) {
233                         logger(LOG_ERR, _("Error during initialisation of cipher for %s (%s): %s"),
234                                         myself->name, myself->hostname, ERR_error_string(ERR_get_error(), NULL));
235                         abort();
236                 }
237
238         }
239 }
240
241 /*
242   Configure node_t myself and set up the local sockets (listen only)
243 */
244 bool setup_myself(void)
245 {
246         config_t *cfg;
247         subnet_t *subnet;
248         char *name, *hostname, *mode, *afname, *cipher, *digest;
249         char *address = NULL;
250         char *envp[5];
251         struct addrinfo *ai, *aip, hint = {0};
252         bool choice;
253         int i, err;
254
255         cp();
256
257         myself = new_node();
258         myself->connection = new_connection();
259         init_configuration(&myself->connection->config_tree);
260
261         asprintf(&myself->hostname, _("MYSELF"));
262         asprintf(&myself->connection->hostname, _("MYSELF"));
263
264         myself->connection->options = 0;
265         myself->connection->protocol_version = PROT_CURRENT;
266
267         if(!get_config_string(lookup_config(config_tree, "Name"), &name)) {     /* Not acceptable */
268                 logger(LOG_ERR, _("Name for tinc daemon required!"));
269                 return false;
270         }
271
272         if(!check_id(name)) {
273                 logger(LOG_ERR, _("Invalid name for myself!"));
274                 free(name);
275                 return false;
276         }
277
278         myself->name = name;
279         myself->connection->name = xstrdup(name);
280
281         if(!read_connection_config(myself->connection)) {
282                 logger(LOG_ERR, _("Cannot open host configuration file for myself!"));
283                 return false;
284         }
285
286         if(!read_rsa_private_key())
287                 return false;
288
289         if(!get_config_string(lookup_config(myself->connection->config_tree, "Port"), &myport))
290                 asprintf(&myport, "655");
291
292         /* Read in all the subnets specified in the host configuration file */
293
294         cfg = lookup_config(myself->connection->config_tree, "Subnet");
295
296         while(cfg) {
297                 if(!get_config_subnet(cfg, &subnet))
298                         return false;
299
300                 subnet_add(myself, subnet);
301
302                 cfg = lookup_config_next(myself->connection->config_tree, cfg);
303         }
304
305         /* Check some options */
306
307         if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice) && choice)
308                 myself->options |= OPTION_INDIRECT;
309
310         if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice) && choice)
311                 myself->options |= OPTION_TCPONLY;
312
313         if(get_config_bool(lookup_config(myself->connection->config_tree, "IndirectData"), &choice) && choice)
314                 myself->options |= OPTION_INDIRECT;
315
316         if(get_config_bool(lookup_config(myself->connection->config_tree, "TCPOnly"), &choice) && choice)
317                 myself->options |= OPTION_TCPONLY;
318
319         if(get_config_bool(lookup_config(myself->connection->config_tree, "PMTUDiscovery"), &choice) && choice)
320                 myself->options |= OPTION_PMTU_DISCOVERY;
321
322         if(myself->options & OPTION_TCPONLY)
323                 myself->options |= OPTION_INDIRECT;
324
325         get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
326
327         if(get_config_string(lookup_config(config_tree, "Mode"), &mode)) {
328                 if(!strcasecmp(mode, "router"))
329                         routing_mode = RMODE_ROUTER;
330                 else if(!strcasecmp(mode, "switch"))
331                         routing_mode = RMODE_SWITCH;
332                 else if(!strcasecmp(mode, "hub"))
333                         routing_mode = RMODE_HUB;
334                 else {
335                         logger(LOG_ERR, _("Invalid routing mode!"));
336                         return false;
337                 }
338                 free(mode);
339         } else
340                 routing_mode = RMODE_ROUTER;
341
342         get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
343
344 #if !defined(SOL_IP) || !defined(IP_TOS)
345         if(priorityinheritance)
346                 logger(LOG_WARNING, _("PriorityInheritance not supported on this platform"));
347 #endif
348
349         if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire))
350                 macexpire = 600;
351
352         if(get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout)) {
353                 if(maxtimeout <= 0) {
354                         logger(LOG_ERR, _("Bogus maximum timeout!"));
355                         return false;
356                 }
357         } else
358                 maxtimeout = 900;
359
360         if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
361                 if(!strcasecmp(afname, "IPv4"))
362                         addressfamily = AF_INET;
363                 else if(!strcasecmp(afname, "IPv6"))
364                         addressfamily = AF_INET6;
365                 else if(!strcasecmp(afname, "any"))
366                         addressfamily = AF_UNSPEC;
367                 else {
368                         logger(LOG_ERR, _("Invalid address family!"));
369                         return false;
370                 }
371                 free(afname);
372         }
373
374         get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
375
376         /* Generate packet encryption key */
377
378         if(get_config_string
379            (lookup_config(myself->connection->config_tree, "Cipher"), &cipher)) {
380                 if(!strcasecmp(cipher, "none")) {
381                         myself->cipher = NULL;
382                 } else {
383                         myself->cipher = EVP_get_cipherbyname(cipher);
384
385                         if(!myself->cipher) {
386                                 logger(LOG_ERR, _("Unrecognized cipher type!"));
387                                 return false;
388                         }
389                 }
390         } else
391                 myself->cipher = EVP_bf_cbc();
392
393         if(myself->cipher)
394                 myself->keylength = myself->cipher->key_len + myself->cipher->iv_len;
395         else
396                 myself->keylength = 1;
397
398         myself->connection->outcipher = EVP_bf_ofb();
399
400         myself->key = xmalloc(myself->keylength);
401
402         if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
403                 keylifetime = 3600;
404
405         regenerate_key();
406         /* Check if we want to use message authentication codes... */
407
408         if(get_config_string
409            (lookup_config(myself->connection->config_tree, "Digest"), &digest)) {
410                 if(!strcasecmp(digest, "none")) {
411                         myself->digest = NULL;
412                 } else {
413                         myself->digest = EVP_get_digestbyname(digest);
414
415                         if(!myself->digest) {
416                                 logger(LOG_ERR, _("Unrecognized digest type!"));
417                                 return false;
418                         }
419                 }
420         } else
421                 myself->digest = EVP_sha1();
422
423         myself->connection->outdigest = EVP_sha1();
424
425         if(get_config_int(lookup_config(myself->connection->config_tree, "MACLength"),
426                 &myself->maclength)) {
427                 if(myself->digest) {
428                         if(myself->maclength > myself->digest->md_size) {
429                                 logger(LOG_ERR, _("MAC length exceeds size of digest!"));
430                                 return false;
431                         } else if(myself->maclength < 0) {
432                                 logger(LOG_ERR, _("Bogus MAC length!"));
433                                 return false;
434                         }
435                 }
436         } else
437                 myself->maclength = 4;
438
439         myself->connection->outmaclength = 0;
440
441         /* Compression */
442
443         if(get_config_int(lookup_config(myself->connection->config_tree, "Compression"),
444                 &myself->compression)) {
445                 if(myself->compression < 0 || myself->compression > 11) {
446                         logger(LOG_ERR, _("Bogus compression level!"));
447                         return false;
448                 }
449         } else
450                 myself->compression = 0;
451
452         myself->connection->outcompression = 0;
453
454         /* Done */
455
456         myself->nexthop = myself;
457         myself->via = myself;
458         myself->status.reachable = true;
459         node_add(myself);
460
461         graph();
462
463         /* Open device */
464
465         if(!setup_device())
466                 return false;
467
468         event_set(&device_ev, device_fd, EV_READ|EV_PERSIST,
469                           handle_device_data, NULL);
470         if (event_add(&device_ev, NULL) < 0) {
471                 logger(LOG_ERR, _("event_add failed: %s"), strerror(errno));
472                 close_device();
473                 return false;
474         }
475
476         /* Run tinc-up script to further initialize the tap interface */
477         asprintf(&envp[0], "NETNAME=%s", netname ? : "");
478         asprintf(&envp[1], "DEVICE=%s", device ? : "");
479         asprintf(&envp[2], "INTERFACE=%s", iface ? : "");
480         asprintf(&envp[3], "NAME=%s", myself->name);
481         envp[4] = NULL;
482
483         execute_script("tinc-up", envp);
484
485         for(i = 0; i < 5; i++)
486                 free(envp[i]);
487
488         /* Run subnet-up scripts for our own subnets */
489
490         subnet_update(myself, NULL, true);
491
492         /* Open sockets */
493
494         get_config_string(lookup_config(config_tree, "BindToAddress"), &address);
495
496         hint.ai_family = addressfamily;
497         hint.ai_socktype = SOCK_STREAM;
498         hint.ai_protocol = IPPROTO_TCP;
499         hint.ai_flags = AI_PASSIVE;
500
501         err = getaddrinfo(address, myport, &hint, &ai);
502
503         if(err || !ai) {
504                 logger(LOG_ERR, _("System call `%s' failed: %s"), "getaddrinfo",
505                            gai_strerror(err));
506                 return false;
507         }
508
509         listen_sockets = 0;
510
511         for(aip = ai; aip; aip = aip->ai_next) {
512                 listen_socket[listen_sockets].tcp =
513                         setup_listen_socket((sockaddr_t *) aip->ai_addr);
514
515                 if(listen_socket[listen_sockets].tcp < 0)
516                         continue;
517
518                 listen_socket[listen_sockets].udp =
519                         setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
520
521                 if(listen_socket[listen_sockets].udp < 0) {
522                         close(listen_socket[listen_sockets].tcp);
523                         continue;
524                 }
525
526                 event_set(&listen_socket[listen_sockets].ev_tcp,
527                                   listen_socket[listen_sockets].tcp,
528                                   EV_READ|EV_PERSIST,
529                                   handle_new_meta_connection, NULL);
530                 if(event_add(&listen_socket[listen_sockets].ev_tcp, NULL) < 0) {
531                         logger(LOG_WARNING, _("event_add failed: %s"), strerror(errno));
532                         close(listen_socket[listen_sockets].tcp);
533                         close(listen_socket[listen_sockets].udp);
534                         continue;
535                 }
536
537                 event_set(&listen_socket[listen_sockets].ev_udp,
538                                   listen_socket[listen_sockets].udp,
539                                   EV_READ|EV_PERSIST,
540                                   handle_incoming_vpn_data, NULL);
541                 if(event_add(&listen_socket[listen_sockets].ev_udp, NULL) < 0) {
542                         logger(LOG_WARNING, _("event_add failed: %s"), strerror(errno));
543                         close(listen_socket[listen_sockets].tcp);
544                         close(listen_socket[listen_sockets].udp);
545                         event_del(&listen_socket[listen_sockets].ev_tcp);
546                         continue;
547                 }
548
549                 ifdebug(CONNECTIONS) {
550                         hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
551                         logger(LOG_NOTICE, _("Listening on %s"), hostname);
552                         free(hostname);
553                 }
554
555                 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
556                 listen_sockets++;
557
558                 if(listen_sockets >= MAXSOCKETS) {
559                         logger(LOG_WARNING, _("Maximum of %d listening sockets reached"), MAXSOCKETS);
560                         break;
561                 }
562         }
563
564         freeaddrinfo(ai);
565
566         if(listen_sockets)
567                 logger(LOG_NOTICE, _("Ready"));
568         else {
569                 logger(LOG_ERR, _("Unable to create any listening socket!"));
570                 return false;
571         }
572
573         return true;
574 }
575
576 /*
577   setup all initial network connections
578 */
579 bool setup_network_connections(void)
580 {
581         cp();
582
583         init_connections();
584         init_subnets();
585         init_nodes();
586         init_edges();
587         init_requests();
588
589         if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
590                 if(pinginterval < 1) {
591                         pinginterval = 86400;
592                 }
593         } else
594                 pinginterval = 60;
595
596         if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
597                 pingtimeout = 5;
598         if(pingtimeout < 1 || pingtimeout > pinginterval)
599                 pingtimeout = pinginterval;
600
601         if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize))
602                 maxoutbufsize = 4 * MTU;
603
604         if(!setup_myself())
605                 return false;
606
607         try_outgoing_connections();
608
609         return true;
610 }
611
612 /*
613   close all open network connections
614 */
615 void close_network_connections(void)
616 {
617         avl_node_t *node, *next;
618         connection_t *c;
619         char *envp[5];
620         int i;
621
622         cp();
623
624         for(node = connection_tree->head; node; node = next) {
625                 next = node->next;
626                 c = node->data;
627
628                 if(c->outgoing) {
629                         if(c->outgoing->ai)
630                                 freeaddrinfo(c->outgoing->ai);
631                         free(c->outgoing->name);
632                         free(c->outgoing);
633                         c->outgoing = NULL;
634                 }
635
636                 terminate_connection(c, false);
637         }
638
639         if(myself && myself->connection) {
640                 subnet_update(myself, NULL, false);
641                 terminate_connection(myself->connection, false);
642         }
643
644         for(i = 0; i < listen_sockets; i++) {
645                 event_del(&listen_socket[i].ev_tcp);
646                 event_del(&listen_socket[i].ev_udp);
647                 close(listen_socket[i].tcp);
648                 close(listen_socket[i].udp);
649         }
650
651         asprintf(&envp[0], "NETNAME=%s", netname ? : "");
652         asprintf(&envp[1], "DEVICE=%s", device ? : "");
653         asprintf(&envp[2], "INTERFACE=%s", iface ? : "");
654         asprintf(&envp[3], "NAME=%s", myself->name);
655         envp[4] = NULL;
656
657         exit_requests();
658         exit_edges();
659         exit_subnets();
660         exit_nodes();
661         exit_connections();
662
663         execute_script("tinc-down", envp);
664
665         for(i = 0; i < 4; i++)
666                 free(envp[i]);
667
668         close_device();
669
670         return;
671 }