Update the address of the Free Software Foundation in all copyright headers.
[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 along
17     with this program; if not, write to the Free Software Foundation, Inc.,
18     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20
21 #include "system.h"
22
23 #include <openssl/pem.h>
24 #include <openssl/rsa.h>
25 #include <openssl/rand.h>
26 #include <openssl/err.h>
27 #include <openssl/evp.h>
28
29 #include "avl_tree.h"
30 #include "conf.h"
31 #include "connection.h"
32 #include "device.h"
33 #include "event.h"
34 #include "graph.h"
35 #include "logger.h"
36 #include "net.h"
37 #include "netutl.h"
38 #include "process.h"
39 #include "protocol.h"
40 #include "route.h"
41 #include "subnet.h"
42 #include "utils.h"
43 #include "xalloc.h"
44
45 char *myport;
46
47 bool read_rsa_public_key(connection_t *c)
48 {
49         FILE *fp;
50         char *fname;
51         char *key;
52
53         cp();
54
55         if(!c->rsa_key) {
56                 c->rsa_key = RSA_new();
57 //              RSA_blinding_on(c->rsa_key, NULL);
58         }
59
60         /* First, check for simple PublicKey statement */
61
62         if(get_config_string(lookup_config(c->config_tree, "PublicKey"), &key)) {
63                 BN_hex2bn(&c->rsa_key->n, key);
64                 BN_hex2bn(&c->rsa_key->e, "FFFF");
65                 free(key);
66                 return true;
67         }
68
69         /* Else, check for PublicKeyFile statement and read it */
70
71         if(get_config_string(lookup_config(c->config_tree, "PublicKeyFile"), &fname)) {
72                 fp = fopen(fname, "r");
73
74                 if(!fp) {
75                         logger(LOG_ERR, _("Error reading RSA public key file `%s': %s"),
76                                    fname, strerror(errno));
77                         free(fname);
78                         return false;
79                 }
80
81                 free(fname);
82                 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
83                 fclose(fp);
84
85                 if(c->rsa_key)
86                         return true;            /* Woohoo. */
87
88                 /* If it fails, try PEM_read_RSA_PUBKEY. */
89                 fp = fopen(fname, "r");
90
91                 if(!fp) {
92                         logger(LOG_ERR, _("Error reading RSA public key file `%s': %s"),
93                                    fname, strerror(errno));
94                         free(fname);
95                         return false;
96                 }
97
98                 free(fname);
99                 c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
100                 fclose(fp);
101
102                 if(c->rsa_key) {
103 //                              RSA_blinding_on(c->rsa_key, NULL);
104                         return true;
105                 }
106
107                 logger(LOG_ERR, _("Reading RSA public key file `%s' failed: %s"),
108                            fname, strerror(errno));
109                 return false;
110         }
111
112         /* Else, check if a harnessed public key is in the config file */
113
114         xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
115         fp = fopen(fname, "r");
116
117         if(fp) {
118                 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
119                 fclose(fp);
120         }
121
122         free(fname);
123
124         if(c->rsa_key)
125                 return true;
126
127         /* Try again with PEM_read_RSA_PUBKEY. */
128
129         xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
130         fp = fopen(fname, "r");
131
132         if(fp) {
133                 c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
134 //              RSA_blinding_on(c->rsa_key, NULL);
135                 fclose(fp);
136         }
137
138         free(fname);
139
140         if(c->rsa_key)
141                 return true;
142
143         logger(LOG_ERR, _("No public key for %s specified!"), c->name);
144
145         return false;
146 }
147
148 bool read_rsa_private_key(void)
149 {
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                 xasprintf(&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 /*
210   Configure node_t myself and set up the local sockets (listen only)
211 */
212 bool setup_myself(void)
213 {
214         config_t *cfg;
215         subnet_t *subnet;
216         char *name, *hostname, *mode, *afname, *cipher, *digest;
217         char *address = NULL;
218         char *envp[5];
219         struct addrinfo *ai, *aip, hint = {0};
220         bool choice;
221         int i, err;
222
223         cp();
224
225         myself = new_node();
226         myself->connection = new_connection();
227         init_configuration(&myself->connection->config_tree);
228
229         xasprintf(&myself->hostname, _("MYSELF"));
230         xasprintf(&myself->connection->hostname, _("MYSELF"));
231
232         myself->connection->options = 0;
233         myself->connection->protocol_version = PROT_CURRENT;
234
235         if(!get_config_string(lookup_config(config_tree, "Name"), &name)) {     /* Not acceptable */
236                 logger(LOG_ERR, _("Name for tinc daemon required!"));
237                 return false;
238         }
239
240         if(!check_id(name)) {
241                 logger(LOG_ERR, _("Invalid name for myself!"));
242                 free(name);
243                 return false;
244         }
245
246         myself->name = name;
247         myself->connection->name = xstrdup(name);
248
249         if(!read_connection_config(myself->connection)) {
250                 logger(LOG_ERR, _("Cannot open host configuration file for myself!"));
251                 return false;
252         }
253
254         if(!read_rsa_private_key())
255                 return false;
256
257         if(!get_config_string(lookup_config(myself->connection->config_tree, "Port"), &myport))
258                 xasprintf(&myport, "655");
259
260         /* Read in all the subnets specified in the host configuration file */
261
262         cfg = lookup_config(myself->connection->config_tree, "Subnet");
263
264         while(cfg) {
265                 if(!get_config_subnet(cfg, &subnet))
266                         return false;
267
268                 subnet_add(myself, subnet);
269
270                 cfg = lookup_config_next(myself->connection->config_tree, cfg);
271         }
272
273         /* Check some options */
274
275         if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice) && choice)
276                 myself->options |= OPTION_INDIRECT;
277
278         if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice) && choice)
279                 myself->options |= OPTION_TCPONLY;
280
281         if(get_config_bool(lookup_config(myself->connection->config_tree, "IndirectData"), &choice) && choice)
282                 myself->options |= OPTION_INDIRECT;
283
284         if(get_config_bool(lookup_config(myself->connection->config_tree, "TCPOnly"), &choice) && choice)
285                 myself->options |= OPTION_TCPONLY;
286
287         if(myself->options & OPTION_TCPONLY)
288                 myself->options |= OPTION_INDIRECT;
289
290         get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
291
292         if(get_config_string(lookup_config(config_tree, "Mode"), &mode)) {
293                 if(!strcasecmp(mode, "router"))
294                         routing_mode = RMODE_ROUTER;
295                 else if(!strcasecmp(mode, "switch"))
296                         routing_mode = RMODE_SWITCH;
297                 else if(!strcasecmp(mode, "hub"))
298                         routing_mode = RMODE_HUB;
299                 else {
300                         logger(LOG_ERR, _("Invalid routing mode!"));
301                         return false;
302                 }
303                 free(mode);
304         } else
305                 routing_mode = RMODE_ROUTER;
306
307         // Enable PMTUDiscovery by default if we are in router mode.
308
309         choice = routing_mode == RMODE_ROUTER;
310         get_config_bool(lookup_config(myself->connection->config_tree, "PMTUDiscovery"), &choice);
311         if(choice)      
312                 myself->options |= OPTION_PMTU_DISCOVERY;
313
314         get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
315
316 #if !defined(SOL_IP) || !defined(IP_TOS)
317         if(priorityinheritance)
318                 logger(LOG_WARNING, _("%s not supported on this platform"), "PriorityInheritance");
319 #endif
320
321         if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire))
322                 macexpire = 600;
323
324         if(get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout)) {
325                 if(maxtimeout <= 0) {
326                         logger(LOG_ERR, _("Bogus maximum timeout!"));
327                         return false;
328                 }
329         } else
330                 maxtimeout = 900;
331
332         if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
333                 if(!strcasecmp(afname, "IPv4"))
334                         addressfamily = AF_INET;
335                 else if(!strcasecmp(afname, "IPv6"))
336                         addressfamily = AF_INET6;
337                 else if(!strcasecmp(afname, "any"))
338                         addressfamily = AF_UNSPEC;
339                 else {
340                         logger(LOG_ERR, _("Invalid address family!"));
341                         return false;
342                 }
343                 free(afname);
344         }
345
346         get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
347
348         /* Generate packet encryption key */
349
350         if(get_config_string
351            (lookup_config(myself->connection->config_tree, "Cipher"), &cipher)) {
352                 if(!strcasecmp(cipher, "none")) {
353                         myself->incipher = NULL;
354                 } else {
355                         myself->incipher = EVP_get_cipherbyname(cipher);
356
357                         if(!myself->incipher) {
358                                 logger(LOG_ERR, _("Unrecognized cipher type!"));
359                                 return false;
360                         }
361                 }
362         } else
363                 myself->incipher = EVP_aes_256_cbc();
364
365         if(myself->incipher)
366                 myself->inkeylength = myself->incipher->key_len + myself->incipher->iv_len;
367         else
368                 myself->inkeylength = 1;
369
370         myself->connection->outcipher = EVP_aes_256_ofb();
371
372         if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
373                 keylifetime = 3600;
374
375         keyexpires = now + keylifetime;
376         
377         /* Check if we want to use message authentication codes... */
378
379         if(get_config_string(lookup_config(myself->connection->config_tree, "Digest"), &digest)) {
380                 if(!strcasecmp(digest, "none")) {
381                         myself->indigest = NULL;
382                 } else {
383                         myself->indigest = EVP_get_digestbyname(digest);
384
385                         if(!myself->indigest) {
386                                 logger(LOG_ERR, _("Unrecognized digest type!"));
387                                 return false;
388                         }
389                 }
390         } else
391                 myself->indigest = EVP_sha256();
392
393         myself->connection->outdigest = EVP_sha256();
394
395         if(get_config_int(lookup_config(myself->connection->config_tree, "MACLength"), &myself->inmaclength)) {
396                 if(myself->indigest) {
397                         if(myself->inmaclength > myself->indigest->md_size) {
398                                 logger(LOG_ERR, _("MAC length exceeds size of digest!"));
399                                 return false;
400                         } else if(myself->inmaclength < 0) {
401                                 logger(LOG_ERR, _("Bogus MAC length!"));
402                                 return false;
403                         }
404                 }
405         } else
406                 myself->inmaclength = 4;
407
408         myself->connection->outmaclength = 0;
409
410         /* Compression */
411
412         if(get_config_int(lookup_config(myself->connection->config_tree, "Compression"), &myself->incompression)) {
413                 if(myself->incompression < 0 || myself->incompression > 11) {
414                         logger(LOG_ERR, _("Bogus compression level!"));
415                         return false;
416                 }
417         } else
418                 myself->incompression = 0;
419
420         myself->connection->outcompression = 0;
421
422         /* Done */
423
424         myself->nexthop = myself;
425         myself->via = myself;
426         myself->status.reachable = true;
427         node_add(myself);
428
429         graph();
430
431         /* Open device */
432
433         if(!setup_device())
434                 return false;
435
436         /* Run tinc-up script to further initialize the tap interface */
437         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
438         xasprintf(&envp[1], "DEVICE=%s", device ? : "");
439         xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
440         xasprintf(&envp[3], "NAME=%s", myself->name);
441         envp[4] = NULL;
442
443         execute_script("tinc-up", envp);
444
445         for(i = 0; i < 5; i++)
446                 free(envp[i]);
447
448         /* Run subnet-up scripts for our own subnets */
449
450         subnet_update(myself, NULL, true);
451
452         /* Open sockets */
453
454         get_config_string(lookup_config(config_tree, "BindToAddress"), &address);
455
456         hint.ai_family = addressfamily;
457         hint.ai_socktype = SOCK_STREAM;
458         hint.ai_protocol = IPPROTO_TCP;
459         hint.ai_flags = AI_PASSIVE;
460
461         err = getaddrinfo(address, myport, &hint, &ai);
462
463         if(err || !ai) {
464                 logger(LOG_ERR, _("System call `%s' failed: %s"), "getaddrinfo",
465                            gai_strerror(err));
466                 return false;
467         }
468
469         listen_sockets = 0;
470
471         for(aip = ai; aip; aip = aip->ai_next) {
472                 listen_socket[listen_sockets].tcp =
473                         setup_listen_socket((sockaddr_t *) aip->ai_addr);
474
475                 if(listen_socket[listen_sockets].tcp < 0)
476                         continue;
477
478                 listen_socket[listen_sockets].udp =
479                         setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
480
481                 if(listen_socket[listen_sockets].udp < 0)
482                         continue;
483
484                 ifdebug(CONNECTIONS) {
485                         hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
486                         logger(LOG_NOTICE, _("Listening on %s"), hostname);
487                         free(hostname);
488                 }
489
490                 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
491                 listen_sockets++;
492         }
493
494         freeaddrinfo(ai);
495
496         if(listen_sockets)
497                 logger(LOG_NOTICE, _("Ready"));
498         else {
499                 logger(LOG_ERR, _("Unable to create any listening socket!"));
500                 return false;
501         }
502
503         return true;
504 }
505
506 /*
507   initialize network
508 */
509 bool setup_network(void)
510 {
511         cp();
512
513         now = time(NULL);
514
515         init_events();
516         init_connections();
517         init_subnets();
518         init_nodes();
519         init_edges();
520         init_requests();
521
522         if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
523                 if(pinginterval < 1) {
524                         pinginterval = 86400;
525                 }
526         } else
527                 pinginterval = 60;
528
529         if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
530                 pingtimeout = 5;
531         if(pingtimeout < 1 || pingtimeout > pinginterval)
532                 pingtimeout = pinginterval;
533
534         if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize))
535                 maxoutbufsize = 10 * MTU;
536
537         if(!setup_myself())
538                 return false;
539
540         return true;
541 }
542
543 /*
544   close all open network connections
545 */
546 void close_network_connections(void)
547 {
548         avl_node_t *node, *next;
549         connection_t *c;
550         char *envp[5];
551         int i;
552
553         cp();
554
555         for(node = connection_tree->head; node; node = next) {
556                 next = node->next;
557                 c = node->data;
558                 c->outgoing = false;
559                 terminate_connection(c, false);
560         }
561
562         list_delete_list(outgoing_list);
563
564         if(myself && myself->connection) {
565                 subnet_update(myself, NULL, false);
566                 terminate_connection(myself->connection, false);
567                 free_connection(myself->connection);
568         }
569
570         for(i = 0; i < listen_sockets; i++) {
571                 close(listen_socket[i].tcp);
572                 close(listen_socket[i].udp);
573         }
574
575         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
576         xasprintf(&envp[1], "DEVICE=%s", device ? : "");
577         xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
578         xasprintf(&envp[3], "NAME=%s", myself->name);
579         envp[4] = NULL;
580
581         exit_requests();
582         exit_edges();
583         exit_subnets();
584         exit_nodes();
585         exit_connections();
586         exit_events();
587
588         execute_script("tinc-down", envp);
589
590         if(myport) free(myport);
591
592         for(i = 0; i < 4; i++)
593                 free(envp[i]);
594
595         close_device();
596
597         return;
598 }