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) {
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 a stream mode for the meta protocol. Use AES for this,
661 but try to match the key size with the one from the cipher selected
664 If Cipher is set to none, still use a low level of encryption for the
668 int keylen = myself->incipher ? EVP_CIPHER_key_length(myself->incipher) : 0;
670 myself->connection->outcipher = EVP_aes_128_cfb();
671 else if(keylen <= 24)
672 myself->connection->outcipher = EVP_aes_192_cfb();
674 myself->connection->outcipher = EVP_aes_256_cfb();
676 if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
679 keyexpires = now + keylifetime;
681 /* Check if we want to use message authentication codes... */
683 if(get_config_string(lookup_config(config_tree, "Digest"), &digest)) {
684 if(!strcasecmp(digest, "none")) {
685 myself->indigest = NULL;
687 myself->indigest = EVP_get_digestbyname(digest);
689 if(!myself->indigest) {
690 logger(LOG_ERR, "Unrecognized digest type!");
698 myself->indigest = EVP_sha256();
700 myself->connection->outdigest = EVP_sha256();
702 if(get_config_int(lookup_config(config_tree, "MACLength"), &myself->inmaclength)) {
703 if(myself->indigest) {
704 if(myself->inmaclength > EVP_MD_size(myself->indigest)) {
705 logger(LOG_ERR, "MAC length exceeds size of digest!");
707 } else if(myself->inmaclength < 0) {
708 logger(LOG_ERR, "Bogus MAC length!");
713 myself->inmaclength = 4;
715 myself->connection->outmaclength = 0;
719 if(get_config_int(lookup_config(config_tree, "Compression"), &myself->incompression)) {
720 if(myself->incompression < 0 || myself->incompression > 11) {
721 logger(LOG_ERR, "Bogus compression level!");
725 myself->incompression = 0;
727 myself->connection->outcompression = 0;
731 myself->nexthop = myself;
732 myself->via = myself;
733 myself->status.reachable = true;
745 if(get_config_string(lookup_config(config_tree, "DeviceType"), &type)) {
746 if(!strcasecmp(type, "dummy"))
747 devops = dummy_devops;
748 else if(!strcasecmp(type, "raw_socket"))
749 devops = raw_socket_devops;
750 else if(!strcasecmp(type, "multicast"))
751 devops = multicast_devops;
753 else if(!strcasecmp(type, "uml"))
757 else if(!strcasecmp(type, "vde"))
766 /* Run tinc-up script to further initialize the tap interface */
767 xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
768 xasprintf(&envp[1], "DEVICE=%s", device ? : "");
769 xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
770 xasprintf(&envp[3], "NAME=%s", myself->name);
778 execute_script("tinc-up", envp);
780 for(i = 0; i < 4; i++)
783 /* Run subnet-up scripts for our own subnets */
785 subnet_update(myself, NULL, true);
789 if(!do_detach && getenv("LISTEN_FDS")) {
793 listen_sockets = atoi(getenv("LISTEN_FDS"));
795 unsetenv("LISTEN_FDS");
798 if(listen_sockets > MAXSOCKETS) {
799 logger(LOG_ERR, "Too many listening sockets");
803 for(i = 0; i < listen_sockets; i++) {
805 if(getsockname(i + 3, &sa.sa, &salen) < 0) {
806 logger(LOG_ERR, "Could not get address of listen fd %d: %s", i + 3, sockstrerror(errno));
810 listen_socket[i].tcp = i + 3;
813 fcntl(i + 3, F_SETFD, FD_CLOEXEC);
816 listen_socket[i].udp = setup_vpn_in_socket(&sa);
817 if(listen_socket[i].udp < 0)
820 ifdebug(CONNECTIONS) {
821 hostname = sockaddr2hostname(&sa);
822 logger(LOG_NOTICE, "Listening on %s", hostname);
826 memcpy(&listen_socket[i].sa, &sa, salen);
830 cfg = lookup_config(config_tree, "BindToAddress");
833 get_config_string(cfg, &address);
835 cfg = lookup_config_next(config_tree, cfg);
840 char *space = strchr(address, ' ');
846 if(!strcmp(address, "*"))
850 hint.ai_family = addressfamily;
851 hint.ai_socktype = SOCK_STREAM;
852 hint.ai_protocol = IPPROTO_TCP;
853 hint.ai_flags = AI_PASSIVE;
855 #if HAVE_DECL_RES_INIT
856 // ensure glibc reloads /etc/resolv.conf.
859 err = getaddrinfo(address && *address ? address : NULL, port, &hint, &ai);
863 logger(LOG_ERR, "System call `%s' failed: %s", "getaddrinfo",
868 for(aip = ai; aip; aip = aip->ai_next) {
869 if(listen_sockets >= MAXSOCKETS) {
870 logger(LOG_ERR, "Too many listening sockets");
874 listen_socket[listen_sockets].tcp =
875 setup_listen_socket((sockaddr_t *) aip->ai_addr);
877 if(listen_socket[listen_sockets].tcp < 0)
880 listen_socket[listen_sockets].udp =
881 setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
883 if(listen_socket[listen_sockets].udp < 0)
886 ifdebug(CONNECTIONS) {
887 hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
888 logger(LOG_NOTICE, "Listening on %s", hostname);
892 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
900 if(!listen_sockets) {
901 logger(LOG_ERR, "Unable to create any listening socket!");
905 /* If no Port option was specified, set myport to the port used by the first listening socket. */
907 if(!port_specified) {
909 socklen_t salen = sizeof sa;
910 if(!getsockname(listen_socket[0].udp, &sa.sa, &salen)) {
912 sockaddr2str(&sa, NULL, &myport);
914 myport = xstrdup("655");
920 logger(LOG_NOTICE, "Ready");
927 bool setup_network(void) {
937 if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
938 if(pinginterval < 1) {
939 pinginterval = 86400;
944 if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
946 if(pingtimeout < 1 || pingtimeout > pinginterval)
947 pingtimeout = pinginterval;
949 if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize))
950 maxoutbufsize = 10 * MTU;
959 close all open network connections
961 void close_network_connections(void) {
962 avl_node_t *node, *next;
964 char *envp[5] = {NULL};
967 for(node = connection_tree->head; node; node = next) {
971 terminate_connection(c, false);
974 for(list_node_t *node = outgoing_list->head; node; node = node->next) {
975 outgoing_t *outgoing = node->data;
978 event_del(outgoing->event);
981 list_delete_list(outgoing_list);
983 if(myself && myself->connection) {
984 subnet_update(myself, NULL, false);
985 terminate_connection(myself->connection, false);
986 free_connection(myself->connection);
989 for(i = 0; i < listen_sockets; i++) {
990 close(listen_socket[i].tcp);
991 close(listen_socket[i].udp);
994 xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
995 xasprintf(&envp[1], "DEVICE=%s", device ? : "");
996 xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
997 xasprintf(&envp[3], "NAME=%s", myself->name);
1006 execute_script("tinc-down", envp);
1008 if(myport) free(myport);
1010 for(i = 0; i < 4; i++)