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