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