3 Copyright (C) 1998-2005 Ivo Timmermans,
4 2000-2013 Guus Sliepen <guus@tinc-vpn.org>
5 2006 Scott Lamb <slamb@slamb.org>
6 2010 Brandon Black <blblack@gmail.com>
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License along
19 with this program; if not, write to the Free Software Foundation, Inc.,
20 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 #include <openssl/pem.h>
26 #include <openssl/rsa.h>
27 #include <openssl/rand.h>
28 #include <openssl/err.h>
29 #include <openssl/evp.h>
33 #include "connection.h"
54 proxytype_t proxytype;
56 bool read_rsa_public_key(connection_t *c) {
63 c->rsa_key = RSA_new();
64 // RSA_blinding_on(c->rsa_key, NULL);
67 /* First, check for simple PublicKey statement */
69 if(get_config_string(lookup_config(c->config_tree, "PublicKey"), &key)) {
70 if(BN_hex2bn(&c->rsa_key->n, key) != strlen(key)) {
71 logger(LOG_ERR, "Invalid PublicKey for %s!", c->name);
74 BN_hex2bn(&c->rsa_key->e, "FFFF");
79 /* Else, check for PublicKeyFile statement and read it */
81 if(get_config_string(lookup_config(c->config_tree, "PublicKeyFile"), &pubname)) {
82 fp = fopen(pubname, "r");
85 logger(LOG_ERR, "Error reading RSA public key file `%s': %s", pubname, strerror(errno));
90 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
95 return true; /* Woohoo. */
98 /* If it fails, try PEM_read_RSA_PUBKEY. */
99 fp = fopen(pubname, "r");
102 logger(LOG_ERR, "Error reading RSA public key file `%s': %s", pubname, strerror(errno));
107 c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
111 // RSA_blinding_on(c->rsa_key, NULL);
116 logger(LOG_ERR, "Reading RSA public key file `%s' failed: %s", pubname, strerror(errno));
121 /* Else, check if a harnessed public key is in the config file */
123 xasprintf(&hcfname, "%s/hosts/%s", confbase, c->name);
124 fp = fopen(hcfname, "r");
127 logger(LOG_ERR, "Error reading RSA public key file `%s': %s", hcfname, strerror(errno));
132 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
140 /* Try again with PEM_read_RSA_PUBKEY. */
142 fp = fopen(hcfname, "r");
145 logger(LOG_ERR, "Error reading RSA public key file `%s': %s", hcfname, strerror(errno));
151 c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
152 // RSA_blinding_on(c->rsa_key, NULL);
158 logger(LOG_ERR, "No public key for %s specified!", c->name);
163 static bool read_rsa_private_key(void) {
165 char *fname, *key, *pubkey;
167 if(get_config_string(lookup_config(config_tree, "PrivateKey"), &key)) {
168 if(!get_config_string(lookup_config(config_tree, "PublicKey"), &pubkey)) {
169 logger(LOG_ERR, "PrivateKey used but no PublicKey found!");
172 myself->connection->rsa_key = RSA_new();
173 // RSA_blinding_on(myself->connection->rsa_key, NULL);
174 if(BN_hex2bn(&myself->connection->rsa_key->d, key) != strlen(key)) {
175 logger(LOG_ERR, "Invalid PrivateKey for myself!");
178 if(BN_hex2bn(&myself->connection->rsa_key->n, pubkey) != strlen(pubkey)) {
179 logger(LOG_ERR, "Invalid PublicKey for myself!");
182 BN_hex2bn(&myself->connection->rsa_key->e, "FFFF");
188 if(!get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname))
189 xasprintf(&fname, "%s/rsa_key.priv", confbase);
191 fp = fopen(fname, "r");
194 logger(LOG_ERR, "Error reading RSA private key file `%s': %s",
195 fname, strerror(errno));
200 #if !defined(HAVE_MINGW) && !defined(HAVE_CYGWIN)
203 if(fstat(fileno(fp), &s)) {
204 logger(LOG_ERR, "Could not stat RSA private key file `%s': %s'",
205 fname, strerror(errno));
210 if(s.st_mode & ~0100700)
211 logger(LOG_WARNING, "Warning: insecure file permissions for RSA private key file `%s'!", fname);
214 myself->connection->rsa_key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
217 if(!myself->connection->rsa_key) {
218 logger(LOG_ERR, "Reading RSA private key file `%s' failed: %s",
219 fname, strerror(errno));
229 Read Subnets from all host config files
231 void load_all_subnets(void) {
236 avl_tree_t *config_tree;
241 xasprintf(&dname, "%s/hosts", confbase);
242 dir = opendir(dname);
244 logger(LOG_ERR, "Could not open %s: %s", dname, strerror(errno));
249 while((ent = readdir(dir))) {
250 if(!check_id(ent->d_name))
253 n = lookup_node(ent->d_name);
254 #ifdef _DIRENT_HAVE_D_TYPE
255 //if(ent->d_type != DT_REG)
259 xasprintf(&fname, "%s/hosts/%s", confbase, ent->d_name);
260 init_configuration(&config_tree);
261 read_config_options(config_tree, ent->d_name);
262 read_config_file(config_tree, fname);
267 n->name = xstrdup(ent->d_name);
271 for(cfg = lookup_config(config_tree, "Subnet"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
272 if(!get_config_subnet(cfg, &s))
275 if((s2 = lookup_subnet(n, s))) {
282 exit_configuration(&config_tree);
288 char *get_name(void) {
291 get_config_string(lookup_config(config_tree, "Name"), &name);
297 char *envname = getenv(name + 1);
299 if(strcmp(name + 1, "HOST")) {
300 fprintf(stderr, "Invalid Name: environment variable %s does not exist\n", name + 1);
304 if(gethostname(envname, 32)) {
305 fprintf(stderr, "Could not get hostname: %s\n", strerror(errno));
311 name = xstrdup(envname);
312 for(char *c = name; *c; c++)
317 if(!check_id(name)) {
318 logger(LOG_ERR, "Invalid name for myself!");
327 Configure node_t myself and set up the local sockets (listen only)
329 static bool setup_myself(void) {
332 char *name, *hostname, *mode, *afname, *cipher, *digest, *type;
334 char *address = NULL;
338 struct addrinfo *ai, *aip, hint = {0};
344 myself->connection = new_connection();
346 myself->hostname = xstrdup("MYSELF");
347 myself->connection->hostname = xstrdup("MYSELF");
349 myself->connection->options = 0;
350 myself->connection->protocol_version = PROT_CURRENT;
352 if(!(name = get_name())) {
353 logger(LOG_ERR, "Name for tinc daemon required!");
358 myself->connection->name = xstrdup(name);
359 xasprintf(&fname, "%s/hosts/%s", confbase, name);
360 read_config_options(config_tree, name);
361 read_config_file(config_tree, fname);
364 if(!read_rsa_private_key())
367 if(!get_config_string(lookup_config(config_tree, "Port"), &myport))
368 myport = xstrdup("655");
371 struct addrinfo *ai = str2addrinfo("localhost", myport, SOCK_DGRAM);
373 if(!ai || !ai->ai_addr)
376 memcpy(&sa, ai->ai_addr, ai->ai_addrlen);
377 sockaddr2str(&sa, NULL, &myport);
380 get_config_string(lookup_config(config_tree, "Proxy"), &proxy);
382 if((space = strchr(proxy, ' ')))
385 if(!strcasecmp(proxy, "none")) {
386 proxytype = PROXY_NONE;
387 } else if(!strcasecmp(proxy, "socks4")) {
388 proxytype = PROXY_SOCKS4;
389 } else if(!strcasecmp(proxy, "socks4a")) {
390 proxytype = PROXY_SOCKS4A;
391 } else if(!strcasecmp(proxy, "socks5")) {
392 proxytype = PROXY_SOCKS5;
393 } else if(!strcasecmp(proxy, "http")) {
394 proxytype = PROXY_HTTP;
395 } else if(!strcasecmp(proxy, "exec")) {
396 proxytype = PROXY_EXEC;
398 logger(LOG_ERR, "Unknown proxy type %s!", proxy);
408 if(!space || !*space) {
409 logger(LOG_ERR, "Argument expected for proxy type exec!");
412 proxyhost = xstrdup(space);
420 if(space && (space = strchr(space, ' ')))
421 *space++ = 0, proxyport = space;
422 if(space && (space = strchr(space, ' ')))
423 *space++ = 0, proxyuser = space;
424 if(space && (space = strchr(space, ' ')))
425 *space++ = 0, proxypass = space;
426 if(!proxyhost || !*proxyhost || !proxyport || !*proxyport) {
427 logger(LOG_ERR, "Host and port argument expected for proxy!");
430 proxyhost = xstrdup(proxyhost);
431 proxyport = xstrdup(proxyport);
432 if(proxyuser && *proxyuser)
433 proxyuser = xstrdup(proxyuser);
434 if(proxypass && *proxypass)
435 proxypass = xstrdup(proxypass);
442 /* Read in all the subnets specified in the host configuration file */
444 cfg = lookup_config(config_tree, "Subnet");
447 if(!get_config_subnet(cfg, &subnet))
450 subnet_add(myself, subnet);
452 cfg = lookup_config_next(config_tree, cfg);
455 /* Check some options */
457 if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice) && choice)
458 myself->options |= OPTION_INDIRECT;
460 if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice) && choice)
461 myself->options |= OPTION_TCPONLY;
463 if(myself->options & OPTION_TCPONLY)
464 myself->options |= OPTION_INDIRECT;
466 get_config_bool(lookup_config(config_tree, "DirectOnly"), &directonly);
467 get_config_bool(lookup_config(config_tree, "StrictSubnets"), &strictsubnets);
468 get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
469 get_config_bool(lookup_config(config_tree, "LocalDiscovery"), &localdiscovery);
470 strictsubnets |= tunnelserver;
472 if(get_config_string(lookup_config(config_tree, "Mode"), &mode)) {
473 if(!strcasecmp(mode, "router"))
474 routing_mode = RMODE_ROUTER;
475 else if(!strcasecmp(mode, "switch"))
476 routing_mode = RMODE_SWITCH;
477 else if(!strcasecmp(mode, "hub"))
478 routing_mode = RMODE_HUB;
480 logger(LOG_ERR, "Invalid routing mode!");
486 if(get_config_string(lookup_config(config_tree, "Forwarding"), &mode)) {
487 if(!strcasecmp(mode, "off"))
488 forwarding_mode = FMODE_OFF;
489 else if(!strcasecmp(mode, "internal"))
490 forwarding_mode = FMODE_INTERNAL;
491 else if(!strcasecmp(mode, "kernel"))
492 forwarding_mode = FMODE_KERNEL;
494 logger(LOG_ERR, "Invalid forwarding mode!");
501 get_config_bool(lookup_config(config_tree, "PMTUDiscovery"), &choice);
503 myself->options |= OPTION_PMTU_DISCOVERY;
506 get_config_bool(lookup_config(config_tree, "ClampMSS"), &choice);
508 myself->options |= OPTION_CLAMP_MSS;
510 get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
511 get_config_bool(lookup_config(config_tree, "DecrementTTL"), &decrement_ttl);
512 if(get_config_string(lookup_config(config_tree, "Broadcast"), &mode)) {
513 if(!strcasecmp(mode, "no"))
514 broadcast_mode = BMODE_NONE;
515 else if(!strcasecmp(mode, "yes") || !strcasecmp(mode, "mst"))
516 broadcast_mode = BMODE_MST;
517 else if(!strcasecmp(mode, "direct"))
518 broadcast_mode = BMODE_DIRECT;
520 logger(LOG_ERR, "Invalid broadcast mode!");
526 #if !defined(SOL_IP) || !defined(IP_TOS)
527 if(priorityinheritance)
528 logger(LOG_WARNING, "%s not supported on this platform", "PriorityInheritance");
531 if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire))
534 if(get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout)) {
535 if(maxtimeout <= 0) {
536 logger(LOG_ERR, "Bogus maximum timeout!");
542 if(get_config_int(lookup_config(config_tree, "UDPRcvBuf"), &udp_rcvbuf)) {
543 if(udp_rcvbuf <= 0) {
544 logger(LOG_ERR, "UDPRcvBuf cannot be negative!");
549 if(get_config_int(lookup_config(config_tree, "UDPSndBuf"), &udp_sndbuf)) {
550 if(udp_sndbuf <= 0) {
551 logger(LOG_ERR, "UDPSndBuf cannot be negative!");
556 if(get_config_int(lookup_config(config_tree, "ReplayWindow"), &replaywin_int)) {
557 if(replaywin_int < 0) {
558 logger(LOG_ERR, "ReplayWindow cannot be negative!");
561 replaywin = (unsigned)replaywin_int;
564 if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
565 if(!strcasecmp(afname, "IPv4"))
566 addressfamily = AF_INET;
567 else if(!strcasecmp(afname, "IPv6"))
568 addressfamily = AF_INET6;
569 else if(!strcasecmp(afname, "any"))
570 addressfamily = AF_UNSPEC;
572 logger(LOG_ERR, "Invalid address family!");
578 get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
580 /* Generate packet encryption key */
583 (lookup_config(config_tree, "Cipher"), &cipher)) {
584 if(!strcasecmp(cipher, "none")) {
585 myself->incipher = NULL;
587 myself->incipher = EVP_get_cipherbyname(cipher);
589 if(!myself->incipher) {
590 logger(LOG_ERR, "Unrecognized cipher type!");
595 myself->incipher = EVP_bf_cbc();
598 myself->inkeylength = myself->incipher->key_len + myself->incipher->iv_len;
600 myself->inkeylength = 1;
602 myself->connection->outcipher = EVP_bf_ofb();
604 if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
607 keyexpires = now + keylifetime;
609 /* Check if we want to use message authentication codes... */
611 if(get_config_string(lookup_config(config_tree, "Digest"), &digest)) {
612 if(!strcasecmp(digest, "none")) {
613 myself->indigest = NULL;
615 myself->indigest = EVP_get_digestbyname(digest);
617 if(!myself->indigest) {
618 logger(LOG_ERR, "Unrecognized digest type!");
623 myself->indigest = EVP_sha1();
625 myself->connection->outdigest = EVP_sha1();
627 if(get_config_int(lookup_config(config_tree, "MACLength"), &myself->inmaclength)) {
628 if(myself->indigest) {
629 if(myself->inmaclength > myself->indigest->md_size) {
630 logger(LOG_ERR, "MAC length exceeds size of digest!");
632 } else if(myself->inmaclength < 0) {
633 logger(LOG_ERR, "Bogus MAC length!");
638 myself->inmaclength = 4;
640 myself->connection->outmaclength = 0;
644 if(get_config_int(lookup_config(config_tree, "Compression"), &myself->incompression)) {
645 if(myself->incompression < 0 || myself->incompression > 11) {
646 logger(LOG_ERR, "Bogus compression level!");
650 myself->incompression = 0;
652 myself->connection->outcompression = 0;
656 myself->nexthop = myself;
657 myself->via = myself;
658 myself->status.reachable = true;
670 if(get_config_string(lookup_config(config_tree, "DeviceType"), &type)) {
671 if(!strcasecmp(type, "dummy"))
672 devops = dummy_devops;
673 else if(!strcasecmp(type, "raw_socket"))
674 devops = raw_socket_devops;
675 else if(!strcasecmp(type, "multicast"))
676 devops = multicast_devops;
678 else if(!strcasecmp(type, "uml"))
682 else if(!strcasecmp(type, "vde"))
690 /* Run tinc-up script to further initialize the tap interface */
691 xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
692 xasprintf(&envp[1], "DEVICE=%s", device ? : "");
693 xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
694 xasprintf(&envp[3], "NAME=%s", myself->name);
697 execute_script("tinc-up", envp);
699 for(i = 0; i < 5; i++)
702 /* Run subnet-up scripts for our own subnets */
704 subnet_update(myself, NULL, true);
708 if(!do_detach && getenv("LISTEN_FDS")) {
712 listen_sockets = atoi(getenv("LISTEN_FDS"));
714 unsetenv("LISTEN_FDS");
717 if(listen_sockets > MAXSOCKETS) {
718 logger(LOG_ERR, "Too many listening sockets");
722 for(i = 0; i < listen_sockets; i++) {
724 if(getsockname(i + 3, &sa.sa, &salen) < 0) {
725 logger(LOG_ERR, "Could not get address of listen fd %d: %s", i + 3, sockstrerror(errno));
729 listen_socket[i].tcp = i + 3;
732 fcntl(i + 3, F_SETFD, FD_CLOEXEC);
735 listen_socket[i].udp = setup_vpn_in_socket(&sa);
736 if(listen_socket[i].udp < 0)
739 ifdebug(CONNECTIONS) {
740 hostname = sockaddr2hostname(&sa);
741 logger(LOG_NOTICE, "Listening on %s", hostname);
745 memcpy(&listen_socket[i].sa, &sa, salen);
749 cfg = lookup_config(config_tree, "BindToAddress");
752 get_config_string(cfg, &address);
754 cfg = lookup_config_next(config_tree, cfg);
759 char *space = strchr(address, ' ');
765 if(!strcmp(address, "*"))
769 hint.ai_family = addressfamily;
770 hint.ai_socktype = SOCK_STREAM;
771 hint.ai_protocol = IPPROTO_TCP;
772 hint.ai_flags = AI_PASSIVE;
774 err = getaddrinfo(address && *address ? address : NULL, port, &hint, &ai);
778 logger(LOG_ERR, "System call `%s' failed: %s", "getaddrinfo",
783 for(aip = ai; aip; aip = aip->ai_next) {
784 if(listen_sockets >= MAXSOCKETS) {
785 logger(LOG_ERR, "Too many listening sockets");
789 listen_socket[listen_sockets].tcp =
790 setup_listen_socket((sockaddr_t *) aip->ai_addr);
792 if(listen_socket[listen_sockets].tcp < 0)
795 listen_socket[listen_sockets].udp =
796 setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
798 if(listen_socket[listen_sockets].udp < 0)
801 ifdebug(CONNECTIONS) {
802 hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
803 logger(LOG_NOTICE, "Listening on %s", hostname);
807 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
816 logger(LOG_NOTICE, "Ready");
818 logger(LOG_ERR, "Unable to create any listening socket!");
828 bool setup_network(void) {
838 if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
839 if(pinginterval < 1) {
840 pinginterval = 86400;
845 if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
847 if(pingtimeout < 1 || pingtimeout > pinginterval)
848 pingtimeout = pinginterval;
850 if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize))
851 maxoutbufsize = 10 * MTU;
860 close all open network connections
862 void close_network_connections(void) {
863 avl_node_t *node, *next;
868 for(node = connection_tree->head; node; node = next) {
872 terminate_connection(c, false);
875 for(list_node_t *node = outgoing_list->head; node; node = node->next) {
876 outgoing_t *outgoing = node->data;
879 event_del(outgoing->event);
882 list_delete_list(outgoing_list);
884 if(myself && myself->connection) {
885 subnet_update(myself, NULL, false);
886 terminate_connection(myself->connection, false);
887 free_connection(myself->connection);
890 for(i = 0; i < listen_sockets; i++) {
891 close(listen_socket[i].tcp);
892 close(listen_socket[i].udp);
895 xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
896 xasprintf(&envp[1], "DEVICE=%s", device ? : "");
897 xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
898 xasprintf(&envp[3], "NAME=%s", myself->name);
908 execute_script("tinc-down", envp);
910 if(myport) free(myport);
912 for(i = 0; i < 4; i++)