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