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