Fix merge of commit 4a0b9981513059755b9fd15b38fc198f46a0d6f2.
[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 "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(myself->connection->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 *address = NULL;
227         char *envp[5];
228         struct addrinfo *ai, *aip, hint = {0};
229         bool choice;
230         int i, err;
231
232         myself = new_node();
233         myself->connection = new_connection();
234         init_configuration(&myself->connection->config_tree);
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
256         if(!read_connection_config(myself->connection)) {
257                 logger(LOG_ERR, "Cannot open host configuration file for myself!");
258                 return false;
259         }
260
261         if(!read_rsa_private_key())
262                 return false;
263
264         if(!get_config_string(lookup_config(config_tree, "Port"), &myport)
265                         && !get_config_string(lookup_config(myself->connection->config_tree, "Port"), &myport))
266                 myport = xstrdup("655");
267
268         if(!atoi(myport)) {
269                 struct addrinfo *ai = str2addrinfo("localhost", myport, SOCK_DGRAM);
270                 sockaddr_t sa;
271                 if(!ai || !ai->ai_addr)
272                         return false;
273                 free(myport);
274                 memcpy(&sa, ai->ai_addr, ai->ai_addrlen);
275                 sockaddr2str(&sa, NULL, &myport);
276         }
277
278         /* Read in all the subnets specified in the host configuration file */
279
280         cfg = lookup_config(myself->connection->config_tree, "Subnet");
281
282         while(cfg) {
283                 if(!get_config_subnet(cfg, &subnet))
284                         return false;
285
286                 subnet_add(myself, subnet);
287
288                 cfg = lookup_config_next(myself->connection->config_tree, cfg);
289         }
290
291         /* Check some options */
292
293         if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice) && choice)
294                 myself->options |= OPTION_INDIRECT;
295
296         if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice) && choice)
297                 myself->options |= OPTION_TCPONLY;
298
299         if(get_config_bool(lookup_config(myself->connection->config_tree, "IndirectData"), &choice) && choice)
300                 myself->options |= OPTION_INDIRECT;
301
302         if(get_config_bool(lookup_config(myself->connection->config_tree, "TCPOnly"), &choice) && choice)
303                 myself->options |= OPTION_TCPONLY;
304
305         if(myself->options & OPTION_TCPONLY)
306                 myself->options |= OPTION_INDIRECT;
307
308         get_config_bool(lookup_config(config_tree, "DirectOnly"), &directonly);
309         get_config_bool(lookup_config(config_tree, "StrictSubnets"), &strictsubnets);
310         get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
311         strictsubnets |= tunnelserver;
312
313         if(get_config_string(lookup_config(config_tree, "Mode"), &mode)) {
314                 if(!strcasecmp(mode, "router"))
315                         routing_mode = RMODE_ROUTER;
316                 else if(!strcasecmp(mode, "switch"))
317                         routing_mode = RMODE_SWITCH;
318                 else if(!strcasecmp(mode, "hub"))
319                         routing_mode = RMODE_HUB;
320                 else {
321                         logger(LOG_ERR, "Invalid routing mode!");
322                         return false;
323                 }
324                 free(mode);
325         }
326
327         if(get_config_string(lookup_config(config_tree, "Forwarding"), &mode)) {
328                 if(!strcasecmp(mode, "off"))
329                         forwarding_mode = FMODE_OFF;
330                 else if(!strcasecmp(mode, "internal"))
331                         forwarding_mode = FMODE_INTERNAL;
332                 else if(!strcasecmp(mode, "kernel"))
333                         forwarding_mode = FMODE_KERNEL;
334                 else {
335                         logger(LOG_ERR, "Invalid forwarding mode!");
336                         return false;
337                 }
338                 free(mode);
339         }
340
341         choice = true;
342         get_config_bool(lookup_config(myself->connection->config_tree, "PMTUDiscovery"), &choice);
343         get_config_bool(lookup_config(config_tree, "PMTUDiscovery"), &choice);
344         if(choice)
345                 myself->options |= OPTION_PMTU_DISCOVERY;
346
347         choice = true;
348         get_config_bool(lookup_config(config_tree, "ClampMSS"), &choice);
349         get_config_bool(lookup_config(myself->connection->config_tree, "ClampMSS"), &choice);
350         if(choice)
351                 myself->options |= OPTION_CLAMP_MSS;
352
353         get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
354
355 #if !defined(SOL_IP) || !defined(IP_TOS)
356         if(priorityinheritance)
357                 logger(LOG_WARNING, "%s not supported on this platform", "PriorityInheritance");
358 #endif
359
360         if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire))
361                 macexpire = 600;
362
363         if(get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout)) {
364                 if(maxtimeout <= 0) {
365                         logger(LOG_ERR, "Bogus maximum timeout!");
366                         return false;
367                 }
368         } else
369                 maxtimeout = 900;
370
371         if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
372                 if(!strcasecmp(afname, "IPv4"))
373                         addressfamily = AF_INET;
374                 else if(!strcasecmp(afname, "IPv6"))
375                         addressfamily = AF_INET6;
376                 else if(!strcasecmp(afname, "any"))
377                         addressfamily = AF_UNSPEC;
378                 else {
379                         logger(LOG_ERR, "Invalid address family!");
380                         return false;
381                 }
382                 free(afname);
383         }
384
385         get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
386
387         /* Generate packet encryption key */
388
389         if(!get_config_string(lookup_config(myself->connection->config_tree, "Cipher"), &cipher))
390                 cipher = xstrdup("blowfish");
391
392         if(!cipher_open_by_name(&myself->incipher, cipher)) {
393                 logger(LOG_ERR, "Unrecognized cipher type!");
394                 return false;
395         }
396
397         if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
398                 keylifetime = 3600;
399
400         regenerate_key();
401
402         /* Check if we want to use message authentication codes... */
403
404         if(!get_config_string(lookup_config(myself->connection->config_tree, "Digest"), &digest))
405                 digest = xstrdup("sha1");
406
407         int maclength = 4;
408         get_config_int(lookup_config(myself->connection->config_tree, "MACLength"), &maclength);
409
410         if(maclength < 0) {
411                 logger(LOG_ERR, "Bogus MAC length!");
412                 return false;
413         }
414
415         if(!digest_open_by_name(&myself->indigest, digest, maclength)) {
416                 logger(LOG_ERR, "Unrecognized digest type!");
417                 return false;
418         }
419
420         /* Compression */
421
422         if(get_config_int(lookup_config(myself->connection->config_tree, "Compression"), &myself->incompression)) {
423                 if(myself->incompression < 0 || myself->incompression > 11) {
424                         logger(LOG_ERR, "Bogus compression level!");
425                         return false;
426                 }
427         } else
428                 myself->incompression = 0;
429
430         myself->connection->outcompression = 0;
431
432         /* Done */
433
434         myself->nexthop = myself;
435         myself->via = myself;
436         myself->status.reachable = true;
437         node_add(myself);
438
439         graph();
440
441         if(strictsubnets)
442                 load_all_subnets();
443
444         /* Open device */
445
446         if(!setup_device())
447                 return false;
448
449         if(device_fd >= 0) {
450                 event_set(&device_ev, device_fd, EV_READ|EV_PERSIST, handle_device_data, NULL);
451
452                 if (event_add(&device_ev, NULL) < 0) {
453                         logger(LOG_ERR, "event_add failed: %s", strerror(errno));
454                         close_device();
455                         return false;
456                 }
457         }
458
459         /* Run tinc-up script to further initialize the tap interface */
460         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
461         xasprintf(&envp[1], "DEVICE=%s", device ? : "");
462         xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
463         xasprintf(&envp[3], "NAME=%s", myself->name);
464         envp[4] = NULL;
465
466         execute_script("tinc-up", envp);
467
468         for(i = 0; i < 5; i++)
469                 free(envp[i]);
470
471         /* Run subnet-up scripts for our own subnets */
472
473         subnet_update(myself, NULL, true);
474
475         /* Open sockets */
476
477         get_config_string(lookup_config(config_tree, "BindToAddress"), &address);
478
479         hint.ai_family = addressfamily;
480         hint.ai_socktype = SOCK_STREAM;
481         hint.ai_protocol = IPPROTO_TCP;
482         hint.ai_flags = AI_PASSIVE;
483
484         err = getaddrinfo(address, myport, &hint, &ai);
485
486         if(err || !ai) {
487                 logger(LOG_ERR, "System call `%s' failed: %s", "getaddrinfo",
488                            gai_strerror(err));
489                 return false;
490         }
491
492         listen_sockets = 0;
493
494         for(aip = ai; aip; aip = aip->ai_next) {
495                 listen_socket[listen_sockets].tcp =
496                         setup_listen_socket((sockaddr_t *) aip->ai_addr);
497
498                 if(listen_socket[listen_sockets].tcp < 0)
499                         continue;
500
501                 listen_socket[listen_sockets].udp =
502                         setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
503
504                 if(listen_socket[listen_sockets].udp < 0) {
505                         close(listen_socket[listen_sockets].tcp);
506                         continue;
507                 }
508
509                 event_set(&listen_socket[listen_sockets].ev_tcp,
510                                   listen_socket[listen_sockets].tcp,
511                                   EV_READ|EV_PERSIST,
512                                   handle_new_meta_connection, NULL);
513                 if(event_add(&listen_socket[listen_sockets].ev_tcp, NULL) < 0) {
514                         logger(LOG_ERR, "event_add failed: %s", strerror(errno));
515                         abort();
516                 }
517
518                 event_set(&listen_socket[listen_sockets].ev_udp,
519                                   listen_socket[listen_sockets].udp,
520                                   EV_READ|EV_PERSIST,
521                                   handle_incoming_vpn_data, NULL);
522                 if(event_add(&listen_socket[listen_sockets].ev_udp, NULL) < 0) {
523                         logger(LOG_ERR, "event_add failed: %s", strerror(errno));
524                         abort();
525                 }
526
527                 ifdebug(CONNECTIONS) {
528                         hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
529                         logger(LOG_NOTICE, "Listening on %s", hostname);
530                         free(hostname);
531                 }
532
533                 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
534                 listen_sockets++;
535
536                 if(listen_sockets >= MAXSOCKETS) {
537                         logger(LOG_WARNING, "Maximum of %d listening sockets reached", MAXSOCKETS);
538                         break;
539                 }
540         }
541
542         freeaddrinfo(ai);
543
544         if(listen_sockets)
545                 logger(LOG_NOTICE, "Ready");
546         else {
547                 logger(LOG_ERR, "Unable to create any listening socket!");
548                 return false;
549         }
550
551         return true;
552 }
553
554 /*
555   initialize network
556 */
557 bool setup_network(void) {
558         init_connections();
559         init_subnets();
560         init_nodes();
561         init_edges();
562         init_requests();
563
564         if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
565                 if(pinginterval < 1) {
566                         pinginterval = 86400;
567                 }
568         } else
569                 pinginterval = 60;
570
571         if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
572                 pingtimeout = 5;
573         if(pingtimeout < 1 || pingtimeout > pinginterval)
574                 pingtimeout = pinginterval;
575
576         if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize))
577                 maxoutbufsize = 10 * MTU;
578
579         if(!setup_myself())
580                 return false;
581
582         return true;
583 }
584
585 /*
586   close all open network connections
587 */
588 void close_network_connections(void) {
589         splay_node_t *node, *next;
590         connection_t *c;
591         char *envp[5];
592         int i;
593
594         for(node = connection_tree->head; node; node = next) {
595                 next = node->next;
596                 c = node->data;
597                 c->outgoing = false;
598                 terminate_connection(c, false);
599         }
600
601         list_delete_list(outgoing_list);
602
603         if(myself && myself->connection) {
604                 subnet_update(myself, NULL, false);
605                 terminate_connection(myself->connection, false);
606                 free_connection(myself->connection);
607         }
608
609         for(i = 0; i < listen_sockets; i++) {
610                 event_del(&listen_socket[i].ev_tcp);
611                 event_del(&listen_socket[i].ev_udp);
612                 close(listen_socket[i].tcp);
613                 close(listen_socket[i].udp);
614         }
615
616         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
617         xasprintf(&envp[1], "DEVICE=%s", device ? : "");
618         xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
619         xasprintf(&envp[3], "NAME=%s", myself->name);
620         envp[4] = NULL;
621
622         exit_requests();
623         exit_edges();
624         exit_subnets();
625         exit_nodes();
626         exit_connections();
627
628         execute_script("tinc-down", envp);
629
630         if(myport) free(myport);
631
632         for(i = 0; i < 4; i++)
633                 free(envp[i]);
634
635         close_device();
636
637         return;
638 }