e279d3741491e403a20c54825d8cf478c80afb5d
[tinc] / 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.32 2003/06/25 20:52:59 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         }
372
373         get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
374
375         /* Generate packet encryption key */
376
377         if(get_config_string
378            (lookup_config(myself->connection->config_tree, "Cipher"), &cipher)) {
379                 if(!strcasecmp(cipher, "none")) {
380                         myself->cipher = NULL;
381                 } else {
382                         myself->cipher = EVP_get_cipherbyname(cipher);
383
384                         if(!myself->cipher) {
385                                 syslog(LOG_ERR, _("Unrecognized cipher type!"));
386                                 return -1;
387                         }
388                 }
389         } else
390                 myself->cipher = EVP_bf_cbc();
391
392         if(myself->cipher)
393                 myself->keylength = myself->cipher->key_len + myself->cipher->iv_len;
394         else
395                 myself->keylength = 1;
396
397         myself->connection->outcipher = EVP_bf_ofb();
398
399         myself->key = (char *) xmalloc(myself->keylength);
400         RAND_pseudo_bytes(myself->key, myself->keylength);
401
402         if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
403                 keylifetime = 3600;
404
405         keyexpires = now + keylifetime;
406         
407         EVP_CIPHER_CTX_init(&packet_ctx);
408         EVP_DecryptInit_ex(&packet_ctx, myself->cipher, NULL, myself->key, myself->key + myself->cipher->key_len);
409
410         /* Check if we want to use message authentication codes... */
411
412         if(get_config_string
413            (lookup_config(myself->connection->config_tree, "Digest"), &digest)) {
414                 if(!strcasecmp(digest, "none")) {
415                         myself->digest = NULL;
416                 } else {
417                         myself->digest = EVP_get_digestbyname(digest);
418
419                         if(!myself->digest) {
420                                 syslog(LOG_ERR, _("Unrecognized digest type!"));
421                                 return -1;
422                         }
423                 }
424         } else
425                 myself->digest = EVP_sha1();
426
427         myself->connection->outdigest = EVP_sha1();
428
429         if(get_config_int
430            (lookup_config(myself->connection->config_tree, "MACLength"),
431                 &myself->maclength)) {
432                 if(myself->digest) {
433                         if(myself->maclength > myself->digest->md_size) {
434                                 syslog(LOG_ERR, _("MAC length exceeds size of digest!"));
435                                 return -1;
436                         } else if(myself->maclength < 0) {
437                                 syslog(LOG_ERR, _("Bogus MAC length!"));
438                                 return -1;
439                         }
440                 }
441         } else
442                 myself->maclength = 4;
443
444         myself->connection->outmaclength = 0;
445
446         /* Compression */
447
448         if(get_config_int
449            (lookup_config(myself->connection->config_tree, "Compression"),
450                 &myself->compression)) {
451                 if(myself->compression < 0 || myself->compression > 11) {
452                         syslog(LOG_ERR, _("Bogus compression level!"));
453                         return -1;
454                 }
455         } else
456                 myself->compression = 0;
457
458         myself->connection->outcompression = 0;
459
460         /* Done */
461
462         myself->nexthop = myself;
463         myself->via = myself;
464         myself->status.active = 1;
465         myself->status.reachable = 1;
466         node_add(myself);
467
468         graph();
469
470         /* Open sockets */
471
472         memset(&hint, 0, sizeof(hint));
473
474         get_config_string(lookup_config(config_tree, "BindToAddress"), &address);
475
476         hint.ai_family = addressfamily;
477         hint.ai_socktype = SOCK_STREAM;
478         hint.ai_protocol = IPPROTO_TCP;
479         hint.ai_flags = AI_PASSIVE;
480
481         err = getaddrinfo(address, myport, &hint, &ai);
482
483         if(err || !ai) {
484                 syslog(LOG_ERR, _("System call `%s' failed: %s"), "getaddrinfo",
485                            gai_strerror(err));
486                 return -1;
487         }
488
489         listen_sockets = 0;
490
491         for(aip = ai; aip; aip = aip->ai_next) {
492                 listen_socket[listen_sockets].tcp =
493                         setup_listen_socket((sockaddr_t *) aip->ai_addr);
494
495                 if(listen_socket[listen_sockets].tcp < 0)
496                         continue;
497
498                 listen_socket[listen_sockets].udp =
499                         setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
500
501                 if(listen_socket[listen_sockets].udp < 0)
502                         continue;
503
504                 if(debug_lvl >= DEBUG_CONNECTIONS) {
505                         hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
506                         syslog(LOG_NOTICE, _("Listening on %s"), hostname);
507                         free(hostname);
508                 }
509
510                 listen_socket[listen_sockets].sa.sa = *aip->ai_addr;
511                 listen_sockets++;
512         }
513
514         freeaddrinfo(ai);
515
516         if(listen_sockets)
517                 syslog(LOG_NOTICE, _("Ready"));
518         else {
519                 syslog(LOG_ERR, _("Unable to create any listening socket!"));
520                 return -1;
521         }
522
523         return 0;
524 }
525
526 /*
527   setup all initial network connections
528 */
529 int setup_network_connections(void)
530 {
531         char *envp[5];
532         int i;
533
534         cp();
535
536         now = time(NULL);
537
538         init_connections();
539         init_subnets();
540         init_nodes();
541         init_edges();
542         init_events();
543         init_requests();
544
545         if(get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout)) {
546                 if(pingtimeout < 1) {
547                         pingtimeout = 86400;
548                 }
549         } else
550                 pingtimeout = 60;
551
552         if(setup_device() < 0)
553                 return -1;
554
555         if(setup_myself() < 0)
556                 return -1;
557
558         /* Run tinc-up script to further initialize the tap interface */
559         asprintf(&envp[0], "NETNAME=%s", netname ? : "");
560         asprintf(&envp[1], "DEVICE=%s", device ? : "");
561         asprintf(&envp[2], "INTERFACE=%s", interface ? : "");
562         asprintf(&envp[3], "NAME=%s", myself->name);
563         envp[4] = NULL;
564
565         execute_script("tinc-up", envp);
566
567         for(i = 0; i < 5; i++)
568                 free(envp[i]);
569
570         try_outgoing_connections();
571
572         return 0;
573 }
574
575 /*
576   close all open network connections
577 */
578 void close_network_connections(void)
579 {
580         avl_node_t *node, *next;
581         connection_t *c;
582         char *envp[5];
583         int i;
584
585         cp();
586
587         for(node = connection_tree->head; node; node = next) {
588                 next = node->next;
589                 c = (connection_t *) node->data;
590
591                 if(c->outgoing)
592                         free(c->outgoing->name), free(c->outgoing), c->outgoing = NULL;
593                 terminate_connection(c, 0);
594         }
595
596         if(myself && myself->connection)
597                 terminate_connection(myself->connection, 0);
598
599         for(i = 0; i < listen_sockets; i++) {
600                 close(listen_socket[i].tcp);
601                 close(listen_socket[i].udp);
602         }
603
604         exit_requests();
605         exit_events();
606         exit_edges();
607         exit_subnets();
608         exit_nodes();
609         exit_connections();
610
611         asprintf(&envp[0], "NETNAME=%s", netname ? : "");
612         asprintf(&envp[1], "DEVICE=%s", device ? : "");
613         asprintf(&envp[2], "INTERFACE=%s", interface ? : "");
614         asprintf(&envp[3], "NAME=%s", myself->name);
615         envp[4] = NULL;
616
617         execute_script("tinc-down", envp);
618
619         for(i = 0; i < 4; i++)
620                 free(envp[i]);
621
622         close_device();
623
624         return;
625 }