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