b46d1ae56096df27db4602aef0bf1b2bac391fa8
[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(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 *fname = NULL;
274         char *address = NULL;
275         char *envp[5];
276         struct addrinfo *ai, *aip, hint = {0};
277         bool choice;
278         int i, err;
279         int replaywin_int;
280
281         myself = new_node();
282         myself->connection = new_connection();
283
284         myself->hostname = xstrdup("MYSELF");
285         myself->connection->hostname = xstrdup("MYSELF");
286
287         myself->connection->options = 0;
288         myself->connection->protocol_version = PROT_CURRENT;
289
290         if(!get_config_string(lookup_config(config_tree, "Name"), &name)) {     /* Not acceptable */
291                 logger(LOG_ERR, "Name for tinc daemon required!");
292                 return false;
293         }
294
295         if(!check_id(name)) {
296                 logger(LOG_ERR, "Invalid name for myself!");
297                 free(name);
298                 return false;
299         }
300
301         myself->name = name;
302         myself->connection->name = xstrdup(name);
303         xasprintf(&fname, "%s/hosts/%s", confbase, name);
304         read_config_options(config_tree, name);
305         read_config_file(config_tree, fname);
306         free(fname);
307
308         if(!read_rsa_private_key())
309                 return false;
310
311         if(!get_config_string(lookup_config(config_tree, "Port"), &myport))
312                 myport = xstrdup("655");
313
314         if(!atoi(myport)) {
315                 struct addrinfo *ai = str2addrinfo("localhost", myport, SOCK_DGRAM);
316                 sockaddr_t sa;
317                 if(!ai || !ai->ai_addr)
318                         return false;
319                 free(myport);
320                 memcpy(&sa, ai->ai_addr, ai->ai_addrlen);
321                 sockaddr2str(&sa, NULL, &myport);
322         }
323
324         /* Read in all the subnets specified in the host configuration file */
325
326         cfg = lookup_config(config_tree, "Subnet");
327
328         while(cfg) {
329                 if(!get_config_subnet(cfg, &subnet))
330                         return false;
331
332                 subnet_add(myself, subnet);
333
334                 cfg = lookup_config_next(config_tree, cfg);
335         }
336
337         /* Check some options */
338
339         if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice) && choice)
340                 myself->options |= OPTION_INDIRECT;
341
342         if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice) && choice)
343                 myself->options |= OPTION_TCPONLY;
344
345         if(myself->options & OPTION_TCPONLY)
346                 myself->options |= OPTION_INDIRECT;
347
348         get_config_bool(lookup_config(config_tree, "DirectOnly"), &directonly);
349         get_config_bool(lookup_config(config_tree, "StrictSubnets"), &strictsubnets);
350         get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
351         strictsubnets |= tunnelserver;
352
353         if(get_config_string(lookup_config(config_tree, "Mode"), &mode)) {
354                 if(!strcasecmp(mode, "router"))
355                         routing_mode = RMODE_ROUTER;
356                 else if(!strcasecmp(mode, "switch"))
357                         routing_mode = RMODE_SWITCH;
358                 else if(!strcasecmp(mode, "hub"))
359                         routing_mode = RMODE_HUB;
360                 else {
361                         logger(LOG_ERR, "Invalid routing mode!");
362                         return false;
363                 }
364                 free(mode);
365         }
366
367         if(get_config_string(lookup_config(config_tree, "Forwarding"), &mode)) {
368                 if(!strcasecmp(mode, "off"))
369                         forwarding_mode = FMODE_OFF;
370                 else if(!strcasecmp(mode, "internal"))
371                         forwarding_mode = FMODE_INTERNAL;
372                 else if(!strcasecmp(mode, "kernel"))
373                         forwarding_mode = FMODE_KERNEL;
374                 else {
375                         logger(LOG_ERR, "Invalid forwarding mode!");
376                         return false;
377                 }
378                 free(mode);
379         }
380
381         choice = true;
382         get_config_bool(lookup_config(config_tree, "PMTUDiscovery"), &choice);
383         if(choice)
384                 myself->options |= OPTION_PMTU_DISCOVERY;
385
386         choice = true;
387         get_config_bool(lookup_config(config_tree, "ClampMSS"), &choice);
388         if(choice)
389                 myself->options |= OPTION_CLAMP_MSS;
390
391         get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
392
393 #if !defined(SOL_IP) || !defined(IP_TOS)
394         if(priorityinheritance)
395                 logger(LOG_WARNING, "%s not supported on this platform", "PriorityInheritance");
396 #endif
397
398         if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire))
399                 macexpire = 600;
400
401         if(get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout)) {
402                 if(maxtimeout <= 0) {
403                         logger(LOG_ERR, "Bogus maximum timeout!");
404                         return false;
405                 }
406         } else
407                 maxtimeout = 900;
408
409         if(get_config_int(lookup_config(config_tree, "UDPRcvBuf"), &udp_rcvbuf)) {
410                 if(udp_rcvbuf <= 0) {
411                         logger(LOG_ERR, "UDPRcvBuf cannot be negative!");
412                         return false;
413                 }
414         }
415
416         if(get_config_int(lookup_config(config_tree, "UDPSndBuf"), &udp_sndbuf)) {
417                 if(udp_sndbuf <= 0) {
418                         logger(LOG_ERR, "UDPSndBuf cannot be negative!");
419                         return false;
420                 }
421         }
422
423         if(get_config_int(lookup_config(config_tree, "ReplayWindow"), &replaywin_int)) {
424                 if(replaywin_int < 0) {
425                         logger(LOG_ERR, "ReplayWindow cannot be negative!");
426                         return false;
427                 }
428                 replaywin = (unsigned)replaywin_int;
429         }
430
431         if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
432                 if(!strcasecmp(afname, "IPv4"))
433                         addressfamily = AF_INET;
434                 else if(!strcasecmp(afname, "IPv6"))
435                         addressfamily = AF_INET6;
436                 else if(!strcasecmp(afname, "any"))
437                         addressfamily = AF_UNSPEC;
438                 else {
439                         logger(LOG_ERR, "Invalid address family!");
440                         return false;
441                 }
442                 free(afname);
443         }
444
445         get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
446
447         /* Generate packet encryption key */
448
449         if(get_config_string
450            (lookup_config(config_tree, "Cipher"), &cipher)) {
451                 if(!strcasecmp(cipher, "none")) {
452                         myself->incipher = NULL;
453                 } else {
454                         myself->incipher = EVP_get_cipherbyname(cipher);
455
456                         if(!myself->incipher) {
457                                 logger(LOG_ERR, "Unrecognized cipher type!");
458                                 return false;
459                         }
460                 }
461         } else
462                 myself->incipher = EVP_bf_cbc();
463
464         if(myself->incipher)
465                 myself->inkeylength = myself->incipher->key_len + myself->incipher->iv_len;
466         else
467                 myself->inkeylength = 1;
468
469         myself->connection->outcipher = EVP_bf_ofb();
470
471         if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
472                 keylifetime = 3600;
473
474         keyexpires = now + keylifetime;
475         
476         /* Check if we want to use message authentication codes... */
477
478         if(get_config_string(lookup_config(config_tree, "Digest"), &digest)) {
479                 if(!strcasecmp(digest, "none")) {
480                         myself->indigest = NULL;
481                 } else {
482                         myself->indigest = EVP_get_digestbyname(digest);
483
484                         if(!myself->indigest) {
485                                 logger(LOG_ERR, "Unrecognized digest type!");
486                                 return false;
487                         }
488                 }
489         } else
490                 myself->indigest = EVP_sha1();
491
492         myself->connection->outdigest = EVP_sha1();
493
494         if(get_config_int(lookup_config(config_tree, "MACLength"), &myself->inmaclength)) {
495                 if(myself->indigest) {
496                         if(myself->inmaclength > myself->indigest->md_size) {
497                                 logger(LOG_ERR, "MAC length exceeds size of digest!");
498                                 return false;
499                         } else if(myself->inmaclength < 0) {
500                                 logger(LOG_ERR, "Bogus MAC length!");
501                                 return false;
502                         }
503                 }
504         } else
505                 myself->inmaclength = 4;
506
507         myself->connection->outmaclength = 0;
508
509         /* Compression */
510
511         if(get_config_int(lookup_config(config_tree, "Compression"), &myself->incompression)) {
512                 if(myself->incompression < 0 || myself->incompression > 11) {
513                         logger(LOG_ERR, "Bogus compression level!");
514                         return false;
515                 }
516         } else
517                 myself->incompression = 0;
518
519         myself->connection->outcompression = 0;
520
521         /* Done */
522
523         myself->nexthop = myself;
524         myself->via = myself;
525         myself->status.reachable = true;
526         node_add(myself);
527
528         graph();
529
530         if(strictsubnets)
531                 load_all_subnets();
532
533         /* Open device */
534
535         if(!setup_device())
536                 return false;
537
538         /* Run tinc-up script to further initialize the tap interface */
539         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
540         xasprintf(&envp[1], "DEVICE=%s", device ? : "");
541         xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
542         xasprintf(&envp[3], "NAME=%s", myself->name);
543         envp[4] = NULL;
544
545         execute_script("tinc-up", envp);
546
547         for(i = 0; i < 5; i++)
548                 free(envp[i]);
549
550         /* Run subnet-up scripts for our own subnets */
551
552         subnet_update(myself, NULL, true);
553
554         /* Open sockets */
555
556         get_config_string(lookup_config(config_tree, "BindToAddress"), &address);
557
558         hint.ai_family = addressfamily;
559         hint.ai_socktype = SOCK_STREAM;
560         hint.ai_protocol = IPPROTO_TCP;
561         hint.ai_flags = AI_PASSIVE;
562
563         err = getaddrinfo(address, myport, &hint, &ai);
564
565         if(err || !ai) {
566                 logger(LOG_ERR, "System call `%s' failed: %s", "getaddrinfo",
567                            gai_strerror(err));
568                 return false;
569         }
570
571         listen_sockets = 0;
572
573         for(aip = ai; aip; aip = aip->ai_next) {
574                 listen_socket[listen_sockets].tcp =
575                         setup_listen_socket((sockaddr_t *) aip->ai_addr);
576
577                 if(listen_socket[listen_sockets].tcp < 0)
578                         continue;
579
580                 listen_socket[listen_sockets].udp =
581                         setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
582
583                 if(listen_socket[listen_sockets].udp < 0)
584                         continue;
585
586                 ifdebug(CONNECTIONS) {
587                         hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
588                         logger(LOG_NOTICE, "Listening on %s", hostname);
589                         free(hostname);
590                 }
591
592                 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
593                 listen_sockets++;
594         }
595
596         freeaddrinfo(ai);
597
598         if(listen_sockets)
599                 logger(LOG_NOTICE, "Ready");
600         else {
601                 logger(LOG_ERR, "Unable to create any listening socket!");
602                 return false;
603         }
604
605         return true;
606 }
607
608 /*
609   initialize network
610 */
611 bool setup_network(void) {
612         now = time(NULL);
613
614         init_events();
615         init_connections();
616         init_subnets();
617         init_nodes();
618         init_edges();
619         init_requests();
620
621         if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
622                 if(pinginterval < 1) {
623                         pinginterval = 86400;
624                 }
625         } else
626                 pinginterval = 60;
627
628         if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
629                 pingtimeout = 5;
630         if(pingtimeout < 1 || pingtimeout > pinginterval)
631                 pingtimeout = pinginterval;
632
633         if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize))
634                 maxoutbufsize = 10 * MTU;
635
636         if(!setup_myself())
637                 return false;
638
639         return true;
640 }
641
642 /*
643   close all open network connections
644 */
645 void close_network_connections(void) {
646         avl_node_t *node, *next;
647         connection_t *c;
648         char *envp[5];
649         int i;
650
651         for(node = connection_tree->head; node; node = next) {
652                 next = node->next;
653                 c = node->data;
654                 c->outgoing = NULL;
655                 terminate_connection(c, false);
656         }
657
658         for(list_node_t *node = outgoing_list->head; node; node = node->next) {
659                 outgoing_t *outgoing = node->data;
660
661                 if(outgoing->event)
662                         event_del(outgoing->event);
663         }
664
665         list_delete_list(outgoing_list);
666
667         if(myself && myself->connection) {
668                 subnet_update(myself, NULL, false);
669                 terminate_connection(myself->connection, false);
670                 free_connection(myself->connection);
671         }
672
673         for(i = 0; i < listen_sockets; i++) {
674                 close(listen_socket[i].tcp);
675                 close(listen_socket[i].udp);
676         }
677
678         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
679         xasprintf(&envp[1], "DEVICE=%s", device ? : "");
680         xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
681         xasprintf(&envp[3], "NAME=%s", myself->name);
682         envp[4] = NULL;
683
684         exit_requests();
685         exit_edges();
686         exit_subnets();
687         exit_nodes();
688         exit_connections();
689         exit_events();
690
691         execute_script("tinc-down", envp);
692
693         if(myport) free(myport);
694
695         for(i = 0; i < 4; i++)
696                 free(envp[i]);
697
698         close_device();
699
700         return;
701 }