3 Copyright (C) 1998-2005 Ivo Timmermans,
4 2000-2012 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) {
62 c->rsa_key = RSA_new();
63 // RSA_blinding_on(c->rsa_key, NULL);
66 /* First, check for simple PublicKey statement */
68 if(get_config_string(lookup_config(c->config_tree, "PublicKey"), &key)) {
69 if(BN_hex2bn(&c->rsa_key->n, key) != strlen(key)) {
70 logger(LOG_ERR, "Invalid PublicKey for %s!", c->name);
73 BN_hex2bn(&c->rsa_key->e, "FFFF");
78 /* Else, check for PublicKeyFile statement and read it */
80 if(get_config_string(lookup_config(c->config_tree, "PublicKeyFile"), &fname)) {
81 fp = fopen(fname, "r");
84 logger(LOG_ERR, "Error reading RSA public key file `%s': %s",
85 fname, strerror(errno));
91 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
95 return true; /* Woohoo. */
97 /* If it fails, try PEM_read_RSA_PUBKEY. */
98 fp = fopen(fname, "r");
101 logger(LOG_ERR, "Error reading RSA public key file `%s': %s",
102 fname, strerror(errno));
108 c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
112 // RSA_blinding_on(c->rsa_key, NULL);
116 logger(LOG_ERR, "Reading RSA public key file `%s' failed: %s",
117 fname, strerror(errno));
121 /* Else, check if a harnessed public key is in the config file */
123 xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
124 fp = fopen(fname, "r");
127 logger(LOG_ERR, "Error reading RSA public key file `%s': %s", fname, strerror(errno));
132 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
139 /* Try again with PEM_read_RSA_PUBKEY. */
141 xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
142 fp = fopen(fname, "r");
145 logger(LOG_ERR, "Error reading RSA public key file `%s': %s", fname, strerror(errno));
150 c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
151 // 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;
168 if(get_config_string(lookup_config(config_tree, "PrivateKey"), &key)) {
169 if(!get_config_string(lookup_config(config_tree, "PublicKey"), &pubkey)) {
170 logger(LOG_ERR, "PrivateKey used but no PublicKey found!");
173 myself->connection->rsa_key = RSA_new();
174 // RSA_blinding_on(myself->connection->rsa_key, NULL);
175 if(BN_hex2bn(&myself->connection->rsa_key->d, key) != strlen(key)) {
176 logger(LOG_ERR, "Invalid PrivateKey for myself!");
179 if(BN_hex2bn(&myself->connection->rsa_key->n, pubkey) != strlen(pubkey)) {
180 logger(LOG_ERR, "Invalid PublicKey for myself!");
183 BN_hex2bn(&myself->connection->rsa_key->e, "FFFF");
189 if(!get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname))
190 xasprintf(&fname, "%s/rsa_key.priv", confbase);
192 fp = fopen(fname, "r");
195 logger(LOG_ERR, "Error reading RSA private key file `%s': %s",
196 fname, strerror(errno));
201 #if !defined(HAVE_MINGW) && !defined(HAVE_CYGWIN)
202 if(fstat(fileno(fp), &s)) {
203 logger(LOG_ERR, "Could not stat RSA private key file `%s': %s'",
204 fname, strerror(errno));
209 if(s.st_mode & ~0100700)
210 logger(LOG_WARNING, "Warning: insecure file permissions for RSA private key file `%s'!", fname);
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);
298 if(strcmp(name + 1, "HOST")) {
299 fprintf(stderr, "Invalid Name: environment variable %s does not exist\n", name + 1);
302 envname = alloca(32);
303 if(gethostname(envname, 32)) {
304 fprintf(stderr, "Could not get hostname: %s\n", strerror(errno));
310 name = xstrdup(envname);
311 for(char *c = name; *c; c++)
316 if(!check_id(name)) {
317 logger(LOG_ERR, "Invalid name for myself!");
326 Configure node_t myself and set up the local sockets (listen only)
328 static bool setup_myself(void) {
331 char *name, *hostname, *mode, *afname, *cipher, *digest, *type;
333 char *address = NULL;
337 struct addrinfo *ai, *aip, hint = {0};
343 myself->connection = new_connection();
345 myself->hostname = xstrdup("MYSELF");
346 myself->connection->hostname = xstrdup("MYSELF");
348 myself->connection->options = 0;
349 myself->connection->protocol_version = PROT_CURRENT;
351 if(!(name = get_name())) {
352 logger(LOG_ERR, "Name for tinc daemon required!");
357 myself->connection->name = xstrdup(name);
358 xasprintf(&fname, "%s/hosts/%s", confbase, name);
359 read_config_options(config_tree, name);
360 read_config_file(config_tree, fname);
363 if(!read_rsa_private_key())
366 if(!get_config_string(lookup_config(config_tree, "Port"), &myport))
367 myport = xstrdup("655");
370 struct addrinfo *ai = str2addrinfo("localhost", myport, SOCK_DGRAM);
372 if(!ai || !ai->ai_addr)
375 memcpy(&sa, ai->ai_addr, ai->ai_addrlen);
376 sockaddr2str(&sa, NULL, &myport);
379 get_config_string(lookup_config(config_tree, "Proxy"), &proxy);
381 if((space = strchr(proxy, ' ')))
384 if(!strcasecmp(proxy, "none")) {
385 proxytype = PROXY_NONE;
386 } else if(!strcasecmp(proxy, "socks4")) {
387 proxytype = PROXY_SOCKS4;
388 } else if(!strcasecmp(proxy, "socks4a")) {
389 proxytype = PROXY_SOCKS4A;
390 } else if(!strcasecmp(proxy, "socks5")) {
391 proxytype = PROXY_SOCKS5;
392 } else if(!strcasecmp(proxy, "http")) {
393 proxytype = PROXY_HTTP;
394 } else if(!strcasecmp(proxy, "exec")) {
395 proxytype = PROXY_EXEC;
397 logger(LOG_ERR, "Unknown proxy type %s!", proxy);
407 if(!space || !*space) {
408 logger(LOG_ERR, "Argument expected for proxy type exec!");
411 proxyhost = xstrdup(space);
419 if(space && (space = strchr(space, ' ')))
420 *space++ = 0, proxyport = space;
421 if(space && (space = strchr(space, ' ')))
422 *space++ = 0, proxyuser = space;
423 if(space && (space = strchr(space, ' ')))
424 *space++ = 0, proxypass = space;
425 if(!proxyhost || !*proxyhost || !proxyport || !*proxyport) {
426 logger(LOG_ERR, "Host and port argument expected for proxy!");
429 proxyhost = xstrdup(proxyhost);
430 proxyport = xstrdup(proxyport);
431 if(proxyuser && *proxyuser)
432 proxyuser = xstrdup(proxyuser);
433 if(proxypass && *proxypass)
434 proxypass = xstrdup(proxypass);
441 /* Read in all the subnets specified in the host configuration file */
443 cfg = lookup_config(config_tree, "Subnet");
446 if(!get_config_subnet(cfg, &subnet))
449 subnet_add(myself, subnet);
451 cfg = lookup_config_next(config_tree, cfg);
454 /* Check some options */
456 if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice) && choice)
457 myself->options |= OPTION_INDIRECT;
459 if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice) && choice)
460 myself->options |= OPTION_TCPONLY;
462 if(myself->options & OPTION_TCPONLY)
463 myself->options |= OPTION_INDIRECT;
465 get_config_bool(lookup_config(config_tree, "DirectOnly"), &directonly);
466 get_config_bool(lookup_config(config_tree, "StrictSubnets"), &strictsubnets);
467 get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
468 get_config_bool(lookup_config(config_tree, "LocalDiscovery"), &localdiscovery);
469 strictsubnets |= tunnelserver;
471 if(get_config_string(lookup_config(config_tree, "Mode"), &mode)) {
472 if(!strcasecmp(mode, "router"))
473 routing_mode = RMODE_ROUTER;
474 else if(!strcasecmp(mode, "switch"))
475 routing_mode = RMODE_SWITCH;
476 else if(!strcasecmp(mode, "hub"))
477 routing_mode = RMODE_HUB;
479 logger(LOG_ERR, "Invalid routing mode!");
485 if(get_config_string(lookup_config(config_tree, "Forwarding"), &mode)) {
486 if(!strcasecmp(mode, "off"))
487 forwarding_mode = FMODE_OFF;
488 else if(!strcasecmp(mode, "internal"))
489 forwarding_mode = FMODE_INTERNAL;
490 else if(!strcasecmp(mode, "kernel"))
491 forwarding_mode = FMODE_KERNEL;
493 logger(LOG_ERR, "Invalid forwarding mode!");
500 get_config_bool(lookup_config(config_tree, "PMTUDiscovery"), &choice);
502 myself->options |= OPTION_PMTU_DISCOVERY;
505 get_config_bool(lookup_config(config_tree, "ClampMSS"), &choice);
507 myself->options |= OPTION_CLAMP_MSS;
509 get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
510 get_config_bool(lookup_config(config_tree, "DecrementTTL"), &decrement_ttl);
511 if(get_config_string(lookup_config(config_tree, "Broadcast"), &mode)) {
512 if(!strcasecmp(mode, "no"))
513 broadcast_mode = BMODE_NONE;
514 else if(!strcasecmp(mode, "yes") || !strcasecmp(mode, "mst"))
515 broadcast_mode = BMODE_MST;
516 else if(!strcasecmp(mode, "direct"))
517 broadcast_mode = BMODE_DIRECT;
519 logger(LOG_ERR, "Invalid broadcast mode!");
525 #if !defined(SOL_IP) || !defined(IP_TOS)
526 if(priorityinheritance)
527 logger(LOG_WARNING, "%s not supported on this platform", "PriorityInheritance");
530 if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire))
533 if(get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout)) {
534 if(maxtimeout <= 0) {
535 logger(LOG_ERR, "Bogus maximum timeout!");
541 if(get_config_int(lookup_config(config_tree, "UDPRcvBuf"), &udp_rcvbuf)) {
542 if(udp_rcvbuf <= 0) {
543 logger(LOG_ERR, "UDPRcvBuf cannot be negative!");
548 if(get_config_int(lookup_config(config_tree, "UDPSndBuf"), &udp_sndbuf)) {
549 if(udp_sndbuf <= 0) {
550 logger(LOG_ERR, "UDPSndBuf cannot be negative!");
555 if(get_config_int(lookup_config(config_tree, "ReplayWindow"), &replaywin_int)) {
556 if(replaywin_int < 0) {
557 logger(LOG_ERR, "ReplayWindow cannot be negative!");
560 replaywin = (unsigned)replaywin_int;
563 if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
564 if(!strcasecmp(afname, "IPv4"))
565 addressfamily = AF_INET;
566 else if(!strcasecmp(afname, "IPv6"))
567 addressfamily = AF_INET6;
568 else if(!strcasecmp(afname, "any"))
569 addressfamily = AF_UNSPEC;
571 logger(LOG_ERR, "Invalid address family!");
577 get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
579 /* Generate packet encryption key */
582 (lookup_config(config_tree, "Cipher"), &cipher)) {
583 if(!strcasecmp(cipher, "none")) {
584 myself->incipher = NULL;
586 myself->incipher = EVP_get_cipherbyname(cipher);
588 if(!myself->incipher) {
589 logger(LOG_ERR, "Unrecognized cipher type!");
594 myself->incipher = EVP_bf_cbc();
597 myself->inkeylength = myself->incipher->key_len + myself->incipher->iv_len;
599 myself->inkeylength = 1;
601 myself->connection->outcipher = EVP_bf_ofb();
603 if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
606 keyexpires = now + keylifetime;
608 /* Check if we want to use message authentication codes... */
610 if(get_config_string(lookup_config(config_tree, "Digest"), &digest)) {
611 if(!strcasecmp(digest, "none")) {
612 myself->indigest = NULL;
614 myself->indigest = EVP_get_digestbyname(digest);
616 if(!myself->indigest) {
617 logger(LOG_ERR, "Unrecognized digest type!");
622 myself->indigest = EVP_sha1();
624 myself->connection->outdigest = EVP_sha1();
626 if(get_config_int(lookup_config(config_tree, "MACLength"), &myself->inmaclength)) {
627 if(myself->indigest) {
628 if(myself->inmaclength > myself->indigest->md_size) {
629 logger(LOG_ERR, "MAC length exceeds size of digest!");
631 } else if(myself->inmaclength < 0) {
632 logger(LOG_ERR, "Bogus MAC length!");
637 myself->inmaclength = 4;
639 myself->connection->outmaclength = 0;
643 if(get_config_int(lookup_config(config_tree, "Compression"), &myself->incompression)) {
644 if(myself->incompression < 0 || myself->incompression > 11) {
645 logger(LOG_ERR, "Bogus compression level!");
649 myself->incompression = 0;
651 myself->connection->outcompression = 0;
655 myself->nexthop = myself;
656 myself->via = myself;
657 myself->status.reachable = true;
669 if(get_config_string(lookup_config(config_tree, "DeviceType"), &type)) {
670 if(!strcasecmp(type, "dummy"))
671 devops = dummy_devops;
672 else if(!strcasecmp(type, "raw_socket"))
673 devops = raw_socket_devops;
674 else if(!strcasecmp(type, "multicast"))
675 devops = multicast_devops;
677 else if(!strcasecmp(type, "uml"))
681 else if(!strcasecmp(type, "vde"))
689 /* Run tinc-up script to further initialize the tap interface */
690 xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
691 xasprintf(&envp[1], "DEVICE=%s", device ? : "");
692 xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
693 xasprintf(&envp[3], "NAME=%s", myself->name);
696 execute_script("tinc-up", envp);
698 for(i = 0; i < 5; i++)
701 /* Run subnet-up scripts for our own subnets */
703 subnet_update(myself, NULL, true);
707 if(!do_detach && getenv("LISTEN_FDS")) {
711 listen_sockets = atoi(getenv("LISTEN_FDS"));
713 unsetenv("LISTEN_FDS");
716 if(listen_sockets > MAXSOCKETS) {
717 logger(LOG_ERR, "Too many listening sockets");
721 for(i = 0; i < listen_sockets; i++) {
723 if(getsockname(i + 3, &sa.sa, &salen) < 0) {
724 logger(LOG_ERR, "Could not get address of listen fd %d: %s", i + 3, sockstrerror(errno));
728 listen_socket[i].tcp = i + 3;
731 fcntl(i + 3, F_SETFD, FD_CLOEXEC);
734 listen_socket[i].udp = setup_vpn_in_socket(&sa);
735 if(listen_socket[i].udp < 0)
738 ifdebug(CONNECTIONS) {
739 hostname = sockaddr2hostname(&sa);
740 logger(LOG_NOTICE, "Listening on %s", hostname);
744 memcpy(&listen_socket[i].sa, &sa, salen);
748 cfg = lookup_config(config_tree, "BindToAddress");
751 get_config_string(cfg, &address);
753 cfg = lookup_config_next(config_tree, cfg);
758 char *space = strchr(address, ' ');
764 if(!strcmp(address, "*"))
768 hint.ai_family = addressfamily;
769 hint.ai_socktype = SOCK_STREAM;
770 hint.ai_protocol = IPPROTO_TCP;
771 hint.ai_flags = AI_PASSIVE;
773 err = getaddrinfo(address && *address ? address : NULL, port, &hint, &ai);
777 logger(LOG_ERR, "System call `%s' failed: %s", "getaddrinfo",
782 for(aip = ai; aip; aip = aip->ai_next) {
783 if(listen_sockets >= MAXSOCKETS) {
784 logger(LOG_ERR, "Too many listening sockets");
788 listen_socket[listen_sockets].tcp =
789 setup_listen_socket((sockaddr_t *) aip->ai_addr);
791 if(listen_socket[listen_sockets].tcp < 0)
794 listen_socket[listen_sockets].udp =
795 setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
797 if(listen_socket[listen_sockets].udp < 0)
800 ifdebug(CONNECTIONS) {
801 hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
802 logger(LOG_NOTICE, "Listening on %s", hostname);
806 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
815 logger(LOG_NOTICE, "Ready");
817 logger(LOG_ERR, "Unable to create any listening socket!");
827 bool setup_network(void) {
837 if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
838 if(pinginterval < 1) {
839 pinginterval = 86400;
844 if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
846 if(pingtimeout < 1 || pingtimeout > pinginterval)
847 pingtimeout = pinginterval;
849 if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize))
850 maxoutbufsize = 10 * MTU;
859 close all open network connections
861 void close_network_connections(void) {
862 avl_node_t *node, *next;
867 for(node = connection_tree->head; node; node = next) {
871 terminate_connection(c, false);
874 for(list_node_t *node = outgoing_list->head; node; node = node->next) {
875 outgoing_t *outgoing = node->data;
878 event_del(outgoing->event);
881 list_delete_list(outgoing_list);
883 if(myself && myself->connection) {
884 subnet_update(myself, NULL, false);
885 terminate_connection(myself->connection, false);
886 free_connection(myself->connection);
889 for(i = 0; i < listen_sockets; i++) {
890 close(listen_socket[i].tcp);
891 close(listen_socket[i].udp);
894 xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
895 xasprintf(&envp[1], "DEVICE=%s", device ? : "");
896 xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
897 xasprintf(&envp[3], "NAME=%s", myself->name);
907 execute_script("tinc-down", envp);
909 if(myport) free(myport);
911 for(i = 0; i < 4; i++)