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