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