Disable PMTUDiscovery in switch and hub modes.
[oweals/tinc.git] / 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 <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 "event.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
49 bool read_rsa_public_key(connection_t *c)
50 {
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 {
152         FILE *fp;
153         char *fname, *key, *pubkey;
154         struct stat s;
155
156         cp();
157
158         if(get_config_string(lookup_config(config_tree, "PrivateKey"), &key)) {
159                 if(!get_config_string(lookup_config(myself->connection->config_tree, "PublicKey"), &pubkey)) {
160                         logger(LOG_ERR, _("PrivateKey used but no PublicKey found!"));
161                         return false;
162                 }
163                 myself->connection->rsa_key = RSA_new();
164 //              RSA_blinding_on(myself->connection->rsa_key, NULL);
165                 BN_hex2bn(&myself->connection->rsa_key->d, key);
166                 BN_hex2bn(&myself->connection->rsa_key->n, pubkey);
167                 BN_hex2bn(&myself->connection->rsa_key->e, "FFFF");
168                 free(key);
169                 free(pubkey);
170                 return true;
171         }
172
173         if(!get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname))
174                 asprintf(&fname, "%s/rsa_key.priv", confbase);
175
176         fp = fopen(fname, "r");
177
178         if(!fp) {
179                 logger(LOG_ERR, _("Error reading RSA private key file `%s': %s"),
180                            fname, strerror(errno));
181                 free(fname);
182                 return false;
183         }
184
185 #if !defined(HAVE_MINGW) && !defined(HAVE_CYGWIN)
186         if(fstat(fileno(fp), &s)) {
187                 logger(LOG_ERR, _("Could not stat RSA private key file `%s': %s'"),
188                                 fname, strerror(errno));
189                 free(fname);
190                 return false;
191         }
192
193         if(s.st_mode & ~0100700)
194                 logger(LOG_WARNING, _("Warning: insecure file permissions for RSA private key file `%s'!"), fname);
195 #endif
196
197         myself->connection->rsa_key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
198         fclose(fp);
199
200         if(!myself->connection->rsa_key) {
201                 logger(LOG_ERR, _("Reading RSA private key file `%s' failed: %s"),
202                            fname, strerror(errno));
203                 free(fname);
204                 return false;
205         }
206
207         free(fname);
208         return true;
209 }
210
211 /*
212   Configure node_t myself and set up the local sockets (listen only)
213 */
214 bool setup_myself(void)
215 {
216         config_t *cfg;
217         subnet_t *subnet;
218         char *name, *hostname, *mode, *afname, *cipher, *digest;
219         char *address = NULL;
220         char *envp[5];
221         struct addrinfo *ai, *aip, hint = {0};
222         bool choice;
223         int i, err;
224
225         cp();
226
227         myself = new_node();
228         myself->connection = new_connection();
229         init_configuration(&myself->connection->config_tree);
230
231         asprintf(&myself->hostname, _("MYSELF"));
232         asprintf(&myself->connection->hostname, _("MYSELF"));
233
234         myself->connection->options = 0;
235         myself->connection->protocol_version = PROT_CURRENT;
236
237         if(!get_config_string(lookup_config(config_tree, "Name"), &name)) {     /* Not acceptable */
238                 logger(LOG_ERR, _("Name for tinc daemon required!"));
239                 return false;
240         }
241
242         if(!check_id(name)) {
243                 logger(LOG_ERR, _("Invalid name for myself!"));
244                 free(name);
245                 return false;
246         }
247
248         myself->name = name;
249         myself->connection->name = xstrdup(name);
250
251         if(!read_connection_config(myself->connection)) {
252                 logger(LOG_ERR, _("Cannot open host configuration file for myself!"));
253                 return false;
254         }
255
256         if(!read_rsa_private_key())
257                 return false;
258
259         if(!get_config_string(lookup_config(myself->connection->config_tree, "Port"), &myport))
260                 asprintf(&myport, "655");
261
262         /* Read in all the subnets specified in the host configuration file */
263
264         cfg = lookup_config(myself->connection->config_tree, "Subnet");
265
266         while(cfg) {
267                 if(!get_config_subnet(cfg, &subnet))
268                         return false;
269
270                 subnet_add(myself, subnet);
271
272                 cfg = lookup_config_next(myself->connection->config_tree, cfg);
273         }
274
275         /* Check some options */
276
277         if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice) && choice)
278                 myself->options |= OPTION_INDIRECT;
279
280         if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice) && choice)
281                 myself->options |= OPTION_TCPONLY;
282
283         if(get_config_bool(lookup_config(myself->connection->config_tree, "IndirectData"), &choice) && choice)
284                 myself->options |= OPTION_INDIRECT;
285
286         if(get_config_bool(lookup_config(myself->connection->config_tree, "TCPOnly"), &choice) && choice)
287                 myself->options |= OPTION_TCPONLY;
288
289         if(myself->options & OPTION_TCPONLY)
290                 myself->options |= OPTION_INDIRECT;
291
292         get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
293
294         if(get_config_string(lookup_config(config_tree, "Mode"), &mode)) {
295                 if(!strcasecmp(mode, "router"))
296                         routing_mode = RMODE_ROUTER;
297                 else if(!strcasecmp(mode, "switch"))
298                         routing_mode = RMODE_SWITCH;
299                 else if(!strcasecmp(mode, "hub"))
300                         routing_mode = RMODE_HUB;
301                 else {
302                         logger(LOG_ERR, _("Invalid routing mode!"));
303                         return false;
304                 }
305                 free(mode);
306         } else
307                 routing_mode = RMODE_ROUTER;
308
309         if(routing_mode == RMODE_ROUTER)
310                 if(!get_config_bool(lookup_config(myself->connection->config_tree, "PMTUDiscovery"), &choice) || choice)
311                         myself->options |= OPTION_PMTU_DISCOVERY;
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         /* Run tinc-up script to further initialize the tap interface */
452         asprintf(&envp[0], "NETNAME=%s", netname ? : "");
453         asprintf(&envp[1], "DEVICE=%s", device ? : "");
454         asprintf(&envp[2], "INTERFACE=%s", iface ? : "");
455         asprintf(&envp[3], "NAME=%s", myself->name);
456         envp[4] = NULL;
457
458         execute_script("tinc-up", envp);
459
460         for(i = 0; i < 5; i++)
461                 free(envp[i]);
462
463         /* Run subnet-up scripts for our own subnets */
464
465         subnet_update(myself, NULL, true);
466
467         /* Open sockets */
468
469         get_config_string(lookup_config(config_tree, "BindToAddress"), &address);
470
471         hint.ai_family = addressfamily;
472         hint.ai_socktype = SOCK_STREAM;
473         hint.ai_protocol = IPPROTO_TCP;
474         hint.ai_flags = AI_PASSIVE;
475
476         err = getaddrinfo(address, myport, &hint, &ai);
477
478         if(err || !ai) {
479                 logger(LOG_ERR, _("System call `%s' failed: %s"), "getaddrinfo",
480                            gai_strerror(err));
481                 return false;
482         }
483
484         listen_sockets = 0;
485
486         for(aip = ai; aip; aip = aip->ai_next) {
487                 listen_socket[listen_sockets].tcp =
488                         setup_listen_socket((sockaddr_t *) aip->ai_addr);
489
490                 if(listen_socket[listen_sockets].tcp < 0)
491                         continue;
492
493                 listen_socket[listen_sockets].udp =
494                         setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
495
496                 if(listen_socket[listen_sockets].udp < 0)
497                         continue;
498
499                 ifdebug(CONNECTIONS) {
500                         hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
501                         logger(LOG_NOTICE, _("Listening on %s"), hostname);
502                         free(hostname);
503                 }
504
505                 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
506                 listen_sockets++;
507         }
508
509         freeaddrinfo(ai);
510
511         if(listen_sockets)
512                 logger(LOG_NOTICE, _("Ready"));
513         else {
514                 logger(LOG_ERR, _("Unable to create any listening socket!"));
515                 return false;
516         }
517
518         return true;
519 }
520
521 /*
522   setup all initial network connections
523 */
524 bool setup_network_connections(void)
525 {
526         cp();
527
528         now = time(NULL);
529
530         init_events();
531         init_connections();
532         init_subnets();
533         init_nodes();
534         init_edges();
535         init_requests();
536
537         if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
538                 if(pinginterval < 1) {
539                         pinginterval = 86400;
540                 }
541         } else
542                 pinginterval = 60;
543
544         if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
545                 pingtimeout = 5;
546         if(pingtimeout < 1 || pingtimeout > pinginterval)
547                 pingtimeout = pinginterval;
548
549         if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize))
550                 maxoutbufsize = 4 * MTU;
551
552         if(!setup_myself())
553                 return false;
554
555         try_outgoing_connections();
556
557         return true;
558 }
559
560 /*
561   close all open network connections
562 */
563 void close_network_connections(void)
564 {
565         avl_node_t *node, *next;
566         connection_t *c;
567         char *envp[5];
568         int i;
569
570         cp();
571
572         for(node = connection_tree->head; node; node = next) {
573                 next = node->next;
574                 c = node->data;
575                 c->outgoing = false;
576                 terminate_connection(c, false);
577         }
578
579         list_delete_list(outgoing_list);
580
581         if(myself && myself->connection) {
582                 subnet_update(myself, NULL, false);
583                 terminate_connection(myself->connection, false);
584                 free_connection(myself->connection);
585         }
586
587         for(i = 0; i < listen_sockets; i++) {
588                 close(listen_socket[i].tcp);
589                 close(listen_socket[i].udp);
590         }
591
592         asprintf(&envp[0], "NETNAME=%s", netname ? : "");
593         asprintf(&envp[1], "DEVICE=%s", device ? : "");
594         asprintf(&envp[2], "INTERFACE=%s", iface ? : "");
595         asprintf(&envp[3], "NAME=%s", myself->name);
596         envp[4] = NULL;
597
598         exit_requests();
599         exit_edges();
600         exit_subnets();
601         exit_nodes();
602         exit_connections();
603         exit_events();
604
605         execute_script("tinc-down", envp);
606
607         if(myport) free(myport);
608
609         EVP_CIPHER_CTX_cleanup(&packet_ctx);
610
611         for(i = 0; i < 4; i++)
612                 free(envp[i]);
613
614         close_device();
615
616         return;
617 }