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