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