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