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