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