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