3 Copyright (C) 1998-2005 Ivo Timmermans,
4 2000-2017 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"
51 #ifndef HAVE_RSA_SET0_KEY
52 int RSA_set0_key(RSA *r, BIGNUM *n, BIGNUM *e, BIGNUM *d) {
63 bool read_rsa_public_key(connection_t *c) {
72 c->rsa_key = RSA_new();
73 // RSA_blinding_on(c->rsa_key, NULL);
76 /* First, check for simple PublicKey statement */
78 if(get_config_string(lookup_config(c->config_tree, "PublicKey"), &key)) {
79 if(BN_hex2bn(&n, key) != strlen(key)) {
81 logger(LOG_ERR, "Invalid PublicKey for %s!", c->name);
86 BN_hex2bn(&e, "FFFF");
88 if(!n || !e || RSA_set0_key(c->rsa_key, n, e, NULL) != 1) {
91 logger(LOG_ERR, "RSA_set0_key() failed with PublicKey for %s!", c->name);
98 /* Else, check for PublicKeyFile statement and read it */
100 if(get_config_string(lookup_config(c->config_tree, "PublicKeyFile"), &pubname)) {
101 fp = fopen(pubname, "r");
104 logger(LOG_ERR, "Error reading RSA public key file `%s': %s", pubname, strerror(errno));
109 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
114 return true; /* Woohoo. */
117 /* If it fails, try PEM_read_RSA_PUBKEY. */
118 fp = fopen(pubname, "r");
121 logger(LOG_ERR, "Error reading RSA public key file `%s': %s", pubname, strerror(errno));
126 c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
130 // RSA_blinding_on(c->rsa_key, NULL);
135 logger(LOG_ERR, "Reading RSA public key file `%s' failed: %s", pubname, strerror(errno));
140 /* Else, check if a harnessed public key is in the config file */
142 xasprintf(&hcfname, "%s/hosts/%s", confbase, c->name);
143 fp = fopen(hcfname, "r");
146 logger(LOG_ERR, "Error reading RSA public key file `%s': %s", hcfname, strerror(errno));
151 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
159 /* Try again with PEM_read_RSA_PUBKEY. */
161 fp = fopen(hcfname, "r");
164 logger(LOG_ERR, "Error reading RSA public key file `%s': %s", hcfname, strerror(errno));
170 c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
171 // RSA_blinding_on(c->rsa_key, NULL);
178 logger(LOG_ERR, "No public key for %s specified!", c->name);
183 static bool read_rsa_private_key(void) {
185 char *fname, *key, *pubkey;
190 if(get_config_string(lookup_config(config_tree, "PrivateKey"), &key)) {
191 myself->connection->rsa_key = RSA_new();
193 // RSA_blinding_on(myself->connection->rsa_key, NULL);
194 if(BN_hex2bn(&d, key) != strlen(key)) {
195 logger(LOG_ERR, "Invalid PrivateKey for myself!");
202 if(!get_config_string(lookup_config(config_tree, "PublicKey"), &pubkey)) {
204 logger(LOG_ERR, "PrivateKey used but no PublicKey found!");
208 if(BN_hex2bn(&n, pubkey) != strlen(pubkey)) {
211 logger(LOG_ERR, "Invalid PublicKey for myself!");
216 BN_hex2bn(&e, "FFFF");
218 if(!n || !e || !d || RSA_set0_key(myself->connection->rsa_key, n, e, d) != 1) {
222 logger(LOG_ERR, "RSA_set0_key() failed with PrivateKey for myself!");
229 if(!get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname)) {
230 xasprintf(&fname, "%s/rsa_key.priv", confbase);
233 fp = fopen(fname, "r");
236 logger(LOG_ERR, "Error reading RSA private key file `%s': %s",
237 fname, strerror(errno));
242 #if !defined(HAVE_MINGW) && !defined(HAVE_CYGWIN)
245 if(!fstat(fileno(fp), &s)) {
246 if(s.st_mode & ~0100700) {
247 logger(LOG_WARNING, "Warning: insecure file permissions for RSA private key file `%s'!", fname);
250 logger(LOG_WARNING, "Could not stat RSA private key file `%s': %s'", fname, strerror(errno));
255 myself->connection->rsa_key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
258 if(!myself->connection->rsa_key) {
259 logger(LOG_ERR, "Reading RSA private key file `%s' failed: %s",
260 fname, strerror(errno));
270 Read Subnets from all host config files
272 void load_all_subnets(void) {
277 avl_tree_t *config_tree;
282 xasprintf(&dname, "%s/hosts", confbase);
283 dir = opendir(dname);
286 logger(LOG_ERR, "Could not open %s: %s", dname, strerror(errno));
291 while((ent = readdir(dir))) {
292 if(!check_id(ent->d_name)) {
296 n = lookup_node(ent->d_name);
297 #ifdef _DIRENT_HAVE_D_TYPE
298 //if(ent->d_type != DT_REG)
302 xasprintf(&fname, "%s/hosts/%s", confbase, ent->d_name);
303 init_configuration(&config_tree);
304 read_config_options(config_tree, ent->d_name);
305 read_config_file(config_tree, fname);
310 n->name = xstrdup(ent->d_name);
314 for(cfg = lookup_config(config_tree, "Subnet"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
315 if(!get_config_subnet(cfg, &s)) {
319 if((s2 = lookup_subnet(n, s))) {
326 exit_configuration(&config_tree);
332 char *get_name(void) {
335 get_config_string(lookup_config(config_tree, "Name"), &name);
342 char *envname = getenv(name + 1);
343 char hostname[32] = "";
346 if(strcmp(name + 1, "HOST")) {
347 fprintf(stderr, "Invalid Name: environment variable %s does not exist\n", name + 1);
352 if(gethostname(hostname, sizeof(hostname)) || !*hostname) {
353 fprintf(stderr, "Could not get hostname: %s\n", strerror(errno));
363 name = xstrdup(envname);
365 for(char *c = name; *c; c++)
371 if(!check_id(name)) {
372 logger(LOG_ERR, "Invalid name for myself!");
381 Configure node_t myself and set up the local sockets (listen only)
383 static bool setup_myself(void) {
386 char *name, *hostname, *mode, *afname, *cipher, *digest, *type;
388 char *address = NULL;
391 char *envp[5] = {NULL};
392 struct addrinfo *ai, *aip, hint = {0};
396 bool port_specified = false;
399 myself->connection = new_connection();
401 myself->hostname = xstrdup("MYSELF");
402 myself->connection->hostname = xstrdup("MYSELF");
404 myself->connection->options = 0;
405 myself->connection->protocol_version = PROT_CURRENT;
407 if(!(name = get_name())) {
408 logger(LOG_ERR, "Name for tinc daemon required!");
412 /* Read tinc.conf and our own host config file */
415 myself->connection->name = xstrdup(name);
416 xasprintf(&fname, "%s/hosts/%s", confbase, name);
417 read_config_options(config_tree, name);
418 read_config_file(config_tree, fname);
421 if(!read_rsa_private_key()) {
425 if(!get_config_string(lookup_config(config_tree, "Port"), &myport)) {
426 myport = xstrdup("655");
428 port_specified = true;
431 /* Ensure myport is numeric */
434 struct addrinfo *ai = str2addrinfo("localhost", myport, SOCK_DGRAM);
437 if(!ai || !ai->ai_addr) {
442 memcpy(&sa, ai->ai_addr, ai->ai_addrlen);
443 sockaddr2str(&sa, NULL, &myport);
446 if(get_config_string(lookup_config(config_tree, "Proxy"), &proxy)) {
447 if((space = strchr(proxy, ' '))) {
451 if(!strcasecmp(proxy, "none")) {
452 proxytype = PROXY_NONE;
453 } else if(!strcasecmp(proxy, "socks4")) {
454 proxytype = PROXY_SOCKS4;
455 } else if(!strcasecmp(proxy, "socks4a")) {
456 proxytype = PROXY_SOCKS4A;
457 } else if(!strcasecmp(proxy, "socks5")) {
458 proxytype = PROXY_SOCKS5;
459 } else if(!strcasecmp(proxy, "http")) {
460 proxytype = PROXY_HTTP;
461 } else if(!strcasecmp(proxy, "exec")) {
462 proxytype = PROXY_EXEC;
464 logger(LOG_ERR, "Unknown proxy type %s!", proxy);
475 if(!space || !*space) {
476 logger(LOG_ERR, "Argument expected for proxy type exec!");
481 proxyhost = xstrdup(space);
490 if(space && (space = strchr(space, ' '))) {
491 *space++ = 0, proxyport = space;
494 if(space && (space = strchr(space, ' '))) {
495 *space++ = 0, proxyuser = space;
498 if(space && (space = strchr(space, ' '))) {
499 *space++ = 0, proxypass = space;
502 if(!proxyhost || !*proxyhost || !proxyport || !*proxyport) {
503 logger(LOG_ERR, "Host and port argument expected for proxy!");
508 proxyhost = xstrdup(proxyhost);
509 proxyport = xstrdup(proxyport);
511 if(proxyuser && *proxyuser) {
512 proxyuser = xstrdup(proxyuser);
515 if(proxypass && *proxypass) {
516 proxypass = xstrdup(proxypass);
525 /* Read in all the subnets specified in the host configuration file */
527 cfg = lookup_config(config_tree, "Subnet");
530 if(!get_config_subnet(cfg, &subnet)) {
534 subnet_add(myself, subnet);
536 cfg = lookup_config_next(config_tree, cfg);
539 /* Check some options */
541 if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice) && choice) {
542 myself->options |= OPTION_INDIRECT;
545 if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice) && choice) {
546 myself->options |= OPTION_TCPONLY;
549 if(myself->options & OPTION_TCPONLY) {
550 myself->options |= OPTION_INDIRECT;
553 get_config_bool(lookup_config(config_tree, "DirectOnly"), &directonly);
554 get_config_bool(lookup_config(config_tree, "StrictSubnets"), &strictsubnets);
555 get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
556 get_config_bool(lookup_config(config_tree, "LocalDiscovery"), &localdiscovery);
557 strictsubnets |= tunnelserver;
559 if(get_config_string(lookup_config(config_tree, "Mode"), &mode)) {
560 if(!strcasecmp(mode, "router")) {
561 routing_mode = RMODE_ROUTER;
562 } else if(!strcasecmp(mode, "switch")) {
563 routing_mode = RMODE_SWITCH;
564 } else if(!strcasecmp(mode, "hub")) {
565 routing_mode = RMODE_HUB;
567 logger(LOG_ERR, "Invalid routing mode!");
575 if(get_config_string(lookup_config(config_tree, "Forwarding"), &mode)) {
576 if(!strcasecmp(mode, "off")) {
577 forwarding_mode = FMODE_OFF;
578 } else if(!strcasecmp(mode, "internal")) {
579 forwarding_mode = FMODE_INTERNAL;
580 } else if(!strcasecmp(mode, "kernel")) {
581 forwarding_mode = FMODE_KERNEL;
583 logger(LOG_ERR, "Invalid forwarding mode!");
592 get_config_bool(lookup_config(config_tree, "PMTUDiscovery"), &choice);
595 myself->options |= OPTION_PMTU_DISCOVERY;
599 get_config_bool(lookup_config(config_tree, "ClampMSS"), &choice);
602 myself->options |= OPTION_CLAMP_MSS;
605 get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
606 get_config_bool(lookup_config(config_tree, "DecrementTTL"), &decrement_ttl);
608 if(get_config_string(lookup_config(config_tree, "Broadcast"), &mode)) {
609 if(!strcasecmp(mode, "no")) {
610 broadcast_mode = BMODE_NONE;
611 } else if(!strcasecmp(mode, "yes") || !strcasecmp(mode, "mst")) {
612 broadcast_mode = BMODE_MST;
613 } else if(!strcasecmp(mode, "direct")) {
614 broadcast_mode = BMODE_DIRECT;
616 logger(LOG_ERR, "Invalid broadcast mode!");
624 #if !defined(SOL_IP) || !defined(IP_TOS)
626 if(priorityinheritance) {
627 logger(LOG_WARNING, "%s not supported on this platform for IPv4 connection", "PriorityInheritance");
632 #if !defined(IPPROTO_IPV6) || !defined(IPV6_TCLASS)
634 if(priorityinheritance) {
635 logger(LOG_WARNING, "%s not supported on this platform for IPv6 connection", "PriorityInheritance");
640 if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire)) {
644 if(get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout)) {
645 if(maxtimeout <= 0) {
646 logger(LOG_ERR, "Bogus maximum timeout!");
653 if(get_config_int(lookup_config(config_tree, "MinTimeout"), &mintimeout)) {
655 logger(LOG_ERR, "Bogus minimum timeout!");
659 if(mintimeout > maxtimeout) {
660 logger(LOG_WARNING, "Minimum timeout (%d s) cannot be larger than maximum timeout (%d s). Correcting !", mintimeout, maxtimeout);
661 mintimeout = maxtimeout;
667 if(get_config_int(lookup_config(config_tree, "UDPRcvBuf"), &udp_rcvbuf)) {
668 if(udp_rcvbuf <= 0) {
669 logger(LOG_ERR, "UDPRcvBuf cannot be negative!");
674 if(get_config_int(lookup_config(config_tree, "UDPSndBuf"), &udp_sndbuf)) {
675 if(udp_sndbuf <= 0) {
676 logger(LOG_ERR, "UDPSndBuf cannot be negative!");
681 if(get_config_int(lookup_config(config_tree, "ReplayWindow"), &replaywin_int)) {
682 if(replaywin_int < 0) {
683 logger(LOG_ERR, "ReplayWindow cannot be negative!");
687 replaywin = (unsigned)replaywin_int;
690 if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
691 if(!strcasecmp(afname, "IPv4")) {
692 addressfamily = AF_INET;
693 } else if(!strcasecmp(afname, "IPv6")) {
694 addressfamily = AF_INET6;
695 } else if(!strcasecmp(afname, "any")) {
696 addressfamily = AF_UNSPEC;
698 logger(LOG_ERR, "Invalid address family!");
706 get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
708 /* Generate packet encryption key */
710 if(get_config_string(lookup_config(config_tree, "Cipher"), &cipher)) {
711 if(!strcasecmp(cipher, "none")) {
712 myself->incipher = NULL;
714 myself->incipher = EVP_get_cipherbyname(cipher);
716 if(!myself->incipher) {
717 logger(LOG_ERR, "Unrecognized cipher type!");
725 myself->incipher = EVP_aes_256_cbc();
728 if(myself->incipher) {
729 myself->inkeylength = EVP_CIPHER_key_length(myself->incipher) + EVP_CIPHER_iv_length(myself->incipher);
731 myself->inkeylength = 1;
734 /* We need to use a stream mode for the meta protocol. Use AES for this,
735 but try to match the key size with the one from the cipher selected
738 If Cipher is set to none, still use a low level of encryption for the
742 int keylen = myself->incipher ? EVP_CIPHER_key_length(myself->incipher) : 0;
745 myself->connection->outcipher = EVP_aes_128_cfb();
746 } else if(keylen <= 24) {
747 myself->connection->outcipher = EVP_aes_192_cfb();
749 myself->connection->outcipher = EVP_aes_256_cfb();
752 if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime)) {
756 keyexpires = now + keylifetime;
758 /* Check if we want to use message authentication codes... */
760 if(get_config_string(lookup_config(config_tree, "Digest"), &digest)) {
761 if(!strcasecmp(digest, "none")) {
762 myself->indigest = NULL;
764 myself->indigest = EVP_get_digestbyname(digest);
766 if(!myself->indigest) {
767 logger(LOG_ERR, "Unrecognized digest type!");
775 myself->indigest = EVP_sha256();
778 myself->connection->outdigest = EVP_sha256();
780 if(get_config_int(lookup_config(config_tree, "MACLength"), &myself->inmaclength)) {
781 if(myself->indigest) {
782 if(myself->inmaclength > EVP_MD_size(myself->indigest)) {
783 logger(LOG_ERR, "MAC length exceeds size of digest!");
785 } else if(myself->inmaclength < 0) {
786 logger(LOG_ERR, "Bogus MAC length!");
791 myself->inmaclength = 4;
794 myself->connection->outmaclength = 0;
798 if(get_config_int(lookup_config(config_tree, "Compression"), &myself->incompression)) {
799 if(myself->incompression < 0 || myself->incompression > 11) {
800 logger(LOG_ERR, "Bogus compression level!");
804 myself->incompression = 0;
807 myself->connection->outcompression = 0;
811 myself->nexthop = myself;
812 myself->via = myself;
813 myself->status.reachable = true;
826 if(get_config_string(lookup_config(config_tree, "DeviceType"), &type)) {
827 if(!strcasecmp(type, "dummy")) {
828 devops = dummy_devops;
829 } else if(!strcasecmp(type, "raw_socket")) {
830 devops = raw_socket_devops;
831 } else if(!strcasecmp(type, "multicast")) {
832 devops = multicast_devops;
836 else if(!strcasecmp(type, "uml")) {
842 else if(!strcasecmp(type, "vde")) {
850 if(!devops.setup()) {
854 /* Run tinc-up script to further initialize the tap interface */
855 xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
856 xasprintf(&envp[1], "DEVICE=%s", device ? : "");
857 xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
858 xasprintf(&envp[3], "NAME=%s", myself->name);
866 execute_script("tinc-up", envp);
868 for(i = 0; i < 4; i++) {
872 /* Run subnet-up scripts for our own subnets */
874 subnet_update(myself, NULL, true);
878 if(!do_detach && getenv("LISTEN_FDS")) {
882 listen_sockets = atoi(getenv("LISTEN_FDS"));
884 unsetenv("LISTEN_FDS");
887 if(listen_sockets > MAXSOCKETS) {
888 logger(LOG_ERR, "Too many listening sockets");
892 for(i = 0; i < listen_sockets; i++) {
895 if(getsockname(i + 3, &sa.sa, &salen) < 0) {
896 logger(LOG_ERR, "Could not get address of listen fd %d: %s", i + 3, sockstrerror(errno));
900 listen_socket[i].tcp = i + 3;
903 fcntl(i + 3, F_SETFD, FD_CLOEXEC);
906 listen_socket[i].udp = setup_vpn_in_socket(&sa);
908 if(listen_socket[i].udp < 0) {
912 ifdebug(CONNECTIONS) {
913 hostname = sockaddr2hostname(&sa);
914 logger(LOG_NOTICE, "Listening on %s", hostname);
918 memcpy(&listen_socket[i].sa, &sa, salen);
922 cfg = lookup_config(config_tree, "BindToAddress");
925 get_config_string(cfg, &address);
928 cfg = lookup_config_next(config_tree, cfg);
934 char *space = strchr(address, ' ');
941 if(!strcmp(address, "*")) {
946 hint.ai_family = addressfamily;
947 hint.ai_socktype = SOCK_STREAM;
948 hint.ai_protocol = IPPROTO_TCP;
949 hint.ai_flags = AI_PASSIVE;
951 #if HAVE_DECL_RES_INIT
952 // ensure glibc reloads /etc/resolv.conf.
955 err = getaddrinfo(address && *address ? address : NULL, port, &hint, &ai);
959 logger(LOG_ERR, "System call `%s' failed: %s", "getaddrinfo",
964 for(aip = ai; aip; aip = aip->ai_next) {
965 if(listen_sockets >= MAXSOCKETS) {
966 logger(LOG_ERR, "Too many listening sockets");
970 listen_socket[listen_sockets].tcp =
971 setup_listen_socket((sockaddr_t *) aip->ai_addr);
973 if(listen_socket[listen_sockets].tcp < 0) {
977 listen_socket[listen_sockets].udp =
978 setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
980 if(listen_socket[listen_sockets].udp < 0) {
984 ifdebug(CONNECTIONS) {
985 hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
986 logger(LOG_NOTICE, "Listening on %s", hostname);
990 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
998 if(!listen_sockets) {
999 logger(LOG_ERR, "Unable to create any listening socket!");
1003 /* If no Port option was specified, set myport to the port used by the first listening socket. */
1005 if(!port_specified) {
1007 socklen_t salen = sizeof(sa);
1009 if(!getsockname(listen_socket[0].udp, &sa.sa, &salen)) {
1011 sockaddr2str(&sa, NULL, &myport);
1014 myport = xstrdup("655");
1021 logger(LOG_NOTICE, "Ready");
1028 bool setup_network(void) {
1038 if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
1039 if(pinginterval < 1) {
1040 pinginterval = 86400;
1046 if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout)) {
1050 if(pingtimeout < 1 || pingtimeout > pinginterval) {
1051 pingtimeout = pinginterval;
1054 if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize)) {
1055 maxoutbufsize = 10 * MTU;
1058 if(!setup_myself()) {
1066 close all open network connections
1068 void close_network_connections(void) {
1069 avl_node_t *node, *next;
1071 char *envp[5] = {NULL};
1074 for(node = connection_tree->head; node; node = next) {
1078 terminate_connection(c, false);
1081 for(list_node_t *node = outgoing_list->head; node; node = node->next) {
1082 outgoing_t *outgoing = node->data;
1084 if(outgoing->event) {
1085 event_del(outgoing->event);
1089 list_delete_list(outgoing_list);
1091 if(myself && myself->connection) {
1092 subnet_update(myself, NULL, false);
1093 terminate_connection(myself->connection, false);
1094 free_connection(myself->connection);
1097 for(i = 0; i < listen_sockets; i++) {
1098 close(listen_socket[i].tcp);
1099 close(listen_socket[i].udp);
1102 xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
1103 xasprintf(&envp[1], "DEVICE=%s", device ? : "");
1104 xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
1105 xasprintf(&envp[3], "NAME=%s", myself->name);
1114 execute_script("tinc-down", envp);
1120 for(i = 0; i < 4; i++) {