6278f5d67df47259c479630204279ccd4d871389
[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.6 2002/03/01 12:25:58 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, sock;
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
331   if(get_config_int(lookup_config(myself->connection->config_tree, "MaxTimeout"), &maxtimeout))
332     {
333       if(maxtimeout <= 0)
334         {
335           syslog(LOG_ERR, _("Bogus maximum timeout!"));
336           return -1;
337         }
338     }
339   else
340     maxtimeout = 900;
341
342   if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname))
343     {
344       if(!strcasecmp(afname, "IPv4"))
345         addressfamily = AF_INET;
346       else if (!strcasecmp(afname, "IPv6"))
347         addressfamily = AF_INET6;
348       else if (!strcasecmp(afname, "any"))
349         addressfamily = AF_UNSPEC;
350       else
351         {
352           syslog(LOG_ERR, _("Invalid address family!"));
353           return -1;
354         }
355       free(afname);
356     }
357   else
358     addressfamily = AF_INET;
359
360   get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
361 cp
362   /* Generate packet encryption key */
363
364   if(get_config_string(lookup_config(myself->connection->config_tree, "Cipher"), &cipher))
365     {
366       if(!strcasecmp(cipher, "none"))
367         {
368           myself->cipher = NULL;
369         }
370       else
371         {
372           if(!(myself->cipher = EVP_get_cipherbyname(cipher)))
373             {
374               syslog(LOG_ERR, _("Unrecognized cipher type!"));
375               return -1;
376             }
377         }
378     }
379   else
380     myself->cipher = EVP_bf_cbc();
381
382   if(myself->cipher)
383     myself->keylength = myself->cipher->key_len + myself->cipher->iv_len;
384   else
385     myself->keylength = 1;
386
387   myself->connection->outcipher = EVP_bf_ofb();
388
389   myself->key = (char *)xmalloc(myself->keylength);
390   RAND_pseudo_bytes(myself->key, myself->keylength);
391
392   if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
393     keylifetime = 3600;
394
395   keyexpires = time(NULL) + keylifetime;
396
397   /* Check if we want to use message authentication codes... */
398
399   if(get_config_string(lookup_config(myself->connection->config_tree, "Digest"), &digest))
400     {
401       if(!strcasecmp(digest, "none"))
402         {
403           myself->digest = NULL;
404         }
405       else
406         {
407           if(!(myself->digest = EVP_get_digestbyname(digest)))
408             {
409               syslog(LOG_ERR, _("Unrecognized digest type!"));
410               return -1;
411             }
412         }
413     }
414   else
415     myself->digest = EVP_sha1();
416
417   myself->connection->outdigest = EVP_sha1();
418
419   if(get_config_int(lookup_config(myself->connection->config_tree, "MACLength"), &myself->maclength))
420     {
421       if(myself->digest)
422         {
423           if(myself->maclength > myself->digest->md_size)
424             {
425               syslog(LOG_ERR, _("MAC length exceeds size of digest!"));
426               return -1;
427             }
428           else if (myself->maclength < 0)
429             {
430               syslog(LOG_ERR, _("Bogus MAC length!"));
431               return -1;
432             }
433         }
434     }
435   else
436     myself->maclength = 4;
437
438   myself->connection->outmaclength = 0;
439
440   /* Compression */
441
442   if(get_config_int(lookup_config(myself->connection->config_tree, "Compression"), &myself->compression))
443     {
444       if(myself->compression < 0 || myself->compression > 9)
445         {
446           syslog(LOG_ERR, _("Bogus compression level!"));
447           return -1;
448         }
449     }
450   else
451     myself->compression = 0;
452
453   myself->connection->outcompression = 0;
454 cp
455   /* Done */
456
457   myself->nexthop = myself;
458   myself->via = myself;
459   myself->status.active = 1;
460   node_add(myself);
461
462   graph();
463
464 cp
465   /* Open sockets */
466   
467   memset(&hint, 0, sizeof(hint));
468   
469   hint.ai_family = addressfamily;
470   hint.ai_socktype = SOCK_STREAM;
471   hint.ai_protocol = IPPROTO_TCP;
472   hint.ai_flags = AI_PASSIVE;
473
474   if((err = getaddrinfo(NULL, myport, &hint, &ai)) || !ai)
475     {
476       syslog(LOG_ERR, _("System call `%s' failed: %s"), "getaddrinfo", gai_strerror(err));
477       return -1;
478     }
479
480   tcp_sockets = 0;
481
482   for(aip = ai; aip; aip = aip->ai_next)
483     {
484       if((sock = setup_listen_socket((sockaddr_t *)aip->ai_addr)) < 0)
485         continue;
486
487       tcp_socket[tcp_sockets++] = sock;
488       if(debug_lvl >= DEBUG_CONNECTIONS)
489         {
490           hostname = sockaddr2hostname((sockaddr_t *)aip->ai_addr);
491           syslog(LOG_NOTICE, _("Listening on %s/tcp"), hostname);
492           free(hostname);
493         }
494     }
495
496   freeaddrinfo(ai);
497
498   hint.ai_socktype = SOCK_DGRAM;
499   hint.ai_protocol = IPPROTO_UDP;
500
501   if((err = getaddrinfo(NULL, myport, &hint, &ai)) || !ai)
502     {
503       syslog(LOG_ERR, _("System call `%s' failed: %s"), "getaddrinfo", gai_strerror(err));
504       return -1;
505     }
506
507   udp_sockets = 0;
508
509   for(aip = ai; aip; aip = aip->ai_next)
510     {
511       if((sock = setup_vpn_in_socket((sockaddr_t *)aip->ai_addr)) < 0)
512         continue;
513
514       udp_socket[udp_sockets++] = sock;
515       if(debug_lvl >= DEBUG_CONNECTIONS)
516         {
517           hostname = sockaddr2hostname((sockaddr_t *)aip->ai_addr);
518           syslog(LOG_NOTICE, _("Listening on %s/udp"), hostname);
519           free(hostname);
520         }
521     }
522
523   freeaddrinfo(ai);
524
525   syslog(LOG_NOTICE, _("Ready"));
526 cp
527   return 0;
528 }
529
530 /*
531   setup all initial network connections
532 */
533 int setup_network_connections(void)
534 {
535 cp
536   init_connections();
537   init_subnets();
538   init_nodes();
539   init_edges();
540   init_events();
541
542   if(get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
543     {
544       if(pingtimeout < 1)
545         {
546           pingtimeout = 86400;
547         }
548     }
549   else
550     pingtimeout = 60;
551
552   if(setup_device() < 0)
553     return -1;
554
555   /* Run tinc-up script to further initialize the tap interface */
556   execute_script("tinc-up");
557
558   if(setup_myself() < 0)
559     return -1;
560
561   try_outgoing_connections();
562 cp
563   return 0;
564 }
565
566 /*
567   close all open network connections
568 */
569 void close_network_connections(void)
570 {
571   avl_node_t *node, *next;
572   connection_t *c;
573   int i;
574 cp
575   for(node = connection_tree->head; node; node = next)
576     {
577       next = node->next;
578       c = (connection_t *)node->data;
579       if(c->outgoing)
580         free(c->outgoing->name), free(c->outgoing);
581       terminate_connection(c, 0);
582     }
583
584   if(myself && myself->connection)
585     terminate_connection(myself->connection, 0);
586
587   for(i = 0; i < udp_sockets; i++)
588     close(udp_socket[i]);
589   for(i = 0; i < tcp_sockets; i++)
590     close(tcp_socket[i]);
591
592   exit_events();
593   exit_edges();
594   exit_subnets();
595   exit_nodes();
596   exit_connections();
597
598   execute_script("tinc-down");
599
600   close_device();
601 cp
602   return;
603 }