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