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