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