subnet-up/down hooks
[tinc] / src / net_setup.c
1 /*
2     net_setup.c -- Setup.
3     Copyright (C) 1998-2004 Ivo Timmermans <ivo@tinc-vpn.org>,
4                   2000-2004 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         get_config_bool(lookup_config(config_tree, "BlockingTCP"), &blockingtcp);
290
291         if(get_config_bool(lookup_config(myself->connection->config_tree, "PMTUDiscovery"), &choice) && choice)
292                 myself->options |= OPTION_PMTU_DISCOVERY;
293
294         if(myself->options & OPTION_TCPONLY)
295                 myself->options |= OPTION_INDIRECT;
296
297         get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
298
299         if(get_config_string(lookup_config(config_tree, "Mode"), &mode)) {
300                 if(!strcasecmp(mode, "router"))
301                         routing_mode = RMODE_ROUTER;
302                 else if(!strcasecmp(mode, "switch"))
303                         routing_mode = RMODE_SWITCH;
304                 else if(!strcasecmp(mode, "hub"))
305                         routing_mode = RMODE_HUB;
306                 else {
307                         logger(LOG_ERR, _("Invalid routing mode!"));
308                         return false;
309                 }
310                 free(mode);
311         } else
312                 routing_mode = RMODE_ROUTER;
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, _("PriorityInheritance not supported on this platform"));
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->cipher = NULL;
354                 } else {
355                         myself->cipher = EVP_get_cipherbyname(cipher);
356
357                         if(!myself->cipher) {
358                                 logger(LOG_ERR, _("Unrecognized cipher type!"));
359                                 return false;
360                         }
361                 }
362         } else
363                 myself->cipher = EVP_bf_cbc();
364
365         if(myself->cipher)
366                 myself->keylength = myself->cipher->key_len + myself->cipher->iv_len;
367         else
368                 myself->keylength = 1;
369
370         myself->connection->outcipher = EVP_bf_ofb();
371
372         myself->key = xmalloc(myself->keylength);
373         RAND_pseudo_bytes(myself->key, myself->keylength);
374
375         if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
376                 keylifetime = 3600;
377
378         keyexpires = now + keylifetime;
379         
380         if(myself->cipher) {
381                 EVP_CIPHER_CTX_init(&packet_ctx);
382                 if(!EVP_DecryptInit_ex(&packet_ctx, myself->cipher, NULL, myself->key, myself->key + myself->cipher->key_len)) {
383                         logger(LOG_ERR, _("Error during initialisation of cipher for %s (%s): %s"),
384                                         myself->name, myself->hostname, ERR_error_string(ERR_get_error(), NULL));
385                         return false;
386                 }
387
388         }
389
390         /* Check if we want to use message authentication codes... */
391
392         if(get_config_string
393            (lookup_config(myself->connection->config_tree, "Digest"), &digest)) {
394                 if(!strcasecmp(digest, "none")) {
395                         myself->digest = NULL;
396                 } else {
397                         myself->digest = EVP_get_digestbyname(digest);
398
399                         if(!myself->digest) {
400                                 logger(LOG_ERR, _("Unrecognized digest type!"));
401                                 return false;
402                         }
403                 }
404         } else
405                 myself->digest = EVP_sha1();
406
407         myself->connection->outdigest = EVP_sha1();
408
409         if(get_config_int(lookup_config(myself->connection->config_tree, "MACLength"),
410                 &myself->maclength)) {
411                 if(myself->digest) {
412                         if(myself->maclength > myself->digest->md_size) {
413                                 logger(LOG_ERR, _("MAC length exceeds size of digest!"));
414                                 return false;
415                         } else if(myself->maclength < 0) {
416                                 logger(LOG_ERR, _("Bogus MAC length!"));
417                                 return false;
418                         }
419                 }
420         } else
421                 myself->maclength = 4;
422
423         myself->connection->outmaclength = 0;
424
425         /* Compression */
426
427         if(get_config_int(lookup_config(myself->connection->config_tree, "Compression"),
428                 &myself->compression)) {
429                 if(myself->compression < 0 || myself->compression > 11) {
430                         logger(LOG_ERR, _("Bogus compression level!"));
431                         return false;
432                 }
433         } else
434                 myself->compression = 0;
435
436         myself->connection->outcompression = 0;
437
438         /* Done */
439
440         myself->nexthop = myself;
441         myself->via = myself;
442         myself->status.active = true;
443         myself->status.reachable = true;
444         node_add(myself);
445
446         graph();
447
448         /* Open device */
449
450         if(!setup_device())
451                 return false;
452
453         /* Run tinc-up script to further initialize the tap interface */
454         asprintf(&envp[0], "NETNAME=%s", netname ? : "");
455         asprintf(&envp[1], "DEVICE=%s", device ? : "");
456         asprintf(&envp[2], "INTERFACE=%s", iface ? : "");
457         asprintf(&envp[3], "NAME=%s", myself->name);
458         envp[4] = NULL;
459
460         execute_script("tinc-up", envp);
461
462         for(i = 0; i < 5; i++)
463                 free(envp[i]);
464
465         /* Run subnet-up scripts for our own subnets */
466
467         subnet_update(myself, NULL, true);
468
469         /* Open sockets */
470
471         get_config_string(lookup_config(config_tree, "BindToAddress"), &address);
472
473         hint.ai_family = addressfamily;
474         hint.ai_socktype = SOCK_STREAM;
475         hint.ai_protocol = IPPROTO_TCP;
476         hint.ai_flags = AI_PASSIVE;
477
478         err = getaddrinfo(address, myport, &hint, &ai);
479
480         if(err || !ai) {
481                 logger(LOG_ERR, _("System call `%s' failed: %s"), "getaddrinfo",
482                            gai_strerror(err));
483                 return false;
484         }
485
486         listen_sockets = 0;
487
488         for(aip = ai; aip; aip = aip->ai_next) {
489                 listen_socket[listen_sockets].tcp =
490                         setup_listen_socket((sockaddr_t *) aip->ai_addr);
491
492                 if(listen_socket[listen_sockets].tcp < 0)
493                         continue;
494
495                 listen_socket[listen_sockets].udp =
496                         setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
497
498                 if(listen_socket[listen_sockets].udp < 0)
499                         continue;
500
501                 ifdebug(CONNECTIONS) {
502                         hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
503                         logger(LOG_NOTICE, _("Listening on %s"), hostname);
504                         free(hostname);
505                 }
506
507                 listen_socket[listen_sockets].sa.sa = *aip->ai_addr;
508                 listen_sockets++;
509         }
510
511         freeaddrinfo(ai);
512
513         if(listen_sockets)
514                 logger(LOG_NOTICE, _("Ready"));
515         else {
516                 logger(LOG_ERR, _("Unable to create any listening socket!"));
517                 return false;
518         }
519
520         return true;
521 }
522
523 /*
524   setup all initial network connections
525 */
526 bool setup_network_connections(void)
527 {
528         cp();
529
530         now = time(NULL);
531
532         init_connections();
533         init_subnets();
534         init_nodes();
535         init_edges();
536         init_events();
537         init_requests();
538
539         if(get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout)) {
540                 if(pingtimeout < 1) {
541                         pingtimeout = 86400;
542                 }
543         } else
544                 pingtimeout = 60;
545
546         if(!setup_myself())
547                 return false;
548
549         try_outgoing_connections();
550
551         return true;
552 }
553
554 /*
555   close all open network connections
556 */
557 void close_network_connections(void)
558 {
559         avl_node_t *node, *next;
560         connection_t *c;
561         char *envp[5];
562         int i;
563
564         cp();
565
566         for(node = connection_tree->head; node; node = next) {
567                 next = node->next;
568                 c = node->data;
569
570                 if(c->outgoing)
571                         free(c->outgoing->name), free(c->outgoing), c->outgoing = NULL;
572                 terminate_connection(c, false);
573         }
574
575         if(myself && myself->connection) {
576                 subnet_update(myself, NULL, false);
577                 terminate_connection(myself->connection, false);
578         }
579
580         for(i = 0; i < listen_sockets; i++) {
581                 close(listen_socket[i].tcp);
582                 close(listen_socket[i].udp);
583         }
584
585         exit_requests();
586         exit_events();
587         exit_edges();
588         exit_subnets();
589         exit_nodes();
590         exit_connections();
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         execute_script("tinc-down", envp);
599
600         for(i = 0; i < 4; i++)
601                 free(envp[i]);
602
603         close_device();
604
605         return;
606 }