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