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
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20     $Id$
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         cp();
54
55         /* First, check for simple PublicKey statement */
56
57         if(get_config_string(lookup_config(c->config_tree, "PublicKey"), &n)) {
58                 result = rsa_set_hex_public_key(&c->rsa, n, "FFFF");
59                 free(n);
60                 return result;
61         }
62
63         /* Else, check for PublicKeyFile statement and read it */
64
65         if(!get_config_string(lookup_config(c->config_tree, "PublicKeyFile"), &fname))
66                 asprintf(&fname, "%s/hosts/%s", confbase, c->name);
67
68         fp = fopen(fname, "r");
69
70         if(!fp) {
71                 logger(LOG_ERR, _("Error reading RSA public key file `%s': %s"),
72                            fname, strerror(errno));
73                 free(fname);
74                 return false;
75         }
76
77         result = rsa_read_pem_public_key(&c->rsa, fp);
78         fclose(fp);
79
80         if(!result) 
81                 logger(LOG_ERR, _("Reading RSA public key file `%s' failed: %s"), fname, strerror(errno));
82         free(fname);
83         return result;
84 }
85
86 bool read_rsa_private_key() {
87         FILE *fp;
88         char *fname;
89         char *n, *d;
90         bool result;
91
92         cp();
93
94         /* First, check for simple PrivateKey statement */
95
96         if(get_config_string(lookup_config(config_tree, "PrivateKey"), &d)) {
97                 if(!get_config_string(lookup_config(myself->connection->config_tree, "PublicKey"), &n)) {
98                         logger(LOG_ERR, _("PrivateKey used but no PublicKey found!"));
99                         free(d);
100                         return false;
101                 }
102                 result = rsa_set_hex_private_key(&myself->connection->rsa, n, "FFFF", d);
103                 free(n);
104                 free(d);
105                 return true;
106         }
107
108         /* Else, check for PrivateKeyFile statement and read it */
109
110         if(!get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname))
111                 asprintf(&fname, "%s/rsa_key.priv", confbase);
112
113         fp = fopen(fname, "r");
114
115         if(!fp) {
116                 logger(LOG_ERR, _("Error reading RSA private key file `%s': %s"),
117                            fname, strerror(errno));
118                 free(fname);
119                 return false;
120         }
121
122 #if !defined(HAVE_MINGW) && !defined(HAVE_CYGWIN)
123         struct stat s;
124
125         if(fstat(fileno(fp), &s)) {
126                 logger(LOG_ERR, _("Could not stat RSA private key file `%s': %s'"), fname, strerror(errno));
127                 free(fname);
128                 return false;
129         }
130
131         if(s.st_mode & ~0100700)
132                 logger(LOG_WARNING, _("Warning: insecure file permissions for RSA private key file `%s'!"), fname);
133 #endif
134
135         result = rsa_read_pem_private_key(&myself->connection->rsa, fp);
136         fclose(fp);
137
138         if(!result) 
139                 logger(LOG_ERR, _("Reading RSA private key file `%s' failed: %s"), fname, strerror(errno));
140         free(fname);
141         return result;
142 }
143
144 static struct event keyexpire_event;
145
146 static void keyexpire_handler(int fd, short events, void *data) {
147         regenerate_key();
148 }
149
150 void regenerate_key() {
151         if(timeout_initialized(&keyexpire_event)) {
152                 ifdebug(STATUS) logger(LOG_INFO, _("Expiring symmetric keys"));
153                 event_del(&keyexpire_event);
154                 send_key_changed(broadcast, myself);
155         } else {
156                 timeout_set(&keyexpire_event, keyexpire_handler, NULL);
157         }
158
159         event_add(&keyexpire_event, &(struct timeval){keylifetime, 0});
160 }
161
162 /*
163   Configure node_t myself and set up the local sockets (listen only)
164 */
165 bool setup_myself(void) {
166         config_t *cfg;
167         subnet_t *subnet;
168         char *name, *hostname, *mode, *afname, *cipher, *digest;
169         char *address = NULL;
170         char *envp[5];
171         struct addrinfo *ai, *aip, hint = {0};
172         bool choice;
173         int i, err;
174
175         cp();
176
177         myself = new_node();
178         myself->connection = new_connection();
179         init_configuration(&myself->connection->config_tree);
180
181         asprintf(&myself->hostname, _("MYSELF"));
182         asprintf(&myself->connection->hostname, _("MYSELF"));
183
184         myself->connection->options = 0;
185         myself->connection->protocol_version = PROT_CURRENT;
186
187         if(!get_config_string(lookup_config(config_tree, "Name"), &name)) {     /* Not acceptable */
188                 logger(LOG_ERR, _("Name for tinc daemon required!"));
189                 return false;
190         }
191
192         if(!check_id(name)) {
193                 logger(LOG_ERR, _("Invalid name for myself!"));
194                 free(name);
195                 return false;
196         }
197
198         myself->name = name;
199         myself->connection->name = xstrdup(name);
200
201         if(!read_connection_config(myself->connection)) {
202                 logger(LOG_ERR, _("Cannot open host configuration file for myself!"));
203                 return false;
204         }
205
206         if(!read_rsa_private_key())
207                 return false;
208
209         if(!get_config_string(lookup_config(myself->connection->config_tree, "Port"), &myport))
210                 asprintf(&myport, "655");
211
212         /* Read in all the subnets specified in the host configuration file */
213
214         cfg = lookup_config(myself->connection->config_tree, "Subnet");
215
216         while(cfg) {
217                 if(!get_config_subnet(cfg, &subnet))
218                         return false;
219
220                 subnet_add(myself, subnet);
221
222                 cfg = lookup_config_next(myself->connection->config_tree, cfg);
223         }
224
225         /* Check some options */
226
227         if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice) && choice)
228                 myself->options |= OPTION_INDIRECT;
229
230         if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice) && choice)
231                 myself->options |= OPTION_TCPONLY;
232
233         if(get_config_bool(lookup_config(myself->connection->config_tree, "IndirectData"), &choice) && choice)
234                 myself->options |= OPTION_INDIRECT;
235
236         if(get_config_bool(lookup_config(myself->connection->config_tree, "TCPOnly"), &choice) && choice)
237                 myself->options |= OPTION_TCPONLY;
238
239         if(myself->options & OPTION_TCPONLY)
240                 myself->options |= OPTION_INDIRECT;
241
242         get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
243
244         if(get_config_string(lookup_config(config_tree, "Mode"), &mode)) {
245                 if(!strcasecmp(mode, "router"))
246                         routing_mode = RMODE_ROUTER;
247                 else if(!strcasecmp(mode, "switch"))
248                         routing_mode = RMODE_SWITCH;
249                 else if(!strcasecmp(mode, "hub"))
250                         routing_mode = RMODE_HUB;
251                 else {
252                         logger(LOG_ERR, _("Invalid routing mode!"));
253                         return false;
254                 }
255                 free(mode);
256         } else
257                 routing_mode = RMODE_ROUTER;
258
259         if(routing_mode == RMODE_ROUTER)
260                 if(!get_config_bool(lookup_config(myself->connection->config_tree, "PMTUDiscovery"), &choice) || choice)
261                         myself->options |= OPTION_PMTU_DISCOVERY;
262
263         get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
264
265 #if !defined(SOL_IP) || !defined(IP_TOS)
266         if(priorityinheritance)
267                 logger(LOG_WARNING, _("%s not supported on this platform"), "PriorityInheritance");
268 #endif
269
270         if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire))
271                 macexpire = 600;
272
273         if(get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout)) {
274                 if(maxtimeout <= 0) {
275                         logger(LOG_ERR, _("Bogus maximum timeout!"));
276                         return false;
277                 }
278         } else
279                 maxtimeout = 900;
280
281         if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
282                 if(!strcasecmp(afname, "IPv4"))
283                         addressfamily = AF_INET;
284                 else if(!strcasecmp(afname, "IPv6"))
285                         addressfamily = AF_INET6;
286                 else if(!strcasecmp(afname, "any"))
287                         addressfamily = AF_UNSPEC;
288                 else {
289                         logger(LOG_ERR, _("Invalid address family!"));
290                         return false;
291                 }
292                 free(afname);
293         }
294
295         get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
296
297         /* Generate packet encryption key */
298
299         if(!get_config_string(lookup_config(myself->connection->config_tree, "Cipher"), &cipher))
300                 cipher = xstrdup("blowfish");
301
302         if(!cipher_open_by_name(&myself->incipher, cipher)) {
303                 logger(LOG_ERR, _("Unrecognized cipher type!"));
304                 return false;
305         }
306
307         if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
308                 keylifetime = 3600;
309
310         regenerate_key();
311
312         /* Check if we want to use message authentication codes... */
313
314         if(!get_config_string(lookup_config(myself->connection->config_tree, "Digest"), &digest))
315                 digest = xstrdup("sha1");
316
317         if(!digest_open_by_name(&myself->indigest, digest)) {
318                 logger(LOG_ERR, _("Unrecognized digest type!"));
319                 return false;
320         }
321
322         if(!get_config_int(lookup_config(myself->connection->config_tree, "MACLength"), &myself->inmaclength))
323
324         if(digest_active(&myself->indigest)) {
325                 if(myself->inmaclength > digest_length(&myself->indigest)) {
326                         logger(LOG_ERR, _("MAC length exceeds size of digest!"));
327                         return false;
328                 } else if(myself->inmaclength < 0) {
329                         logger(LOG_ERR, _("Bogus MAC length!"));
330                         return false;
331                 }
332         }
333
334         /* Compression */
335
336         if(get_config_int(lookup_config(myself->connection->config_tree, "Compression"), &myself->incompression)) {
337                 if(myself->incompression < 0 || myself->incompression > 11) {
338                         logger(LOG_ERR, _("Bogus compression level!"));
339                         return false;
340                 }
341         } else
342                 myself->incompression = 0;
343
344         myself->connection->outcompression = 0;
345
346         /* Done */
347
348         myself->nexthop = myself;
349         myself->via = myself;
350         myself->status.reachable = true;
351         node_add(myself);
352
353         graph();
354
355         /* Open device */
356
357         if(!setup_device())
358                 return false;
359
360         event_set(&device_ev, device_fd, EV_READ|EV_PERSIST, handle_device_data, NULL);
361
362         if (event_add(&device_ev, NULL) < 0) {
363                 logger(LOG_ERR, _("event_add failed: %s"), strerror(errno));
364                 close_device();
365                 return false;
366         }
367
368         /* Run tinc-up script to further initialize the tap interface */
369         asprintf(&envp[0], "NETNAME=%s", netname ? : "");
370         asprintf(&envp[1], "DEVICE=%s", device ? : "");
371         asprintf(&envp[2], "INTERFACE=%s", iface ? : "");
372         asprintf(&envp[3], "NAME=%s", myself->name);
373         envp[4] = NULL;
374
375         execute_script("tinc-up", envp);
376
377         for(i = 0; i < 5; i++)
378                 free(envp[i]);
379
380         /* Run subnet-up scripts for our own subnets */
381
382         subnet_update(myself, NULL, true);
383
384         /* Open sockets */
385
386         get_config_string(lookup_config(config_tree, "BindToAddress"), &address);
387
388         hint.ai_family = addressfamily;
389         hint.ai_socktype = SOCK_STREAM;
390         hint.ai_protocol = IPPROTO_TCP;
391         hint.ai_flags = AI_PASSIVE;
392
393         err = getaddrinfo(address, myport, &hint, &ai);
394
395         if(err || !ai) {
396                 logger(LOG_ERR, _("System call `%s' failed: %s"), "getaddrinfo",
397                            gai_strerror(err));
398                 return false;
399         }
400
401         listen_sockets = 0;
402
403         for(aip = ai; aip; aip = aip->ai_next) {
404                 listen_socket[listen_sockets].tcp =
405                         setup_listen_socket((sockaddr_t *) aip->ai_addr);
406
407                 if(listen_socket[listen_sockets].tcp < 0)
408                         continue;
409
410                 listen_socket[listen_sockets].udp =
411                         setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
412
413                 if(listen_socket[listen_sockets].udp < 0) {
414                         close(listen_socket[listen_sockets].tcp);
415                         continue;
416                 }
417
418                 event_set(&listen_socket[listen_sockets].ev_tcp,
419                                   listen_socket[listen_sockets].tcp,
420                                   EV_READ|EV_PERSIST,
421                                   handle_new_meta_connection, NULL);
422                 if(event_add(&listen_socket[listen_sockets].ev_tcp, NULL) < 0) {
423                         logger(LOG_EMERG, _("event_add failed: %s"), strerror(errno));
424                         abort();
425                 }
426
427                 event_set(&listen_socket[listen_sockets].ev_udp,
428                                   listen_socket[listen_sockets].udp,
429                                   EV_READ|EV_PERSIST,
430                                   handle_incoming_vpn_data, NULL);
431                 if(event_add(&listen_socket[listen_sockets].ev_udp, NULL) < 0) {
432                         logger(LOG_EMERG, _("event_add failed: %s"), strerror(errno));
433                         abort();
434                 }
435
436                 ifdebug(CONNECTIONS) {
437                         hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
438                         logger(LOG_NOTICE, _("Listening on %s"), hostname);
439                         free(hostname);
440                 }
441
442                 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
443                 listen_sockets++;
444
445                 if(listen_sockets >= MAXSOCKETS) {
446                         logger(LOG_WARNING, _("Maximum of %d listening sockets reached"), MAXSOCKETS);
447                         break;
448                 }
449         }
450
451         freeaddrinfo(ai);
452
453         if(listen_sockets)
454                 logger(LOG_NOTICE, _("Ready"));
455         else {
456                 logger(LOG_ERR, _("Unable to create any listening socket!"));
457                 return false;
458         }
459
460         return true;
461 }
462
463 /*
464   initialize network
465 */
466 bool setup_network(void)
467 {
468         cp();
469
470         init_connections();
471         init_subnets();
472         init_nodes();
473         init_edges();
474         init_requests();
475
476         if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
477                 if(pinginterval < 1) {
478                         pinginterval = 86400;
479                 }
480         } else
481                 pinginterval = 60;
482
483         if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
484                 pingtimeout = 5;
485         if(pingtimeout < 1 || pingtimeout > pinginterval)
486                 pingtimeout = pinginterval;
487
488         if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize))
489                 maxoutbufsize = 10 * MTU;
490
491         if(!setup_myself())
492                 return false;
493
494         return true;
495 }
496
497 /*
498   close all open network connections
499 */
500 void close_network_connections(void) {
501         splay_node_t *node, *next;
502         connection_t *c;
503         char *envp[5];
504         int i;
505
506         cp();
507
508         for(node = connection_tree->head; node; node = next) {
509                 next = node->next;
510                 c = node->data;
511                 c->outgoing = false;
512                 terminate_connection(c, false);
513         }
514
515         list_delete_list(outgoing_list);
516
517         if(myself && myself->connection) {
518                 subnet_update(myself, NULL, false);
519                 terminate_connection(myself->connection, false);
520                 free_connection(myself->connection);
521         }
522
523         for(i = 0; i < listen_sockets; i++) {
524                 event_del(&listen_socket[i].ev_tcp);
525                 event_del(&listen_socket[i].ev_udp);
526                 close(listen_socket[i].tcp);
527                 close(listen_socket[i].udp);
528         }
529
530         asprintf(&envp[0], "NETNAME=%s", netname ? : "");
531         asprintf(&envp[1], "DEVICE=%s", device ? : "");
532         asprintf(&envp[2], "INTERFACE=%s", iface ? : "");
533         asprintf(&envp[3], "NAME=%s", myself->name);
534         envp[4] = NULL;
535
536         exit_requests();
537         exit_edges();
538         exit_subnets();
539         exit_nodes();
540         exit_connections();
541
542         execute_script("tinc-down", envp);
543
544         if(myport) free(myport);
545
546         for(i = 0; i < 4; i++)
547                 free(envp[i]);
548
549         close_device();
550
551         return;
552 }