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 bool read_rsa_public_key(connection_t *c) {
61 c->rsa_key = RSA_new();
62 // RSA_blinding_on(c->rsa_key, NULL);
65 /* First, check for simple PublicKey statement */
67 if(get_config_string(lookup_config(c->config_tree, "PublicKey"), &key)) {
68 if((size_t)BN_hex2bn(&n, key) != strlen(key)) {
70 logger(LOG_ERR, "Invalid PublicKey for %s!", c->name);
75 BN_hex2bn(&e, "FFFF");
77 if(!n || !e || RSA_set0_key(c->rsa_key, n, e, NULL) != 1) {
80 logger(LOG_ERR, "RSA_set0_key() failed with PublicKey for %s!", c->name);
87 /* Else, check for PublicKeyFile statement and read it */
89 if(get_config_string(lookup_config(c->config_tree, "PublicKeyFile"), &pubname)) {
90 fp = fopen(pubname, "r");
93 logger(LOG_ERR, "Error reading RSA public key file `%s': %s", pubname, strerror(errno));
98 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
103 return true; /* Woohoo. */
106 /* If it fails, try PEM_read_RSA_PUBKEY. */
107 fp = fopen(pubname, "r");
110 logger(LOG_ERR, "Error reading RSA public key file `%s': %s", pubname, strerror(errno));
115 c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
119 // RSA_blinding_on(c->rsa_key, NULL);
124 logger(LOG_ERR, "Reading RSA public key file `%s' failed: %s", pubname, strerror(errno));
129 /* Else, check if a harnessed public key is in the config file */
131 xasprintf(&hcfname, "%s/hosts/%s", confbase, c->name);
132 fp = fopen(hcfname, "r");
135 logger(LOG_ERR, "Error reading RSA public key file `%s': %s", hcfname, strerror(errno));
140 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
148 /* Try again with PEM_read_RSA_PUBKEY. */
150 fp = fopen(hcfname, "r");
153 logger(LOG_ERR, "Error reading RSA public key file `%s': %s", hcfname, strerror(errno));
159 c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
160 // RSA_blinding_on(c->rsa_key, NULL);
167 logger(LOG_ERR, "No public key for %s specified!", c->name);
172 static bool read_rsa_private_key(void) {
174 char *fname, *key, *pubkey;
179 if(get_config_string(lookup_config(config_tree, "PrivateKey"), &key)) {
180 myself->connection->rsa_key = RSA_new();
182 // RSA_blinding_on(myself->connection->rsa_key, NULL);
183 if((size_t)BN_hex2bn(&d, key) != strlen(key)) {
184 logger(LOG_ERR, "Invalid PrivateKey for myself!");
191 if(!get_config_string(lookup_config(config_tree, "PublicKey"), &pubkey)) {
193 logger(LOG_ERR, "PrivateKey used but no PublicKey found!");
197 if((size_t)BN_hex2bn(&n, pubkey) != strlen(pubkey)) {
200 logger(LOG_ERR, "Invalid PublicKey for myself!");
205 BN_hex2bn(&e, "FFFF");
207 if(!n || !e || !d || RSA_set0_key(myself->connection->rsa_key, n, e, d) != 1) {
211 logger(LOG_ERR, "RSA_set0_key() failed with PrivateKey for myself!");
218 if(!get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname)) {
219 xasprintf(&fname, "%s/rsa_key.priv", confbase);
222 fp = fopen(fname, "r");
225 logger(LOG_ERR, "Error reading RSA private key file `%s': %s",
226 fname, strerror(errno));
231 #if !defined(HAVE_MINGW) && !defined(HAVE_CYGWIN)
234 if(!fstat(fileno(fp), &s)) {
235 if(s.st_mode & ~0100700) {
236 logger(LOG_WARNING, "Warning: insecure file permissions for RSA private key file `%s'!", fname);
239 logger(LOG_WARNING, "Could not stat RSA private key file `%s': %s'", fname, strerror(errno));
244 myself->connection->rsa_key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
247 if(!myself->connection->rsa_key) {
248 logger(LOG_ERR, "Reading RSA private key file `%s' failed: %s",
249 fname, strerror(errno));
259 Read Subnets from all host config files
261 void load_all_subnets(void) {
266 avl_tree_t *config_tree;
271 xasprintf(&dname, "%s/hosts", confbase);
272 dir = opendir(dname);
275 logger(LOG_ERR, "Could not open %s: %s", dname, strerror(errno));
280 while((ent = readdir(dir))) {
281 if(!check_id(ent->d_name)) {
285 n = lookup_node(ent->d_name);
286 #ifdef _DIRENT_HAVE_D_TYPE
287 //if(ent->d_type != DT_REG)
291 xasprintf(&fname, "%s/hosts/%s", confbase, ent->d_name);
292 init_configuration(&config_tree);
293 read_config_options(config_tree, ent->d_name);
294 read_config_file(config_tree, fname);
299 n->name = xstrdup(ent->d_name);
303 for(cfg = lookup_config(config_tree, "Subnet"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
304 if(!get_config_subnet(cfg, &s)) {
308 if((s2 = lookup_subnet(n, s))) {
315 exit_configuration(&config_tree);
321 char *get_name(void) {
324 get_config_string(lookup_config(config_tree, "Name"), &name);
331 char *envname = getenv(name + 1);
332 char hostname[32] = "";
335 if(strcmp(name + 1, "HOST")) {
336 fprintf(stderr, "Invalid Name: environment variable %s does not exist\n", name + 1);
341 if(gethostname(hostname, sizeof(hostname)) || !*hostname) {
342 fprintf(stderr, "Could not get hostname: %s\n", strerror(errno));
352 name = xstrdup(envname);
354 for(char *c = name; *c; c++)
360 if(!check_id(name)) {
361 logger(LOG_ERR, "Invalid name for myself!");
370 Configure node_t myself and set up the local sockets (listen only)
372 static bool setup_myself(void) {
375 char *name, *hostname, *mode, *afname, *cipher, *digest, *type;
377 char *address = NULL;
381 struct addrinfo *ai, *aip, hint = {0};
385 bool port_specified = false;
388 myself->connection = new_connection();
390 myself->hostname = xstrdup("MYSELF");
391 myself->connection->hostname = xstrdup("MYSELF");
393 myself->connection->options = 0;
394 myself->connection->protocol_version = PROT_CURRENT;
396 if(!(name = get_name())) {
397 logger(LOG_ERR, "Name for tinc daemon required!");
401 /* Read tinc.conf and our own host config file */
404 myself->connection->name = xstrdup(name);
405 xasprintf(&fname, "%s/hosts/%s", confbase, name);
406 read_config_options(config_tree, name);
407 read_config_file(config_tree, fname);
410 if(!read_rsa_private_key()) {
414 if(!get_config_string(lookup_config(config_tree, "Port"), &myport)) {
415 myport = xstrdup("655");
417 port_specified = true;
420 /* Ensure myport is numeric */
423 struct addrinfo *ai = str2addrinfo("localhost", myport, SOCK_DGRAM);
426 if(!ai || !ai->ai_addr) {
431 memcpy(&sa, ai->ai_addr, ai->ai_addrlen);
432 sockaddr2str(&sa, NULL, &myport);
435 if(get_config_string(lookup_config(config_tree, "Proxy"), &proxy)) {
436 if((space = strchr(proxy, ' '))) {
440 if(!strcasecmp(proxy, "none")) {
441 proxytype = PROXY_NONE;
442 } else if(!strcasecmp(proxy, "socks4")) {
443 proxytype = PROXY_SOCKS4;
444 } else if(!strcasecmp(proxy, "socks4a")) {
445 proxytype = PROXY_SOCKS4A;
446 } else if(!strcasecmp(proxy, "socks5")) {
447 proxytype = PROXY_SOCKS5;
448 } else if(!strcasecmp(proxy, "http")) {
449 proxytype = PROXY_HTTP;
450 } else if(!strcasecmp(proxy, "exec")) {
451 proxytype = PROXY_EXEC;
453 logger(LOG_ERR, "Unknown proxy type %s!", proxy);
464 if(!space || !*space) {
465 logger(LOG_ERR, "Argument expected for proxy type exec!");
470 proxyhost = xstrdup(space);
479 if(space && (space = strchr(space, ' '))) {
480 *space++ = 0, proxyport = space;
483 if(space && (space = strchr(space, ' '))) {
484 *space++ = 0, proxyuser = space;
487 if(space && (space = strchr(space, ' '))) {
488 *space++ = 0, proxypass = space;
491 if(!proxyhost || !*proxyhost || !proxyport || !*proxyport) {
492 logger(LOG_ERR, "Host and port argument expected for proxy!");
497 proxyhost = xstrdup(proxyhost);
498 proxyport = xstrdup(proxyport);
500 if(proxyuser && *proxyuser) {
501 proxyuser = xstrdup(proxyuser);
504 if(proxypass && *proxypass) {
505 proxypass = xstrdup(proxypass);
514 /* Read in all the subnets specified in the host configuration file */
516 cfg = lookup_config(config_tree, "Subnet");
519 if(!get_config_subnet(cfg, &subnet)) {
523 subnet_add(myself, subnet);
525 cfg = lookup_config_next(config_tree, cfg);
528 /* Check some options */
530 if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice) && choice) {
531 myself->options |= OPTION_INDIRECT;
534 if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice) && choice) {
535 myself->options |= OPTION_TCPONLY;
538 if(myself->options & OPTION_TCPONLY) {
539 myself->options |= OPTION_INDIRECT;
542 get_config_bool(lookup_config(config_tree, "DirectOnly"), &directonly);
543 get_config_bool(lookup_config(config_tree, "StrictSubnets"), &strictsubnets);
544 get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
545 get_config_bool(lookup_config(config_tree, "LocalDiscovery"), &localdiscovery);
546 strictsubnets |= tunnelserver;
548 if(get_config_string(lookup_config(config_tree, "Mode"), &mode)) {
549 if(!strcasecmp(mode, "router")) {
550 routing_mode = RMODE_ROUTER;
551 } else if(!strcasecmp(mode, "switch")) {
552 routing_mode = RMODE_SWITCH;
553 } else if(!strcasecmp(mode, "hub")) {
554 routing_mode = RMODE_HUB;
556 logger(LOG_ERR, "Invalid routing mode!");
564 if(get_config_string(lookup_config(config_tree, "Forwarding"), &mode)) {
565 if(!strcasecmp(mode, "off")) {
566 forwarding_mode = FMODE_OFF;
567 } else if(!strcasecmp(mode, "internal")) {
568 forwarding_mode = FMODE_INTERNAL;
569 } else if(!strcasecmp(mode, "kernel")) {
570 forwarding_mode = FMODE_KERNEL;
572 logger(LOG_ERR, "Invalid forwarding mode!");
580 choice = !(myself->options & OPTION_TCPONLY);
581 get_config_bool(lookup_config(config_tree, "PMTUDiscovery"), &choice);
584 myself->options |= OPTION_PMTU_DISCOVERY;
588 get_config_bool(lookup_config(config_tree, "ClampMSS"), &choice);
591 myself->options |= OPTION_CLAMP_MSS;
594 get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
595 get_config_bool(lookup_config(config_tree, "DecrementTTL"), &decrement_ttl);
597 if(get_config_string(lookup_config(config_tree, "Broadcast"), &mode)) {
598 if(!strcasecmp(mode, "no")) {
599 broadcast_mode = BMODE_NONE;
600 } else if(!strcasecmp(mode, "yes") || !strcasecmp(mode, "mst")) {
601 broadcast_mode = BMODE_MST;
602 } else if(!strcasecmp(mode, "direct")) {
603 broadcast_mode = BMODE_DIRECT;
605 logger(LOG_ERR, "Invalid broadcast mode!");
613 #if !defined(SOL_IP) || !defined(IP_TOS)
615 if(priorityinheritance) {
616 logger(LOG_WARNING, "%s not supported on this platform for IPv4 connection", "PriorityInheritance");
621 #if !defined(IPPROTO_IPV6) || !defined(IPV6_TCLASS)
623 if(priorityinheritance) {
624 logger(LOG_WARNING, "%s not supported on this platform for IPv6 connection", "PriorityInheritance");
629 if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire)) {
633 if(get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout)) {
634 if(maxtimeout <= 0) {
635 logger(LOG_ERR, "Bogus maximum timeout!");
642 if(get_config_int(lookup_config(config_tree, "MinTimeout"), &mintimeout)) {
644 logger(LOG_ERR, "Bogus minimum timeout!");
648 if(mintimeout > maxtimeout) {
649 logger(LOG_WARNING, "Minimum timeout (%d s) cannot be larger than maximum timeout (%d s). Correcting !", mintimeout, maxtimeout);
650 mintimeout = maxtimeout;
656 if(get_config_int(lookup_config(config_tree, "UDPRcvBuf"), &udp_rcvbuf)) {
657 if(udp_rcvbuf <= 0) {
658 logger(LOG_ERR, "UDPRcvBuf cannot be negative!");
663 if(get_config_int(lookup_config(config_tree, "UDPSndBuf"), &udp_sndbuf)) {
664 if(udp_sndbuf <= 0) {
665 logger(LOG_ERR, "UDPSndBuf cannot be negative!");
670 if(get_config_int(lookup_config(config_tree, "ReplayWindow"), &replaywin_int)) {
671 if(replaywin_int < 0) {
672 logger(LOG_ERR, "ReplayWindow cannot be negative!");
676 replaywin = (unsigned)replaywin_int;
679 if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
680 if(!strcasecmp(afname, "IPv4")) {
681 addressfamily = AF_INET;
682 } else if(!strcasecmp(afname, "IPv6")) {
683 addressfamily = AF_INET6;
684 } else if(!strcasecmp(afname, "any")) {
685 addressfamily = AF_UNSPEC;
687 logger(LOG_ERR, "Invalid address family!");
695 get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
697 /* Generate packet encryption key */
699 if(get_config_string(lookup_config(config_tree, "Cipher"), &cipher)) {
700 if(!strcasecmp(cipher, "none")) {
701 myself->incipher = NULL;
703 myself->incipher = EVP_get_cipherbyname(cipher);
705 if(!myself->incipher) {
706 logger(LOG_ERR, "Unrecognized cipher type!");
714 myself->incipher = EVP_aes_256_cbc();
717 if(myself->incipher) {
718 myself->inkeylength = EVP_CIPHER_key_length(myself->incipher) + EVP_CIPHER_iv_length(myself->incipher);
720 myself->inkeylength = 1;
723 /* We need to use a stream mode for the meta protocol. Use AES for this,
724 but try to match the key size with the one from the cipher selected
727 If Cipher is set to none, still use a low level of encryption for the
731 int keylen = myself->incipher ? EVP_CIPHER_key_length(myself->incipher) : 0;
734 myself->connection->outcipher = EVP_aes_128_cfb();
735 } else if(keylen <= 24) {
736 myself->connection->outcipher = EVP_aes_192_cfb();
738 myself->connection->outcipher = EVP_aes_256_cfb();
741 if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime)) {
745 keyexpires = now + keylifetime;
747 /* Check if we want to use message authentication codes... */
749 if(get_config_string(lookup_config(config_tree, "Digest"), &digest)) {
750 if(!strcasecmp(digest, "none")) {
751 myself->indigest = NULL;
753 myself->indigest = EVP_get_digestbyname(digest);
755 if(!myself->indigest) {
756 logger(LOG_ERR, "Unrecognized digest type!");
764 myself->indigest = EVP_sha256();
767 myself->connection->outdigest = EVP_sha256();
769 if(get_config_int(lookup_config(config_tree, "MACLength"), &myself->inmaclength)) {
770 if(myself->indigest) {
771 if(myself->inmaclength > EVP_MD_size(myself->indigest)) {
772 logger(LOG_ERR, "MAC length exceeds size of digest!");
774 } else if(myself->inmaclength < 0) {
775 logger(LOG_ERR, "Bogus MAC length!");
780 myself->inmaclength = 4;
783 myself->connection->outmaclength = 0;
787 if(get_config_int(lookup_config(config_tree, "Compression"), &myself->incompression)) {
788 if(myself->incompression < 0 || myself->incompression > 11) {
789 logger(LOG_ERR, "Bogus compression level!");
793 myself->incompression = 0;
796 myself->connection->outcompression = 0;
800 myself->nexthop = myself;
801 myself->via = myself;
802 myself->status.reachable = true;
815 if(get_config_string(lookup_config(config_tree, "DeviceType"), &type)) {
816 if(!strcasecmp(type, "dummy")) {
817 devops = dummy_devops;
818 } else if(!strcasecmp(type, "raw_socket")) {
819 devops = raw_socket_devops;
820 } else if(!strcasecmp(type, "multicast")) {
821 devops = multicast_devops;
825 else if(!strcasecmp(type, "uml")) {
831 else if(!strcasecmp(type, "vde")) {
839 if(!devops.setup()) {
843 /* Run tinc-up script to further initialize the tap interface */
844 xasprintf(&envp[0], "NETNAME=%s", netname ? netname : "");
845 xasprintf(&envp[1], "DEVICE=%s", device ? device : "");
846 xasprintf(&envp[2], "INTERFACE=%s", iface ? iface : "");
847 xasprintf(&envp[3], "NAME=%s", myself->name);
855 execute_script("tinc-up", envp);
857 for(i = 0; i < 4; i++) {
861 /* Run subnet-up scripts for our own subnets */
863 subnet_update(myself, NULL, true);
867 if(!do_detach && getenv("LISTEN_FDS")) {
871 listen_sockets = atoi(getenv("LISTEN_FDS"));
873 unsetenv("LISTEN_FDS");
876 if(listen_sockets > MAXSOCKETS) {
877 logger(LOG_ERR, "Too many listening sockets");
881 for(i = 0; i < listen_sockets; i++) {
884 if(getsockname(i + 3, &sa.sa, &salen) < 0) {
885 logger(LOG_ERR, "Could not get address of listen fd %d: %s", i + 3, sockstrerror(errno));
889 listen_socket[i].tcp = i + 3;
892 fcntl(i + 3, F_SETFD, FD_CLOEXEC);
895 listen_socket[i].udp = setup_vpn_in_socket(&sa);
897 if(listen_socket[i].udp < 0) {
901 ifdebug(CONNECTIONS) {
902 hostname = sockaddr2hostname(&sa);
903 logger(LOG_NOTICE, "Listening on %s", hostname);
907 memcpy(&listen_socket[i].sa, &sa, salen);
911 cfg = lookup_config(config_tree, "BindToAddress");
914 get_config_string(cfg, &address);
917 cfg = lookup_config_next(config_tree, cfg);
923 char *space = strchr(address, ' ');
930 if(!strcmp(address, "*")) {
935 hint.ai_family = addressfamily;
936 hint.ai_socktype = SOCK_STREAM;
937 hint.ai_protocol = IPPROTO_TCP;
938 hint.ai_flags = AI_PASSIVE;
940 #if HAVE_DECL_RES_INIT
941 // ensure glibc reloads /etc/resolv.conf.
944 err = getaddrinfo(address && *address ? address : NULL, port, &hint, &ai);
948 logger(LOG_ERR, "System call `%s' failed: %s", "getaddrinfo",
953 for(aip = ai; aip; aip = aip->ai_next) {
954 if(listen_sockets >= MAXSOCKETS) {
955 logger(LOG_ERR, "Too many listening sockets");
959 listen_socket[listen_sockets].tcp =
960 setup_listen_socket((sockaddr_t *) aip->ai_addr);
962 if(listen_socket[listen_sockets].tcp < 0) {
966 listen_socket[listen_sockets].udp =
967 setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
969 if(listen_socket[listen_sockets].udp < 0) {
973 ifdebug(CONNECTIONS) {
974 hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
975 logger(LOG_NOTICE, "Listening on %s", hostname);
979 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
987 if(!listen_sockets) {
988 logger(LOG_ERR, "Unable to create any listening socket!");
992 /* If no Port option was specified, set myport to the port used by the first listening socket. */
994 if(!port_specified) {
996 socklen_t salen = sizeof(sa);
998 if(!getsockname(listen_socket[0].udp, &sa.sa, &salen)) {
1000 sockaddr2str(&sa, NULL, &myport);
1003 myport = xstrdup("655");
1010 logger(LOG_NOTICE, "Ready");
1017 bool setup_network(void) {
1027 if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
1028 if(pinginterval < 1) {
1029 pinginterval = 86400;
1035 if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout)) {
1039 if(pingtimeout < 1 || pingtimeout > pinginterval) {
1040 pingtimeout = pinginterval;
1043 if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize)) {
1044 maxoutbufsize = 10 * MTU;
1047 if(!setup_myself()) {
1055 close all open network connections
1057 void close_network_connections(void) {
1058 avl_node_t *node, *next;
1060 char *envp[5] = {0};
1063 for(node = connection_tree->head; node; node = next) {
1067 terminate_connection(c, false);
1070 for(list_node_t *node = outgoing_list->head; node; node = node->next) {
1071 outgoing_t *outgoing = node->data;
1073 if(outgoing->event) {
1074 event_del(outgoing->event);
1078 list_delete_list(outgoing_list);
1080 if(myself && myself->connection) {
1081 subnet_update(myself, NULL, false);
1082 terminate_connection(myself->connection, false);
1083 free_connection(myself->connection);
1086 for(i = 0; i < listen_sockets; i++) {
1087 close(listen_socket[i].tcp);
1088 close(listen_socket[i].udp);
1091 xasprintf(&envp[0], "NETNAME=%s", netname ? netname : "");
1092 xasprintf(&envp[1], "DEVICE=%s", device ? device : "");
1093 xasprintf(&envp[2], "INTERFACE=%s", iface ? iface : "");
1094 xasprintf(&envp[3], "NAME=%s", myself->name);
1103 execute_script("tinc-down", envp);
1109 for(i = 0; i < 4; i++) {