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"
47 proxytype_t proxytype;
49 bool disablebuggypeers;
51 bool node_read_ecdsa_public_key(node_t *n) {
52 if(ecdsa_active(n->ecdsa))
55 splay_tree_t *config_tree;
60 init_configuration(&config_tree);
61 if(!read_host_config(config_tree, n->name))
64 /* First, check for simple ECDSAPublicKey statement */
66 if(get_config_string(lookup_config(config_tree, "ECDSAPublicKey"), &p)) {
67 n->ecdsa = ecdsa_set_base64_public_key(p);
72 /* Else, check for ECDSAPublicKeyFile statement and read it */
74 if(!get_config_string(lookup_config(config_tree, "ECDSAPublicKeyFile"), &pubname))
75 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, n->name);
77 fp = fopen(pubname, "r");
82 n->ecdsa = ecdsa_read_pem_public_key(fp);
86 exit_configuration(&config_tree);
91 bool read_ecdsa_public_key(connection_t *c) {
92 if(ecdsa_active(c->ecdsa))
100 init_configuration(&c->config_tree);
101 if(!read_host_config(c->config_tree, c->name))
105 /* First, check for simple ECDSAPublicKey statement */
107 if(get_config_string(lookup_config(c->config_tree, "ECDSAPublicKey"), &p)) {
108 c->ecdsa = ecdsa_set_base64_public_key(p);
113 /* Else, check for ECDSAPublicKeyFile statement and read it */
115 if(!get_config_string(lookup_config(c->config_tree, "ECDSAPublicKeyFile"), &fname))
116 xasprintf(&fname, "%s" SLASH "hosts" SLASH "%s", confbase, c->name);
118 fp = fopen(fname, "r");
121 logger(DEBUG_ALWAYS, LOG_ERR, "Error reading ECDSA public key file `%s': %s",
122 fname, strerror(errno));
127 c->ecdsa = ecdsa_read_pem_public_key(fp);
131 logger(DEBUG_ALWAYS, LOG_ERR, "Parsing ECDSA public key file `%s' failed.", fname);
136 bool read_rsa_public_key(connection_t *c) {
137 if(ecdsa_active(c->ecdsa))
144 /* First, check for simple PublicKey statement */
146 if(get_config_string(lookup_config(c->config_tree, "PublicKey"), &n)) {
147 c->rsa = rsa_set_hex_public_key(n, "FFFF");
152 /* Else, check for PublicKeyFile statement and read it */
154 if(!get_config_string(lookup_config(c->config_tree, "PublicKeyFile"), &fname))
155 xasprintf(&fname, "%s" SLASH "hosts" SLASH "%s", confbase, c->name);
157 fp = fopen(fname, "r");
160 logger(DEBUG_ALWAYS, LOG_ERR, "Error reading RSA public key file `%s': %s", fname, strerror(errno));
165 c->rsa = rsa_read_pem_public_key(fp);
169 logger(DEBUG_ALWAYS, LOG_ERR, "Reading RSA public key file `%s' failed: %s", fname, strerror(errno));
174 static bool read_ecdsa_private_key(void) {
178 /* Check for PrivateKeyFile statement and read it */
180 if(!get_config_string(lookup_config(config_tree, "ECDSAPrivateKeyFile"), &fname))
181 xasprintf(&fname, "%s" SLASH "ecdsa_key.priv", confbase);
183 fp = fopen(fname, "r");
186 logger(DEBUG_ALWAYS, LOG_ERR, "Error reading ECDSA private key file `%s': %s", fname, strerror(errno));
188 logger(DEBUG_ALWAYS, LOG_INFO, "Create an ECDSA keypair with `tinc -n %s generate-ecdsa-keys'.", netname ?: ".");
193 #if !defined(HAVE_MINGW) && !defined(HAVE_CYGWIN)
196 if(fstat(fileno(fp), &s)) {
197 logger(DEBUG_ALWAYS, LOG_ERR, "Could not stat ECDSA private key file `%s': %s'", fname, strerror(errno));
202 if(s.st_mode & ~0100700)
203 logger(DEBUG_ALWAYS, LOG_WARNING, "Warning: insecure file permissions for ECDSA private key file `%s'!", fname);
206 myself->connection->ecdsa = ecdsa_read_pem_private_key(fp);
209 if(!myself->connection->ecdsa)
210 logger(DEBUG_ALWAYS, LOG_ERR, "Reading ECDSA private key file `%s' failed: %s", fname, strerror(errno));
212 return myself->connection->ecdsa;
215 static bool read_invitation_key(void) {
220 ecdsa_free(invitation_key);
221 invitation_key = NULL;
224 xasprintf(&fname, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", confbase);
226 fp = fopen(fname, "r");
229 invitation_key = ecdsa_read_pem_private_key(fp);
232 logger(DEBUG_ALWAYS, LOG_ERR, "Reading ECDSA private key file `%s' failed: %s", fname, strerror(errno));
236 return invitation_key;
239 static bool read_rsa_private_key(void) {
244 /* First, check for simple PrivateKey statement */
246 if(get_config_string(lookup_config(config_tree, "PrivateKey"), &d)) {
247 if(!get_config_string(lookup_config(config_tree, "PublicKey"), &n)) {
248 logger(DEBUG_ALWAYS, LOG_ERR, "PrivateKey used but no PublicKey found!");
252 myself->connection->rsa = rsa_set_hex_private_key(n, "FFFF", d);
255 return myself->connection->rsa;
258 /* Else, check for PrivateKeyFile statement and read it */
260 if(!get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname))
261 xasprintf(&fname, "%s" SLASH "rsa_key.priv", confbase);
263 fp = fopen(fname, "r");
266 logger(DEBUG_ALWAYS, LOG_ERR, "Error reading RSA private key file `%s': %s",
267 fname, strerror(errno));
272 #if !defined(HAVE_MINGW) && !defined(HAVE_CYGWIN)
275 if(fstat(fileno(fp), &s)) {
276 logger(DEBUG_ALWAYS, LOG_ERR, "Could not stat RSA private key file `%s': %s'", fname, strerror(errno));
281 if(s.st_mode & ~0100700)
282 logger(DEBUG_ALWAYS, LOG_WARNING, "Warning: insecure file permissions for RSA private key file `%s'!", fname);
285 myself->connection->rsa = rsa_read_pem_private_key(fp);
288 if(!myself->connection->rsa)
289 logger(DEBUG_ALWAYS, LOG_ERR, "Reading RSA private key file `%s' failed: %s", fname, strerror(errno));
291 return myself->connection->rsa;
294 static timeout_t keyexpire_timeout;
296 static void keyexpire_handler(void *data) {
298 timeout_set(data, &(struct timeval){keylifetime, rand() % 100000});
301 void regenerate_key(void) {
302 logger(DEBUG_STATUS, LOG_INFO, "Expiring symmetric keys");
306 void load_all_nodes(void) {
311 xasprintf(&dname, "%s" SLASH "hosts", confbase);
312 dir = opendir(dname);
314 logger(DEBUG_ALWAYS, LOG_ERR, "Could not open %s: %s", dname, strerror(errno));
319 while((ent = readdir(dir))) {
320 if(!check_id(ent->d_name))
323 node_t *n = lookup_node(ent->d_name);
328 n->name = xstrdup(ent->d_name);
336 char *get_name(void) {
339 get_config_string(lookup_config(config_tree, "Name"), &name);
345 char *envname = getenv(name + 1);
346 char hostname[32] = "";
348 if(strcmp(name + 1, "HOST")) {
349 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid Name: environment variable %s does not exist\n", name + 1);
352 if(gethostname(hostname, sizeof hostname) || !*hostname) {
353 logger(DEBUG_ALWAYS, LOG_ERR, "Could not get hostname: %s\n", strerror(errno));
360 name = xstrdup(envname);
361 for(char *c = name; *c; c++)
366 if(!check_id(name)) {
367 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid name for myself!");
375 bool setup_myself_reloadable(void) {
381 char *address = NULL;
385 get_config_string(lookup_config(config_tree, "Proxy"), &proxy);
387 if((space = strchr(proxy, ' ')))
390 if(!strcasecmp(proxy, "none")) {
391 proxytype = PROXY_NONE;
392 } else if(!strcasecmp(proxy, "socks4")) {
393 proxytype = PROXY_SOCKS4;
394 } else if(!strcasecmp(proxy, "socks4a")) {
395 proxytype = PROXY_SOCKS4A;
396 } else if(!strcasecmp(proxy, "socks5")) {
397 proxytype = PROXY_SOCKS5;
398 } else if(!strcasecmp(proxy, "http")) {
399 proxytype = PROXY_HTTP;
400 } else if(!strcasecmp(proxy, "exec")) {
401 proxytype = PROXY_EXEC;
403 logger(DEBUG_ALWAYS, LOG_ERR, "Unknown proxy type %s!", proxy);
413 if(!space || !*space) {
414 logger(DEBUG_ALWAYS, LOG_ERR, "Argument expected for proxy type exec!");
417 proxyhost = xstrdup(space);
425 if(space && (space = strchr(space, ' ')))
426 *space++ = 0, proxyport = space;
427 if(space && (space = strchr(space, ' ')))
428 *space++ = 0, proxyuser = space;
429 if(space && (space = strchr(space, ' ')))
430 *space++ = 0, proxypass = space;
431 if(!proxyhost || !*proxyhost || !proxyport || !*proxyport) {
432 logger(DEBUG_ALWAYS, LOG_ERR, "Host and port argument expected for proxy!");
435 proxyhost = xstrdup(proxyhost);
436 proxyport = xstrdup(proxyport);
437 if(proxyuser && *proxyuser)
438 proxyuser = xstrdup(proxyuser);
439 if(proxypass && *proxypass)
440 proxypass = xstrdup(proxypass);
447 if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice) && choice)
448 myself->options |= OPTION_INDIRECT;
450 if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice) && choice)
451 myself->options |= OPTION_TCPONLY;
453 if(myself->options & OPTION_TCPONLY)
454 myself->options |= OPTION_INDIRECT;
456 get_config_bool(lookup_config(config_tree, "DirectOnly"), &directonly);
457 get_config_bool(lookup_config(config_tree, "LocalDiscovery"), &localdiscovery);
459 memset(&localdiscovery_address, 0, sizeof localdiscovery_address);
460 if(get_config_string(lookup_config(config_tree, "LocalDiscoveryAddress"), &address)) {
461 struct addrinfo *ai = str2addrinfo(address, myport, SOCK_DGRAM);
465 memcpy(&localdiscovery_address, ai->ai_addr, ai->ai_addrlen);
469 if(get_config_string(lookup_config(config_tree, "Mode"), &rmode)) {
470 if(!strcasecmp(rmode, "router"))
471 routing_mode = RMODE_ROUTER;
472 else if(!strcasecmp(rmode, "switch"))
473 routing_mode = RMODE_SWITCH;
474 else if(!strcasecmp(rmode, "hub"))
475 routing_mode = RMODE_HUB;
477 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid routing mode!");
483 if(get_config_string(lookup_config(config_tree, "Forwarding"), &fmode)) {
484 if(!strcasecmp(fmode, "off"))
485 forwarding_mode = FMODE_OFF;
486 else if(!strcasecmp(fmode, "internal"))
487 forwarding_mode = FMODE_INTERNAL;
488 else if(!strcasecmp(fmode, "kernel"))
489 forwarding_mode = FMODE_KERNEL;
491 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid forwarding mode!");
498 get_config_bool(lookup_config(config_tree, "PMTUDiscovery"), &choice);
500 myself->options |= OPTION_PMTU_DISCOVERY;
503 get_config_bool(lookup_config(config_tree, "ClampMSS"), &choice);
505 myself->options |= OPTION_CLAMP_MSS;
507 get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
508 get_config_bool(lookup_config(config_tree, "DecrementTTL"), &decrement_ttl);
509 if(get_config_string(lookup_config(config_tree, "Broadcast"), &bmode)) {
510 if(!strcasecmp(bmode, "no"))
511 broadcast_mode = BMODE_NONE;
512 else if(!strcasecmp(bmode, "yes") || !strcasecmp(bmode, "mst"))
513 broadcast_mode = BMODE_MST;
514 else if(!strcasecmp(bmode, "direct"))
515 broadcast_mode = BMODE_DIRECT;
517 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid broadcast mode!");
523 #if !defined(SOL_IP) || !defined(IP_TOS)
524 if(priorityinheritance)
525 logger(DEBUG_ALWAYS, LOG_WARNING, "%s not supported on this platform", "PriorityInheritance");
528 if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire))
531 if(get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout)) {
532 if(maxtimeout <= 0) {
533 logger(DEBUG_ALWAYS, LOG_ERR, "Bogus maximum timeout!");
539 if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
540 if(!strcasecmp(afname, "IPv4"))
541 addressfamily = AF_INET;
542 else if(!strcasecmp(afname, "IPv6"))
543 addressfamily = AF_INET6;
544 else if(!strcasecmp(afname, "any"))
545 addressfamily = AF_UNSPEC;
547 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid address family!");
553 get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
555 if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
558 get_config_int(lookup_config(config_tree, "AutoConnect"), &autoconnect);
562 get_config_bool(lookup_config(config_tree, "DisableBuggyPeers"), &disablebuggypeers);
564 read_invitation_key();
570 Add listening sockets.
572 static bool add_listen_address(char *address, bool bindto) {
576 char *space = strchr(address, ' ');
582 if(!strcmp(address, "*"))
586 struct addrinfo *ai, hint = {0};
587 hint.ai_family = addressfamily;
588 hint.ai_socktype = SOCK_STREAM;
589 hint.ai_protocol = IPPROTO_TCP;
590 hint.ai_flags = AI_PASSIVE;
592 int err = getaddrinfo(address && *address ? address : NULL, port, &hint, &ai);
596 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "getaddrinfo", err == EAI_SYSTEM ? strerror(err) : gai_strerror(err));
600 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
601 // Ignore duplicate addresses
604 for(int i = 0; i < listen_sockets; i++)
605 if(!memcmp(&listen_socket[i].sa, aip->ai_addr, aip->ai_addrlen)) {
613 if(listen_sockets >= MAXSOCKETS) {
614 logger(DEBUG_ALWAYS, LOG_ERR, "Too many listening sockets");
618 int tcp_fd = setup_listen_socket((sockaddr_t *) aip->ai_addr);
623 int udp_fd = setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
630 io_add(&listen_socket[listen_sockets].tcp, handle_new_meta_connection, &listen_socket[listen_sockets], tcp_fd, IO_READ);
631 io_add(&listen_socket[listen_sockets].udp, handle_incoming_vpn_data, &listen_socket[listen_sockets], udp_fd, IO_READ);
633 if(debug_level >= DEBUG_CONNECTIONS) {
634 char *hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
635 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Listening on %s", hostname);
639 listen_socket[listen_sockets].bindto = bindto;
640 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
649 Configure node_t myself and set up the local sockets (listen only)
651 bool setup_myself(void) {
652 char *name, *hostname, *cipher, *digest, *type;
653 char *address = NULL;
654 bool port_specified = false;
656 if(!(name = get_name())) {
657 logger(DEBUG_ALWAYS, LOG_ERR, "Name for tinc daemon required!");
662 myself->connection = new_connection();
664 myself->connection->name = xstrdup(name);
665 read_host_config(config_tree, name);
667 if(!get_config_string(lookup_config(config_tree, "Port"), &myport))
668 myport = xstrdup("655");
670 port_specified = true;
672 myself->connection->options = 0;
673 myself->connection->protocol_major = PROT_MAJOR;
674 myself->connection->protocol_minor = PROT_MINOR;
676 myself->options |= PROT_MINOR << 24;
678 if(!get_config_bool(lookup_config(config_tree, "ExperimentalProtocol"), &experimental)) {
679 experimental = read_ecdsa_private_key();
681 logger(DEBUG_ALWAYS, LOG_WARNING, "Support for SPTPS disabled.");
683 if(experimental && !read_ecdsa_private_key())
687 if(!read_rsa_private_key())
690 /* Ensure myport is numeric */
693 struct addrinfo *ai = str2addrinfo("localhost", myport, SOCK_DGRAM);
695 if(!ai || !ai->ai_addr)
698 memcpy(&sa, ai->ai_addr, ai->ai_addrlen);
699 sockaddr2str(&sa, NULL, &myport);
702 /* Check some options */
704 if(!setup_myself_reloadable())
707 get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
709 if(get_config_int(lookup_config(config_tree, "MaxConnectionBurst"), &max_connection_burst)) {
710 if(max_connection_burst <= 0) {
711 logger(DEBUG_ALWAYS, LOG_ERR, "MaxConnectionBurst cannot be negative!");
716 if(get_config_int(lookup_config(config_tree, "UDPRcvBuf"), &udp_rcvbuf)) {
717 if(udp_rcvbuf <= 0) {
718 logger(DEBUG_ALWAYS, LOG_ERR, "UDPRcvBuf cannot be negative!");
723 if(get_config_int(lookup_config(config_tree, "UDPSndBuf"), &udp_sndbuf)) {
724 if(udp_sndbuf <= 0) {
725 logger(DEBUG_ALWAYS, LOG_ERR, "UDPSndBuf cannot be negative!");
731 if(get_config_int(lookup_config(config_tree, "ReplayWindow"), &replaywin_int)) {
732 if(replaywin_int < 0) {
733 logger(DEBUG_ALWAYS, LOG_ERR, "ReplayWindow cannot be negative!");
736 replaywin = (unsigned)replaywin_int;
737 sptps_replaywin = replaywin;
740 /* Generate packet encryption key */
742 if(!get_config_string(lookup_config(config_tree, "Cipher"), &cipher))
743 cipher = xstrdup("blowfish");
745 if(!strcasecmp(cipher, "none")) {
746 myself->incipher = NULL;
747 } else if(!(myself->incipher = cipher_open_by_name(cipher))) {
748 logger(DEBUG_ALWAYS, LOG_ERR, "Unrecognized cipher type!");
754 timeout_add(&keyexpire_timeout, keyexpire_handler, &keyexpire_timeout, &(struct timeval){keylifetime, rand() % 100000});
756 /* Check if we want to use message authentication codes... */
759 get_config_int(lookup_config(config_tree, "MACLength"), &maclength);
762 logger(DEBUG_ALWAYS, LOG_ERR, "Bogus MAC length!");
766 if(!get_config_string(lookup_config(config_tree, "Digest"), &digest))
767 digest = xstrdup("sha1");
769 if(!strcasecmp(digest, "none")) {
770 myself->indigest = NULL;
771 } else if(!(myself->indigest = digest_open_by_name(digest, maclength))) {
772 logger(DEBUG_ALWAYS, LOG_ERR, "Unrecognized digest type!");
780 if(get_config_int(lookup_config(config_tree, "Compression"), &myself->incompression)) {
781 if(myself->incompression < 0 || myself->incompression > 11) {
782 logger(DEBUG_ALWAYS, LOG_ERR, "Bogus compression level!");
786 myself->incompression = 0;
788 myself->connection->outcompression = 0;
792 myself->nexthop = myself;
793 myself->via = myself;
794 myself->status.reachable = true;
795 myself->last_state_change = now.tv_sec;
796 myself->status.sptps = experimental;
809 for(config_t *cfg = lookup_config(config_tree, "BindToAddress"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
811 get_config_string(cfg, &address);
812 if(!add_listen_address(address, true))
816 for(config_t *cfg = lookup_config(config_tree, "ListenAddress"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
818 get_config_string(cfg, &address);
819 if(!add_listen_address(address, false))
824 if(!add_listen_address(address, NULL))
827 if(!listen_sockets) {
828 logger(DEBUG_ALWAYS, LOG_ERR, "Unable to create any listening socket!");
832 /* If no Port option was specified, set myport to the port used by the first listening socket. */
834 if(!port_specified) {
836 socklen_t salen = sizeof sa;
837 if(!getsockname(listen_socket[0].udp.fd, &sa.sa, &salen)) {
839 sockaddr2str(&sa, NULL, &myport);
841 myport = xstrdup("655");
845 xasprintf(&myself->hostname, "MYSELF port %s", myport);
846 myself->connection->hostname = xstrdup(myself->hostname);
850 last_config_check = now.tv_sec;
858 bool setup_network(void) {
864 if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
865 if(pinginterval < 1) {
866 pinginterval = 86400;
871 if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
873 if(pingtimeout < 1 || pingtimeout > pinginterval)
874 pingtimeout = pinginterval;
876 if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize))
877 maxoutbufsize = 10 * MTU;
886 close all open network connections
888 void close_network_connections(void) {
889 for(list_node_t *node = connection_list->head, *next; node; node = next) {
891 connection_t *c = node->data;
893 terminate_connection(c, false);
897 list_delete_list(outgoing_list);
899 if(myself && myself->connection) {
900 terminate_connection(myself->connection, false);
901 free_connection(myself->connection);
904 for(int i = 0; i < listen_sockets; i++) {
905 io_del(&listen_socket[i].tcp);
906 io_del(&listen_socket[i].udp);
907 close(listen_socket[i].tcp.fd);
908 close(listen_socket[i].udp.fd);
916 if(myport) free(myport);