3 Copyright (C) 2014 Guus Sliepen <guus@meshlink.io>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 #include "connection.h"
43 proxytype_t proxytype;
45 bool disablebuggypeers;
47 bool node_read_ecdsa_public_key(node_t *n) {
48 if(ecdsa_active(n->ecdsa))
51 splay_tree_t *config_tree;
56 init_configuration(&config_tree);
57 if(!read_host_config(config_tree, n->name))
60 /* First, check for simple ECDSAPublicKey statement */
62 if(get_config_string(lookup_config(config_tree, "ECDSAPublicKey"), &p)) {
63 n->ecdsa = ecdsa_set_base64_public_key(p);
68 /* Else, check for ECDSAPublicKeyFile statement and read it */
70 if(!get_config_string(lookup_config(config_tree, "ECDSAPublicKeyFile"), &pubname))
71 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, n->name);
73 fp = fopen(pubname, "r");
78 n->ecdsa = ecdsa_read_pem_public_key(fp);
82 exit_configuration(&config_tree);
87 bool read_ecdsa_public_key(connection_t *c) {
88 if(ecdsa_active(c->ecdsa))
96 init_configuration(&c->config_tree);
97 if(!read_host_config(c->config_tree, c->name))
101 /* First, check for simple ECDSAPublicKey statement */
103 if(get_config_string(lookup_config(c->config_tree, "ECDSAPublicKey"), &p)) {
104 c->ecdsa = ecdsa_set_base64_public_key(p);
109 /* Else, check for ECDSAPublicKeyFile statement and read it */
111 if(!get_config_string(lookup_config(c->config_tree, "ECDSAPublicKeyFile"), &fname))
112 xasprintf(&fname, "%s" SLASH "hosts" SLASH "%s", confbase, c->name);
114 fp = fopen(fname, "r");
117 logger(DEBUG_ALWAYS, LOG_ERR, "Error reading ECDSA public key file `%s': %s",
118 fname, strerror(errno));
123 c->ecdsa = ecdsa_read_pem_public_key(fp);
127 logger(DEBUG_ALWAYS, LOG_ERR, "Parsing ECDSA public key file `%s' failed.", fname);
132 bool read_rsa_public_key(connection_t *c) {
133 if(ecdsa_active(c->ecdsa))
140 /* First, check for simple PublicKey statement */
142 if(get_config_string(lookup_config(c->config_tree, "PublicKey"), &n)) {
143 c->rsa = rsa_set_hex_public_key(n, "FFFF");
148 /* Else, check for PublicKeyFile statement and read it */
150 if(!get_config_string(lookup_config(c->config_tree, "PublicKeyFile"), &fname))
151 xasprintf(&fname, "%s" SLASH "hosts" SLASH "%s", confbase, c->name);
153 fp = fopen(fname, "r");
156 logger(DEBUG_ALWAYS, LOG_ERR, "Error reading RSA public key file `%s': %s", fname, strerror(errno));
161 c->rsa = rsa_read_pem_public_key(fp);
165 logger(DEBUG_ALWAYS, LOG_ERR, "Reading RSA public key file `%s' failed: %s", fname, strerror(errno));
170 static bool read_ecdsa_private_key(void) {
174 /* Check for PrivateKeyFile statement and read it */
176 if(!get_config_string(lookup_config(config_tree, "ECDSAPrivateKeyFile"), &fname))
177 xasprintf(&fname, "%s" SLASH "ecdsa_key.priv", confbase);
179 fp = fopen(fname, "r");
182 logger(DEBUG_ALWAYS, LOG_ERR, "Error reading ECDSA private key file `%s': %s", fname, strerror(errno));
184 logger(DEBUG_ALWAYS, LOG_INFO, "Create an ECDSA keypair with `tinc generate-ecdsa-keys'.");
189 #if !defined(HAVE_MINGW) && !defined(HAVE_CYGWIN)
192 if(fstat(fileno(fp), &s)) {
193 logger(DEBUG_ALWAYS, LOG_ERR, "Could not stat ECDSA private key file `%s': %s'", fname, strerror(errno));
198 if(s.st_mode & ~0100700)
199 logger(DEBUG_ALWAYS, LOG_WARNING, "Warning: insecure file permissions for ECDSA private key file `%s'!", fname);
202 myself->connection->ecdsa = ecdsa_read_pem_private_key(fp);
205 if(!myself->connection->ecdsa)
206 logger(DEBUG_ALWAYS, LOG_ERR, "Reading ECDSA private key file `%s' failed: %s", fname, strerror(errno));
208 return myself->connection->ecdsa;
211 static bool read_invitation_key(void) {
216 ecdsa_free(invitation_key);
217 invitation_key = NULL;
220 xasprintf(&fname, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", confbase);
222 fp = fopen(fname, "r");
225 invitation_key = ecdsa_read_pem_private_key(fp);
228 logger(DEBUG_ALWAYS, LOG_ERR, "Reading ECDSA private key file `%s' failed: %s", fname, strerror(errno));
232 return invitation_key;
235 static bool read_rsa_private_key(void) {
240 /* First, check for simple PrivateKey statement */
242 if(get_config_string(lookup_config(config_tree, "PrivateKey"), &d)) {
243 if(!get_config_string(lookup_config(config_tree, "PublicKey"), &n)) {
244 logger(DEBUG_ALWAYS, LOG_ERR, "PrivateKey used but no PublicKey found!");
248 myself->connection->rsa = rsa_set_hex_private_key(n, "FFFF", d);
251 return myself->connection->rsa;
254 /* Else, check for PrivateKeyFile statement and read it */
256 if(!get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname))
257 xasprintf(&fname, "%s" SLASH "rsa_key.priv", confbase);
259 fp = fopen(fname, "r");
262 logger(DEBUG_ALWAYS, LOG_ERR, "Error reading RSA private key file `%s': %s",
263 fname, strerror(errno));
268 #if !defined(HAVE_MINGW) && !defined(HAVE_CYGWIN)
271 if(fstat(fileno(fp), &s)) {
272 logger(DEBUG_ALWAYS, LOG_ERR, "Could not stat RSA private key file `%s': %s'", fname, strerror(errno));
277 if(s.st_mode & ~0100700)
278 logger(DEBUG_ALWAYS, LOG_WARNING, "Warning: insecure file permissions for RSA private key file `%s'!", fname);
281 myself->connection->rsa = rsa_read_pem_private_key(fp);
284 if(!myself->connection->rsa)
285 logger(DEBUG_ALWAYS, LOG_ERR, "Reading RSA private key file `%s' failed: %s", fname, strerror(errno));
287 return myself->connection->rsa;
290 static timeout_t keyexpire_timeout;
292 static void keyexpire_handler(void *data) {
294 timeout_set(data, &(struct timeval){keylifetime, rand() % 100000});
297 void regenerate_key(void) {
298 logger(DEBUG_STATUS, LOG_INFO, "Expiring symmetric keys");
302 void load_all_nodes(void) {
307 xasprintf(&dname, "%s" SLASH "hosts", confbase);
308 dir = opendir(dname);
310 logger(DEBUG_ALWAYS, LOG_ERR, "Could not open %s: %s", dname, strerror(errno));
315 while((ent = readdir(dir))) {
316 if(!check_id(ent->d_name))
319 node_t *n = lookup_node(ent->d_name);
324 n->name = xstrdup(ent->d_name);
332 char *get_name(void) {
335 get_config_string(lookup_config(config_tree, "Name"), &name);
341 char *envname = getenv(name + 1);
342 char hostname[32] = "";
344 if(strcmp(name + 1, "HOST")) {
345 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid Name: environment variable %s does not exist\n", name + 1);
348 if(gethostname(hostname, sizeof hostname) || !*hostname) {
349 logger(DEBUG_ALWAYS, LOG_ERR, "Could not get hostname: %s\n", strerror(errno));
356 name = xstrdup(envname);
357 for(char *c = name; *c; c++)
362 if(!check_id(name)) {
363 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid name for myself!");
371 bool setup_myself_reloadable(void) {
377 char *address = NULL;
381 get_config_string(lookup_config(config_tree, "Proxy"), &proxy);
383 if((space = strchr(proxy, ' ')))
386 if(!strcasecmp(proxy, "none")) {
387 proxytype = PROXY_NONE;
388 } else if(!strcasecmp(proxy, "socks4")) {
389 proxytype = PROXY_SOCKS4;
390 } else if(!strcasecmp(proxy, "socks4a")) {
391 proxytype = PROXY_SOCKS4A;
392 } else if(!strcasecmp(proxy, "socks5")) {
393 proxytype = PROXY_SOCKS5;
394 } else if(!strcasecmp(proxy, "http")) {
395 proxytype = PROXY_HTTP;
396 } else if(!strcasecmp(proxy, "exec")) {
397 proxytype = PROXY_EXEC;
399 logger(DEBUG_ALWAYS, LOG_ERR, "Unknown proxy type %s!", proxy);
409 if(!space || !*space) {
410 logger(DEBUG_ALWAYS, LOG_ERR, "Argument expected for proxy type exec!");
413 proxyhost = xstrdup(space);
421 if(space && (space = strchr(space, ' ')))
422 *space++ = 0, proxyport = space;
423 if(space && (space = strchr(space, ' ')))
424 *space++ = 0, proxyuser = space;
425 if(space && (space = strchr(space, ' ')))
426 *space++ = 0, proxypass = space;
427 if(!proxyhost || !*proxyhost || !proxyport || !*proxyport) {
428 logger(DEBUG_ALWAYS, LOG_ERR, "Host and port argument expected for proxy!");
431 proxyhost = xstrdup(proxyhost);
432 proxyport = xstrdup(proxyport);
433 if(proxyuser && *proxyuser)
434 proxyuser = xstrdup(proxyuser);
435 if(proxypass && *proxypass)
436 proxypass = xstrdup(proxypass);
443 if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice) && choice)
444 myself->options |= OPTION_INDIRECT;
446 if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice) && choice)
447 myself->options |= OPTION_TCPONLY;
449 if(myself->options & OPTION_TCPONLY)
450 myself->options |= OPTION_INDIRECT;
452 get_config_bool(lookup_config(config_tree, "DirectOnly"), &directonly);
453 get_config_bool(lookup_config(config_tree, "LocalDiscovery"), &localdiscovery);
455 memset(&localdiscovery_address, 0, sizeof localdiscovery_address);
456 if(get_config_string(lookup_config(config_tree, "LocalDiscoveryAddress"), &address)) {
457 struct addrinfo *ai = str2addrinfo(address, myport, SOCK_DGRAM);
461 memcpy(&localdiscovery_address, ai->ai_addr, ai->ai_addrlen);
465 if(get_config_string(lookup_config(config_tree, "Mode"), &rmode)) {
466 if(!strcasecmp(rmode, "router"))
467 routing_mode = RMODE_ROUTER;
468 else if(!strcasecmp(rmode, "switch"))
469 routing_mode = RMODE_SWITCH;
470 else if(!strcasecmp(rmode, "hub"))
471 routing_mode = RMODE_HUB;
473 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid routing mode!");
479 if(get_config_string(lookup_config(config_tree, "Forwarding"), &fmode)) {
480 if(!strcasecmp(fmode, "off"))
481 forwarding_mode = FMODE_OFF;
482 else if(!strcasecmp(fmode, "internal"))
483 forwarding_mode = FMODE_INTERNAL;
484 else if(!strcasecmp(fmode, "kernel"))
485 forwarding_mode = FMODE_KERNEL;
487 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid forwarding mode!");
494 get_config_bool(lookup_config(config_tree, "PMTUDiscovery"), &choice);
496 myself->options |= OPTION_PMTU_DISCOVERY;
499 get_config_bool(lookup_config(config_tree, "ClampMSS"), &choice);
501 myself->options |= OPTION_CLAMP_MSS;
503 get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
504 get_config_bool(lookup_config(config_tree, "DecrementTTL"), &decrement_ttl);
505 if(get_config_string(lookup_config(config_tree, "Broadcast"), &bmode)) {
506 if(!strcasecmp(bmode, "no"))
507 broadcast_mode = BMODE_NONE;
508 else if(!strcasecmp(bmode, "yes") || !strcasecmp(bmode, "mst"))
509 broadcast_mode = BMODE_MST;
510 else if(!strcasecmp(bmode, "direct"))
511 broadcast_mode = BMODE_DIRECT;
513 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid broadcast mode!");
519 #if !defined(SOL_IP) || !defined(IP_TOS)
520 if(priorityinheritance)
521 logger(DEBUG_ALWAYS, LOG_WARNING, "%s not supported on this platform", "PriorityInheritance");
524 if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire))
527 if(get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout)) {
528 if(maxtimeout <= 0) {
529 logger(DEBUG_ALWAYS, LOG_ERR, "Bogus maximum timeout!");
535 if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
536 if(!strcasecmp(afname, "IPv4"))
537 addressfamily = AF_INET;
538 else if(!strcasecmp(afname, "IPv6"))
539 addressfamily = AF_INET6;
540 else if(!strcasecmp(afname, "any"))
541 addressfamily = AF_UNSPEC;
543 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid address family!");
549 get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
551 if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
554 get_config_int(lookup_config(config_tree, "AutoConnect"), &autoconnect);
558 get_config_bool(lookup_config(config_tree, "DisableBuggyPeers"), &disablebuggypeers);
560 read_invitation_key();
566 Add listening sockets.
568 static bool add_listen_address(char *address, bool bindto) {
572 char *space = strchr(address, ' ');
578 if(!strcmp(address, "*"))
582 struct addrinfo *ai, hint = {0};
583 hint.ai_family = addressfamily;
584 hint.ai_socktype = SOCK_STREAM;
585 hint.ai_protocol = IPPROTO_TCP;
586 hint.ai_flags = AI_PASSIVE;
588 int err = getaddrinfo(address && *address ? address : NULL, port, &hint, &ai);
592 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "getaddrinfo", err == EAI_SYSTEM ? strerror(err) : gai_strerror(err));
596 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
597 // Ignore duplicate addresses
600 for(int i = 0; i < listen_sockets; i++)
601 if(!memcmp(&listen_socket[i].sa, aip->ai_addr, aip->ai_addrlen)) {
609 if(listen_sockets >= MAXSOCKETS) {
610 logger(DEBUG_ALWAYS, LOG_ERR, "Too many listening sockets");
614 int tcp_fd = setup_listen_socket((sockaddr_t *) aip->ai_addr);
619 int udp_fd = setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
626 io_add(&listen_socket[listen_sockets].tcp, handle_new_meta_connection, &listen_socket[listen_sockets], tcp_fd, IO_READ);
627 io_add(&listen_socket[listen_sockets].udp, handle_incoming_vpn_data, &listen_socket[listen_sockets], udp_fd, IO_READ);
629 if(debug_level >= DEBUG_CONNECTIONS) {
630 char *hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
631 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Listening on %s", hostname);
635 listen_socket[listen_sockets].bindto = bindto;
636 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
645 Configure node_t myself and set up the local sockets (listen only)
647 bool setup_myself(void) {
648 char *name, *hostname, *cipher, *digest, *type;
649 char *address = NULL;
650 bool port_specified = false;
652 if(!(name = get_name())) {
653 logger(DEBUG_ALWAYS, LOG_ERR, "Name for tinc daemon required!");
658 myself->connection = new_connection();
660 myself->connection->name = xstrdup(name);
661 read_host_config(config_tree, name);
663 if(!get_config_string(lookup_config(config_tree, "Port"), &myport))
664 myport = xstrdup("655");
666 port_specified = true;
668 myself->connection->options = 0;
669 myself->connection->protocol_major = PROT_MAJOR;
670 myself->connection->protocol_minor = PROT_MINOR;
672 myself->options |= PROT_MINOR << 24;
674 if(!get_config_bool(lookup_config(config_tree, "ExperimentalProtocol"), &experimental)) {
675 experimental = read_ecdsa_private_key();
677 logger(DEBUG_ALWAYS, LOG_WARNING, "Support for SPTPS disabled.");
679 if(experimental && !read_ecdsa_private_key())
683 if(!read_rsa_private_key())
686 /* Ensure myport is numeric */
689 struct addrinfo *ai = str2addrinfo("localhost", myport, SOCK_DGRAM);
691 if(!ai || !ai->ai_addr)
694 memcpy(&sa, ai->ai_addr, ai->ai_addrlen);
695 sockaddr2str(&sa, NULL, &myport);
698 /* Check some options */
700 if(!setup_myself_reloadable())
703 if(get_config_int(lookup_config(config_tree, "MaxConnectionBurst"), &max_connection_burst)) {
704 if(max_connection_burst <= 0) {
705 logger(DEBUG_ALWAYS, LOG_ERR, "MaxConnectionBurst cannot be negative!");
711 if(get_config_int(lookup_config(config_tree, "ReplayWindow"), &replaywin_int)) {
712 if(replaywin_int < 0) {
713 logger(DEBUG_ALWAYS, LOG_ERR, "ReplayWindow cannot be negative!");
716 replaywin = (unsigned)replaywin_int;
717 sptps_replaywin = replaywin;
720 /* Generate packet encryption key */
722 if(!get_config_string(lookup_config(config_tree, "Cipher"), &cipher))
723 cipher = xstrdup("blowfish");
725 if(!strcasecmp(cipher, "none")) {
726 myself->incipher = NULL;
727 } else if(!(myself->incipher = cipher_open_by_name(cipher))) {
728 logger(DEBUG_ALWAYS, LOG_ERR, "Unrecognized cipher type!");
734 timeout_add(&keyexpire_timeout, keyexpire_handler, &keyexpire_timeout, &(struct timeval){keylifetime, rand() % 100000});
736 /* Check if we want to use message authentication codes... */
739 get_config_int(lookup_config(config_tree, "MACLength"), &maclength);
742 logger(DEBUG_ALWAYS, LOG_ERR, "Bogus MAC length!");
746 if(!get_config_string(lookup_config(config_tree, "Digest"), &digest))
747 digest = xstrdup("sha1");
749 if(!strcasecmp(digest, "none")) {
750 myself->indigest = NULL;
751 } else if(!(myself->indigest = digest_open_by_name(digest, maclength))) {
752 logger(DEBUG_ALWAYS, LOG_ERR, "Unrecognized digest type!");
760 if(get_config_int(lookup_config(config_tree, "Compression"), &myself->incompression)) {
761 if(myself->incompression < 0 || myself->incompression > 11) {
762 logger(DEBUG_ALWAYS, LOG_ERR, "Bogus compression level!");
766 myself->incompression = 0;
768 myself->connection->outcompression = 0;
772 myself->nexthop = myself;
773 myself->via = myself;
774 myself->status.reachable = true;
775 myself->last_state_change = now.tv_sec;
776 myself->status.sptps = experimental;
789 for(config_t *cfg = lookup_config(config_tree, "BindToAddress"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
791 get_config_string(cfg, &address);
792 if(!add_listen_address(address, true))
796 for(config_t *cfg = lookup_config(config_tree, "ListenAddress"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
798 get_config_string(cfg, &address);
799 if(!add_listen_address(address, false))
804 if(!add_listen_address(address, NULL))
807 if(!listen_sockets) {
808 logger(DEBUG_ALWAYS, LOG_ERR, "Unable to create any listening socket!");
812 /* If no Port option was specified, set myport to the port used by the first listening socket. */
814 if(!port_specified) {
816 socklen_t salen = sizeof sa;
817 if(!getsockname(listen_socket[0].udp.fd, &sa.sa, &salen)) {
819 sockaddr2str(&sa, NULL, &myport);
821 myport = xstrdup("655");
825 xasprintf(&myself->hostname, "MYSELF port %s", myport);
826 myself->connection->hostname = xstrdup(myself->hostname);
830 last_config_check = now.tv_sec;
838 bool setup_network(void) {
844 if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
845 if(pinginterval < 1) {
846 pinginterval = 86400;
851 if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
853 if(pingtimeout < 1 || pingtimeout > pinginterval)
854 pingtimeout = pinginterval;
856 if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize))
857 maxoutbufsize = 10 * MTU;
866 close all open network connections
868 void close_network_connections(void) {
869 for(list_node_t *node = connection_list->head, *next; node; node = next) {
871 connection_t *c = node->data;
873 terminate_connection(c, false);
877 list_delete_list(outgoing_list);
879 if(myself && myself->connection) {
880 terminate_connection(myself->connection, false);
881 free_connection(myself->connection);
884 for(int i = 0; i < listen_sockets; i++) {
885 io_del(&listen_socket[i].tcp);
886 io_del(&listen_socket[i].udp);
887 close(listen_socket[i].tcp.fd);
888 close(listen_socket[i].udp.fd);
896 if(myport) free(myport);