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.
27 #include "connection.h"
46 proxytype_t proxytype;
48 bool disablebuggypeers;
50 bool node_read_ecdsa_public_key(node_t *n) {
51 if(ecdsa_active(n->ecdsa))
54 splay_tree_t *config_tree;
59 init_configuration(&config_tree);
60 if(!read_host_config(config_tree, n->name))
63 /* First, check for simple ECDSAPublicKey statement */
65 if(get_config_string(lookup_config(config_tree, "ECDSAPublicKey"), &p)) {
66 n->ecdsa = ecdsa_set_base64_public_key(p);
71 /* Else, check for ECDSAPublicKeyFile statement and read it */
73 if(!get_config_string(lookup_config(config_tree, "ECDSAPublicKeyFile"), &pubname))
74 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, n->name);
76 fp = fopen(pubname, "r");
81 n->ecdsa = ecdsa_read_pem_public_key(fp);
85 exit_configuration(&config_tree);
90 bool read_ecdsa_public_key(connection_t *c) {
91 if(ecdsa_active(c->ecdsa))
99 init_configuration(&c->config_tree);
100 if(!read_host_config(c->config_tree, c->name))
104 /* First, check for simple ECDSAPublicKey statement */
106 if(get_config_string(lookup_config(c->config_tree, "ECDSAPublicKey"), &p)) {
107 c->ecdsa = ecdsa_set_base64_public_key(p);
112 /* Else, check for ECDSAPublicKeyFile statement and read it */
114 if(!get_config_string(lookup_config(c->config_tree, "ECDSAPublicKeyFile"), &fname))
115 xasprintf(&fname, "%s" SLASH "hosts" SLASH "%s", confbase, c->name);
117 fp = fopen(fname, "r");
120 logger(DEBUG_ALWAYS, LOG_ERR, "Error reading ECDSA public key file `%s': %s",
121 fname, strerror(errno));
126 c->ecdsa = ecdsa_read_pem_public_key(fp);
130 logger(DEBUG_ALWAYS, LOG_ERR, "Parsing ECDSA public key file `%s' failed.", fname);
135 bool read_rsa_public_key(connection_t *c) {
136 if(ecdsa_active(c->ecdsa))
143 /* First, check for simple PublicKey statement */
145 if(get_config_string(lookup_config(c->config_tree, "PublicKey"), &n)) {
146 c->rsa = rsa_set_hex_public_key(n, "FFFF");
151 /* Else, check for PublicKeyFile statement and read it */
153 if(!get_config_string(lookup_config(c->config_tree, "PublicKeyFile"), &fname))
154 xasprintf(&fname, "%s" SLASH "hosts" SLASH "%s", confbase, c->name);
156 fp = fopen(fname, "r");
159 logger(DEBUG_ALWAYS, LOG_ERR, "Error reading RSA public key file `%s': %s", fname, strerror(errno));
164 c->rsa = rsa_read_pem_public_key(fp);
168 logger(DEBUG_ALWAYS, LOG_ERR, "Reading RSA public key file `%s' failed: %s", fname, strerror(errno));
173 static bool read_ecdsa_private_key(void) {
177 /* Check for PrivateKeyFile statement and read it */
179 if(!get_config_string(lookup_config(config_tree, "ECDSAPrivateKeyFile"), &fname))
180 xasprintf(&fname, "%s" SLASH "ecdsa_key.priv", confbase);
182 fp = fopen(fname, "r");
185 logger(DEBUG_ALWAYS, LOG_ERR, "Error reading ECDSA private key file `%s': %s", fname, strerror(errno));
187 logger(DEBUG_ALWAYS, LOG_INFO, "Create an ECDSA keypair with `tinc generate-ecdsa-keys'.");
192 #if !defined(HAVE_MINGW) && !defined(HAVE_CYGWIN)
195 if(fstat(fileno(fp), &s)) {
196 logger(DEBUG_ALWAYS, LOG_ERR, "Could not stat ECDSA private key file `%s': %s'", fname, strerror(errno));
201 if(s.st_mode & ~0100700)
202 logger(DEBUG_ALWAYS, LOG_WARNING, "Warning: insecure file permissions for ECDSA private key file `%s'!", fname);
205 myself->connection->ecdsa = ecdsa_read_pem_private_key(fp);
208 if(!myself->connection->ecdsa)
209 logger(DEBUG_ALWAYS, LOG_ERR, "Reading ECDSA private key file `%s' failed: %s", fname, strerror(errno));
211 return myself->connection->ecdsa;
214 static bool read_invitation_key(void) {
219 ecdsa_free(invitation_key);
220 invitation_key = NULL;
223 xasprintf(&fname, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", confbase);
225 fp = fopen(fname, "r");
228 invitation_key = ecdsa_read_pem_private_key(fp);
231 logger(DEBUG_ALWAYS, LOG_ERR, "Reading ECDSA private key file `%s' failed: %s", fname, strerror(errno));
235 return invitation_key;
238 static bool read_rsa_private_key(void) {
243 /* First, check for simple PrivateKey statement */
245 if(get_config_string(lookup_config(config_tree, "PrivateKey"), &d)) {
246 if(!get_config_string(lookup_config(config_tree, "PublicKey"), &n)) {
247 logger(DEBUG_ALWAYS, LOG_ERR, "PrivateKey used but no PublicKey found!");
251 myself->connection->rsa = rsa_set_hex_private_key(n, "FFFF", d);
254 return myself->connection->rsa;
257 /* Else, check for PrivateKeyFile statement and read it */
259 if(!get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname))
260 xasprintf(&fname, "%s" SLASH "rsa_key.priv", confbase);
262 fp = fopen(fname, "r");
265 logger(DEBUG_ALWAYS, LOG_ERR, "Error reading RSA private key file `%s': %s",
266 fname, strerror(errno));
271 #if !defined(HAVE_MINGW) && !defined(HAVE_CYGWIN)
274 if(fstat(fileno(fp), &s)) {
275 logger(DEBUG_ALWAYS, LOG_ERR, "Could not stat RSA private key file `%s': %s'", fname, strerror(errno));
280 if(s.st_mode & ~0100700)
281 logger(DEBUG_ALWAYS, LOG_WARNING, "Warning: insecure file permissions for RSA private key file `%s'!", fname);
284 myself->connection->rsa = rsa_read_pem_private_key(fp);
287 if(!myself->connection->rsa)
288 logger(DEBUG_ALWAYS, LOG_ERR, "Reading RSA private key file `%s' failed: %s", fname, strerror(errno));
290 return myself->connection->rsa;
293 static timeout_t keyexpire_timeout;
295 static void keyexpire_handler(void *data) {
297 timeout_set(data, &(struct timeval){keylifetime, rand() % 100000});
300 void regenerate_key(void) {
301 logger(DEBUG_STATUS, LOG_INFO, "Expiring symmetric keys");
305 void load_all_nodes(void) {
310 xasprintf(&dname, "%s" SLASH "hosts", confbase);
311 dir = opendir(dname);
313 logger(DEBUG_ALWAYS, LOG_ERR, "Could not open %s: %s", dname, strerror(errno));
318 while((ent = readdir(dir))) {
319 if(!check_id(ent->d_name))
322 node_t *n = lookup_node(ent->d_name);
327 n->name = xstrdup(ent->d_name);
335 char *get_name(void) {
338 get_config_string(lookup_config(config_tree, "Name"), &name);
344 char *envname = getenv(name + 1);
345 char hostname[32] = "";
347 if(strcmp(name + 1, "HOST")) {
348 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid Name: environment variable %s does not exist\n", name + 1);
351 if(gethostname(hostname, sizeof hostname) || !*hostname) {
352 logger(DEBUG_ALWAYS, LOG_ERR, "Could not get hostname: %s\n", strerror(errno));
359 name = xstrdup(envname);
360 for(char *c = name; *c; c++)
365 if(!check_id(name)) {
366 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid name for myself!");
374 bool setup_myself_reloadable(void) {
380 char *address = NULL;
384 get_config_string(lookup_config(config_tree, "Proxy"), &proxy);
386 if((space = strchr(proxy, ' ')))
389 if(!strcasecmp(proxy, "none")) {
390 proxytype = PROXY_NONE;
391 } else if(!strcasecmp(proxy, "socks4")) {
392 proxytype = PROXY_SOCKS4;
393 } else if(!strcasecmp(proxy, "socks4a")) {
394 proxytype = PROXY_SOCKS4A;
395 } else if(!strcasecmp(proxy, "socks5")) {
396 proxytype = PROXY_SOCKS5;
397 } else if(!strcasecmp(proxy, "http")) {
398 proxytype = PROXY_HTTP;
399 } else if(!strcasecmp(proxy, "exec")) {
400 proxytype = PROXY_EXEC;
402 logger(DEBUG_ALWAYS, LOG_ERR, "Unknown proxy type %s!", proxy);
412 if(!space || !*space) {
413 logger(DEBUG_ALWAYS, LOG_ERR, "Argument expected for proxy type exec!");
416 proxyhost = xstrdup(space);
424 if(space && (space = strchr(space, ' ')))
425 *space++ = 0, proxyport = space;
426 if(space && (space = strchr(space, ' ')))
427 *space++ = 0, proxyuser = space;
428 if(space && (space = strchr(space, ' ')))
429 *space++ = 0, proxypass = space;
430 if(!proxyhost || !*proxyhost || !proxyport || !*proxyport) {
431 logger(DEBUG_ALWAYS, LOG_ERR, "Host and port argument expected for proxy!");
434 proxyhost = xstrdup(proxyhost);
435 proxyport = xstrdup(proxyport);
436 if(proxyuser && *proxyuser)
437 proxyuser = xstrdup(proxyuser);
438 if(proxypass && *proxypass)
439 proxypass = xstrdup(proxypass);
446 if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice) && choice)
447 myself->options |= OPTION_INDIRECT;
449 if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice) && choice)
450 myself->options |= OPTION_TCPONLY;
452 if(myself->options & OPTION_TCPONLY)
453 myself->options |= OPTION_INDIRECT;
455 get_config_bool(lookup_config(config_tree, "DirectOnly"), &directonly);
456 get_config_bool(lookup_config(config_tree, "LocalDiscovery"), &localdiscovery);
458 memset(&localdiscovery_address, 0, sizeof localdiscovery_address);
459 if(get_config_string(lookup_config(config_tree, "LocalDiscoveryAddress"), &address)) {
460 struct addrinfo *ai = str2addrinfo(address, myport, SOCK_DGRAM);
464 memcpy(&localdiscovery_address, ai->ai_addr, ai->ai_addrlen);
468 if(get_config_string(lookup_config(config_tree, "Mode"), &rmode)) {
469 if(!strcasecmp(rmode, "router"))
470 routing_mode = RMODE_ROUTER;
471 else if(!strcasecmp(rmode, "switch"))
472 routing_mode = RMODE_SWITCH;
473 else if(!strcasecmp(rmode, "hub"))
474 routing_mode = RMODE_HUB;
476 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid routing mode!");
482 if(get_config_string(lookup_config(config_tree, "Forwarding"), &fmode)) {
483 if(!strcasecmp(fmode, "off"))
484 forwarding_mode = FMODE_OFF;
485 else if(!strcasecmp(fmode, "internal"))
486 forwarding_mode = FMODE_INTERNAL;
487 else if(!strcasecmp(fmode, "kernel"))
488 forwarding_mode = FMODE_KERNEL;
490 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid forwarding mode!");
497 get_config_bool(lookup_config(config_tree, "PMTUDiscovery"), &choice);
499 myself->options |= OPTION_PMTU_DISCOVERY;
502 get_config_bool(lookup_config(config_tree, "ClampMSS"), &choice);
504 myself->options |= OPTION_CLAMP_MSS;
506 get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
507 get_config_bool(lookup_config(config_tree, "DecrementTTL"), &decrement_ttl);
508 if(get_config_string(lookup_config(config_tree, "Broadcast"), &bmode)) {
509 if(!strcasecmp(bmode, "no"))
510 broadcast_mode = BMODE_NONE;
511 else if(!strcasecmp(bmode, "yes") || !strcasecmp(bmode, "mst"))
512 broadcast_mode = BMODE_MST;
513 else if(!strcasecmp(bmode, "direct"))
514 broadcast_mode = BMODE_DIRECT;
516 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid broadcast mode!");
522 #if !defined(SOL_IP) || !defined(IP_TOS)
523 if(priorityinheritance)
524 logger(DEBUG_ALWAYS, LOG_WARNING, "%s not supported on this platform", "PriorityInheritance");
527 if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire))
530 if(get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout)) {
531 if(maxtimeout <= 0) {
532 logger(DEBUG_ALWAYS, LOG_ERR, "Bogus maximum timeout!");
538 if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
539 if(!strcasecmp(afname, "IPv4"))
540 addressfamily = AF_INET;
541 else if(!strcasecmp(afname, "IPv6"))
542 addressfamily = AF_INET6;
543 else if(!strcasecmp(afname, "any"))
544 addressfamily = AF_UNSPEC;
546 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid address family!");
552 get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
554 if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
557 get_config_int(lookup_config(config_tree, "AutoConnect"), &autoconnect);
561 get_config_bool(lookup_config(config_tree, "DisableBuggyPeers"), &disablebuggypeers);
563 read_invitation_key();
569 Add listening sockets.
571 static bool add_listen_address(char *address, bool bindto) {
575 char *space = strchr(address, ' ');
581 if(!strcmp(address, "*"))
585 struct addrinfo *ai, hint = {0};
586 hint.ai_family = addressfamily;
587 hint.ai_socktype = SOCK_STREAM;
588 hint.ai_protocol = IPPROTO_TCP;
589 hint.ai_flags = AI_PASSIVE;
591 int err = getaddrinfo(address && *address ? address : NULL, port, &hint, &ai);
595 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "getaddrinfo", err == EAI_SYSTEM ? strerror(err) : gai_strerror(err));
599 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
600 // Ignore duplicate addresses
603 for(int i = 0; i < listen_sockets; i++)
604 if(!memcmp(&listen_socket[i].sa, aip->ai_addr, aip->ai_addrlen)) {
612 if(listen_sockets >= MAXSOCKETS) {
613 logger(DEBUG_ALWAYS, LOG_ERR, "Too many listening sockets");
617 int tcp_fd = setup_listen_socket((sockaddr_t *) aip->ai_addr);
622 int udp_fd = setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
629 io_add(&listen_socket[listen_sockets].tcp, handle_new_meta_connection, &listen_socket[listen_sockets], tcp_fd, IO_READ);
630 io_add(&listen_socket[listen_sockets].udp, handle_incoming_vpn_data, &listen_socket[listen_sockets], udp_fd, IO_READ);
632 if(debug_level >= DEBUG_CONNECTIONS) {
633 char *hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
634 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Listening on %s", hostname);
638 listen_socket[listen_sockets].bindto = bindto;
639 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
648 Configure node_t myself and set up the local sockets (listen only)
650 bool setup_myself(void) {
651 char *name, *hostname, *cipher, *digest, *type;
652 char *address = NULL;
653 bool port_specified = false;
655 if(!(name = get_name())) {
656 logger(DEBUG_ALWAYS, LOG_ERR, "Name for tinc daemon required!");
661 myself->connection = new_connection();
663 myself->connection->name = xstrdup(name);
664 read_host_config(config_tree, name);
666 if(!get_config_string(lookup_config(config_tree, "Port"), &myport))
667 myport = xstrdup("655");
669 port_specified = true;
671 myself->connection->options = 0;
672 myself->connection->protocol_major = PROT_MAJOR;
673 myself->connection->protocol_minor = PROT_MINOR;
675 myself->options |= PROT_MINOR << 24;
677 if(!get_config_bool(lookup_config(config_tree, "ExperimentalProtocol"), &experimental)) {
678 experimental = read_ecdsa_private_key();
680 logger(DEBUG_ALWAYS, LOG_WARNING, "Support for SPTPS disabled.");
682 if(experimental && !read_ecdsa_private_key())
686 if(!read_rsa_private_key())
689 /* Ensure myport is numeric */
692 struct addrinfo *ai = str2addrinfo("localhost", myport, SOCK_DGRAM);
694 if(!ai || !ai->ai_addr)
697 memcpy(&sa, ai->ai_addr, ai->ai_addrlen);
698 sockaddr2str(&sa, NULL, &myport);
701 /* Check some options */
703 if(!setup_myself_reloadable())
706 get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
708 if(get_config_int(lookup_config(config_tree, "MaxConnectionBurst"), &max_connection_burst)) {
709 if(max_connection_burst <= 0) {
710 logger(DEBUG_ALWAYS, LOG_ERR, "MaxConnectionBurst cannot be negative!");
715 if(get_config_int(lookup_config(config_tree, "UDPRcvBuf"), &udp_rcvbuf)) {
716 if(udp_rcvbuf <= 0) {
717 logger(DEBUG_ALWAYS, LOG_ERR, "UDPRcvBuf cannot be negative!");
722 if(get_config_int(lookup_config(config_tree, "UDPSndBuf"), &udp_sndbuf)) {
723 if(udp_sndbuf <= 0) {
724 logger(DEBUG_ALWAYS, LOG_ERR, "UDPSndBuf cannot be negative!");
730 if(get_config_int(lookup_config(config_tree, "ReplayWindow"), &replaywin_int)) {
731 if(replaywin_int < 0) {
732 logger(DEBUG_ALWAYS, LOG_ERR, "ReplayWindow cannot be negative!");
735 replaywin = (unsigned)replaywin_int;
736 sptps_replaywin = replaywin;
739 /* Generate packet encryption key */
741 if(!get_config_string(lookup_config(config_tree, "Cipher"), &cipher))
742 cipher = xstrdup("blowfish");
744 if(!strcasecmp(cipher, "none")) {
745 myself->incipher = NULL;
746 } else if(!(myself->incipher = cipher_open_by_name(cipher))) {
747 logger(DEBUG_ALWAYS, LOG_ERR, "Unrecognized cipher type!");
753 timeout_add(&keyexpire_timeout, keyexpire_handler, &keyexpire_timeout, &(struct timeval){keylifetime, rand() % 100000});
755 /* Check if we want to use message authentication codes... */
758 get_config_int(lookup_config(config_tree, "MACLength"), &maclength);
761 logger(DEBUG_ALWAYS, LOG_ERR, "Bogus MAC length!");
765 if(!get_config_string(lookup_config(config_tree, "Digest"), &digest))
766 digest = xstrdup("sha1");
768 if(!strcasecmp(digest, "none")) {
769 myself->indigest = NULL;
770 } else if(!(myself->indigest = digest_open_by_name(digest, maclength))) {
771 logger(DEBUG_ALWAYS, LOG_ERR, "Unrecognized digest type!");
779 if(get_config_int(lookup_config(config_tree, "Compression"), &myself->incompression)) {
780 if(myself->incompression < 0 || myself->incompression > 11) {
781 logger(DEBUG_ALWAYS, LOG_ERR, "Bogus compression level!");
785 myself->incompression = 0;
787 myself->connection->outcompression = 0;
791 myself->nexthop = myself;
792 myself->via = myself;
793 myself->status.reachable = true;
794 myself->last_state_change = now.tv_sec;
795 myself->status.sptps = experimental;
808 for(config_t *cfg = lookup_config(config_tree, "BindToAddress"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
810 get_config_string(cfg, &address);
811 if(!add_listen_address(address, true))
815 for(config_t *cfg = lookup_config(config_tree, "ListenAddress"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
817 get_config_string(cfg, &address);
818 if(!add_listen_address(address, false))
823 if(!add_listen_address(address, NULL))
826 if(!listen_sockets) {
827 logger(DEBUG_ALWAYS, LOG_ERR, "Unable to create any listening socket!");
831 /* If no Port option was specified, set myport to the port used by the first listening socket. */
833 if(!port_specified) {
835 socklen_t salen = sizeof sa;
836 if(!getsockname(listen_socket[0].udp.fd, &sa.sa, &salen)) {
838 sockaddr2str(&sa, NULL, &myport);
840 myport = xstrdup("655");
844 xasprintf(&myself->hostname, "MYSELF port %s", myport);
845 myself->connection->hostname = xstrdup(myself->hostname);
849 last_config_check = now.tv_sec;
857 bool setup_network(void) {
863 if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
864 if(pinginterval < 1) {
865 pinginterval = 86400;
870 if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
872 if(pingtimeout < 1 || pingtimeout > pinginterval)
873 pingtimeout = pinginterval;
875 if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize))
876 maxoutbufsize = 10 * MTU;
885 close all open network connections
887 void close_network_connections(void) {
888 for(list_node_t *node = connection_list->head, *next; node; node = next) {
890 connection_t *c = node->data;
892 terminate_connection(c, false);
896 list_delete_list(outgoing_list);
898 if(myself && myself->connection) {
899 terminate_connection(myself->connection, false);
900 free_connection(myself->connection);
903 for(int i = 0; i < listen_sockets; i++) {
904 io_del(&listen_socket[i].tcp);
905 io_del(&listen_socket[i].udp);
906 close(listen_socket[i].tcp.fd);
907 close(listen_socket[i].udp.fd);
915 if(myport) free(myport);