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>
30 #include <openssl/bn.h>
34 #include "connection.h"
52 #ifndef HAVE_RSA_SET0_KEY
53 int RSA_set0_key(RSA *r, BIGNUM *n, BIGNUM *e, BIGNUM *d) {
64 bool read_rsa_public_key(connection_t *c) {
73 c->rsa_key = RSA_new();
74 // RSA_blinding_on(c->rsa_key, NULL);
77 /* First, check for simple PublicKey statement */
79 if(get_config_string(lookup_config(c->config_tree, "PublicKey"), &key)) {
80 if((size_t)BN_hex2bn(&n, key) != strlen(key)) {
82 logger(LOG_ERR, "Invalid PublicKey for %s!", c->name);
87 BN_hex2bn(&e, "FFFF");
89 if(!n || !e || RSA_set0_key(c->rsa_key, n, e, NULL) != 1) {
92 logger(LOG_ERR, "RSA_set0_key() failed with PublicKey for %s!", c->name);
99 /* Else, check for PublicKeyFile statement and read it */
101 if(get_config_string(lookup_config(c->config_tree, "PublicKeyFile"), &pubname)) {
102 fp = fopen(pubname, "r");
105 logger(LOG_ERR, "Error reading RSA public key file `%s': %s", pubname, strerror(errno));
110 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
115 return true; /* Woohoo. */
118 /* If it fails, try PEM_read_RSA_PUBKEY. */
119 fp = fopen(pubname, "r");
122 logger(LOG_ERR, "Error reading RSA public key file `%s': %s", pubname, strerror(errno));
127 c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
131 // RSA_blinding_on(c->rsa_key, NULL);
136 logger(LOG_ERR, "Reading RSA public key file `%s' failed: %s", pubname, strerror(errno));
141 /* Else, check if a harnessed public key is in the config file */
143 xasprintf(&hcfname, "%s/hosts/%s", confbase, c->name);
144 fp = fopen(hcfname, "r");
147 logger(LOG_ERR, "Error reading RSA public key file `%s': %s", hcfname, strerror(errno));
152 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
160 /* Try again with PEM_read_RSA_PUBKEY. */
162 fp = fopen(hcfname, "r");
165 logger(LOG_ERR, "Error reading RSA public key file `%s': %s", hcfname, strerror(errno));
171 c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
172 // RSA_blinding_on(c->rsa_key, NULL);
179 logger(LOG_ERR, "No public key for %s specified!", c->name);
184 static bool read_rsa_private_key(void) {
186 char *fname, *key, *pubkey;
191 if(get_config_string(lookup_config(config_tree, "PrivateKey"), &key)) {
192 myself->connection->rsa_key = RSA_new();
194 // RSA_blinding_on(myself->connection->rsa_key, NULL);
195 if((size_t)BN_hex2bn(&d, key) != strlen(key)) {
196 logger(LOG_ERR, "Invalid PrivateKey for myself!");
203 if(!get_config_string(lookup_config(config_tree, "PublicKey"), &pubkey)) {
205 logger(LOG_ERR, "PrivateKey used but no PublicKey found!");
209 if((size_t)BN_hex2bn(&n, pubkey) != strlen(pubkey)) {
212 logger(LOG_ERR, "Invalid PublicKey for myself!");
217 BN_hex2bn(&e, "FFFF");
219 if(!n || !e || !d || RSA_set0_key(myself->connection->rsa_key, n, e, d) != 1) {
223 logger(LOG_ERR, "RSA_set0_key() failed with PrivateKey for myself!");
230 if(!get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname)) {
231 xasprintf(&fname, "%s/rsa_key.priv", confbase);
234 fp = fopen(fname, "r");
237 logger(LOG_ERR, "Error reading RSA private key file `%s': %s",
238 fname, strerror(errno));
243 #if !defined(HAVE_MINGW) && !defined(HAVE_CYGWIN)
246 if(!fstat(fileno(fp), &s)) {
247 if(s.st_mode & ~0100700) {
248 logger(LOG_WARNING, "Warning: insecure file permissions for RSA private key file `%s'!", fname);
251 logger(LOG_WARNING, "Could not stat RSA private key file `%s': %s'", fname, strerror(errno));
256 myself->connection->rsa_key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
259 if(!myself->connection->rsa_key) {
260 logger(LOG_ERR, "Reading RSA private key file `%s' failed: %s",
261 fname, strerror(errno));
271 Read Subnets from all host config files
273 void load_all_subnets(void) {
278 avl_tree_t *config_tree;
283 xasprintf(&dname, "%s/hosts", confbase);
284 dir = opendir(dname);
287 logger(LOG_ERR, "Could not open %s: %s", dname, strerror(errno));
292 while((ent = readdir(dir))) {
293 if(!check_id(ent->d_name)) {
297 n = lookup_node(ent->d_name);
298 #ifdef _DIRENT_HAVE_D_TYPE
299 //if(ent->d_type != DT_REG)
303 xasprintf(&fname, "%s/hosts/%s", confbase, ent->d_name);
304 init_configuration(&config_tree);
305 read_config_options(config_tree, ent->d_name);
306 read_config_file(config_tree, fname);
311 n->name = xstrdup(ent->d_name);
315 for(cfg = lookup_config(config_tree, "Subnet"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
316 if(!get_config_subnet(cfg, &s)) {
320 if((s2 = lookup_subnet(n, s))) {
327 exit_configuration(&config_tree);
333 char *get_name(void) {
336 get_config_string(lookup_config(config_tree, "Name"), &name);
343 char *envname = getenv(name + 1);
344 char hostname[32] = "";
347 if(strcmp(name + 1, "HOST")) {
348 fprintf(stderr, "Invalid Name: environment variable %s does not exist\n", name + 1);
353 if(gethostname(hostname, sizeof(hostname)) || !*hostname) {
354 fprintf(stderr, "Could not get hostname: %s\n", strerror(errno));
364 name = xstrdup(envname);
366 for(char *c = name; *c; c++)
372 if(!check_id(name)) {
373 logger(LOG_ERR, "Invalid name for myself!");
382 Configure node_t myself and set up the local sockets (listen only)
384 static bool setup_myself(void) {
387 char *name, *hostname, *mode, *afname, *cipher, *digest, *type;
389 char *address = NULL;
393 struct addrinfo *ai, *aip, hint = {0};
397 bool port_specified = false;
400 myself->connection = new_connection();
402 myself->hostname = xstrdup("MYSELF");
403 myself->connection->hostname = xstrdup("MYSELF");
405 myself->connection->options = 0;
406 myself->connection->protocol_version = PROT_CURRENT;
408 if(!(name = get_name())) {
409 logger(LOG_ERR, "Name for tinc daemon required!");
413 /* Read tinc.conf and our own host config file */
416 myself->connection->name = xstrdup(name);
417 xasprintf(&fname, "%s/hosts/%s", confbase, name);
418 read_config_options(config_tree, name);
419 read_config_file(config_tree, fname);
422 if(!read_rsa_private_key()) {
426 if(!get_config_string(lookup_config(config_tree, "Port"), &myport)) {
427 myport = xstrdup("655");
429 port_specified = true;
432 /* Ensure myport is numeric */
435 struct addrinfo *ai = str2addrinfo("localhost", myport, SOCK_DGRAM);
438 if(!ai || !ai->ai_addr) {
443 memcpy(&sa, ai->ai_addr, ai->ai_addrlen);
444 sockaddr2str(&sa, NULL, &myport);
447 if(get_config_string(lookup_config(config_tree, "Proxy"), &proxy)) {
448 if((space = strchr(proxy, ' '))) {
452 if(!strcasecmp(proxy, "none")) {
453 proxytype = PROXY_NONE;
454 } else if(!strcasecmp(proxy, "socks4")) {
455 proxytype = PROXY_SOCKS4;
456 } else if(!strcasecmp(proxy, "socks4a")) {
457 proxytype = PROXY_SOCKS4A;
458 } else if(!strcasecmp(proxy, "socks5")) {
459 proxytype = PROXY_SOCKS5;
460 } else if(!strcasecmp(proxy, "http")) {
461 proxytype = PROXY_HTTP;
462 } else if(!strcasecmp(proxy, "exec")) {
463 proxytype = PROXY_EXEC;
465 logger(LOG_ERR, "Unknown proxy type %s!", proxy);
476 if(!space || !*space) {
477 logger(LOG_ERR, "Argument expected for proxy type exec!");
482 proxyhost = xstrdup(space);
491 if(space && (space = strchr(space, ' '))) {
492 *space++ = 0, proxyport = space;
495 if(space && (space = strchr(space, ' '))) {
496 *space++ = 0, proxyuser = space;
499 if(space && (space = strchr(space, ' '))) {
500 *space++ = 0, proxypass = space;
503 if(!proxyhost || !*proxyhost || !proxyport || !*proxyport) {
504 logger(LOG_ERR, "Host and port argument expected for proxy!");
509 proxyhost = xstrdup(proxyhost);
510 proxyport = xstrdup(proxyport);
512 if(proxyuser && *proxyuser) {
513 proxyuser = xstrdup(proxyuser);
516 if(proxypass && *proxypass) {
517 proxypass = xstrdup(proxypass);
526 /* Read in all the subnets specified in the host configuration file */
528 cfg = lookup_config(config_tree, "Subnet");
531 if(!get_config_subnet(cfg, &subnet)) {
535 subnet_add(myself, subnet);
537 cfg = lookup_config_next(config_tree, cfg);
540 /* Check some options */
542 if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice) && choice) {
543 myself->options |= OPTION_INDIRECT;
546 if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice) && choice) {
547 myself->options |= OPTION_TCPONLY;
550 if(myself->options & OPTION_TCPONLY) {
551 myself->options |= OPTION_INDIRECT;
554 get_config_bool(lookup_config(config_tree, "DirectOnly"), &directonly);
555 get_config_bool(lookup_config(config_tree, "StrictSubnets"), &strictsubnets);
556 get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
557 get_config_bool(lookup_config(config_tree, "LocalDiscovery"), &localdiscovery);
558 strictsubnets |= tunnelserver;
560 if(get_config_string(lookup_config(config_tree, "Mode"), &mode)) {
561 if(!strcasecmp(mode, "router")) {
562 routing_mode = RMODE_ROUTER;
563 } else if(!strcasecmp(mode, "switch")) {
564 routing_mode = RMODE_SWITCH;
565 } else if(!strcasecmp(mode, "hub")) {
566 routing_mode = RMODE_HUB;
568 logger(LOG_ERR, "Invalid routing mode!");
576 if(get_config_string(lookup_config(config_tree, "Forwarding"), &mode)) {
577 if(!strcasecmp(mode, "off")) {
578 forwarding_mode = FMODE_OFF;
579 } else if(!strcasecmp(mode, "internal")) {
580 forwarding_mode = FMODE_INTERNAL;
581 } else if(!strcasecmp(mode, "kernel")) {
582 forwarding_mode = FMODE_KERNEL;
584 logger(LOG_ERR, "Invalid forwarding mode!");
592 choice = !(myself->options & OPTION_TCPONLY);
593 get_config_bool(lookup_config(config_tree, "PMTUDiscovery"), &choice);
596 myself->options |= OPTION_PMTU_DISCOVERY;
600 get_config_bool(lookup_config(config_tree, "ClampMSS"), &choice);
603 myself->options |= OPTION_CLAMP_MSS;
606 get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
607 get_config_bool(lookup_config(config_tree, "DecrementTTL"), &decrement_ttl);
609 if(get_config_string(lookup_config(config_tree, "Broadcast"), &mode)) {
610 if(!strcasecmp(mode, "no")) {
611 broadcast_mode = BMODE_NONE;
612 } else if(!strcasecmp(mode, "yes") || !strcasecmp(mode, "mst")) {
613 broadcast_mode = BMODE_MST;
614 } else if(!strcasecmp(mode, "direct")) {
615 broadcast_mode = BMODE_DIRECT;
617 logger(LOG_ERR, "Invalid broadcast mode!");
625 #if !defined(SOL_IP) || !defined(IP_TOS)
627 if(priorityinheritance) {
628 logger(LOG_WARNING, "%s not supported on this platform for IPv4 connection", "PriorityInheritance");
633 #if !defined(IPPROTO_IPV6) || !defined(IPV6_TCLASS)
635 if(priorityinheritance) {
636 logger(LOG_WARNING, "%s not supported on this platform for IPv6 connection", "PriorityInheritance");
641 if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire)) {
645 if(get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout)) {
646 if(maxtimeout <= 0) {
647 logger(LOG_ERR, "Bogus maximum timeout!");
654 if(get_config_int(lookup_config(config_tree, "MinTimeout"), &mintimeout)) {
656 logger(LOG_ERR, "Bogus minimum timeout!");
660 if(mintimeout > maxtimeout) {
661 logger(LOG_WARNING, "Minimum timeout (%d s) cannot be larger than maximum timeout (%d s). Correcting !", mintimeout, maxtimeout);
662 mintimeout = maxtimeout;
668 if(get_config_int(lookup_config(config_tree, "UDPRcvBuf"), &udp_rcvbuf)) {
669 if(udp_rcvbuf <= 0) {
670 logger(LOG_ERR, "UDPRcvBuf cannot be negative!");
675 if(get_config_int(lookup_config(config_tree, "UDPSndBuf"), &udp_sndbuf)) {
676 if(udp_sndbuf <= 0) {
677 logger(LOG_ERR, "UDPSndBuf cannot be negative!");
682 if(get_config_int(lookup_config(config_tree, "ReplayWindow"), &replaywin_int)) {
683 if(replaywin_int < 0) {
684 logger(LOG_ERR, "ReplayWindow cannot be negative!");
688 replaywin = (unsigned)replaywin_int;
691 if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
692 if(!strcasecmp(afname, "IPv4")) {
693 addressfamily = AF_INET;
694 } else if(!strcasecmp(afname, "IPv6")) {
695 addressfamily = AF_INET6;
696 } else if(!strcasecmp(afname, "any")) {
697 addressfamily = AF_UNSPEC;
699 logger(LOG_ERR, "Invalid address family!");
707 get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
709 /* Generate packet encryption key */
711 if(get_config_string(lookup_config(config_tree, "Cipher"), &cipher)) {
712 if(!strcasecmp(cipher, "none")) {
713 myself->incipher = NULL;
715 myself->incipher = EVP_get_cipherbyname(cipher);
717 if(!myself->incipher) {
718 logger(LOG_ERR, "Unrecognized cipher type!");
726 myself->incipher = EVP_aes_256_cbc();
729 if(myself->incipher) {
730 myself->inkeylength = EVP_CIPHER_key_length(myself->incipher) + EVP_CIPHER_iv_length(myself->incipher);
732 myself->inkeylength = 1;
735 /* We need to use a stream mode for the meta protocol. Use AES for this,
736 but try to match the key size with the one from the cipher selected
739 If Cipher is set to none, still use a low level of encryption for the
743 int keylen = myself->incipher ? EVP_CIPHER_key_length(myself->incipher) : 0;
746 myself->connection->outcipher = EVP_aes_128_cfb();
747 } else if(keylen <= 24) {
748 myself->connection->outcipher = EVP_aes_192_cfb();
750 myself->connection->outcipher = EVP_aes_256_cfb();
753 if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime)) {
757 keyexpires = now + keylifetime;
759 /* Check if we want to use message authentication codes... */
761 if(get_config_string(lookup_config(config_tree, "Digest"), &digest)) {
762 if(!strcasecmp(digest, "none")) {
763 myself->indigest = NULL;
765 myself->indigest = EVP_get_digestbyname(digest);
767 if(!myself->indigest) {
768 logger(LOG_ERR, "Unrecognized digest type!");
776 myself->indigest = EVP_sha256();
779 myself->connection->outdigest = EVP_sha256();
781 if(get_config_int(lookup_config(config_tree, "MACLength"), &myself->inmaclength)) {
782 if(myself->indigest) {
783 if(myself->inmaclength > EVP_MD_size(myself->indigest)) {
784 logger(LOG_ERR, "MAC length exceeds size of digest!");
786 } else if(myself->inmaclength < 0) {
787 logger(LOG_ERR, "Bogus MAC length!");
792 myself->inmaclength = 4;
795 myself->connection->outmaclength = 0;
799 if(get_config_int(lookup_config(config_tree, "Compression"), &myself->incompression)) {
800 if(myself->incompression < 0 || myself->incompression > 11) {
801 logger(LOG_ERR, "Bogus compression level!");
805 myself->incompression = 0;
808 myself->connection->outcompression = 0;
812 myself->nexthop = myself;
813 myself->via = myself;
814 myself->status.reachable = true;
827 if(get_config_string(lookup_config(config_tree, "DeviceType"), &type)) {
828 if(!strcasecmp(type, "dummy")) {
829 devops = dummy_devops;
830 } else if(!strcasecmp(type, "raw_socket")) {
831 devops = raw_socket_devops;
832 } else if(!strcasecmp(type, "multicast")) {
833 devops = multicast_devops;
837 else if(!strcasecmp(type, "uml")) {
843 else if(!strcasecmp(type, "vde")) {
851 if(!devops.setup()) {
855 /* Run tinc-up script to further initialize the tap interface */
856 xasprintf(&envp[0], "NETNAME=%s", netname ? netname : "");
857 xasprintf(&envp[1], "DEVICE=%s", device ? device : "");
858 xasprintf(&envp[2], "INTERFACE=%s", iface ? iface : "");
859 xasprintf(&envp[3], "NAME=%s", myself->name);
867 execute_script("tinc-up", envp);
869 for(i = 0; i < 4; i++) {
873 /* Run subnet-up scripts for our own subnets */
875 subnet_update(myself, NULL, true);
879 if(!do_detach && getenv("LISTEN_FDS")) {
883 listen_sockets = atoi(getenv("LISTEN_FDS"));
885 unsetenv("LISTEN_FDS");
888 if(listen_sockets > MAXSOCKETS) {
889 logger(LOG_ERR, "Too many listening sockets");
893 for(i = 0; i < listen_sockets; i++) {
896 if(getsockname(i + 3, &sa.sa, &salen) < 0) {
897 logger(LOG_ERR, "Could not get address of listen fd %d: %s", i + 3, sockstrerror(errno));
901 listen_socket[i].tcp = i + 3;
904 fcntl(i + 3, F_SETFD, FD_CLOEXEC);
907 listen_socket[i].udp = setup_vpn_in_socket(&sa);
909 if(listen_socket[i].udp < 0) {
913 ifdebug(CONNECTIONS) {
914 hostname = sockaddr2hostname(&sa);
915 logger(LOG_NOTICE, "Listening on %s", hostname);
919 memcpy(&listen_socket[i].sa, &sa, salen);
923 cfg = lookup_config(config_tree, "BindToAddress");
926 get_config_string(cfg, &address);
929 cfg = lookup_config_next(config_tree, cfg);
935 char *space = strchr(address, ' ');
942 if(!strcmp(address, "*")) {
947 hint.ai_family = addressfamily;
948 hint.ai_socktype = SOCK_STREAM;
949 hint.ai_protocol = IPPROTO_TCP;
950 hint.ai_flags = AI_PASSIVE;
952 #if HAVE_DECL_RES_INIT
953 // ensure glibc reloads /etc/resolv.conf.
956 err = getaddrinfo(address && *address ? address : NULL, port, &hint, &ai);
960 logger(LOG_ERR, "System call `%s' failed: %s", "getaddrinfo",
965 for(aip = ai; aip; aip = aip->ai_next) {
966 if(listen_sockets >= MAXSOCKETS) {
967 logger(LOG_ERR, "Too many listening sockets");
971 listen_socket[listen_sockets].tcp =
972 setup_listen_socket((sockaddr_t *) aip->ai_addr);
974 if(listen_socket[listen_sockets].tcp < 0) {
978 listen_socket[listen_sockets].udp =
979 setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
981 if(listen_socket[listen_sockets].udp < 0) {
985 ifdebug(CONNECTIONS) {
986 hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
987 logger(LOG_NOTICE, "Listening on %s", hostname);
991 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
999 if(!listen_sockets) {
1000 logger(LOG_ERR, "Unable to create any listening socket!");
1004 /* If no Port option was specified, set myport to the port used by the first listening socket. */
1006 if(!port_specified) {
1008 socklen_t salen = sizeof(sa);
1010 if(!getsockname(listen_socket[0].udp, &sa.sa, &salen)) {
1012 sockaddr2str(&sa, NULL, &myport);
1015 myport = xstrdup("655");
1022 logger(LOG_NOTICE, "Ready");
1029 bool setup_network(void) {
1039 if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
1040 if(pinginterval < 1) {
1041 pinginterval = 86400;
1047 if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout)) {
1051 if(pingtimeout < 1 || pingtimeout > pinginterval) {
1052 pingtimeout = pinginterval;
1055 if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize)) {
1056 maxoutbufsize = 10 * MTU;
1059 if(!setup_myself()) {
1067 close all open network connections
1069 void close_network_connections(void) {
1070 avl_node_t *node, *next;
1072 char *envp[5] = {0};
1075 for(node = connection_tree->head; node; node = next) {
1079 terminate_connection(c, false);
1082 for(list_node_t *node = outgoing_list->head; node; node = node->next) {
1083 outgoing_t *outgoing = node->data;
1085 if(outgoing->event) {
1086 event_del(outgoing->event);
1090 list_delete_list(outgoing_list);
1092 if(myself && myself->connection) {
1093 subnet_update(myself, NULL, false);
1094 terminate_connection(myself->connection, false);
1095 free_connection(myself->connection);
1098 for(i = 0; i < listen_sockets; i++) {
1099 close(listen_socket[i].tcp);
1100 close(listen_socket[i].udp);
1103 xasprintf(&envp[0], "NETNAME=%s", netname ? netname : "");
1104 xasprintf(&envp[1], "DEVICE=%s", device ? device : "");
1105 xasprintf(&envp[2], "INTERFACE=%s", iface ? iface : "");
1106 xasprintf(&envp[3], "NAME=%s", myself->name);
1115 execute_script("tinc-down", envp);
1121 for(i = 0; i < 4; i++) {