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