3 Copyright (C) 1998-2005 Ivo Timmermans,
4 2000-2016 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) {
53 BN_free(r->n); r->n = n;
54 BN_free(r->e); r->e = e;
55 BN_free(r->d); r->d = d;
60 bool read_rsa_public_key(connection_t *c) {
69 c->rsa_key = RSA_new();
70 // RSA_blinding_on(c->rsa_key, NULL);
73 /* First, check for simple PublicKey statement */
75 if(get_config_string(lookup_config(c->config_tree, "PublicKey"), &key)) {
76 if(BN_hex2bn(&n, key) != strlen(key)) {
78 logger(LOG_ERR, "Invalid PublicKey for %s!", c->name);
82 BN_hex2bn(&e, "FFFF");
83 if(!n || !e || RSA_set0_key(c->rsa_key, n, e, NULL) != 1) {
86 logger(LOG_ERR, "RSA_set0_key() failed with PublicKey for %s!", c->name);
92 /* Else, check for PublicKeyFile statement and read it */
94 if(get_config_string(lookup_config(c->config_tree, "PublicKeyFile"), &pubname)) {
95 fp = fopen(pubname, "r");
98 logger(LOG_ERR, "Error reading RSA public key file `%s': %s", pubname, strerror(errno));
103 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
108 return true; /* Woohoo. */
111 /* If it fails, try PEM_read_RSA_PUBKEY. */
112 fp = fopen(pubname, "r");
115 logger(LOG_ERR, "Error reading RSA public key file `%s': %s", pubname, strerror(errno));
120 c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
124 // RSA_blinding_on(c->rsa_key, NULL);
129 logger(LOG_ERR, "Reading RSA public key file `%s' failed: %s", pubname, strerror(errno));
134 /* Else, check if a harnessed public key is in the config file */
136 xasprintf(&hcfname, "%s/hosts/%s", confbase, c->name);
137 fp = fopen(hcfname, "r");
140 logger(LOG_ERR, "Error reading RSA public key file `%s': %s", hcfname, strerror(errno));
145 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
153 /* Try again with PEM_read_RSA_PUBKEY. */
155 fp = fopen(hcfname, "r");
158 logger(LOG_ERR, "Error reading RSA public key file `%s': %s", hcfname, strerror(errno));
164 c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
165 // RSA_blinding_on(c->rsa_key, NULL);
171 logger(LOG_ERR, "No public key for %s specified!", c->name);
176 static bool read_rsa_private_key(void) {
178 char *fname, *key, *pubkey;
183 if(get_config_string(lookup_config(config_tree, "PrivateKey"), &key)) {
184 myself->connection->rsa_key = RSA_new();
185 // RSA_blinding_on(myself->connection->rsa_key, NULL);
186 if(BN_hex2bn(&d, key) != strlen(key)) {
187 logger(LOG_ERR, "Invalid PrivateKey for myself!");
192 if(!get_config_string(lookup_config(config_tree, "PublicKey"), &pubkey)) {
194 logger(LOG_ERR, "PrivateKey used but no PublicKey found!");
197 if(BN_hex2bn(&n, pubkey) != strlen(pubkey)) {
200 logger(LOG_ERR, "Invalid PublicKey for myself!");
204 BN_hex2bn(&e, "FFFF");
205 if(!n || !e || !d || RSA_set0_key(myself->connection->rsa_key, n, e, d) != 1) {
209 logger(LOG_ERR, "RSA_set0_key() failed with PrivateKey for myself!");
215 if(!get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname))
216 xasprintf(&fname, "%s/rsa_key.priv", confbase);
218 fp = fopen(fname, "r");
221 logger(LOG_ERR, "Error reading RSA private key file `%s': %s",
222 fname, strerror(errno));
227 #if !defined(HAVE_MINGW) && !defined(HAVE_CYGWIN)
230 if(!fstat(fileno(fp), &s)) {
231 if(s.st_mode & ~0100700)
232 logger(LOG_WARNING, "Warning: insecure file permissions for RSA private key file `%s'!", fname);
234 logger(LOG_WARNING, "Could not stat RSA private key file `%s': %s'", fname, strerror(errno));
238 myself->connection->rsa_key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
241 if(!myself->connection->rsa_key) {
242 logger(LOG_ERR, "Reading RSA private key file `%s' failed: %s",
243 fname, strerror(errno));
253 Read Subnets from all host config files
255 void load_all_subnets(void) {
260 avl_tree_t *config_tree;
265 xasprintf(&dname, "%s/hosts", confbase);
266 dir = opendir(dname);
268 logger(LOG_ERR, "Could not open %s: %s", dname, strerror(errno));
273 while((ent = readdir(dir))) {
274 if(!check_id(ent->d_name))
277 n = lookup_node(ent->d_name);
278 #ifdef _DIRENT_HAVE_D_TYPE
279 //if(ent->d_type != DT_REG)
283 xasprintf(&fname, "%s/hosts/%s", confbase, ent->d_name);
284 init_configuration(&config_tree);
285 read_config_options(config_tree, ent->d_name);
286 read_config_file(config_tree, fname);
291 n->name = xstrdup(ent->d_name);
295 for(cfg = lookup_config(config_tree, "Subnet"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
296 if(!get_config_subnet(cfg, &s))
299 if((s2 = lookup_subnet(n, s))) {
306 exit_configuration(&config_tree);
312 char *get_name(void) {
315 get_config_string(lookup_config(config_tree, "Name"), &name);
321 char *envname = getenv(name + 1);
322 char hostname[32] = "";
324 if(strcmp(name + 1, "HOST")) {
325 fprintf(stderr, "Invalid Name: environment variable %s does not exist\n", name + 1);
329 if(gethostname(hostname, sizeof hostname) || !*hostname) {
330 fprintf(stderr, "Could not get hostname: %s\n", strerror(errno));
338 name = xstrdup(envname);
339 for(char *c = name; *c; c++)
344 if(!check_id(name)) {
345 logger(LOG_ERR, "Invalid name for myself!");
354 Configure node_t myself and set up the local sockets (listen only)
356 static bool setup_myself(void) {
359 char *name, *hostname, *mode, *afname, *cipher, *digest, *type;
361 char *address = NULL;
364 char *envp[5] = {NULL};
365 struct addrinfo *ai, *aip, hint = {0};
369 bool port_specified = false;
372 myself->connection = new_connection();
374 myself->hostname = xstrdup("MYSELF");
375 myself->connection->hostname = xstrdup("MYSELF");
377 myself->connection->options = 0;
378 myself->connection->protocol_version = PROT_CURRENT;
380 if(!(name = get_name())) {
381 logger(LOG_ERR, "Name for tinc daemon required!");
385 /* Read tinc.conf and our own host config file */
388 myself->connection->name = xstrdup(name);
389 xasprintf(&fname, "%s/hosts/%s", confbase, name);
390 read_config_options(config_tree, name);
391 read_config_file(config_tree, fname);
394 if(!read_rsa_private_key())
397 if(!get_config_string(lookup_config(config_tree, "Port"), &myport))
398 myport = xstrdup("655");
400 port_specified = true;
402 /* Ensure myport is numeric */
405 struct addrinfo *ai = str2addrinfo("localhost", myport, SOCK_DGRAM);
407 if(!ai || !ai->ai_addr)
410 memcpy(&sa, ai->ai_addr, ai->ai_addrlen);
411 sockaddr2str(&sa, NULL, &myport);
414 if(get_config_string(lookup_config(config_tree, "Proxy"), &proxy)) {
415 if((space = strchr(proxy, ' ')))
418 if(!strcasecmp(proxy, "none")) {
419 proxytype = PROXY_NONE;
420 } else if(!strcasecmp(proxy, "socks4")) {
421 proxytype = PROXY_SOCKS4;
422 } else if(!strcasecmp(proxy, "socks4a")) {
423 proxytype = PROXY_SOCKS4A;
424 } else if(!strcasecmp(proxy, "socks5")) {
425 proxytype = PROXY_SOCKS5;
426 } else if(!strcasecmp(proxy, "http")) {
427 proxytype = PROXY_HTTP;
428 } else if(!strcasecmp(proxy, "exec")) {
429 proxytype = PROXY_EXEC;
431 logger(LOG_ERR, "Unknown proxy type %s!", proxy);
442 if(!space || !*space) {
443 logger(LOG_ERR, "Argument expected for proxy type exec!");
447 proxyhost = xstrdup(space);
455 if(space && (space = strchr(space, ' ')))
456 *space++ = 0, proxyport = space;
457 if(space && (space = strchr(space, ' ')))
458 *space++ = 0, proxyuser = space;
459 if(space && (space = strchr(space, ' ')))
460 *space++ = 0, proxypass = space;
461 if(!proxyhost || !*proxyhost || !proxyport || !*proxyport) {
462 logger(LOG_ERR, "Host and port argument expected for proxy!");
466 proxyhost = xstrdup(proxyhost);
467 proxyport = xstrdup(proxyport);
468 if(proxyuser && *proxyuser)
469 proxyuser = xstrdup(proxyuser);
470 if(proxypass && *proxypass)
471 proxypass = xstrdup(proxypass);
478 /* Read in all the subnets specified in the host configuration file */
480 cfg = lookup_config(config_tree, "Subnet");
483 if(!get_config_subnet(cfg, &subnet))
486 subnet_add(myself, subnet);
488 cfg = lookup_config_next(config_tree, cfg);
491 /* Check some options */
493 if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice) && choice)
494 myself->options |= OPTION_INDIRECT;
496 if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice) && choice)
497 myself->options |= OPTION_TCPONLY;
499 if(myself->options & OPTION_TCPONLY)
500 myself->options |= OPTION_INDIRECT;
502 get_config_bool(lookup_config(config_tree, "DirectOnly"), &directonly);
503 get_config_bool(lookup_config(config_tree, "StrictSubnets"), &strictsubnets);
504 get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
505 get_config_bool(lookup_config(config_tree, "LocalDiscovery"), &localdiscovery);
506 strictsubnets |= tunnelserver;
508 if(get_config_string(lookup_config(config_tree, "Mode"), &mode)) {
509 if(!strcasecmp(mode, "router"))
510 routing_mode = RMODE_ROUTER;
511 else if(!strcasecmp(mode, "switch"))
512 routing_mode = RMODE_SWITCH;
513 else if(!strcasecmp(mode, "hub"))
514 routing_mode = RMODE_HUB;
516 logger(LOG_ERR, "Invalid routing mode!");
523 if(get_config_string(lookup_config(config_tree, "Forwarding"), &mode)) {
524 if(!strcasecmp(mode, "off"))
525 forwarding_mode = FMODE_OFF;
526 else if(!strcasecmp(mode, "internal"))
527 forwarding_mode = FMODE_INTERNAL;
528 else if(!strcasecmp(mode, "kernel"))
529 forwarding_mode = FMODE_KERNEL;
531 logger(LOG_ERR, "Invalid forwarding mode!");
539 get_config_bool(lookup_config(config_tree, "PMTUDiscovery"), &choice);
541 myself->options |= OPTION_PMTU_DISCOVERY;
544 get_config_bool(lookup_config(config_tree, "ClampMSS"), &choice);
546 myself->options |= OPTION_CLAMP_MSS;
548 get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
549 get_config_bool(lookup_config(config_tree, "DecrementTTL"), &decrement_ttl);
550 if(get_config_string(lookup_config(config_tree, "Broadcast"), &mode)) {
551 if(!strcasecmp(mode, "no"))
552 broadcast_mode = BMODE_NONE;
553 else if(!strcasecmp(mode, "yes") || !strcasecmp(mode, "mst"))
554 broadcast_mode = BMODE_MST;
555 else if(!strcasecmp(mode, "direct"))
556 broadcast_mode = BMODE_DIRECT;
558 logger(LOG_ERR, "Invalid broadcast mode!");
565 #if !defined(SOL_IP) || !defined(IP_TOS)
566 if(priorityinheritance)
567 logger(LOG_WARNING, "%s not supported on this platform for IPv4 connection", "PriorityInheritance");
570 #if !defined(IPPROTO_IPV6) || !defined(IPV6_TCLASS)
571 if(priorityinheritance)
572 logger(LOG_WARNING, "%s not supported on this platform for IPv6 connection", "PriorityInheritance");
575 if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire))
578 if(get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout)) {
579 if(maxtimeout <= 0) {
580 logger(LOG_ERR, "Bogus maximum timeout!");
586 if(get_config_int(lookup_config(config_tree, "MinTimeout"), &mintimeout)) {
588 logger(LOG_ERR, "Bogus minimum timeout!");
591 if(mintimeout > maxtimeout) {
592 logger(LOG_WARNING, "Minimum timeout (%d s) cannot be larger than maximum timeout (%d s). Correcting !", mintimeout, maxtimeout );
593 mintimeout=maxtimeout;
598 if(get_config_int(lookup_config(config_tree, "UDPRcvBuf"), &udp_rcvbuf)) {
599 if(udp_rcvbuf <= 0) {
600 logger(LOG_ERR, "UDPRcvBuf cannot be negative!");
605 if(get_config_int(lookup_config(config_tree, "UDPSndBuf"), &udp_sndbuf)) {
606 if(udp_sndbuf <= 0) {
607 logger(LOG_ERR, "UDPSndBuf cannot be negative!");
612 if(get_config_int(lookup_config(config_tree, "ReplayWindow"), &replaywin_int)) {
613 if(replaywin_int < 0) {
614 logger(LOG_ERR, "ReplayWindow cannot be negative!");
617 replaywin = (unsigned)replaywin_int;
620 if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
621 if(!strcasecmp(afname, "IPv4"))
622 addressfamily = AF_INET;
623 else if(!strcasecmp(afname, "IPv6"))
624 addressfamily = AF_INET6;
625 else if(!strcasecmp(afname, "any"))
626 addressfamily = AF_UNSPEC;
628 logger(LOG_ERR, "Invalid address family!");
635 get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
637 /* Generate packet encryption key */
639 if(get_config_string(lookup_config(config_tree, "Cipher"), &cipher)) {
640 if(!strcasecmp(cipher, "none")) {
641 myself->incipher = NULL;
643 myself->incipher = EVP_get_cipherbyname(cipher);
645 if(!myself->incipher) {
646 logger(LOG_ERR, "Unrecognized cipher type!");
653 myself->incipher = EVP_aes_256_cbc();
656 myself->inkeylength = EVP_CIPHER_key_length(myself->incipher) + EVP_CIPHER_iv_length(myself->incipher);
658 myself->inkeylength = 1;
660 /* We need to use OFB mode for the meta protocol. Use AES for this,
661 but try to match the key size with the one from the cipher selected
665 int keylen = EVP_CIPHER_key_length(myself->incipher);
667 myself->connection->outcipher = EVP_aes_128_ctr();
668 else if(keylen <= 24)
669 myself->connection->outcipher = EVP_aes_192_ctr();
671 myself->connection->outcipher = EVP_aes_256_ctr();
673 if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
676 keyexpires = now + keylifetime;
678 /* Check if we want to use message authentication codes... */
680 if(get_config_string(lookup_config(config_tree, "Digest"), &digest)) {
681 if(!strcasecmp(digest, "none")) {
682 myself->indigest = NULL;
684 myself->indigest = EVP_get_digestbyname(digest);
686 if(!myself->indigest) {
687 logger(LOG_ERR, "Unrecognized digest type!");
695 myself->indigest = EVP_sha256();
697 myself->connection->outdigest = EVP_sha256();
699 if(get_config_int(lookup_config(config_tree, "MACLength"), &myself->inmaclength)) {
700 if(myself->indigest) {
701 if(myself->inmaclength > EVP_MD_size(myself->indigest)) {
702 logger(LOG_ERR, "MAC length exceeds size of digest!");
704 } else if(myself->inmaclength < 0) {
705 logger(LOG_ERR, "Bogus MAC length!");
710 myself->inmaclength = 4;
712 myself->connection->outmaclength = 0;
716 if(get_config_int(lookup_config(config_tree, "Compression"), &myself->incompression)) {
717 if(myself->incompression < 0 || myself->incompression > 11) {
718 logger(LOG_ERR, "Bogus compression level!");
722 myself->incompression = 0;
724 myself->connection->outcompression = 0;
728 myself->nexthop = myself;
729 myself->via = myself;
730 myself->status.reachable = true;
742 if(get_config_string(lookup_config(config_tree, "DeviceType"), &type)) {
743 if(!strcasecmp(type, "dummy"))
744 devops = dummy_devops;
745 else if(!strcasecmp(type, "raw_socket"))
746 devops = raw_socket_devops;
747 else if(!strcasecmp(type, "multicast"))
748 devops = multicast_devops;
750 else if(!strcasecmp(type, "uml"))
754 else if(!strcasecmp(type, "vde"))
763 /* Run tinc-up script to further initialize the tap interface */
764 xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
765 xasprintf(&envp[1], "DEVICE=%s", device ? : "");
766 xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
767 xasprintf(&envp[3], "NAME=%s", myself->name);
775 execute_script("tinc-up", envp);
777 for(i = 0; i < 4; i++)
780 /* Run subnet-up scripts for our own subnets */
782 subnet_update(myself, NULL, true);
786 if(!do_detach && getenv("LISTEN_FDS")) {
790 listen_sockets = atoi(getenv("LISTEN_FDS"));
792 unsetenv("LISTEN_FDS");
795 if(listen_sockets > MAXSOCKETS) {
796 logger(LOG_ERR, "Too many listening sockets");
800 for(i = 0; i < listen_sockets; i++) {
802 if(getsockname(i + 3, &sa.sa, &salen) < 0) {
803 logger(LOG_ERR, "Could not get address of listen fd %d: %s", i + 3, sockstrerror(errno));
807 listen_socket[i].tcp = i + 3;
810 fcntl(i + 3, F_SETFD, FD_CLOEXEC);
813 listen_socket[i].udp = setup_vpn_in_socket(&sa);
814 if(listen_socket[i].udp < 0)
817 ifdebug(CONNECTIONS) {
818 hostname = sockaddr2hostname(&sa);
819 logger(LOG_NOTICE, "Listening on %s", hostname);
823 memcpy(&listen_socket[i].sa, &sa, salen);
827 cfg = lookup_config(config_tree, "BindToAddress");
830 get_config_string(cfg, &address);
832 cfg = lookup_config_next(config_tree, cfg);
837 char *space = strchr(address, ' ');
843 if(!strcmp(address, "*"))
847 hint.ai_family = addressfamily;
848 hint.ai_socktype = SOCK_STREAM;
849 hint.ai_protocol = IPPROTO_TCP;
850 hint.ai_flags = AI_PASSIVE;
852 #if HAVE_DECL_RES_INIT
853 // ensure glibc reloads /etc/resolv.conf.
856 err = getaddrinfo(address && *address ? address : NULL, port, &hint, &ai);
860 logger(LOG_ERR, "System call `%s' failed: %s", "getaddrinfo",
865 for(aip = ai; aip; aip = aip->ai_next) {
866 if(listen_sockets >= MAXSOCKETS) {
867 logger(LOG_ERR, "Too many listening sockets");
871 listen_socket[listen_sockets].tcp =
872 setup_listen_socket((sockaddr_t *) aip->ai_addr);
874 if(listen_socket[listen_sockets].tcp < 0)
877 listen_socket[listen_sockets].udp =
878 setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
880 if(listen_socket[listen_sockets].udp < 0)
883 ifdebug(CONNECTIONS) {
884 hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
885 logger(LOG_NOTICE, "Listening on %s", hostname);
889 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
897 if(!listen_sockets) {
898 logger(LOG_ERR, "Unable to create any listening socket!");
902 /* If no Port option was specified, set myport to the port used by the first listening socket. */
904 if(!port_specified) {
906 socklen_t salen = sizeof sa;
907 if(!getsockname(listen_socket[0].udp, &sa.sa, &salen)) {
909 sockaddr2str(&sa, NULL, &myport);
911 myport = xstrdup("655");
917 logger(LOG_NOTICE, "Ready");
924 bool setup_network(void) {
934 if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
935 if(pinginterval < 1) {
936 pinginterval = 86400;
941 if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
943 if(pingtimeout < 1 || pingtimeout > pinginterval)
944 pingtimeout = pinginterval;
946 if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize))
947 maxoutbufsize = 10 * MTU;
956 close all open network connections
958 void close_network_connections(void) {
959 avl_node_t *node, *next;
961 char *envp[5] = {NULL};
964 for(node = connection_tree->head; node; node = next) {
968 terminate_connection(c, false);
971 for(list_node_t *node = outgoing_list->head; node; node = node->next) {
972 outgoing_t *outgoing = node->data;
975 event_del(outgoing->event);
978 list_delete_list(outgoing_list);
980 if(myself && myself->connection) {
981 subnet_update(myself, NULL, false);
982 terminate_connection(myself->connection, false);
983 free_connection(myself->connection);
986 for(i = 0; i < listen_sockets; i++) {
987 close(listen_socket[i].tcp);
988 close(listen_socket[i].udp);
991 xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
992 xasprintf(&envp[1], "DEVICE=%s", device ? : "");
993 xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
994 xasprintf(&envp[3], "NAME=%s", myself->name);
1003 execute_script("tinc-down", envp);
1005 if(myport) free(myport);
1007 for(i = 0; i < 4; i++)