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