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