Drop graph and edge stuff. Use new node stuff instead.
[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.22 2002/09/03 20:43:25 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 "process.h"
71 #include "route.h"
72 #include "device.h"
73 #include "event.h"
74
75 #include "system.h"
76
77 char *myport;
78
79 int read_rsa_public_key(connection_t *c)
80 {
81   FILE *fp;
82   char *fname;
83   char *key;
84 cp
85   if(!c->rsa_key)
86     c->rsa_key = RSA_new();
87
88   /* First, check for simple PublicKey statement */
89
90   if(get_config_string(lookup_config(c->config_tree, "PublicKey"), &key))
91     {
92       BN_hex2bn(&c->rsa_key->n, key);
93       BN_hex2bn(&c->rsa_key->e, "FFFF");
94       free(key);
95       return 0;
96     }
97
98   /* Else, check for PublicKeyFile statement and read it */
99
100   if(get_config_string(lookup_config(c->config_tree, "PublicKeyFile"), &fname))
101     {
102       if(is_safe_path(fname))
103         {
104           if((fp = fopen(fname, "r")) == NULL)
105             {
106               syslog(LOG_ERR, _("Error reading RSA public key file `%s': %s"),
107                      fname, strerror(errno));
108               free(fname);
109               return -1;
110             }
111           free(fname);
112           c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
113           fclose(fp);
114           if(c->rsa_key)
115             return 0; /* Woohoo. */
116           
117           /* If it fails, try PEM_read_RSA_PUBKEY. */
118           if((fp = fopen(fname, "r")) == NULL)
119             {
120               syslog(LOG_ERR, _("Error reading RSA public key file `%s': %s"),
121                      fname, strerror(errno));
122               free(fname);
123               return -1;
124             }
125           free(fname);
126           c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
127           fclose(fp);
128           if(c->rsa_key)
129             return 0;
130
131           syslog(LOG_ERR, _("Reading RSA public key file `%s' failed: %s"),
132                  fname, strerror(errno));
133           return -1;
134         }
135       else
136         {
137           free(fname);
138           return -1;
139         }
140     }
141
142   /* Else, check if a harnessed public key is in the config file */
143
144   asprintf(&fname, "%s/hosts/%s", confbase, c->name);
145   if((fp = fopen(fname, "r")))
146     {
147       c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
148       fclose(fp);
149     }
150
151   free(fname);
152
153   if(c->rsa_key)
154     return 0;
155
156   /* Try again with PEM_read_RSA_PUBKEY. */
157
158   asprintf(&fname, "%s/hosts/%s", confbase, c->name);
159   if((fp = fopen(fname, "r")))
160     {
161       c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
162       fclose(fp);
163     }
164
165   free(fname);
166
167   if(c->rsa_key)
168     return 0;
169
170   syslog(LOG_ERR, _("No public key for %s specified!"), c->name);
171   return -1;
172 }
173
174 int read_rsa_private_key(void)
175 {
176   FILE *fp;
177   char *fname, *key;
178 cp
179   if(get_config_string(lookup_config(config_tree, "PrivateKey"), &key))
180     {
181       myself->connection->rsa_key = RSA_new();
182       BN_hex2bn(&myself->connection->rsa_key->d, key);
183       BN_hex2bn(&myself->connection->rsa_key->e, "FFFF");
184       free(key);
185       return 0;
186     }
187
188   if(!get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname))
189     asprintf(&fname, "%s/rsa_key.priv", confbase);
190
191   if(is_safe_path(fname))
192     {
193       if((fp = fopen(fname, "r")) == NULL)
194         {
195           syslog(LOG_ERR, _("Error reading RSA private key file `%s': %s"),
196                  fname, strerror(errno));
197           free(fname);
198           return -1;
199         }
200       free(fname);
201       myself->connection->rsa_key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
202       fclose(fp);
203       if(!myself->connection->rsa_key)
204         {
205           syslog(LOG_ERR, _("Reading RSA private key file `%s' failed: %s"),
206                  fname, strerror(errno));
207           return -1;
208         }
209       return 0;
210     }
211
212   free(fname);
213   return -1;
214 }
215
216 /*
217   Configure node_t myself and set up the local sockets (listen only)
218 */
219 int setup_myself(void)
220 {
221   config_t *cfg;
222   subnet_t *subnet;
223   char *name, *hostname, *mode, *afname, *cipher, *digest;
224   char *address = NULL;
225   struct addrinfo hint, *ai, *aip;
226   int choice, err;
227 cp
228   myself = new_node();
229   myself->connection = new_connection();
230   init_configuration(&myself->connection->config_tree);
231
232   asprintf(&myself->hostname, _("MYSELF"));
233   asprintf(&myself->connection->hostname, _("MYSELF"));
234
235   myself->connection->options = 0;
236   myself->connection->protocol_version = PROT_CURRENT;
237
238   if(!get_config_string(lookup_config(config_tree, "Name"), &name)) /* Not acceptable */
239     {
240       syslog(LOG_ERR, _("Name for tinc daemon required!"));
241       return -1;
242     }
243
244   if(check_id(name))
245     {
246       syslog(LOG_ERR, _("Invalid name for myself!"));
247       free(name);
248       return -1;
249     }
250
251   myself->name = name;
252   myself->connection->name = xstrdup(name);
253
254 cp
255   if(read_rsa_private_key())
256     return -1;
257
258   if(read_connection_config(myself->connection))
259     {
260       syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
261       return -1;
262     }
263
264   if(read_rsa_public_key(myself->connection))
265     return -1;
266 cp
267
268   if(!get_config_string(lookup_config(myself->connection->config_tree, "Port"), &myport))
269     asprintf(&myport, "655");
270
271 /* Read in all the subnets specified in the host configuration file */
272
273   cfg = lookup_config(myself->connection->config_tree, "Subnet");
274
275   while(cfg)
276     {
277       if(!get_config_subnet(cfg, &subnet))
278         return -1;
279
280       subnet_add(myself, subnet);
281
282       cfg = lookup_config_next(myself->connection->config_tree, cfg);
283     }
284
285 cp
286   /* Check some options */
287
288   if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice))
289     if(choice)
290       myself->options |= OPTION_INDIRECT;
291
292   if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice))
293     if(choice)
294       myself->options |= OPTION_TCPONLY;
295
296   if(get_config_bool(lookup_config(myself->connection->config_tree, "IndirectData"), &choice))
297     if(choice)
298       myself->options |= OPTION_INDIRECT;
299
300   if(get_config_bool(lookup_config(myself->connection->config_tree, "TCPOnly"), &choice))
301     if(choice)
302       myself->options |= OPTION_TCPONLY;
303
304   if(myself->options & OPTION_TCPONLY)
305     myself->options |= OPTION_INDIRECT;
306
307   if(get_config_string(lookup_config(config_tree, "Mode"), &mode))
308     {
309       if(!strcasecmp(mode, "router"))
310         routing_mode = RMODE_ROUTER;
311       else if (!strcasecmp(mode, "switch"))
312         routing_mode = RMODE_SWITCH;
313       else if (!strcasecmp(mode, "hub"))
314         routing_mode = RMODE_HUB;
315       else
316         {
317           syslog(LOG_ERR, _("Invalid routing mode!"));
318           return -1;
319         }
320       free(mode);
321     }
322   else
323     routing_mode = RMODE_ROUTER;
324
325   get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
326 #if !defined(SOL_IP) || !defined(IP_TOS)
327   if(priorityinheritance)
328     syslog(LOG_WARNING, _("PriorityInheritance not supported on this platform"));
329 #endif
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   myself->status.reachable = 1;
464   node_add(myself);
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   listen_sockets = 0;
485
486   for(aip = ai; aip; aip = aip->ai_next)
487     {
488       if((listen_socket[listen_sockets].tcp = setup_listen_socket((sockaddr_t *)aip->ai_addr)) < 0)
489         continue;
490
491       if((listen_socket[listen_sockets].udp = setup_vpn_in_socket((sockaddr_t *)aip->ai_addr)) < 0)
492         continue;
493
494       if(debug_lvl >= DEBUG_CONNECTIONS)
495         {
496           hostname = sockaddr2hostname((sockaddr_t *)aip->ai_addr);
497           syslog(LOG_NOTICE, _("Listening on %s"), hostname);
498           free(hostname);
499         }
500
501       listen_socket[listen_sockets].sa.sa = *aip->ai_addr;
502       listen_sockets++;
503     }
504
505   freeaddrinfo(ai);
506
507   if(listen_sockets)
508     syslog(LOG_NOTICE, _("Ready"));
509   else
510     {
511       syslog(LOG_ERR, _("Unable to create any listening socket!"));
512       return -1;
513     }
514 cp
515   return 0;
516 }
517
518 /*
519   setup all initial network connections
520 */
521 int setup_network_connections(void)
522 {
523   char *envp[4];
524   int i;
525 cp
526   now = time(NULL);
527
528   init_connections();
529   init_subnets();
530   init_nodes();
531   init_events();
532   init_requests();
533
534   if(get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
535     {
536       if(pingtimeout < 1)
537         {
538           pingtimeout = 86400;
539         }
540     }
541   else
542     pingtimeout = 60;
543
544   if(setup_device() < 0)
545     return -1;
546
547   /* Run tinc-up script to further initialize the tap interface */
548   asprintf(&envp[0], "NETNAME=%s", netname?netname:"");
549   asprintf(&envp[1], "DEVICE=%s", device?device:"");
550   asprintf(&envp[2], "INTERFACE=%s", interface?interface:"");
551   envp[3] = NULL;
552
553   execute_script("tinc-up", envp);
554
555   for(i = 0; i < 4; i++)
556     free(envp[i]);
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   char *envp[4];
574   int i;
575 cp
576   for(node = connection_tree->head; node; node = next)
577     {
578       next = node->next;
579       c = (connection_t *)node->data;
580       if(c->outgoing)
581         free(c->outgoing->name), free(c->outgoing), c->outgoing = NULL;
582       terminate_connection(c, 0);
583     }
584
585   if(myself && myself->connection)
586     terminate_connection(myself->connection, 0);
587
588   for(i = 0; i < listen_sockets; i++)
589     {
590       close(listen_socket[i].tcp);
591       close(listen_socket[i].udp);
592     }
593
594   exit_requests();
595   exit_events();
596   exit_subnets();
597   exit_nodes();
598   exit_connections();
599
600   asprintf(&envp[0], "NETNAME=%s", netname?netname:"");
601   asprintf(&envp[1], "DEVICE=%s", device?device:"");
602   asprintf(&envp[2], "INTERFACE=%s", interface?interface:"");
603   envp[3] = NULL;
604
605   execute_script("tinc-down", envp);
606
607   for(i = 0; i < 4; i++)
608     free(envp[i]);
609
610   close_device();
611 cp
612   return;
613 }