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