cb70926ad0c3dbaa13bac715514098a536f533a8
[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 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, *s2;
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                 #ifdef _DIRENT_HAVE_D_TYPE
232                 //if(ent->d_type != DT_REG)
233                 //      continue;
234                 #endif
235
236                 xasprintf(&fname, "%s/hosts/%s", confbase, ent->d_name);
237                 init_configuration(&config_tree);
238                 result = read_config_file(config_tree, fname);
239                 free(fname);
240                 if(!result)
241                         continue;
242
243                 if(!n) {
244                         n = new_node();
245                         n->name = xstrdup(ent->d_name);
246                         node_add(n);
247                 }
248
249                 for(cfg = lookup_config(config_tree, "Subnet"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
250                         if(!get_config_subnet(cfg, &s))
251                                 continue;
252
253                         if((s2 = lookup_subnet(n, s))) {
254                                 s2->expires = -1;
255                         } else {
256                                 subnet_add(n, s);
257                         }
258                 }
259
260                 exit_configuration(&config_tree);
261         }
262
263         closedir(dir);
264 }
265
266 /*
267   Configure node_t myself and set up the local sockets (listen only)
268 */
269 bool setup_myself(void) {
270         config_t *cfg;
271         subnet_t *subnet;
272         char *name, *hostname, *mode, *afname, *cipher, *digest;
273         char *address = NULL;
274         char *envp[5];
275         struct addrinfo *ai, *aip, hint = {0};
276         bool choice;
277         int i, err;
278
279         myself = new_node();
280         myself->connection = new_connection();
281         init_configuration(&myself->connection->config_tree);
282
283         myself->hostname = xstrdup("MYSELF");
284         myself->connection->hostname = xstrdup("MYSELF");
285
286         myself->connection->options = 0;
287         myself->connection->protocol_version = PROT_CURRENT;
288
289         if(!get_config_string(lookup_config(config_tree, "Name"), &name)) {     /* Not acceptable */
290                 logger(LOG_ERR, "Name for tinc daemon required!");
291                 return false;
292         }
293
294         if(!check_id(name)) {
295                 logger(LOG_ERR, "Invalid name for myself!");
296                 free(name);
297                 return false;
298         }
299
300         myself->name = name;
301         myself->connection->name = xstrdup(name);
302
303         if(!read_connection_config(myself->connection)) {
304                 logger(LOG_ERR, "Cannot open host configuration file for myself!");
305                 return false;
306         }
307
308         if(!read_rsa_private_key())
309                 return false;
310
311         if(!get_config_string(lookup_config(config_tree, "Port"), &myport)
312                         && !get_config_string(lookup_config(myself->connection->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(myself->connection->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(myself->connection->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(get_config_bool(lookup_config(myself->connection->config_tree, "IndirectData"), &choice) && choice)
347                 myself->options |= OPTION_INDIRECT;
348
349         if(get_config_bool(lookup_config(myself->connection->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(myself->connection->config_tree, "PMTUDiscovery"), &choice);
390         get_config_bool(lookup_config(config_tree, "PMTUDiscovery"), &choice);
391         if(choice)
392                 myself->options |= OPTION_PMTU_DISCOVERY;
393
394         choice = true;
395         get_config_bool(lookup_config(config_tree, "ClampMSS"), &choice);
396         get_config_bool(lookup_config(myself->connection->config_tree, "ClampMSS"), &choice);
397         if(choice)
398                 myself->options |= OPTION_CLAMP_MSS;
399
400         get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
401
402 #if !defined(SOL_IP) || !defined(IP_TOS)
403         if(priorityinheritance)
404                 logger(LOG_WARNING, "%s not supported on this platform", "PriorityInheritance");
405 #endif
406
407         if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire))
408                 macexpire = 600;
409
410         if(get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout)) {
411                 if(maxtimeout <= 0) {
412                         logger(LOG_ERR, "Bogus maximum timeout!");
413                         return false;
414                 }
415         } else
416                 maxtimeout = 900;
417
418         if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
419                 if(!strcasecmp(afname, "IPv4"))
420                         addressfamily = AF_INET;
421                 else if(!strcasecmp(afname, "IPv6"))
422                         addressfamily = AF_INET6;
423                 else if(!strcasecmp(afname, "any"))
424                         addressfamily = AF_UNSPEC;
425                 else {
426                         logger(LOG_ERR, "Invalid address family!");
427                         return false;
428                 }
429                 free(afname);
430         }
431
432         get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
433
434         /* Generate packet encryption key */
435
436         if(get_config_string
437            (lookup_config(myself->connection->config_tree, "Cipher"), &cipher)) {
438                 if(!strcasecmp(cipher, "none")) {
439                         myself->incipher = NULL;
440                 } else {
441                         myself->incipher = EVP_get_cipherbyname(cipher);
442
443                         if(!myself->incipher) {
444                                 logger(LOG_ERR, "Unrecognized cipher type!");
445                                 return false;
446                         }
447                 }
448         } else
449                 myself->incipher = EVP_bf_cbc();
450
451         if(myself->incipher)
452                 myself->inkeylength = myself->incipher->key_len + myself->incipher->iv_len;
453         else
454                 myself->inkeylength = 1;
455
456         myself->connection->outcipher = EVP_bf_ofb();
457
458         if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
459                 keylifetime = 3600;
460
461         keyexpires = now + keylifetime;
462         
463         /* Check if we want to use message authentication codes... */
464
465         if(get_config_string(lookup_config(myself->connection->config_tree, "Digest"), &digest)) {
466                 if(!strcasecmp(digest, "none")) {
467                         myself->indigest = NULL;
468                 } else {
469                         myself->indigest = EVP_get_digestbyname(digest);
470
471                         if(!myself->indigest) {
472                                 logger(LOG_ERR, "Unrecognized digest type!");
473                                 return false;
474                         }
475                 }
476         } else
477                 myself->indigest = EVP_sha1();
478
479         myself->connection->outdigest = EVP_sha1();
480
481         if(get_config_int(lookup_config(myself->connection->config_tree, "MACLength"), &myself->inmaclength)) {
482                 if(myself->indigest) {
483                         if(myself->inmaclength > myself->indigest->md_size) {
484                                 logger(LOG_ERR, "MAC length exceeds size of digest!");
485                                 return false;
486                         } else if(myself->inmaclength < 0) {
487                                 logger(LOG_ERR, "Bogus MAC length!");
488                                 return false;
489                         }
490                 }
491         } else
492                 myself->inmaclength = 4;
493
494         myself->connection->outmaclength = 0;
495
496         /* Compression */
497
498         if(get_config_int(lookup_config(myself->connection->config_tree, "Compression"), &myself->incompression)) {
499                 if(myself->incompression < 0 || myself->incompression > 11) {
500                         logger(LOG_ERR, "Bogus compression level!");
501                         return false;
502                 }
503         } else
504                 myself->incompression = 0;
505
506         myself->connection->outcompression = 0;
507
508         /* Done */
509
510         myself->nexthop = myself;
511         myself->via = myself;
512         myself->status.reachable = true;
513         node_add(myself);
514
515         graph();
516
517         if(strictsubnets)
518                 load_all_subnets();
519
520         /* Open device */
521
522         if(!setup_device())
523                 return false;
524
525         /* Run tinc-up script to further initialize the tap interface */
526         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
527         xasprintf(&envp[1], "DEVICE=%s", device ? : "");
528         xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
529         xasprintf(&envp[3], "NAME=%s", myself->name);
530         envp[4] = NULL;
531
532         execute_script("tinc-up", envp);
533
534         for(i = 0; i < 5; i++)
535                 free(envp[i]);
536
537         /* Run subnet-up scripts for our own subnets */
538
539         subnet_update(myself, NULL, true);
540
541         /* Open sockets */
542
543         get_config_string(lookup_config(config_tree, "BindToAddress"), &address);
544
545         hint.ai_family = addressfamily;
546         hint.ai_socktype = SOCK_STREAM;
547         hint.ai_protocol = IPPROTO_TCP;
548         hint.ai_flags = AI_PASSIVE;
549
550         err = getaddrinfo(address, myport, &hint, &ai);
551
552         if(err || !ai) {
553                 logger(LOG_ERR, "System call `%s' failed: %s", "getaddrinfo",
554                            gai_strerror(err));
555                 return false;
556         }
557
558         listen_sockets = 0;
559
560         for(aip = ai; aip; aip = aip->ai_next) {
561                 listen_socket[listen_sockets].tcp =
562                         setup_listen_socket((sockaddr_t *) aip->ai_addr);
563
564                 if(listen_socket[listen_sockets].tcp < 0)
565                         continue;
566
567                 listen_socket[listen_sockets].udp =
568                         setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
569
570                 if(listen_socket[listen_sockets].udp < 0)
571                         continue;
572
573                 ifdebug(CONNECTIONS) {
574                         hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
575                         logger(LOG_NOTICE, "Listening on %s", hostname);
576                         free(hostname);
577                 }
578
579                 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
580                 listen_sockets++;
581         }
582
583         freeaddrinfo(ai);
584
585         if(listen_sockets)
586                 logger(LOG_NOTICE, "Ready");
587         else {
588                 logger(LOG_ERR, "Unable to create any listening socket!");
589                 return false;
590         }
591
592         return true;
593 }
594
595 /*
596   initialize network
597 */
598 bool setup_network(void) {
599         now = time(NULL);
600
601         init_events();
602         init_connections();
603         init_subnets();
604         init_nodes();
605         init_edges();
606         init_requests();
607
608         if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
609                 if(pinginterval < 1) {
610                         pinginterval = 86400;
611                 }
612         } else
613                 pinginterval = 60;
614
615         if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
616                 pingtimeout = 5;
617         if(pingtimeout < 1 || pingtimeout > pinginterval)
618                 pingtimeout = pinginterval;
619
620         if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize))
621                 maxoutbufsize = 10 * MTU;
622
623         if(!setup_myself())
624                 return false;
625
626         return true;
627 }
628
629 /*
630   close all open network connections
631 */
632 void close_network_connections(void) {
633         avl_node_t *node, *next;
634         connection_t *c;
635         char *envp[5];
636         int i;
637
638         for(node = connection_tree->head; node; node = next) {
639                 next = node->next;
640                 c = node->data;
641                 c->outgoing = NULL;
642                 terminate_connection(c, false);
643         }
644
645         for(list_node_t *node = outgoing_list->head; node; node = node->next) {
646                 outgoing_t *outgoing = node->data;
647
648                 if(outgoing->event)
649                         event_del(outgoing->event);
650         }
651
652         list_delete_list(outgoing_list);
653
654         if(myself && myself->connection) {
655                 subnet_update(myself, NULL, false);
656                 terminate_connection(myself->connection, false);
657                 free_connection(myself->connection);
658         }
659
660         for(i = 0; i < listen_sockets; i++) {
661                 close(listen_socket[i].tcp);
662                 close(listen_socket[i].udp);
663         }
664
665         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
666         xasprintf(&envp[1], "DEVICE=%s", device ? : "");
667         xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
668         xasprintf(&envp[3], "NAME=%s", myself->name);
669         envp[4] = NULL;
670
671         exit_requests();
672         exit_edges();
673         exit_subnets();
674         exit_nodes();
675         exit_connections();
676         exit_events();
677
678         execute_script("tinc-down", envp);
679
680         if(myport) free(myport);
681
682         for(i = 0; i < 4; i++)
683                 free(envp[i]);
684
685         close_device();
686
687         return;
688 }