Merge branch 'master' into 1.1
[tinc] / src / net_setup.c
1 /*
2     net_setup.c -- Setup.
3     Copyright (C) 1998-2005 Ivo Timmermans,
4                   2000-2009 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   Configure node_t myself and set up the local sockets (listen only)
159 */
160 bool setup_myself(void) {
161         config_t *cfg;
162         subnet_t *subnet;
163         char *name, *hostname, *mode, *afname, *cipher, *digest;
164         char *address = NULL;
165         char *envp[5];
166         struct addrinfo *ai, *aip, hint = {0};
167         bool choice;
168         int i, err;
169
170         myself = new_node();
171         myself->connection = new_connection();
172         init_configuration(&myself->connection->config_tree);
173
174         xasprintf(&myself->hostname, "MYSELF");
175         xasprintf(&myself->connection->hostname, "MYSELF");
176
177         myself->connection->options = 0;
178         myself->connection->protocol_version = PROT_CURRENT;
179
180         if(!get_config_string(lookup_config(config_tree, "Name"), &name)) {     /* Not acceptable */
181                 logger(LOG_ERR, "Name for tinc daemon required!");
182                 return false;
183         }
184
185         if(!check_id(name)) {
186                 logger(LOG_ERR, "Invalid name for myself!");
187                 free(name);
188                 return false;
189         }
190
191         myself->name = name;
192         myself->connection->name = xstrdup(name);
193
194         if(!read_connection_config(myself->connection)) {
195                 logger(LOG_ERR, "Cannot open host configuration file for myself!");
196                 return false;
197         }
198
199         if(!read_rsa_private_key())
200                 return false;
201
202         if(!get_config_string(lookup_config(myself->connection->config_tree, "Port"), &myport))
203                 xasprintf(&myport, "655");
204
205         /* Read in all the subnets specified in the host configuration file */
206
207         cfg = lookup_config(myself->connection->config_tree, "Subnet");
208
209         while(cfg) {
210                 if(!get_config_subnet(cfg, &subnet))
211                         return false;
212
213                 subnet_add(myself, subnet);
214
215                 cfg = lookup_config_next(myself->connection->config_tree, cfg);
216         }
217
218         /* Check some options */
219
220         if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice) && choice)
221                 myself->options |= OPTION_INDIRECT;
222
223         if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice) && choice)
224                 myself->options |= OPTION_TCPONLY;
225
226         if(get_config_bool(lookup_config(myself->connection->config_tree, "IndirectData"), &choice) && choice)
227                 myself->options |= OPTION_INDIRECT;
228
229         if(get_config_bool(lookup_config(myself->connection->config_tree, "TCPOnly"), &choice) && choice)
230                 myself->options |= OPTION_TCPONLY;
231
232         if(myself->options & OPTION_TCPONLY)
233                 myself->options |= OPTION_INDIRECT;
234
235         get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
236
237         if(get_config_string(lookup_config(config_tree, "Mode"), &mode)) {
238                 if(!strcasecmp(mode, "router"))
239                         routing_mode = RMODE_ROUTER;
240                 else if(!strcasecmp(mode, "switch"))
241                         routing_mode = RMODE_SWITCH;
242                 else if(!strcasecmp(mode, "hub"))
243                         routing_mode = RMODE_HUB;
244                 else {
245                         logger(LOG_ERR, "Invalid routing mode!");
246                         return false;
247                 }
248                 free(mode);
249         } else
250                 routing_mode = RMODE_ROUTER;
251
252         // Enable PMTUDiscovery by default if we are in router mode.
253
254         choice = routing_mode == RMODE_ROUTER;
255         get_config_bool(lookup_config(myself->connection->config_tree, "PMTUDiscovery"), &choice);
256         if(choice)      
257                 myself->options |= OPTION_PMTU_DISCOVERY;
258
259         get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
260
261 #if !defined(SOL_IP) || !defined(IP_TOS)
262         if(priorityinheritance)
263                 logger(LOG_WARNING, "%s not supported on this platform", "PriorityInheritance");
264 #endif
265
266         if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire))
267                 macexpire = 600;
268
269         if(get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout)) {
270                 if(maxtimeout <= 0) {
271                         logger(LOG_ERR, "Bogus maximum timeout!");
272                         return false;
273                 }
274         } else
275                 maxtimeout = 900;
276
277         if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
278                 if(!strcasecmp(afname, "IPv4"))
279                         addressfamily = AF_INET;
280                 else if(!strcasecmp(afname, "IPv6"))
281                         addressfamily = AF_INET6;
282                 else if(!strcasecmp(afname, "any"))
283                         addressfamily = AF_UNSPEC;
284                 else {
285                         logger(LOG_ERR, "Invalid address family!");
286                         return false;
287                 }
288                 free(afname);
289         }
290
291         get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
292
293         /* Generate packet encryption key */
294
295         if(!get_config_string(lookup_config(myself->connection->config_tree, "Cipher"), &cipher))
296                 cipher = xstrdup("aes256");
297
298         if(!cipher_open_by_name(&myself->incipher, cipher)) {
299                 logger(LOG_ERR, "Unrecognized cipher type!");
300                 return false;
301         }
302
303         if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
304                 keylifetime = 3600;
305
306         regenerate_key();
307
308         /* Check if we want to use message authentication codes... */
309
310         if(!get_config_string(lookup_config(myself->connection->config_tree, "Digest"), &digest))
311                 digest = xstrdup("sha256");
312
313         int maclength = 4;
314         get_config_int(lookup_config(myself->connection->config_tree, "MACLength"), &maclength);
315
316         if(maclength < 0) {
317                 logger(LOG_ERR, "Bogus MAC length!");
318                 return false;
319         }
320
321         if(!digest_open_by_name(&myself->indigest, digest, maclength)) {
322                 logger(LOG_ERR, "Unrecognized digest type!");
323                 return false;
324         }
325
326         /* Compression */
327
328         if(get_config_int(lookup_config(myself->connection->config_tree, "Compression"), &myself->incompression)) {
329                 if(myself->incompression < 0 || myself->incompression > 11) {
330                         logger(LOG_ERR, "Bogus compression level!");
331                         return false;
332                 }
333         } else
334                 myself->incompression = 0;
335
336         myself->connection->outcompression = 0;
337
338         /* Done */
339
340         myself->nexthop = myself;
341         myself->via = myself;
342         myself->status.reachable = true;
343         node_add(myself);
344
345         graph();
346
347         /* Open device */
348
349         if(!setup_device())
350                 return false;
351
352         event_set(&device_ev, device_fd, EV_READ|EV_PERSIST, handle_device_data, NULL);
353
354         if (event_add(&device_ev, NULL) < 0) {
355                 logger(LOG_ERR, "event_add failed: %s", strerror(errno));
356                 close_device();
357                 return false;
358         }
359
360         /* Run tinc-up script to further initialize the tap interface */
361         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
362         xasprintf(&envp[1], "DEVICE=%s", device ? : "");
363         xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
364         xasprintf(&envp[3], "NAME=%s", myself->name);
365         envp[4] = NULL;
366
367         execute_script("tinc-up", envp);
368
369         for(i = 0; i < 5; i++)
370                 free(envp[i]);
371
372         /* Run subnet-up scripts for our own subnets */
373
374         subnet_update(myself, NULL, true);
375
376         /* Open sockets */
377
378         get_config_string(lookup_config(config_tree, "BindToAddress"), &address);
379
380         hint.ai_family = addressfamily;
381         hint.ai_socktype = SOCK_STREAM;
382         hint.ai_protocol = IPPROTO_TCP;
383         hint.ai_flags = AI_PASSIVE;
384
385         err = getaddrinfo(address, myport, &hint, &ai);
386
387         if(err || !ai) {
388                 logger(LOG_ERR, "System call `%s' failed: %s", "getaddrinfo",
389                            gai_strerror(err));
390                 return false;
391         }
392
393         listen_sockets = 0;
394
395         for(aip = ai; aip; aip = aip->ai_next) {
396                 listen_socket[listen_sockets].tcp =
397                         setup_listen_socket((sockaddr_t *) aip->ai_addr);
398
399                 if(listen_socket[listen_sockets].tcp < 0)
400                         continue;
401
402                 listen_socket[listen_sockets].udp =
403                         setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
404
405                 if(listen_socket[listen_sockets].udp < 0) {
406                         close(listen_socket[listen_sockets].tcp);
407                         continue;
408                 }
409
410                 event_set(&listen_socket[listen_sockets].ev_tcp,
411                                   listen_socket[listen_sockets].tcp,
412                                   EV_READ|EV_PERSIST,
413                                   handle_new_meta_connection, NULL);
414                 if(event_add(&listen_socket[listen_sockets].ev_tcp, NULL) < 0) {
415                         logger(LOG_EMERG, "event_add failed: %s", strerror(errno));
416                         abort();
417                 }
418
419                 event_set(&listen_socket[listen_sockets].ev_udp,
420                                   listen_socket[listen_sockets].udp,
421                                   EV_READ|EV_PERSIST,
422                                   handle_incoming_vpn_data, NULL);
423                 if(event_add(&listen_socket[listen_sockets].ev_udp, NULL) < 0) {
424                         logger(LOG_EMERG, "event_add failed: %s", strerror(errno));
425                         abort();
426                 }
427
428                 ifdebug(CONNECTIONS) {
429                         hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
430                         logger(LOG_NOTICE, "Listening on %s", hostname);
431                         free(hostname);
432                 }
433
434                 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
435                 listen_sockets++;
436
437                 if(listen_sockets >= MAXSOCKETS) {
438                         logger(LOG_WARNING, "Maximum of %d listening sockets reached", MAXSOCKETS);
439                         break;
440                 }
441         }
442
443         freeaddrinfo(ai);
444
445         if(listen_sockets)
446                 logger(LOG_NOTICE, "Ready");
447         else {
448                 logger(LOG_ERR, "Unable to create any listening socket!");
449                 return false;
450         }
451
452         return true;
453 }
454
455 /*
456   initialize network
457 */
458 bool setup_network(void) {
459         init_connections();
460         init_subnets();
461         init_nodes();
462         init_edges();
463         init_requests();
464
465         if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
466                 if(pinginterval < 1) {
467                         pinginterval = 86400;
468                 }
469         } else
470                 pinginterval = 60;
471
472         if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
473                 pingtimeout = 5;
474         if(pingtimeout < 1 || pingtimeout > pinginterval)
475                 pingtimeout = pinginterval;
476
477         if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize))
478                 maxoutbufsize = 10 * MTU;
479
480         if(!setup_myself())
481                 return false;
482
483         return true;
484 }
485
486 /*
487   close all open network connections
488 */
489 void close_network_connections(void) {
490         splay_node_t *node, *next;
491         connection_t *c;
492         char *envp[5];
493         int i;
494
495         for(node = connection_tree->head; node; node = next) {
496                 next = node->next;
497                 c = node->data;
498                 c->outgoing = false;
499                 terminate_connection(c, false);
500         }
501
502         list_delete_list(outgoing_list);
503
504         if(myself && myself->connection) {
505                 subnet_update(myself, NULL, false);
506                 terminate_connection(myself->connection, false);
507                 free_connection(myself->connection);
508         }
509
510         for(i = 0; i < listen_sockets; i++) {
511                 event_del(&listen_socket[i].ev_tcp);
512                 event_del(&listen_socket[i].ev_udp);
513                 close(listen_socket[i].tcp);
514                 close(listen_socket[i].udp);
515         }
516
517         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
518         xasprintf(&envp[1], "DEVICE=%s", device ? : "");
519         xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
520         xasprintf(&envp[3], "NAME=%s", myself->name);
521         envp[4] = NULL;
522
523         exit_requests();
524         exit_edges();
525         exit_subnets();
526         exit_nodes();
527         exit_connections();
528
529         execute_script("tinc-down", envp);
530
531         if(myport) free(myport);
532
533         for(i = 0; i < 4; i++)
534                 free(envp[i]);
535
536         close_device();
537
538         return;
539 }