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