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