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