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_bf_cbc();
656 myself->inkeylength = EVP_CIPHER_key_length(myself->incipher) + EVP_CIPHER_iv_length(myself->incipher);
658 myself->inkeylength = 1;
660 myself->connection->outcipher = EVP_bf_ofb();
662 if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
665 keyexpires = now + keylifetime;
667 /* Check if we want to use message authentication codes... */
669 if(get_config_string(lookup_config(config_tree, "Digest"), &digest)) {
670 if(!strcasecmp(digest, "none")) {
671 myself->indigest = NULL;
673 myself->indigest = EVP_get_digestbyname(digest);
675 if(!myself->indigest) {
676 logger(LOG_ERR, "Unrecognized digest type!");
684 myself->indigest = EVP_sha1();
686 myself->connection->outdigest = EVP_sha1();
688 if(get_config_int(lookup_config(config_tree, "MACLength"), &myself->inmaclength)) {
689 if(myself->indigest) {
690 if(myself->inmaclength > EVP_MD_size(myself->indigest)) {
691 logger(LOG_ERR, "MAC length exceeds size of digest!");
693 } else if(myself->inmaclength < 0) {
694 logger(LOG_ERR, "Bogus MAC length!");
699 myself->inmaclength = 4;
701 myself->connection->outmaclength = 0;
705 if(get_config_int(lookup_config(config_tree, "Compression"), &myself->incompression)) {
706 if(myself->incompression < 0 || myself->incompression > 11) {
707 logger(LOG_ERR, "Bogus compression level!");
711 myself->incompression = 0;
713 myself->connection->outcompression = 0;
717 myself->nexthop = myself;
718 myself->via = myself;
719 myself->status.reachable = true;
731 if(get_config_string(lookup_config(config_tree, "DeviceType"), &type)) {
732 if(!strcasecmp(type, "dummy"))
733 devops = dummy_devops;
734 else if(!strcasecmp(type, "raw_socket"))
735 devops = raw_socket_devops;
736 else if(!strcasecmp(type, "multicast"))
737 devops = multicast_devops;
739 else if(!strcasecmp(type, "uml"))
743 else if(!strcasecmp(type, "vde"))
752 /* Run tinc-up script to further initialize the tap interface */
753 xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
754 xasprintf(&envp[1], "DEVICE=%s", device ? : "");
755 xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
756 xasprintf(&envp[3], "NAME=%s", myself->name);
764 execute_script("tinc-up", envp);
766 for(i = 0; i < 4; i++)
769 /* Run subnet-up scripts for our own subnets */
771 subnet_update(myself, NULL, true);
775 if(!do_detach && getenv("LISTEN_FDS")) {
779 listen_sockets = atoi(getenv("LISTEN_FDS"));
781 unsetenv("LISTEN_FDS");
784 if(listen_sockets > MAXSOCKETS) {
785 logger(LOG_ERR, "Too many listening sockets");
789 for(i = 0; i < listen_sockets; i++) {
791 if(getsockname(i + 3, &sa.sa, &salen) < 0) {
792 logger(LOG_ERR, "Could not get address of listen fd %d: %s", i + 3, sockstrerror(errno));
796 listen_socket[i].tcp = i + 3;
799 fcntl(i + 3, F_SETFD, FD_CLOEXEC);
802 listen_socket[i].udp = setup_vpn_in_socket(&sa);
803 if(listen_socket[i].udp < 0)
806 ifdebug(CONNECTIONS) {
807 hostname = sockaddr2hostname(&sa);
808 logger(LOG_NOTICE, "Listening on %s", hostname);
812 memcpy(&listen_socket[i].sa, &sa, salen);
816 cfg = lookup_config(config_tree, "BindToAddress");
819 get_config_string(cfg, &address);
821 cfg = lookup_config_next(config_tree, cfg);
826 char *space = strchr(address, ' ');
832 if(!strcmp(address, "*"))
836 hint.ai_family = addressfamily;
837 hint.ai_socktype = SOCK_STREAM;
838 hint.ai_protocol = IPPROTO_TCP;
839 hint.ai_flags = AI_PASSIVE;
841 #if HAVE_DECL_RES_INIT
842 // ensure glibc reloads /etc/resolv.conf.
845 err = getaddrinfo(address && *address ? address : NULL, port, &hint, &ai);
849 logger(LOG_ERR, "System call `%s' failed: %s", "getaddrinfo",
854 for(aip = ai; aip; aip = aip->ai_next) {
855 if(listen_sockets >= MAXSOCKETS) {
856 logger(LOG_ERR, "Too many listening sockets");
860 listen_socket[listen_sockets].tcp =
861 setup_listen_socket((sockaddr_t *) aip->ai_addr);
863 if(listen_socket[listen_sockets].tcp < 0)
866 listen_socket[listen_sockets].udp =
867 setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
869 if(listen_socket[listen_sockets].udp < 0)
872 ifdebug(CONNECTIONS) {
873 hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
874 logger(LOG_NOTICE, "Listening on %s", hostname);
878 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
886 if(!listen_sockets) {
887 logger(LOG_ERR, "Unable to create any listening socket!");
891 /* If no Port option was specified, set myport to the port used by the first listening socket. */
893 if(!port_specified) {
895 socklen_t salen = sizeof sa;
896 if(!getsockname(listen_socket[0].udp, &sa.sa, &salen)) {
898 sockaddr2str(&sa, NULL, &myport);
900 myport = xstrdup("655");
906 logger(LOG_NOTICE, "Ready");
913 bool setup_network(void) {
923 if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
924 if(pinginterval < 1) {
925 pinginterval = 86400;
930 if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
932 if(pingtimeout < 1 || pingtimeout > pinginterval)
933 pingtimeout = pinginterval;
935 if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize))
936 maxoutbufsize = 10 * MTU;
945 close all open network connections
947 void close_network_connections(void) {
948 avl_node_t *node, *next;
950 char *envp[5] = {NULL};
953 for(node = connection_tree->head; node; node = next) {
957 terminate_connection(c, false);
960 for(list_node_t *node = outgoing_list->head; node; node = node->next) {
961 outgoing_t *outgoing = node->data;
964 event_del(outgoing->event);
967 list_delete_list(outgoing_list);
969 if(myself && myself->connection) {
970 subnet_update(myself, NULL, false);
971 terminate_connection(myself->connection, false);
972 free_connection(myself->connection);
975 for(i = 0; i < listen_sockets; i++) {
976 close(listen_socket[i].tcp);
977 close(listen_socket[i].udp);
980 xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
981 xasprintf(&envp[1], "DEVICE=%s", device ? : "");
982 xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
983 xasprintf(&envp[3], "NAME=%s", myself->name);
992 execute_script("tinc-down", envp);
994 if(myport) free(myport);
996 for(i = 0; i < 4; i++)