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