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