Cleanup:
[oweals/tinc.git] / 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.17 2002/06/08 12:57:10 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_NETINET_IP_H
30  #include <netinet/ip.h>
31 #endif
32 #ifdef HAVE_NETINET_TCP_H
33  #include <netinet/tcp.h>
34 #endif
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <signal.h>
39 #include <sys/time.h>
40 #include <sys/types.h>
41 #include <syslog.h>
42 #include <unistd.h>
43 #include <sys/ioctl.h>
44 /* SunOS really wants sys/socket.h BEFORE net/if.h,
45    and FreeBSD wants these lines below the rest. */
46 #include <arpa/inet.h>
47 #include <sys/socket.h>
48 #include <net/if.h>
49
50 #include <openssl/pem.h>
51 #include <openssl/rsa.h>
52 #include <openssl/rand.h>
53
54 #include <utils.h>
55 #include <xalloc.h>
56 #include <avl_tree.h>
57 #include <list.h>
58
59 #include "conf.h"
60 #include "connection.h"
61 #include "meta.h"
62 #include "net.h"
63 #include "netutl.h"
64 #include "process.h"
65 #include "protocol.h"
66 #include "subnet.h"
67 #include "graph.h"
68 #include "process.h"
69 #include "route.h"
70 #include "device.h"
71 #include "event.h"
72
73 #include "system.h"
74
75 char *myport;
76
77 int read_rsa_public_key(connection_t *c)
78 {
79   FILE *fp;
80   char *fname;
81   char *key;
82 cp
83   if(!c->rsa_key)
84     c->rsa_key = RSA_new();
85
86   /* First, check for simple PublicKey statement */
87
88   if(get_config_string(lookup_config(c->config_tree, "PublicKey"), &key))
89     {
90       BN_hex2bn(&c->rsa_key->n, key);
91       BN_hex2bn(&c->rsa_key->e, "FFFF");
92       free(key);
93       return 0;
94     }
95
96   /* Else, check for PublicKeyFile statement and read it */
97
98   if(get_config_string(lookup_config(c->config_tree, "PublicKeyFile"), &fname))
99     {
100       if(is_safe_path(fname))
101         {
102           if((fp = fopen(fname, "r")) == NULL)
103             {
104               syslog(LOG_ERR, _("Error reading RSA public key file `%s': %s"),
105                      fname, strerror(errno));
106               free(fname);
107               return -1;
108             }
109           free(fname);
110           c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
111           fclose(fp);
112           if(c->rsa_key)
113             return 0; /* Woohoo. */
114           
115           /* If it fails, try PEM_read_RSA_PUBKEY. */
116           if((fp = fopen(fname, "r")) == NULL)
117             {
118               syslog(LOG_ERR, _("Error reading RSA public key file `%s': %s"),
119                      fname, strerror(errno));
120               free(fname);
121               return -1;
122             }
123           free(fname);
124           c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
125           fclose(fp);
126           if(c->rsa_key)
127             return 0;
128
129           syslog(LOG_ERR, _("Reading RSA public key file `%s' failed: %s"),
130                  fname, strerror(errno));
131           return -1;
132         }
133       else
134         {
135           free(fname);
136           return -1;
137         }
138     }
139
140   /* Else, check if a harnessed public key is in the config file */
141
142   asprintf(&fname, "%s/hosts/%s", confbase, c->name);
143   if((fp = fopen(fname, "r")))
144     {
145       c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
146       fclose(fp);
147     }
148
149   free(fname);
150
151   if(c->rsa_key)
152     return 0;
153
154   /* Try again with PEM_read_RSA_PUBKEY. */
155
156   asprintf(&fname, "%s/hosts/%s", confbase, c->name);
157   if((fp = fopen(fname, "r")))
158     {
159       c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
160       fclose(fp);
161     }
162
163   free(fname);
164
165   if(c->rsa_key)
166     return 0;
167
168   syslog(LOG_ERR, _("No public key for %s specified!"), c->name);
169   return -1;
170 }
171
172 int read_rsa_private_key(void)
173 {
174   FILE *fp;
175   char *fname, *key;
176 cp
177   if(get_config_string(lookup_config(config_tree, "PrivateKey"), &key))
178     {
179       myself->connection->rsa_key = RSA_new();
180       BN_hex2bn(&myself->connection->rsa_key->d, key);
181       BN_hex2bn(&myself->connection->rsa_key->e, "FFFF");
182       free(key);
183       return 0;
184     }
185
186   if(!get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname))
187     asprintf(&fname, "%s/rsa_key.priv", confbase);
188
189   if(is_safe_path(fname))
190     {
191       if((fp = fopen(fname, "r")) == NULL)
192         {
193           syslog(LOG_ERR, _("Error reading RSA private key file `%s': %s"),
194                  fname, strerror(errno));
195           free(fname);
196           return -1;
197         }
198       free(fname);
199       myself->connection->rsa_key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
200       fclose(fp);
201       if(!myself->connection->rsa_key)
202         {
203           syslog(LOG_ERR, _("Reading RSA private key file `%s' failed: %s"),
204                  fname, strerror(errno));
205           return -1;
206         }
207       return 0;
208     }
209
210   free(fname);
211   return -1;
212 }
213
214 /*
215   Configure node_t myself and set up the local sockets (listen only)
216 */
217 int setup_myself(void)
218 {
219   config_t *cfg;
220   subnet_t *subnet;
221   char *name, *hostname, *mode, *afname, *cipher, *digest;
222   char *address = NULL;
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(!get_config_string(lookup_config(myself->connection->config_tree, "Port"), &myport))
267     asprintf(&myport, "655");
268
269 /* Read in all the subnets specified in the host configuration file */
270
271   cfg = lookup_config(myself->connection->config_tree, "Subnet");
272
273   while(cfg)
274     {
275       if(!get_config_subnet(cfg, &subnet))
276         return -1;
277
278       subnet_add(myself, subnet);
279
280       cfg = lookup_config_next(myself->connection->config_tree, cfg);
281     }
282
283 cp
284   /* Check some options */
285
286   if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice))
287     if(choice)
288       myself->options |= OPTION_INDIRECT;
289
290   if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice))
291     if(choice)
292       myself->options |= OPTION_TCPONLY;
293
294   if(get_config_bool(lookup_config(myself->connection->config_tree, "IndirectData"), &choice))
295     if(choice)
296       myself->options |= OPTION_INDIRECT;
297
298   if(get_config_bool(lookup_config(myself->connection->config_tree, "TCPOnly"), &choice))
299     if(choice)
300       myself->options |= OPTION_TCPONLY;
301
302   if(myself->options & OPTION_TCPONLY)
303     myself->options |= OPTION_INDIRECT;
304
305   if(get_config_string(lookup_config(config_tree, "Mode"), &mode))
306     {
307       if(!strcasecmp(mode, "router"))
308         routing_mode = RMODE_ROUTER;
309       else if (!strcasecmp(mode, "switch"))
310         routing_mode = RMODE_SWITCH;
311       else if (!strcasecmp(mode, "hub"))
312         routing_mode = RMODE_HUB;
313       else
314         {
315           syslog(LOG_ERR, _("Invalid routing mode!"));
316           return -1;
317         }
318       free(mode);
319     }
320   else
321     routing_mode = RMODE_ROUTER;
322
323   get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
324 #if !defined(SOL_IP) || !defined(IP_TOS)
325   if(priorityinheritance)
326     syslog(LOG_WARNING, _("PriorityInheritance not supported on this platform"));
327 #endif
328
329   if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire))
330     macexpire= 600;
331
332   if(get_config_int(lookup_config(myself->connection->config_tree, "MaxTimeout"), &maxtimeout))
333     {
334       if(maxtimeout <= 0)
335         {
336           syslog(LOG_ERR, _("Bogus maximum timeout!"));
337           return -1;
338         }
339     }
340   else
341     maxtimeout = 900;
342
343   if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname))
344     {
345       if(!strcasecmp(afname, "IPv4"))
346         addressfamily = AF_INET;
347       else if (!strcasecmp(afname, "IPv6"))
348         addressfamily = AF_INET6;
349       else if (!strcasecmp(afname, "any"))
350         addressfamily = AF_UNSPEC;
351       else
352         {
353           syslog(LOG_ERR, _("Invalid address family!"));
354           return -1;
355         }
356       free(afname);
357     }
358   else
359     addressfamily = AF_INET;
360
361   get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
362 cp
363   /* Generate packet encryption key */
364
365   if(get_config_string(lookup_config(myself->connection->config_tree, "Cipher"), &cipher))
366     {
367       if(!strcasecmp(cipher, "none"))
368         {
369           myself->cipher = NULL;
370         }
371       else
372         {
373           if(!(myself->cipher = EVP_get_cipherbyname(cipher)))
374             {
375               syslog(LOG_ERR, _("Unrecognized cipher type!"));
376               return -1;
377             }
378         }
379     }
380   else
381     myself->cipher = EVP_bf_cbc();
382
383   if(myself->cipher)
384     myself->keylength = myself->cipher->key_len + myself->cipher->iv_len;
385   else
386     myself->keylength = 1;
387
388   myself->connection->outcipher = EVP_bf_ofb();
389
390   myself->key = (char *)xmalloc(myself->keylength);
391   RAND_pseudo_bytes(myself->key, myself->keylength);
392
393   if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
394     keylifetime = 3600;
395
396   keyexpires = now + keylifetime;
397
398   /* Check if we want to use message authentication codes... */
399
400   if(get_config_string(lookup_config(myself->connection->config_tree, "Digest"), &digest))
401     {
402       if(!strcasecmp(digest, "none"))
403         {
404           myself->digest = NULL;
405         }
406       else
407         {
408           if(!(myself->digest = EVP_get_digestbyname(digest)))
409             {
410               syslog(LOG_ERR, _("Unrecognized digest type!"));
411               return -1;
412             }
413         }
414     }
415   else
416     myself->digest = EVP_sha1();
417
418   myself->connection->outdigest = EVP_sha1();
419
420   if(get_config_int(lookup_config(myself->connection->config_tree, "MACLength"), &myself->maclength))
421     {
422       if(myself->digest)
423         {
424           if(myself->maclength > myself->digest->md_size)
425             {
426               syslog(LOG_ERR, _("MAC length exceeds size of digest!"));
427               return -1;
428             }
429           else if (myself->maclength < 0)
430             {
431               syslog(LOG_ERR, _("Bogus MAC length!"));
432               return -1;
433             }
434         }
435     }
436   else
437     myself->maclength = 4;
438
439   myself->connection->outmaclength = 0;
440
441   /* Compression */
442
443   if(get_config_int(lookup_config(myself->connection->config_tree, "Compression"), &myself->compression))
444     {
445       if(myself->compression < 0 || myself->compression > 9)
446         {
447           syslog(LOG_ERR, _("Bogus compression level!"));
448           return -1;
449         }
450     }
451   else
452     myself->compression = 0;
453
454   myself->connection->outcompression = 0;
455 cp
456   /* Done */
457
458   myself->nexthop = myself;
459   myself->via = myself;
460   myself->status.active = 1;
461   myself->status.reachable = 1;
462   node_add(myself);
463
464   graph();
465
466 cp
467   /* Open sockets */
468   
469   memset(&hint, 0, sizeof(hint));
470   
471   get_config_string(lookup_config(config_tree, "BindToAddress"), &address);
472
473   hint.ai_family = addressfamily;
474   hint.ai_socktype = SOCK_STREAM;
475   hint.ai_protocol = IPPROTO_TCP;
476   hint.ai_flags = AI_PASSIVE;
477
478   if((err = getaddrinfo(address, myport, &hint, &ai)) || !ai)
479     {
480       syslog(LOG_ERR, _("System call `%s' failed: %s"), "getaddrinfo", gai_strerror(err));
481       return -1;
482     }
483
484   for(aip = ai; aip; aip = aip->ai_next)
485     {
486       if((listen_socket[listen_sockets].tcp = setup_listen_socket((sockaddr_t *)aip->ai_addr)) < 0)
487         continue;
488
489       if((listen_socket[listen_sockets].udp = setup_vpn_in_socket((sockaddr_t *)aip->ai_addr)) < 0)
490         continue;
491
492       if(debug_lvl >= DEBUG_CONNECTIONS)
493         {
494           hostname = sockaddr2hostname((sockaddr_t *)aip->ai_addr);
495           syslog(LOG_NOTICE, _("Listening on %s"), hostname);
496           free(hostname);
497         }
498
499       listen_socket[listen_sockets].sa.sa = *aip->ai_addr;
500       listen_sockets++;
501     }
502
503   freeaddrinfo(ai);
504
505   if(listen_sockets)
506     syslog(LOG_NOTICE, _("Ready"));
507   else
508     {
509       syslog(LOG_ERR, _("Unable to create any listening socket!"));
510       return -1;
511     }
512 cp
513   return 0;
514 }
515
516 /*
517   setup all initial network connections
518 */
519 int setup_network_connections(void)
520 {
521 cp
522   now = time(NULL);
523
524   init_connections();
525   init_subnets();
526   init_nodes();
527   init_edges();
528   init_events();
529   init_requests();
530
531   if(get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
532     {
533       if(pingtimeout < 1)
534         {
535           pingtimeout = 86400;
536         }
537     }
538   else
539     pingtimeout = 60;
540
541   if(setup_device() < 0)
542     return -1;
543
544   /* Run tinc-up script to further initialize the tap interface */
545   execute_script("tinc-up");
546
547   if(setup_myself() < 0)
548     return -1;
549
550   try_outgoing_connections();
551 cp
552   return 0;
553 }
554
555 /*
556   close all open network connections
557 */
558 void close_network_connections(void)
559 {
560   avl_node_t *node, *next;
561   connection_t *c;
562   int i;
563 cp
564   for(node = connection_tree->head; node; node = next)
565     {
566       next = node->next;
567       c = (connection_t *)node->data;
568       if(c->outgoing)
569         free(c->outgoing->name), free(c->outgoing), c->outgoing = NULL;
570       terminate_connection(c, 0);
571     }
572
573   if(myself && myself->connection)
574     terminate_connection(myself->connection, 0);
575
576   for(i = 0; i < listen_sockets; i++)
577     {
578       close(listen_socket[i].tcp);
579       close(listen_socket[i].udp);
580     }
581
582   exit_requests();
583   exit_events();
584   exit_edges();
585   exit_subnets();
586   exit_nodes();
587   exit_connections();
588
589   execute_script("tinc-down");
590
591   close_device();
592 cp
593   return;
594 }