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