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