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