3 Copyright (C) 1998-2005 Ivo Timmermans,
4 2000-2014 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"
54 proxytype_t proxytype;
56 bool read_rsa_public_key(connection_t *c) {
63 c->rsa_key = RSA_new();
64 // RSA_blinding_on(c->rsa_key, NULL);
67 /* First, check for simple PublicKey statement */
69 if(get_config_string(lookup_config(c->config_tree, "PublicKey"), &key)) {
70 if(BN_hex2bn(&c->rsa_key->n, key) != strlen(key)) {
71 logger(LOG_ERR, "Invalid PublicKey for %s!", c->name);
74 BN_hex2bn(&c->rsa_key->e, "FFFF");
79 /* Else, check for PublicKeyFile statement and read it */
81 if(get_config_string(lookup_config(c->config_tree, "PublicKeyFile"), &pubname)) {
82 fp = fopen(pubname, "r");
85 logger(LOG_ERR, "Error reading RSA public key file `%s': %s", pubname, strerror(errno));
90 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
95 return true; /* Woohoo. */
98 /* If it fails, try PEM_read_RSA_PUBKEY. */
99 fp = fopen(pubname, "r");
102 logger(LOG_ERR, "Error reading RSA public key file `%s': %s", pubname, strerror(errno));
107 c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
111 // RSA_blinding_on(c->rsa_key, NULL);
116 logger(LOG_ERR, "Reading RSA public key file `%s' failed: %s", pubname, strerror(errno));
121 /* Else, check if a harnessed public key is in the config file */
123 xasprintf(&hcfname, "%s/hosts/%s", confbase, c->name);
124 fp = fopen(hcfname, "r");
127 logger(LOG_ERR, "Error reading RSA public key file `%s': %s", hcfname, strerror(errno));
132 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
140 /* Try again with PEM_read_RSA_PUBKEY. */
142 fp = fopen(hcfname, "r");
145 logger(LOG_ERR, "Error reading RSA public key file `%s': %s", hcfname, strerror(errno));
151 c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
152 // RSA_blinding_on(c->rsa_key, NULL);
158 logger(LOG_ERR, "No public key for %s specified!", c->name);
163 static bool read_rsa_private_key(void) {
165 char *fname, *key, *pubkey;
167 if(get_config_string(lookup_config(config_tree, "PrivateKey"), &key)) {
168 myself->connection->rsa_key = RSA_new();
169 // RSA_blinding_on(myself->connection->rsa_key, NULL);
170 if(BN_hex2bn(&myself->connection->rsa_key->d, key) != strlen(key)) {
171 logger(LOG_ERR, "Invalid PrivateKey for myself!");
176 if(!get_config_string(lookup_config(config_tree, "PublicKey"), &pubkey)) {
177 logger(LOG_ERR, "PrivateKey used but no PublicKey found!");
180 if(BN_hex2bn(&myself->connection->rsa_key->n, pubkey) != strlen(pubkey)) {
181 logger(LOG_ERR, "Invalid PublicKey for myself!");
186 BN_hex2bn(&myself->connection->rsa_key->e, "FFFF");
190 if(!get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname))
191 xasprintf(&fname, "%s/rsa_key.priv", confbase);
193 fp = fopen(fname, "r");
196 logger(LOG_ERR, "Error reading RSA private key file `%s': %s",
197 fname, strerror(errno));
202 #if !defined(HAVE_MINGW) && !defined(HAVE_CYGWIN)
205 if(!fstat(fileno(fp), &s)) {
206 if(s.st_mode & ~0100700)
207 logger(LOG_WARNING, "Warning: insecure file permissions for RSA private key file `%s'!", fname);
209 logger(LOG_WARNING, "Could not stat RSA private key file `%s': %s'", fname, strerror(errno));
213 myself->connection->rsa_key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
216 if(!myself->connection->rsa_key) {
217 logger(LOG_ERR, "Reading RSA private key file `%s' failed: %s",
218 fname, strerror(errno));
228 Read Subnets from all host config files
230 void load_all_subnets(void) {
235 avl_tree_t *config_tree;
240 xasprintf(&dname, "%s/hosts", confbase);
241 dir = opendir(dname);
243 logger(LOG_ERR, "Could not open %s: %s", dname, strerror(errno));
248 while((ent = readdir(dir))) {
249 if(!check_id(ent->d_name))
252 n = lookup_node(ent->d_name);
253 #ifdef _DIRENT_HAVE_D_TYPE
254 //if(ent->d_type != DT_REG)
258 xasprintf(&fname, "%s/hosts/%s", confbase, ent->d_name);
259 init_configuration(&config_tree);
260 read_config_options(config_tree, ent->d_name);
261 read_config_file(config_tree, fname);
266 n->name = xstrdup(ent->d_name);
270 for(cfg = lookup_config(config_tree, "Subnet"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
271 if(!get_config_subnet(cfg, &s))
274 if((s2 = lookup_subnet(n, s))) {
281 exit_configuration(&config_tree);
287 char *get_name(void) {
290 get_config_string(lookup_config(config_tree, "Name"), &name);
296 char *envname = getenv(name + 1);
297 char hostname[32] = "";
299 if(strcmp(name + 1, "HOST")) {
300 fprintf(stderr, "Invalid Name: environment variable %s does not exist\n", name + 1);
304 if(gethostname(hostname, sizeof hostname) || !*hostname) {
305 fprintf(stderr, "Could not get hostname: %s\n", strerror(errno));
313 name = xstrdup(envname);
314 for(char *c = name; *c; c++)
319 if(!check_id(name)) {
320 logger(LOG_ERR, "Invalid name for myself!");
329 Configure node_t myself and set up the local sockets (listen only)
331 static bool setup_myself(void) {
334 char *name, *hostname, *mode, *afname, *cipher, *digest, *type;
336 char *address = NULL;
339 char *envp[5] = {NULL};
340 struct addrinfo *ai, *aip, hint = {0};
344 bool port_specified = false;
347 myself->connection = new_connection();
349 myself->hostname = xstrdup("MYSELF");
350 myself->connection->hostname = xstrdup("MYSELF");
352 myself->connection->options = 0;
353 myself->connection->protocol_version = PROT_CURRENT;
355 if(!(name = get_name())) {
356 logger(LOG_ERR, "Name for tinc daemon required!");
360 /* Read tinc.conf and our own host config file */
363 myself->connection->name = xstrdup(name);
364 xasprintf(&fname, "%s/hosts/%s", confbase, name);
365 read_config_options(config_tree, name);
366 read_config_file(config_tree, fname);
369 if(!read_rsa_private_key())
372 if(!get_config_string(lookup_config(config_tree, "Port"), &myport))
373 myport = xstrdup("655");
375 port_specified = true;
377 /* Ensure myport is numeric */
380 struct addrinfo *ai = str2addrinfo("localhost", myport, SOCK_DGRAM);
382 if(!ai || !ai->ai_addr)
385 memcpy(&sa, ai->ai_addr, ai->ai_addrlen);
386 sockaddr2str(&sa, NULL, &myport);
389 if(get_config_string(lookup_config(config_tree, "Proxy"), &proxy)) {
390 if((space = strchr(proxy, ' ')))
393 if(!strcasecmp(proxy, "none")) {
394 proxytype = PROXY_NONE;
395 } else if(!strcasecmp(proxy, "socks4")) {
396 proxytype = PROXY_SOCKS4;
397 } else if(!strcasecmp(proxy, "socks4a")) {
398 proxytype = PROXY_SOCKS4A;
399 } else if(!strcasecmp(proxy, "socks5")) {
400 proxytype = PROXY_SOCKS5;
401 } else if(!strcasecmp(proxy, "http")) {
402 proxytype = PROXY_HTTP;
403 } else if(!strcasecmp(proxy, "exec")) {
404 proxytype = PROXY_EXEC;
406 logger(LOG_ERR, "Unknown proxy type %s!", proxy);
417 if(!space || !*space) {
418 logger(LOG_ERR, "Argument expected for proxy type exec!");
422 proxyhost = xstrdup(space);
430 if(space && (space = strchr(space, ' ')))
431 *space++ = 0, proxyport = space;
432 if(space && (space = strchr(space, ' ')))
433 *space++ = 0, proxyuser = space;
434 if(space && (space = strchr(space, ' ')))
435 *space++ = 0, proxypass = space;
436 if(!proxyhost || !*proxyhost || !proxyport || !*proxyport) {
437 logger(LOG_ERR, "Host and port argument expected for proxy!");
441 proxyhost = xstrdup(proxyhost);
442 proxyport = xstrdup(proxyport);
443 if(proxyuser && *proxyuser)
444 proxyuser = xstrdup(proxyuser);
445 if(proxypass && *proxypass)
446 proxypass = xstrdup(proxypass);
453 /* Read in all the subnets specified in the host configuration file */
455 cfg = lookup_config(config_tree, "Subnet");
458 if(!get_config_subnet(cfg, &subnet))
461 subnet_add(myself, subnet);
463 cfg = lookup_config_next(config_tree, cfg);
466 /* Check some options */
468 if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice) && choice)
469 myself->options |= OPTION_INDIRECT;
471 if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice) && choice)
472 myself->options |= OPTION_TCPONLY;
474 if(myself->options & OPTION_TCPONLY)
475 myself->options |= OPTION_INDIRECT;
477 get_config_bool(lookup_config(config_tree, "DirectOnly"), &directonly);
478 get_config_bool(lookup_config(config_tree, "StrictSubnets"), &strictsubnets);
479 get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
480 get_config_bool(lookup_config(config_tree, "LocalDiscovery"), &localdiscovery);
481 strictsubnets |= tunnelserver;
483 if(get_config_string(lookup_config(config_tree, "Mode"), &mode)) {
484 if(!strcasecmp(mode, "router"))
485 routing_mode = RMODE_ROUTER;
486 else if(!strcasecmp(mode, "switch"))
487 routing_mode = RMODE_SWITCH;
488 else if(!strcasecmp(mode, "hub"))
489 routing_mode = RMODE_HUB;
491 logger(LOG_ERR, "Invalid routing mode!");
498 if(get_config_string(lookup_config(config_tree, "Forwarding"), &mode)) {
499 if(!strcasecmp(mode, "off"))
500 forwarding_mode = FMODE_OFF;
501 else if(!strcasecmp(mode, "internal"))
502 forwarding_mode = FMODE_INTERNAL;
503 else if(!strcasecmp(mode, "kernel"))
504 forwarding_mode = FMODE_KERNEL;
506 logger(LOG_ERR, "Invalid forwarding mode!");
514 get_config_bool(lookup_config(config_tree, "PMTUDiscovery"), &choice);
516 myself->options |= OPTION_PMTU_DISCOVERY;
519 get_config_bool(lookup_config(config_tree, "ClampMSS"), &choice);
521 myself->options |= OPTION_CLAMP_MSS;
523 get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
524 get_config_bool(lookup_config(config_tree, "DecrementTTL"), &decrement_ttl);
525 if(get_config_string(lookup_config(config_tree, "Broadcast"), &mode)) {
526 if(!strcasecmp(mode, "no"))
527 broadcast_mode = BMODE_NONE;
528 else if(!strcasecmp(mode, "yes") || !strcasecmp(mode, "mst"))
529 broadcast_mode = BMODE_MST;
530 else if(!strcasecmp(mode, "direct"))
531 broadcast_mode = BMODE_DIRECT;
533 logger(LOG_ERR, "Invalid broadcast mode!");
540 #if !defined(SOL_IP) || !defined(IP_TOS)
541 if(priorityinheritance)
542 logger(LOG_WARNING, "%s not supported on this platform for IPv4 connection", "PriorityInheritance");
545 #if !defined(IPPROTO_IPV6) || !defined(IPV6_TCLASS)
546 if(priorityinheritance)
547 logger(LOG_WARNING, "%s not supported on this platform for IPv6 connection", "PriorityInheritance");
550 if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire))
553 if(get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout)) {
554 if(maxtimeout <= 0) {
555 logger(LOG_ERR, "Bogus maximum timeout!");
561 if(get_config_int(lookup_config(config_tree, "MinTimeout"), &mintimeout)) {
563 logger(LOG_ERR, "Bogus minimum timeout!");
566 if(mintimeout > maxtimeout) {
567 logger(LOG_WARNING, "Minimum timeout (%d s) cannot be larger than maximum timeout (%d s). Correcting !", mintimeout, maxtimeout );
568 mintimeout=maxtimeout;
573 if(get_config_int(lookup_config(config_tree, "UDPRcvBuf"), &udp_rcvbuf)) {
574 if(udp_rcvbuf <= 0) {
575 logger(LOG_ERR, "UDPRcvBuf cannot be negative!");
580 if(get_config_int(lookup_config(config_tree, "UDPSndBuf"), &udp_sndbuf)) {
581 if(udp_sndbuf <= 0) {
582 logger(LOG_ERR, "UDPSndBuf cannot be negative!");
587 if(get_config_int(lookup_config(config_tree, "ReplayWindow"), &replaywin_int)) {
588 if(replaywin_int < 0) {
589 logger(LOG_ERR, "ReplayWindow cannot be negative!");
592 replaywin = (unsigned)replaywin_int;
595 if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
596 if(!strcasecmp(afname, "IPv4"))
597 addressfamily = AF_INET;
598 else if(!strcasecmp(afname, "IPv6"))
599 addressfamily = AF_INET6;
600 else if(!strcasecmp(afname, "any"))
601 addressfamily = AF_UNSPEC;
603 logger(LOG_ERR, "Invalid address family!");
610 get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
612 /* Generate packet encryption key */
614 if(get_config_string(lookup_config(config_tree, "Cipher"), &cipher)) {
615 if(!strcasecmp(cipher, "none")) {
616 myself->incipher = NULL;
618 myself->incipher = EVP_get_cipherbyname(cipher);
620 if(!myself->incipher) {
621 logger(LOG_ERR, "Unrecognized cipher type!");
628 myself->incipher = EVP_bf_cbc();
631 myself->inkeylength = myself->incipher->key_len + myself->incipher->iv_len;
633 myself->inkeylength = 1;
635 myself->connection->outcipher = EVP_bf_ofb();
637 if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
640 keyexpires = now + keylifetime;
642 /* Check if we want to use message authentication codes... */
644 if(get_config_string(lookup_config(config_tree, "Digest"), &digest)) {
645 if(!strcasecmp(digest, "none")) {
646 myself->indigest = NULL;
648 myself->indigest = EVP_get_digestbyname(digest);
650 if(!myself->indigest) {
651 logger(LOG_ERR, "Unrecognized digest type!");
659 myself->indigest = EVP_sha1();
661 myself->connection->outdigest = EVP_sha1();
663 if(get_config_int(lookup_config(config_tree, "MACLength"), &myself->inmaclength)) {
664 if(myself->indigest) {
665 if(myself->inmaclength > myself->indigest->md_size) {
666 logger(LOG_ERR, "MAC length exceeds size of digest!");
668 } else if(myself->inmaclength < 0) {
669 logger(LOG_ERR, "Bogus MAC length!");
674 myself->inmaclength = 4;
676 myself->connection->outmaclength = 0;
680 if(get_config_int(lookup_config(config_tree, "Compression"), &myself->incompression)) {
681 if(myself->incompression < 0 || myself->incompression > 11) {
682 logger(LOG_ERR, "Bogus compression level!");
686 myself->incompression = 0;
688 myself->connection->outcompression = 0;
692 myself->nexthop = myself;
693 myself->via = myself;
694 myself->status.reachable = true;
706 if(get_config_string(lookup_config(config_tree, "DeviceType"), &type)) {
707 if(!strcasecmp(type, "dummy"))
708 devops = dummy_devops;
709 else if(!strcasecmp(type, "raw_socket"))
710 devops = raw_socket_devops;
711 else if(!strcasecmp(type, "multicast"))
712 devops = multicast_devops;
714 else if(!strcasecmp(type, "uml"))
718 else if(!strcasecmp(type, "vde"))
727 /* Run tinc-up script to further initialize the tap interface */
728 xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
729 xasprintf(&envp[1], "DEVICE=%s", device ? : "");
730 xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
731 xasprintf(&envp[3], "NAME=%s", myself->name);
739 execute_script("tinc-up", envp);
741 for(i = 0; i < 4; i++)
744 /* Run subnet-up scripts for our own subnets */
746 subnet_update(myself, NULL, true);
750 if(!do_detach && getenv("LISTEN_FDS")) {
754 listen_sockets = atoi(getenv("LISTEN_FDS"));
756 unsetenv("LISTEN_FDS");
759 if(listen_sockets > MAXSOCKETS) {
760 logger(LOG_ERR, "Too many listening sockets");
764 for(i = 0; i < listen_sockets; i++) {
766 if(getsockname(i + 3, &sa.sa, &salen) < 0) {
767 logger(LOG_ERR, "Could not get address of listen fd %d: %s", i + 3, sockstrerror(errno));
771 listen_socket[i].tcp = i + 3;
774 fcntl(i + 3, F_SETFD, FD_CLOEXEC);
777 listen_socket[i].udp = setup_vpn_in_socket(&sa);
778 if(listen_socket[i].udp < 0)
781 ifdebug(CONNECTIONS) {
782 hostname = sockaddr2hostname(&sa);
783 logger(LOG_NOTICE, "Listening on %s", hostname);
787 memcpy(&listen_socket[i].sa, &sa, salen);
791 cfg = lookup_config(config_tree, "BindToAddress");
794 get_config_string(cfg, &address);
796 cfg = lookup_config_next(config_tree, cfg);
801 char *space = strchr(address, ' ');
807 if(!strcmp(address, "*"))
811 hint.ai_family = addressfamily;
812 hint.ai_socktype = SOCK_STREAM;
813 hint.ai_protocol = IPPROTO_TCP;
814 hint.ai_flags = AI_PASSIVE;
816 err = getaddrinfo(address && *address ? address : NULL, port, &hint, &ai);
820 logger(LOG_ERR, "System call `%s' failed: %s", "getaddrinfo",
825 for(aip = ai; aip; aip = aip->ai_next) {
826 if(listen_sockets >= MAXSOCKETS) {
827 logger(LOG_ERR, "Too many listening sockets");
831 listen_socket[listen_sockets].tcp =
832 setup_listen_socket((sockaddr_t *) aip->ai_addr);
834 if(listen_socket[listen_sockets].tcp < 0)
837 listen_socket[listen_sockets].udp =
838 setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
840 if(listen_socket[listen_sockets].udp < 0)
843 ifdebug(CONNECTIONS) {
844 hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
845 logger(LOG_NOTICE, "Listening on %s", hostname);
849 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
857 if(!listen_sockets) {
858 logger(LOG_ERR, "Unable to create any listening socket!");
862 /* If no Port option was specified, set myport to the port used by the first listening socket. */
864 if(!port_specified) {
866 socklen_t salen = sizeof sa;
867 if(!getsockname(listen_socket[0].udp, &sa.sa, &salen)) {
869 sockaddr2str(&sa, NULL, &myport);
871 myport = xstrdup("655");
877 logger(LOG_NOTICE, "Ready");
884 bool setup_network(void) {
894 if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
895 if(pinginterval < 1) {
896 pinginterval = 86400;
901 if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
903 if(pingtimeout < 1 || pingtimeout > pinginterval)
904 pingtimeout = pinginterval;
906 if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize))
907 maxoutbufsize = 10 * MTU;
916 close all open network connections
918 void close_network_connections(void) {
919 avl_node_t *node, *next;
921 char *envp[5] = {NULL};
924 for(node = connection_tree->head; node; node = next) {
928 terminate_connection(c, false);
931 for(list_node_t *node = outgoing_list->head; node; node = node->next) {
932 outgoing_t *outgoing = node->data;
935 event_del(outgoing->event);
938 list_delete_list(outgoing_list);
940 if(myself && myself->connection) {
941 subnet_update(myself, NULL, false);
942 terminate_connection(myself->connection, false);
943 free_connection(myself->connection);
946 for(i = 0; i < listen_sockets; i++) {
947 close(listen_socket[i].tcp);
948 close(listen_socket[i].udp);
951 xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
952 xasprintf(&envp[1], "DEVICE=%s", device ? : "");
953 xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
954 xasprintf(&envp[3], "NAME=%s", myself->name);
963 execute_script("tinc-down", envp);
965 if(myport) free(myport);
967 for(i = 0; i < 4; i++)