Require OpenSSL 1.1.0 or later.
[tinc] / src / net_setup.c
1 /*
2     net_setup.c -- Setup.
3     Copyright (C) 1998-2005 Ivo Timmermans,
4                   2000-2017 Guus Sliepen <guus@tinc-vpn.org>
5                   2006      Scott Lamb <slamb@slamb.org>
6                   2010      Brandon Black <blblack@gmail.com>
7
8     This program is free software; you can redistribute it and/or modify
9     it under the terms of the GNU General Public License as published by
10     the Free Software Foundation; either version 2 of the License, or
11     (at your option) any later version.
12
13     This program is distributed in the hope that it will be useful,
14     but WITHOUT ANY WARRANTY; without even the implied warranty of
15     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16     GNU General Public License for more details.
17
18     You should have received a copy of the GNU General Public License along
19     with this program; if not, write to the Free Software Foundation, Inc.,
20     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
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 #include <openssl/bn.h>
31
32 #include "avl_tree.h"
33 #include "conf.h"
34 #include "connection.h"
35 #include "device.h"
36 #include "event.h"
37 #include "graph.h"
38 #include "logger.h"
39 #include "net.h"
40 #include "netutl.h"
41 #include "process.h"
42 #include "protocol.h"
43 #include "proxy.h"
44 #include "route.h"
45 #include "subnet.h"
46 #include "utils.h"
47 #include "xalloc.h"
48
49 char *myport;
50 devops_t devops;
51
52 bool read_rsa_public_key(connection_t *c) {
53         FILE *fp;
54         char *pubname;
55         char *hcfname;
56         char *key;
57         BIGNUM *n = NULL;
58         BIGNUM *e = NULL;
59
60         if(!c->rsa_key) {
61                 c->rsa_key = RSA_new();
62 //              RSA_blinding_on(c->rsa_key, NULL);
63         }
64
65         /* First, check for simple PublicKey statement */
66
67         if(get_config_string(lookup_config(c->config_tree, "PublicKey"), &key)) {
68                 if((size_t)BN_hex2bn(&n, key) != strlen(key)) {
69                         free(key);
70                         logger(LOG_ERR, "Invalid PublicKey for %s!", c->name);
71                         return false;
72                 }
73
74                 free(key);
75                 BN_hex2bn(&e, "FFFF");
76
77                 if(!n || !e || RSA_set0_key(c->rsa_key, n, e, NULL) != 1) {
78                         BN_free(e);
79                         BN_free(n);
80                         logger(LOG_ERR, "RSA_set0_key() failed with PublicKey for %s!", c->name);
81                         return false;
82                 }
83
84                 return true;
85         }
86
87         /* Else, check for PublicKeyFile statement and read it */
88
89         if(get_config_string(lookup_config(c->config_tree, "PublicKeyFile"), &pubname)) {
90                 fp = fopen(pubname, "r");
91
92                 if(!fp) {
93                         logger(LOG_ERR, "Error reading RSA public key file `%s': %s", pubname, strerror(errno));
94                         free(pubname);
95                         return false;
96                 }
97
98                 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
99                 fclose(fp);
100
101                 if(c->rsa_key) {
102                         free(pubname);
103                         return true;            /* Woohoo. */
104                 }
105
106                 /* If it fails, try PEM_read_RSA_PUBKEY. */
107                 fp = fopen(pubname, "r");
108
109                 if(!fp) {
110                         logger(LOG_ERR, "Error reading RSA public key file `%s': %s", pubname, strerror(errno));
111                         free(pubname);
112                         return false;
113                 }
114
115                 c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
116                 fclose(fp);
117
118                 if(c->rsa_key) {
119 //                              RSA_blinding_on(c->rsa_key, NULL);
120                         free(pubname);
121                         return true;
122                 }
123
124                 logger(LOG_ERR, "Reading RSA public key file `%s' failed: %s", pubname, strerror(errno));
125                 free(pubname);
126                 return false;
127         }
128
129         /* Else, check if a harnessed public key is in the config file */
130
131         xasprintf(&hcfname, "%s/hosts/%s", confbase, c->name);
132         fp = fopen(hcfname, "r");
133
134         if(!fp) {
135                 logger(LOG_ERR, "Error reading RSA public key file `%s': %s", hcfname, strerror(errno));
136                 free(hcfname);
137                 return false;
138         }
139
140         c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
141         fclose(fp);
142
143         if(c->rsa_key) {
144                 free(hcfname);
145                 return true;
146         }
147
148         /* Try again with PEM_read_RSA_PUBKEY. */
149
150         fp = fopen(hcfname, "r");
151
152         if(!fp) {
153                 logger(LOG_ERR, "Error reading RSA public key file `%s': %s", hcfname, strerror(errno));
154                 free(hcfname);
155                 return false;
156         }
157
158         free(hcfname);
159         c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
160 //      RSA_blinding_on(c->rsa_key, NULL);
161         fclose(fp);
162
163         if(c->rsa_key) {
164                 return true;
165         }
166
167         logger(LOG_ERR, "No public key for %s specified!", c->name);
168
169         return false;
170 }
171
172 static bool read_rsa_private_key(void) {
173         FILE *fp;
174         char *fname, *key, *pubkey;
175         BIGNUM *n = NULL;
176         BIGNUM *e = NULL;
177         BIGNUM *d = NULL;
178
179         if(get_config_string(lookup_config(config_tree, "PrivateKey"), &key)) {
180                 myself->connection->rsa_key = RSA_new();
181
182 //              RSA_blinding_on(myself->connection->rsa_key, NULL);
183                 if((size_t)BN_hex2bn(&d, key) != strlen(key)) {
184                         logger(LOG_ERR, "Invalid PrivateKey for myself!");
185                         free(key);
186                         return false;
187                 }
188
189                 free(key);
190
191                 if(!get_config_string(lookup_config(config_tree, "PublicKey"), &pubkey)) {
192                         BN_free(d);
193                         logger(LOG_ERR, "PrivateKey used but no PublicKey found!");
194                         return false;
195                 }
196
197                 if((size_t)BN_hex2bn(&n, pubkey) != strlen(pubkey)) {
198                         free(pubkey);
199                         BN_free(d);
200                         logger(LOG_ERR, "Invalid PublicKey for myself!");
201                         return false;
202                 }
203
204                 free(pubkey);
205                 BN_hex2bn(&e, "FFFF");
206
207                 if(!n || !e || !d || RSA_set0_key(myself->connection->rsa_key, n, e, d) != 1) {
208                         BN_free(d);
209                         BN_free(e);
210                         BN_free(n);
211                         logger(LOG_ERR, "RSA_set0_key() failed with PrivateKey for myself!");
212                         return false;
213                 }
214
215                 return true;
216         }
217
218         if(!get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname)) {
219                 xasprintf(&fname, "%s/rsa_key.priv", confbase);
220         }
221
222         fp = fopen(fname, "r");
223
224         if(!fp) {
225                 logger(LOG_ERR, "Error reading RSA private key file `%s': %s",
226                        fname, strerror(errno));
227                 free(fname);
228                 return false;
229         }
230
231 #if !defined(HAVE_MINGW) && !defined(HAVE_CYGWIN)
232         struct stat s;
233
234         if(!fstat(fileno(fp), &s)) {
235                 if(s.st_mode & ~0100700) {
236                         logger(LOG_WARNING, "Warning: insecure file permissions for RSA private key file `%s'!", fname);
237                 }
238         } else {
239                 logger(LOG_WARNING, "Could not stat RSA private key file `%s': %s'", fname, strerror(errno));
240         }
241
242 #endif
243
244         myself->connection->rsa_key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
245         fclose(fp);
246
247         if(!myself->connection->rsa_key) {
248                 logger(LOG_ERR, "Reading RSA private key file `%s' failed: %s",
249                        fname, strerror(errno));
250                 free(fname);
251                 return false;
252         }
253
254         free(fname);
255         return true;
256 }
257
258 /*
259   Read Subnets from all host config files
260 */
261 void load_all_subnets(void) {
262         DIR *dir;
263         struct dirent *ent;
264         char *dname;
265         char *fname;
266         avl_tree_t *config_tree;
267         config_t *cfg;
268         subnet_t *s, *s2;
269         node_t *n;
270
271         xasprintf(&dname, "%s/hosts", confbase);
272         dir = opendir(dname);
273
274         if(!dir) {
275                 logger(LOG_ERR, "Could not open %s: %s", dname, strerror(errno));
276                 free(dname);
277                 return;
278         }
279
280         while((ent = readdir(dir))) {
281                 if(!check_id(ent->d_name)) {
282                         continue;
283                 }
284
285                 n = lookup_node(ent->d_name);
286 #ifdef _DIRENT_HAVE_D_TYPE
287                 //if(ent->d_type != DT_REG)
288                 //      continue;
289 #endif
290
291                 xasprintf(&fname, "%s/hosts/%s", confbase, ent->d_name);
292                 init_configuration(&config_tree);
293                 read_config_options(config_tree, ent->d_name);
294                 read_config_file(config_tree, fname);
295                 free(fname);
296
297                 if(!n) {
298                         n = new_node();
299                         n->name = xstrdup(ent->d_name);
300                         node_add(n);
301                 }
302
303                 for(cfg = lookup_config(config_tree, "Subnet"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
304                         if(!get_config_subnet(cfg, &s)) {
305                                 continue;
306                         }
307
308                         if((s2 = lookup_subnet(n, s))) {
309                                 s2->expires = -1;
310                         } else {
311                                 subnet_add(n, s);
312                         }
313                 }
314
315                 exit_configuration(&config_tree);
316         }
317
318         closedir(dir);
319 }
320
321 char *get_name(void) {
322         char *name = NULL;
323
324         get_config_string(lookup_config(config_tree, "Name"), &name);
325
326         if(!name) {
327                 return NULL;
328         }
329
330         if(*name == '$') {
331                 char *envname = getenv(name + 1);
332                 char hostname[32] = "";
333
334                 if(!envname) {
335                         if(strcmp(name + 1, "HOST")) {
336                                 fprintf(stderr, "Invalid Name: environment variable %s does not exist\n", name + 1);
337                                 free(name);
338                                 return false;
339                         }
340
341                         if(gethostname(hostname, sizeof(hostname)) || !*hostname) {
342                                 fprintf(stderr, "Could not get hostname: %s\n", strerror(errno));
343                                 free(name);
344                                 return false;
345                         }
346
347                         hostname[31] = 0;
348                         envname = hostname;
349                 }
350
351                 free(name);
352                 name = xstrdup(envname);
353
354                 for(char *c = name; *c; c++)
355                         if(!isalnum(*c)) {
356                                 *c = '_';
357                         }
358         }
359
360         if(!check_id(name)) {
361                 logger(LOG_ERR, "Invalid name for myself!");
362                 free(name);
363                 return false;
364         }
365
366         return name;
367 }
368
369 /*
370   Configure node_t myself and set up the local sockets (listen only)
371 */
372 static bool setup_myself(void) {
373         config_t *cfg;
374         subnet_t *subnet;
375         char *name, *hostname, *mode, *afname, *cipher, *digest, *type;
376         char *fname = NULL;
377         char *address = NULL;
378         char *proxy = NULL;
379         char *space;
380         char *envp[5] = {0};
381         struct addrinfo *ai, *aip, hint = {0};
382         bool choice;
383         int i, err;
384         int replaywin_int;
385         bool port_specified = false;
386
387         myself = new_node();
388         myself->connection = new_connection();
389
390         myself->hostname = xstrdup("MYSELF");
391         myself->connection->hostname = xstrdup("MYSELF");
392
393         myself->connection->options = 0;
394         myself->connection->protocol_version = PROT_CURRENT;
395
396         if(!(name = get_name())) {
397                 logger(LOG_ERR, "Name for tinc daemon required!");
398                 return false;
399         }
400
401         /* Read tinc.conf and our own host config file */
402
403         myself->name = name;
404         myself->connection->name = xstrdup(name);
405         xasprintf(&fname, "%s/hosts/%s", confbase, name);
406         read_config_options(config_tree, name);
407         read_config_file(config_tree, fname);
408         free(fname);
409
410         if(!read_rsa_private_key()) {
411                 return false;
412         }
413
414         if(!get_config_string(lookup_config(config_tree, "Port"), &myport)) {
415                 myport = xstrdup("655");
416         } else {
417                 port_specified = true;
418         }
419
420         /* Ensure myport is numeric */
421
422         if(!atoi(myport)) {
423                 struct addrinfo *ai = str2addrinfo("localhost", myport, SOCK_DGRAM);
424                 sockaddr_t sa;
425
426                 if(!ai || !ai->ai_addr) {
427                         return false;
428                 }
429
430                 free(myport);
431                 memcpy(&sa, ai->ai_addr, ai->ai_addrlen);
432                 sockaddr2str(&sa, NULL, &myport);
433         }
434
435         if(get_config_string(lookup_config(config_tree, "Proxy"), &proxy)) {
436                 if((space = strchr(proxy, ' '))) {
437                         *space++ = 0;
438                 }
439
440                 if(!strcasecmp(proxy, "none")) {
441                         proxytype = PROXY_NONE;
442                 } else if(!strcasecmp(proxy, "socks4")) {
443                         proxytype = PROXY_SOCKS4;
444                 } else if(!strcasecmp(proxy, "socks4a")) {
445                         proxytype = PROXY_SOCKS4A;
446                 } else if(!strcasecmp(proxy, "socks5")) {
447                         proxytype = PROXY_SOCKS5;
448                 } else if(!strcasecmp(proxy, "http")) {
449                         proxytype = PROXY_HTTP;
450                 } else if(!strcasecmp(proxy, "exec")) {
451                         proxytype = PROXY_EXEC;
452                 } else {
453                         logger(LOG_ERR, "Unknown proxy type %s!", proxy);
454                         free(proxy);
455                         return false;
456                 }
457
458                 switch(proxytype) {
459                 case PROXY_NONE:
460                 default:
461                         break;
462
463                 case PROXY_EXEC:
464                         if(!space || !*space) {
465                                 logger(LOG_ERR, "Argument expected for proxy type exec!");
466                                 free(proxy);
467                                 return false;
468                         }
469
470                         proxyhost =  xstrdup(space);
471                         break;
472
473                 case PROXY_SOCKS4:
474                 case PROXY_SOCKS4A:
475                 case PROXY_SOCKS5:
476                 case PROXY_HTTP:
477                         proxyhost = space;
478
479                         if(space && (space = strchr(space, ' '))) {
480                                 *space++ = 0, proxyport = space;
481                         }
482
483                         if(space && (space = strchr(space, ' '))) {
484                                 *space++ = 0, proxyuser = space;
485                         }
486
487                         if(space && (space = strchr(space, ' '))) {
488                                 *space++ = 0, proxypass = space;
489                         }
490
491                         if(!proxyhost || !*proxyhost || !proxyport || !*proxyport) {
492                                 logger(LOG_ERR, "Host and port argument expected for proxy!");
493                                 free(proxy);
494                                 return false;
495                         }
496
497                         proxyhost = xstrdup(proxyhost);
498                         proxyport = xstrdup(proxyport);
499
500                         if(proxyuser && *proxyuser) {
501                                 proxyuser = xstrdup(proxyuser);
502                         }
503
504                         if(proxypass && *proxypass) {
505                                 proxypass = xstrdup(proxypass);
506                         }
507
508                         break;
509                 }
510
511                 free(proxy);
512         }
513
514         /* Read in all the subnets specified in the host configuration file */
515
516         cfg = lookup_config(config_tree, "Subnet");
517
518         while(cfg) {
519                 if(!get_config_subnet(cfg, &subnet)) {
520                         return false;
521                 }
522
523                 subnet_add(myself, subnet);
524
525                 cfg = lookup_config_next(config_tree, cfg);
526         }
527
528         /* Check some options */
529
530         if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice) && choice) {
531                 myself->options |= OPTION_INDIRECT;
532         }
533
534         if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice) && choice) {
535                 myself->options |= OPTION_TCPONLY;
536         }
537
538         if(myself->options & OPTION_TCPONLY) {
539                 myself->options |= OPTION_INDIRECT;
540         }
541
542         get_config_bool(lookup_config(config_tree, "DirectOnly"), &directonly);
543         get_config_bool(lookup_config(config_tree, "StrictSubnets"), &strictsubnets);
544         get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
545         get_config_bool(lookup_config(config_tree, "LocalDiscovery"), &localdiscovery);
546         strictsubnets |= tunnelserver;
547
548         if(get_config_string(lookup_config(config_tree, "Mode"), &mode)) {
549                 if(!strcasecmp(mode, "router")) {
550                         routing_mode = RMODE_ROUTER;
551                 } else if(!strcasecmp(mode, "switch")) {
552                         routing_mode = RMODE_SWITCH;
553                 } else if(!strcasecmp(mode, "hub")) {
554                         routing_mode = RMODE_HUB;
555                 } else {
556                         logger(LOG_ERR, "Invalid routing mode!");
557                         free(mode);
558                         return false;
559                 }
560
561                 free(mode);
562         }
563
564         if(get_config_string(lookup_config(config_tree, "Forwarding"), &mode)) {
565                 if(!strcasecmp(mode, "off")) {
566                         forwarding_mode = FMODE_OFF;
567                 } else if(!strcasecmp(mode, "internal")) {
568                         forwarding_mode = FMODE_INTERNAL;
569                 } else if(!strcasecmp(mode, "kernel")) {
570                         forwarding_mode = FMODE_KERNEL;
571                 } else {
572                         logger(LOG_ERR, "Invalid forwarding mode!");
573                         free(mode);
574                         return false;
575                 }
576
577                 free(mode);
578         }
579
580         choice = !(myself->options & OPTION_TCPONLY);
581         get_config_bool(lookup_config(config_tree, "PMTUDiscovery"), &choice);
582
583         if(choice) {
584                 myself->options |= OPTION_PMTU_DISCOVERY;
585         }
586
587         choice = true;
588         get_config_bool(lookup_config(config_tree, "ClampMSS"), &choice);
589
590         if(choice) {
591                 myself->options |= OPTION_CLAMP_MSS;
592         }
593
594         get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
595         get_config_bool(lookup_config(config_tree, "DecrementTTL"), &decrement_ttl);
596
597         if(get_config_string(lookup_config(config_tree, "Broadcast"), &mode)) {
598                 if(!strcasecmp(mode, "no")) {
599                         broadcast_mode = BMODE_NONE;
600                 } else if(!strcasecmp(mode, "yes") || !strcasecmp(mode, "mst")) {
601                         broadcast_mode = BMODE_MST;
602                 } else if(!strcasecmp(mode, "direct")) {
603                         broadcast_mode = BMODE_DIRECT;
604                 } else {
605                         logger(LOG_ERR, "Invalid broadcast mode!");
606                         free(mode);
607                         return false;
608                 }
609
610                 free(mode);
611         }
612
613 #if !defined(SOL_IP) || !defined(IP_TOS)
614
615         if(priorityinheritance) {
616                 logger(LOG_WARNING, "%s not supported on this platform for IPv4 connection", "PriorityInheritance");
617         }
618
619 #endif
620
621 #if !defined(IPPROTO_IPV6) || !defined(IPV6_TCLASS)
622
623         if(priorityinheritance) {
624                 logger(LOG_WARNING, "%s not supported on this platform for IPv6 connection", "PriorityInheritance");
625         }
626
627 #endif
628
629         if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire)) {
630                 macexpire = 600;
631         }
632
633         if(get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout)) {
634                 if(maxtimeout <= 0) {
635                         logger(LOG_ERR, "Bogus maximum timeout!");
636                         return false;
637                 }
638         } else {
639                 maxtimeout = 900;
640         }
641
642         if(get_config_int(lookup_config(config_tree, "MinTimeout"), &mintimeout)) {
643                 if(mintimeout < 0) {
644                         logger(LOG_ERR, "Bogus minimum timeout!");
645                         return false;
646                 }
647
648                 if(mintimeout > maxtimeout) {
649                         logger(LOG_WARNING, "Minimum timeout (%d s) cannot be larger than maximum timeout (%d s). Correcting !", mintimeout, maxtimeout);
650                         mintimeout = maxtimeout;
651                 }
652         } else {
653                 mintimeout = 0;
654         }
655
656         if(get_config_int(lookup_config(config_tree, "UDPRcvBuf"), &udp_rcvbuf)) {
657                 if(udp_rcvbuf <= 0) {
658                         logger(LOG_ERR, "UDPRcvBuf cannot be negative!");
659                         return false;
660                 }
661         }
662
663         if(get_config_int(lookup_config(config_tree, "UDPSndBuf"), &udp_sndbuf)) {
664                 if(udp_sndbuf <= 0) {
665                         logger(LOG_ERR, "UDPSndBuf cannot be negative!");
666                         return false;
667                 }
668         }
669
670         if(get_config_int(lookup_config(config_tree, "ReplayWindow"), &replaywin_int)) {
671                 if(replaywin_int < 0) {
672                         logger(LOG_ERR, "ReplayWindow cannot be negative!");
673                         return false;
674                 }
675
676                 replaywin = (unsigned)replaywin_int;
677         }
678
679         if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
680                 if(!strcasecmp(afname, "IPv4")) {
681                         addressfamily = AF_INET;
682                 } else if(!strcasecmp(afname, "IPv6")) {
683                         addressfamily = AF_INET6;
684                 } else if(!strcasecmp(afname, "any")) {
685                         addressfamily = AF_UNSPEC;
686                 } else {
687                         logger(LOG_ERR, "Invalid address family!");
688                         free(afname);
689                         return false;
690                 }
691
692                 free(afname);
693         }
694
695         get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
696
697         /* Generate packet encryption key */
698
699         if(get_config_string(lookup_config(config_tree, "Cipher"), &cipher)) {
700                 if(!strcasecmp(cipher, "none")) {
701                         myself->incipher = NULL;
702                 } else {
703                         myself->incipher = EVP_get_cipherbyname(cipher);
704
705                         if(!myself->incipher) {
706                                 logger(LOG_ERR, "Unrecognized cipher type!");
707                                 free(cipher);
708                                 return false;
709                         }
710                 }
711
712                 free(cipher);
713         } else {
714                 myself->incipher = EVP_aes_256_cbc();
715         }
716
717         if(myself->incipher) {
718                 myself->inkeylength = EVP_CIPHER_key_length(myself->incipher) + EVP_CIPHER_iv_length(myself->incipher);
719         } else {
720                 myself->inkeylength = 1;
721         }
722
723         /* We need to use a stream mode for the meta protocol. Use AES for this,
724            but try to match the key size with the one from the cipher selected
725            by Cipher.
726
727            If Cipher is set to none, still use a low level of encryption for the
728            meta protocol.
729         */
730
731         int keylen = myself->incipher ? EVP_CIPHER_key_length(myself->incipher) : 0;
732
733         if(keylen <= 16) {
734                 myself->connection->outcipher = EVP_aes_128_cfb();
735         } else if(keylen <= 24) {
736                 myself->connection->outcipher = EVP_aes_192_cfb();
737         } else {
738                 myself->connection->outcipher = EVP_aes_256_cfb();
739         }
740
741         if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime)) {
742                 keylifetime = 3600;
743         }
744
745         keyexpires = now + keylifetime;
746
747         /* Check if we want to use message authentication codes... */
748
749         if(get_config_string(lookup_config(config_tree, "Digest"), &digest)) {
750                 if(!strcasecmp(digest, "none")) {
751                         myself->indigest = NULL;
752                 } else {
753                         myself->indigest = EVP_get_digestbyname(digest);
754
755                         if(!myself->indigest) {
756                                 logger(LOG_ERR, "Unrecognized digest type!");
757                                 free(digest);
758                                 return false;
759                         }
760                 }
761
762                 free(digest);
763         } else {
764                 myself->indigest = EVP_sha256();
765         }
766
767         myself->connection->outdigest = EVP_sha256();
768
769         if(get_config_int(lookup_config(config_tree, "MACLength"), &myself->inmaclength)) {
770                 if(myself->indigest) {
771                         if(myself->inmaclength > EVP_MD_size(myself->indigest)) {
772                                 logger(LOG_ERR, "MAC length exceeds size of digest!");
773                                 return false;
774                         } else if(myself->inmaclength < 0) {
775                                 logger(LOG_ERR, "Bogus MAC length!");
776                                 return false;
777                         }
778                 }
779         } else {
780                 myself->inmaclength = 4;
781         }
782
783         myself->connection->outmaclength = 0;
784
785         /* Compression */
786
787         if(get_config_int(lookup_config(config_tree, "Compression"), &myself->incompression)) {
788                 if(myself->incompression < 0 || myself->incompression > 11) {
789                         logger(LOG_ERR, "Bogus compression level!");
790                         return false;
791                 }
792         } else {
793                 myself->incompression = 0;
794         }
795
796         myself->connection->outcompression = 0;
797
798         /* Done */
799
800         myself->nexthop = myself;
801         myself->via = myself;
802         myself->status.reachable = true;
803         node_add(myself);
804
805         graph();
806
807         if(strictsubnets) {
808                 load_all_subnets();
809         }
810
811         /* Open device */
812
813         devops = os_devops;
814
815         if(get_config_string(lookup_config(config_tree, "DeviceType"), &type)) {
816                 if(!strcasecmp(type, "dummy")) {
817                         devops = dummy_devops;
818                 } else if(!strcasecmp(type, "raw_socket")) {
819                         devops = raw_socket_devops;
820                 } else if(!strcasecmp(type, "multicast")) {
821                         devops = multicast_devops;
822                 }
823
824 #ifdef ENABLE_UML
825                 else if(!strcasecmp(type, "uml")) {
826                         devops = uml_devops;
827                 }
828
829 #endif
830 #ifdef ENABLE_VDE
831                 else if(!strcasecmp(type, "vde")) {
832                         devops = vde_devops;
833                 }
834
835 #endif
836                 free(type);
837         }
838
839         if(!devops.setup()) {
840                 return false;
841         }
842
843         /* Run tinc-up script to further initialize the tap interface */
844         xasprintf(&envp[0], "NETNAME=%s", netname ? netname : "");
845         xasprintf(&envp[1], "DEVICE=%s", device ? device : "");
846         xasprintf(&envp[2], "INTERFACE=%s", iface ? iface : "");
847         xasprintf(&envp[3], "NAME=%s", myself->name);
848
849 #ifdef HAVE_MINGW
850         Sleep(1000);
851 #endif
852 #ifdef HAVE_CYGWIN
853         sleep(1);
854 #endif
855         execute_script("tinc-up", envp);
856
857         for(i = 0; i < 4; i++) {
858                 free(envp[i]);
859         }
860
861         /* Run subnet-up scripts for our own subnets */
862
863         subnet_update(myself, NULL, true);
864
865         /* Open sockets */
866
867         if(!do_detach && getenv("LISTEN_FDS")) {
868                 sockaddr_t sa;
869                 socklen_t salen;
870
871                 listen_sockets = atoi(getenv("LISTEN_FDS"));
872 #ifdef HAVE_UNSETENV
873                 unsetenv("LISTEN_FDS");
874 #endif
875
876                 if(listen_sockets > MAXSOCKETS) {
877                         logger(LOG_ERR, "Too many listening sockets");
878                         return false;
879                 }
880
881                 for(i = 0; i < listen_sockets; i++) {
882                         salen = sizeof(sa);
883
884                         if(getsockname(i + 3, &sa.sa, &salen) < 0) {
885                                 logger(LOG_ERR, "Could not get address of listen fd %d: %s", i + 3, sockstrerror(errno));
886                                 return false;
887                         }
888
889                         listen_socket[i].tcp = i + 3;
890
891 #ifdef FD_CLOEXEC
892                         fcntl(i + 3, F_SETFD, FD_CLOEXEC);
893 #endif
894
895                         listen_socket[i].udp = setup_vpn_in_socket(&sa);
896
897                         if(listen_socket[i].udp < 0) {
898                                 return false;
899                         }
900
901                         ifdebug(CONNECTIONS) {
902                                 hostname = sockaddr2hostname(&sa);
903                                 logger(LOG_NOTICE, "Listening on %s", hostname);
904                                 free(hostname);
905                         }
906
907                         memcpy(&listen_socket[i].sa, &sa, salen);
908                 }
909         } else {
910                 listen_sockets = 0;
911                 cfg = lookup_config(config_tree, "BindToAddress");
912
913                 do {
914                         get_config_string(cfg, &address);
915
916                         if(cfg) {
917                                 cfg = lookup_config_next(config_tree, cfg);
918                         }
919
920                         char *port = myport;
921
922                         if(address) {
923                                 char *space = strchr(address, ' ');
924
925                                 if(space) {
926                                         *space++ = 0;
927                                         port = space;
928                                 }
929
930                                 if(!strcmp(address, "*")) {
931                                         *address = 0;
932                                 }
933                         }
934
935                         hint.ai_family = addressfamily;
936                         hint.ai_socktype = SOCK_STREAM;
937                         hint.ai_protocol = IPPROTO_TCP;
938                         hint.ai_flags = AI_PASSIVE;
939
940 #if HAVE_DECL_RES_INIT
941                         // ensure glibc reloads /etc/resolv.conf.
942                         res_init();
943 #endif
944                         err = getaddrinfo(address && *address ? address : NULL, port, &hint, &ai);
945                         free(address);
946
947                         if(err || !ai) {
948                                 logger(LOG_ERR, "System call `%s' failed: %s", "getaddrinfo",
949                                        gai_strerror(err));
950                                 return false;
951                         }
952
953                         for(aip = ai; aip; aip = aip->ai_next) {
954                                 if(listen_sockets >= MAXSOCKETS) {
955                                         logger(LOG_ERR, "Too many listening sockets");
956                                         return false;
957                                 }
958
959                                 listen_socket[listen_sockets].tcp =
960                                         setup_listen_socket((sockaddr_t *) aip->ai_addr);
961
962                                 if(listen_socket[listen_sockets].tcp < 0) {
963                                         continue;
964                                 }
965
966                                 listen_socket[listen_sockets].udp =
967                                         setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
968
969                                 if(listen_socket[listen_sockets].udp < 0) {
970                                         continue;
971                                 }
972
973                                 ifdebug(CONNECTIONS) {
974                                         hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
975                                         logger(LOG_NOTICE, "Listening on %s", hostname);
976                                         free(hostname);
977                                 }
978
979                                 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
980                                 listen_sockets++;
981                         }
982
983                         freeaddrinfo(ai);
984                 } while(cfg);
985         }
986
987         if(!listen_sockets) {
988                 logger(LOG_ERR, "Unable to create any listening socket!");
989                 return false;
990         }
991
992         /* If no Port option was specified, set myport to the port used by the first listening socket. */
993
994         if(!port_specified) {
995                 sockaddr_t sa;
996                 socklen_t salen = sizeof(sa);
997
998                 if(!getsockname(listen_socket[0].udp, &sa.sa, &salen)) {
999                         free(myport);
1000                         sockaddr2str(&sa, NULL, &myport);
1001
1002                         if(!myport) {
1003                                 myport = xstrdup("655");
1004                         }
1005                 }
1006         }
1007
1008         /* Done. */
1009
1010         logger(LOG_NOTICE, "Ready");
1011         return true;
1012 }
1013
1014 /*
1015   initialize network
1016 */
1017 bool setup_network(void) {
1018         now = time(NULL);
1019
1020         init_events();
1021         init_connections();
1022         init_subnets();
1023         init_nodes();
1024         init_edges();
1025         init_requests();
1026
1027         if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
1028                 if(pinginterval < 1) {
1029                         pinginterval = 86400;
1030                 }
1031         } else {
1032                 pinginterval = 60;
1033         }
1034
1035         if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout)) {
1036                 pingtimeout = 5;
1037         }
1038
1039         if(pingtimeout < 1 || pingtimeout > pinginterval) {
1040                 pingtimeout = pinginterval;
1041         }
1042
1043         if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize)) {
1044                 maxoutbufsize = 10 * MTU;
1045         }
1046
1047         if(!setup_myself()) {
1048                 return false;
1049         }
1050
1051         return true;
1052 }
1053
1054 /*
1055   close all open network connections
1056 */
1057 void close_network_connections(void) {
1058         avl_node_t *node, *next;
1059         connection_t *c;
1060         char *envp[5] = {0};
1061         int i;
1062
1063         for(node = connection_tree->head; node; node = next) {
1064                 next = node->next;
1065                 c = node->data;
1066                 c->outgoing = NULL;
1067                 terminate_connection(c, false);
1068         }
1069
1070         for(list_node_t *node = outgoing_list->head; node; node = node->next) {
1071                 outgoing_t *outgoing = node->data;
1072
1073                 if(outgoing->event) {
1074                         event_del(outgoing->event);
1075                 }
1076         }
1077
1078         list_delete_list(outgoing_list);
1079
1080         if(myself && myself->connection) {
1081                 subnet_update(myself, NULL, false);
1082                 terminate_connection(myself->connection, false);
1083                 free_connection(myself->connection);
1084         }
1085
1086         for(i = 0; i < listen_sockets; i++) {
1087                 close(listen_socket[i].tcp);
1088                 close(listen_socket[i].udp);
1089         }
1090
1091         xasprintf(&envp[0], "NETNAME=%s", netname ? netname : "");
1092         xasprintf(&envp[1], "DEVICE=%s", device ? device : "");
1093         xasprintf(&envp[2], "INTERFACE=%s", iface ? iface : "");
1094         xasprintf(&envp[3], "NAME=%s", myself->name);
1095
1096         exit_requests();
1097         exit_edges();
1098         exit_subnets();
1099         exit_nodes();
1100         exit_connections();
1101         exit_events();
1102
1103         execute_script("tinc-down", envp);
1104
1105         if(myport) {
1106                 free(myport);
1107         }
1108
1109         for(i = 0; i < 4; i++) {
1110                 free(envp[i]);
1111         }
1112
1113         devops.close();
1114
1115         return;
1116 }