When purging nodes, only delete them if nobody references them anymore.
[tinc] / src / net_setup.c
1 /*
2     net_setup.c -- Setup.
3     Copyright (C) 1998-2003 Ivo Timmermans <ivo@o2w.nl>,
4                   2000-2003 Guus Sliepen <guus@sliepen.eu.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: net_setup.c,v 1.1.2.43 2003/08/14 14:21:35 guus Exp $
21 */
22
23 #include "system.h"
24
25 #include <openssl/pem.h>
26 #include <openssl/rsa.h>
27 #include <openssl/rand.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         asprintf(&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         asprintf(&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;
152         struct stat s;
153
154         cp();
155
156         if(get_config_string(lookup_config(config_tree, "PrivateKey"), &key)) {
157                 myself->connection->rsa_key = RSA_new();
158 //              RSA_blinding_on(myself->connection->rsa_key, NULL);
159                 BN_hex2bn(&myself->connection->rsa_key->d, key);
160                 BN_hex2bn(&myself->connection->rsa_key->e, "FFFF");
161                 free(key);
162                 return true;
163         }
164
165         if(!get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname))
166                 asprintf(&fname, "%s/rsa_key.priv", confbase);
167
168         fp = fopen(fname, "r");
169
170         if(!fp) {
171                 logger(LOG_ERR, _("Error reading RSA private key file `%s': %s"),
172                            fname, strerror(errno));
173                 free(fname);
174                 return false;
175         }
176
177 #if !defined(HAVE_MINGW) && !defined(HAVE_CYGWIN)
178         if(fstat(fileno(fp), &s)) {
179                 logger(LOG_ERR, _("Could not stat RSA private key file `%s': %s'"),
180                                 fname, strerror(errno));
181                 free(fname);
182                 return false;
183         }
184
185         if(s.st_mode & ~0100700)
186                 logger(LOG_WARNING, _("Warning: insecure file permissions for RSA private key file `%s'!"), fname);
187 #endif
188
189         myself->connection->rsa_key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
190         fclose(fp);
191
192         if(!myself->connection->rsa_key) {
193                 logger(LOG_ERR, _("Reading RSA private key file `%s' failed: %s"),
194                            fname, strerror(errno));
195                 free(fname);
196                 return false;
197         }
198
199         free(fname);
200         return true;
201 }
202
203 /*
204   Configure node_t myself and set up the local sockets (listen only)
205 */
206 bool setup_myself(void)
207 {
208         config_t *cfg;
209         subnet_t *subnet;
210         char *name, *hostname, *mode, *afname, *cipher, *digest;
211         char *address = NULL;
212         char *envp[5];
213         struct addrinfo *ai, *aip, hint = {0};
214         bool choice;
215         int i, err;
216
217         cp();
218
219         myself = new_node();
220         myself->connection = new_connection();
221         init_configuration(&myself->connection->config_tree);
222
223         asprintf(&myself->hostname, _("MYSELF"));
224         asprintf(&myself->connection->hostname, _("MYSELF"));
225
226         myself->connection->options = 0;
227         myself->connection->protocol_version = PROT_CURRENT;
228
229         if(!get_config_string(lookup_config(config_tree, "Name"), &name)) {     /* Not acceptable */
230                 logger(LOG_ERR, _("Name for tinc daemon required!"));
231                 return false;
232         }
233
234         if(!check_id(name)) {
235                 logger(LOG_ERR, _("Invalid name for myself!"));
236                 free(name);
237                 return false;
238         }
239
240         myself->name = name;
241         myself->connection->name = xstrdup(name);
242
243         if(!read_rsa_private_key())
244                 return false;
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_public_key(myself->connection))
252                 return false;
253
254         if(!get_config_string
255            (lookup_config(myself->connection->config_tree, "Port"), &myport))
256                 asprintf(&myport, "655");
257
258         /* Read in all the subnets specified in the host configuration file */
259
260         cfg = lookup_config(myself->connection->config_tree, "Subnet");
261
262         while(cfg) {
263                 if(!get_config_subnet(cfg, &subnet))
264                         return false;
265
266                 subnet_add(myself, subnet);
267
268                 cfg = lookup_config_next(myself->connection->config_tree, cfg);
269         }
270
271         /* Check some options */
272
273         if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice))
274                 if(choice)
275                         myself->options |= OPTION_INDIRECT;
276
277         if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice))
278                 if(choice)
279                         myself->options |= OPTION_TCPONLY;
280
281         if(get_config_bool(lookup_config(myself->connection->config_tree, "IndirectData"), &choice))
282                 if(choice)
283                         myself->options |= OPTION_INDIRECT;
284
285         if(get_config_bool(lookup_config(myself->connection->config_tree, "TCPOnly"), &choice))
286                 if(choice)
287                         myself->options |= OPTION_TCPONLY;
288
289         if(myself->options & OPTION_TCPONLY)
290                 myself->options |= OPTION_INDIRECT;
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         get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
308
309 #if !defined(SOL_IP) || !defined(IP_TOS)
310         if(priorityinheritance)
311                 logger(LOG_WARNING, _("PriorityInheritance not supported on this platform"));
312 #endif
313
314         if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire))
315                 macexpire = 600;
316
317         if(get_config_int(lookup_config(myself->connection->config_tree, "MaxTimeout"), &maxtimeout)) {
318                 if(maxtimeout <= 0) {
319                         logger(LOG_ERR, _("Bogus maximum timeout!"));
320                         return false;
321                 }
322         } else
323                 maxtimeout = 900;
324
325         if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
326                 if(!strcasecmp(afname, "IPv4"))
327                         addressfamily = AF_INET;
328                 else if(!strcasecmp(afname, "IPv6"))
329                         addressfamily = AF_INET6;
330                 else if(!strcasecmp(afname, "any"))
331                         addressfamily = AF_UNSPEC;
332                 else {
333                         logger(LOG_ERR, _("Invalid address family!"));
334                         return false;
335                 }
336                 free(afname);
337         }
338
339         get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
340
341         /* Generate packet encryption key */
342
343         if(get_config_string
344            (lookup_config(myself->connection->config_tree, "Cipher"), &cipher)) {
345                 if(!strcasecmp(cipher, "none")) {
346                         myself->cipher = NULL;
347                 } else {
348                         myself->cipher = EVP_get_cipherbyname(cipher);
349
350                         if(!myself->cipher) {
351                                 logger(LOG_ERR, _("Unrecognized cipher type!"));
352                                 return false;
353                         }
354                 }
355         } else
356                 myself->cipher = EVP_bf_cbc();
357
358         if(myself->cipher)
359                 myself->keylength = myself->cipher->key_len + myself->cipher->iv_len;
360         else
361                 myself->keylength = 1;
362
363         myself->connection->outcipher = EVP_bf_ofb();
364
365         myself->key = (char *) xmalloc(myself->keylength);
366         RAND_pseudo_bytes(myself->key, myself->keylength);
367
368         if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
369                 keylifetime = 3600;
370
371         keyexpires = now + keylifetime;
372         
373         if(myself->cipher) {
374                 EVP_CIPHER_CTX_init(&packet_ctx);
375                 EVP_DecryptInit_ex(&packet_ctx, myself->cipher, NULL, myself->key, myself->key + myself->cipher->key_len);
376         }
377
378         /* Check if we want to use message authentication codes... */
379
380         if(get_config_string
381            (lookup_config(myself->connection->config_tree, "Digest"), &digest)) {
382                 if(!strcasecmp(digest, "none")) {
383                         myself->digest = NULL;
384                 } else {
385                         myself->digest = EVP_get_digestbyname(digest);
386
387                         if(!myself->digest) {
388                                 logger(LOG_ERR, _("Unrecognized digest type!"));
389                                 return false;
390                         }
391                 }
392         } else
393                 myself->digest = EVP_sha1();
394
395         myself->connection->outdigest = EVP_sha1();
396
397         if(get_config_int(lookup_config(myself->connection->config_tree, "MACLength"),
398                 &myself->maclength)) {
399                 if(myself->digest) {
400                         if(myself->maclength > myself->digest->md_size) {
401                                 logger(LOG_ERR, _("MAC length exceeds size of digest!"));
402                                 return false;
403                         } else if(myself->maclength < 0) {
404                                 logger(LOG_ERR, _("Bogus MAC length!"));
405                                 return false;
406                         }
407                 }
408         } else
409                 myself->maclength = 4;
410
411         myself->connection->outmaclength = 0;
412
413         /* Compression */
414
415         if(get_config_int(lookup_config(myself->connection->config_tree, "Compression"),
416                 &myself->compression)) {
417                 if(myself->compression < 0 || myself->compression > 11) {
418                         logger(LOG_ERR, _("Bogus compression level!"));
419                         return false;
420                 }
421         } else
422                 myself->compression = 0;
423
424         myself->connection->outcompression = 0;
425
426         /* Done */
427
428         myself->nexthop = myself;
429         myself->via = myself;
430         myself->status.active = true;
431         myself->status.reachable = true;
432         node_add(myself);
433
434         graph();
435
436         /* Open device */
437
438         if(!setup_device())
439                 return false;
440
441         /* Run tinc-up script to further initialize the tap interface */
442         asprintf(&envp[0], "NETNAME=%s", netname ? : "");
443         asprintf(&envp[1], "DEVICE=%s", device ? : "");
444         asprintf(&envp[2], "INTERFACE=%s", iface ? : "");
445         asprintf(&envp[3], "NAME=%s", myself->name);
446         envp[4] = NULL;
447
448         execute_script("tinc-up", envp);
449
450         for(i = 0; i < 5; i++)
451                 free(envp[i]);
452
453         /* Open sockets */
454
455         get_config_string(lookup_config(config_tree, "BindToAddress"), &address);
456
457         hint.ai_family = addressfamily;
458         hint.ai_socktype = SOCK_STREAM;
459         hint.ai_protocol = IPPROTO_TCP;
460         hint.ai_flags = AI_PASSIVE;
461
462         err = getaddrinfo(address, myport, &hint, &ai);
463
464         if(err || !ai) {
465                 logger(LOG_ERR, _("System call `%s' failed: %s"), "getaddrinfo",
466                            gai_strerror(err));
467                 return false;
468         }
469
470         listen_sockets = 0;
471
472         for(aip = ai; aip; aip = aip->ai_next) {
473                 listen_socket[listen_sockets].tcp =
474                         setup_listen_socket((sockaddr_t *) aip->ai_addr);
475
476                 if(listen_socket[listen_sockets].tcp < 0)
477                         continue;
478
479                 listen_socket[listen_sockets].udp =
480                         setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
481
482                 if(listen_socket[listen_sockets].udp < 0)
483                         continue;
484
485                 ifdebug(CONNECTIONS) {
486                         hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
487                         logger(LOG_NOTICE, _("Listening on %s"), hostname);
488                         free(hostname);
489                 }
490
491                 listen_socket[listen_sockets].sa.sa = *aip->ai_addr;
492                 listen_sockets++;
493         }
494
495         freeaddrinfo(ai);
496
497         if(listen_sockets)
498                 logger(LOG_NOTICE, _("Ready"));
499         else {
500                 logger(LOG_ERR, _("Unable to create any listening socket!"));
501                 return false;
502         }
503
504         return true;
505 }
506
507 /*
508   setup all initial network connections
509 */
510 bool setup_network_connections(void)
511 {
512         cp();
513
514         now = time(NULL);
515
516         init_connections();
517         init_subnets();
518         init_nodes();
519         init_edges();
520         init_events();
521         init_requests();
522
523         if(get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout)) {
524                 if(pingtimeout < 1) {
525                         pingtimeout = 86400;
526                 }
527         } else
528                 pingtimeout = 60;
529
530         if(!setup_myself())
531                 return false;
532
533         try_outgoing_connections();
534
535         return true;
536 }
537
538 /*
539   close all open network connections
540 */
541 void close_network_connections(void)
542 {
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 = (connection_t *) node->data;
553
554                 if(c->outgoing)
555                         free(c->outgoing->name), free(c->outgoing), c->outgoing = NULL;
556                 terminate_connection(c, false);
557         }
558
559         if(myself && myself->connection)
560                 terminate_connection(myself->connection, false);
561
562         for(i = 0; i < listen_sockets; i++) {
563                 close(listen_socket[i].tcp);
564                 close(listen_socket[i].udp);
565         }
566
567         exit_requests();
568         exit_events();
569         exit_edges();
570         exit_subnets();
571         exit_nodes();
572         exit_connections();
573
574         asprintf(&envp[0], "NETNAME=%s", netname ? : "");
575         asprintf(&envp[1], "DEVICE=%s", device ? : "");
576         asprintf(&envp[2], "INTERFACE=%s", iface ? : "");
577         asprintf(&envp[3], "NAME=%s", myself->name);
578         envp[4] = NULL;
579
580         execute_script("tinc-down", envp);
581
582         for(i = 0; i < 4; i++)
583                 free(envp[i]);
584
585         close_device();
586
587         return;
588 }