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 BN_hex2bn(&c->rsa_key->n, key);
70 BN_hex2bn(&c->rsa_key->e, "FFFF");
75 /* Else, check for PublicKeyFile statement and read it */
77 if(get_config_string(lookup_config(c->config_tree, "PublicKeyFile"), &fname)) {
78 fp = fopen(fname, "r");
81 logger(LOG_ERR, "Error reading RSA public key file `%s': %s",
82 fname, strerror(errno));
88 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
92 return true; /* Woohoo. */
94 /* If it fails, try PEM_read_RSA_PUBKEY. */
95 fp = fopen(fname, "r");
98 logger(LOG_ERR, "Error reading RSA public key file `%s': %s",
99 fname, strerror(errno));
105 c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
109 // RSA_blinding_on(c->rsa_key, NULL);
113 logger(LOG_ERR, "Reading RSA public key file `%s' failed: %s",
114 fname, strerror(errno));
118 /* Else, check if a harnessed public key is in the config file */
120 xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
121 fp = fopen(fname, "r");
124 logger(LOG_ERR, "Error reading RSA public key file `%s': %s", fname, strerror(errno));
129 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
136 /* Try again with PEM_read_RSA_PUBKEY. */
138 xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
139 fp = fopen(fname, "r");
142 logger(LOG_ERR, "Error reading RSA public key file `%s': %s", fname, strerror(errno));
147 c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
148 // RSA_blinding_on(c->rsa_key, NULL);
155 logger(LOG_ERR, "No public key for %s specified!", c->name);
160 static bool read_rsa_private_key(void) {
162 char *fname, *key, *pubkey;
165 if(get_config_string(lookup_config(config_tree, "PrivateKey"), &key)) {
166 if(!get_config_string(lookup_config(config_tree, "PublicKey"), &pubkey)) {
167 logger(LOG_ERR, "PrivateKey used but no PublicKey found!");
170 myself->connection->rsa_key = RSA_new();
171 // RSA_blinding_on(myself->connection->rsa_key, NULL);
172 BN_hex2bn(&myself->connection->rsa_key->d, key);
173 BN_hex2bn(&myself->connection->rsa_key->n, pubkey);
174 BN_hex2bn(&myself->connection->rsa_key->e, "FFFF");
180 if(!get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname))
181 xasprintf(&fname, "%s/rsa_key.priv", confbase);
183 fp = fopen(fname, "r");
186 logger(LOG_ERR, "Error reading RSA private key file `%s': %s",
187 fname, strerror(errno));
192 #if !defined(HAVE_MINGW) && !defined(HAVE_CYGWIN)
193 if(fstat(fileno(fp), &s)) {
194 logger(LOG_ERR, "Could not stat RSA private key file `%s': %s'",
195 fname, strerror(errno));
200 if(s.st_mode & ~0100700)
201 logger(LOG_WARNING, "Warning: insecure file permissions for RSA private key file `%s'!", fname);
204 myself->connection->rsa_key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
207 if(!myself->connection->rsa_key) {
208 logger(LOG_ERR, "Reading RSA private key file `%s' failed: %s",
209 fname, strerror(errno));
219 Read Subnets from all host config files
221 void load_all_subnets(void) {
226 avl_tree_t *config_tree;
231 xasprintf(&dname, "%s/hosts", confbase);
232 dir = opendir(dname);
234 logger(LOG_ERR, "Could not open %s: %s", dname, strerror(errno));
239 while((ent = readdir(dir))) {
240 if(!check_id(ent->d_name))
243 n = lookup_node(ent->d_name);
244 #ifdef _DIRENT_HAVE_D_TYPE
245 //if(ent->d_type != DT_REG)
249 xasprintf(&fname, "%s/hosts/%s", confbase, ent->d_name);
250 init_configuration(&config_tree);
251 read_config_options(config_tree, ent->d_name);
252 read_config_file(config_tree, fname);
257 n->name = xstrdup(ent->d_name);
261 for(cfg = lookup_config(config_tree, "Subnet"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
262 if(!get_config_subnet(cfg, &s))
265 if((s2 = lookup_subnet(n, s))) {
272 exit_configuration(&config_tree);
278 char *get_name(void) {
281 get_config_string(lookup_config(config_tree, "Name"), &name);
287 char *envname = getenv(name + 1);
289 if(strcmp(name + 1, "HOST")) {
290 fprintf(stderr, "Invalid Name: environment variable %s does not exist\n", name + 1);
293 envname = alloca(32);
294 if(gethostname(envname, 32)) {
295 fprintf(stderr, "Could not get hostname: %s\n", strerror(errno));
301 name = xstrdup(envname);
302 for(char *c = name; *c; c++)
307 if(!check_id(name)) {
308 logger(LOG_ERR, "Invalid name for myself!");
317 Configure node_t myself and set up the local sockets (listen only)
319 static bool setup_myself(void) {
322 char *name, *hostname, *mode, *afname, *cipher, *digest, *type;
324 char *address = NULL;
328 struct addrinfo *ai, *aip, hint = {0};
334 myself->connection = new_connection();
336 myself->hostname = xstrdup("MYSELF");
337 myself->connection->hostname = xstrdup("MYSELF");
339 myself->connection->options = 0;
340 myself->connection->protocol_version = PROT_CURRENT;
342 if(!(name = get_name())) {
343 logger(LOG_ERR, "Name for tinc daemon required!");
348 myself->connection->name = xstrdup(name);
349 xasprintf(&fname, "%s/hosts/%s", confbase, name);
350 read_config_options(config_tree, name);
351 read_config_file(config_tree, fname);
354 if(!read_rsa_private_key())
357 if(!get_config_string(lookup_config(config_tree, "Port"), &myport))
358 myport = xstrdup("655");
361 struct addrinfo *ai = str2addrinfo("localhost", myport, SOCK_DGRAM);
363 if(!ai || !ai->ai_addr)
366 memcpy(&sa, ai->ai_addr, ai->ai_addrlen);
367 sockaddr2str(&sa, NULL, &myport);
370 get_config_string(lookup_config(config_tree, "Proxy"), &proxy);
372 if((space = strchr(proxy, ' ')))
375 if(!strcasecmp(proxy, "none")) {
376 proxytype = PROXY_NONE;
377 } else if(!strcasecmp(proxy, "socks4")) {
378 proxytype = PROXY_SOCKS4;
379 } else if(!strcasecmp(proxy, "socks4a")) {
380 proxytype = PROXY_SOCKS4A;
381 } else if(!strcasecmp(proxy, "socks5")) {
382 proxytype = PROXY_SOCKS5;
383 } else if(!strcasecmp(proxy, "http")) {
384 proxytype = PROXY_HTTP;
385 } else if(!strcasecmp(proxy, "exec")) {
386 proxytype = PROXY_EXEC;
388 logger(LOG_ERR, "Unknown proxy type %s!", proxy);
398 if(!space || !*space) {
399 logger(LOG_ERR, "Argument expected for proxy type exec!");
402 proxyhost = xstrdup(space);
410 if(space && (space = strchr(space, ' ')))
411 *space++ = 0, proxyport = space;
412 if(space && (space = strchr(space, ' ')))
413 *space++ = 0, proxyuser = space;
414 if(space && (space = strchr(space, ' ')))
415 *space++ = 0, proxypass = space;
416 if(!proxyhost || !*proxyhost || !proxyport || !*proxyport) {
417 logger(LOG_ERR, "Host and port argument expected for proxy!");
420 proxyhost = xstrdup(proxyhost);
421 proxyport = xstrdup(proxyport);
422 if(proxyuser && *proxyuser)
423 proxyuser = xstrdup(proxyuser);
424 if(proxypass && *proxypass)
425 proxypass = xstrdup(proxypass);
432 /* Read in all the subnets specified in the host configuration file */
434 cfg = lookup_config(config_tree, "Subnet");
437 if(!get_config_subnet(cfg, &subnet))
440 subnet_add(myself, subnet);
442 cfg = lookup_config_next(config_tree, cfg);
445 /* Check some options */
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, "StrictSubnets"), &strictsubnets);
458 get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
459 get_config_bool(lookup_config(config_tree, "LocalDiscovery"), &localdiscovery);
460 strictsubnets |= tunnelserver;
462 if(get_config_string(lookup_config(config_tree, "Mode"), &mode)) {
463 if(!strcasecmp(mode, "router"))
464 routing_mode = RMODE_ROUTER;
465 else if(!strcasecmp(mode, "switch"))
466 routing_mode = RMODE_SWITCH;
467 else if(!strcasecmp(mode, "hub"))
468 routing_mode = RMODE_HUB;
470 logger(LOG_ERR, "Invalid routing mode!");
476 if(get_config_string(lookup_config(config_tree, "Forwarding"), &mode)) {
477 if(!strcasecmp(mode, "off"))
478 forwarding_mode = FMODE_OFF;
479 else if(!strcasecmp(mode, "internal"))
480 forwarding_mode = FMODE_INTERNAL;
481 else if(!strcasecmp(mode, "kernel"))
482 forwarding_mode = FMODE_KERNEL;
484 logger(LOG_ERR, "Invalid forwarding mode!");
491 get_config_bool(lookup_config(config_tree, "PMTUDiscovery"), &choice);
493 myself->options |= OPTION_PMTU_DISCOVERY;
496 get_config_bool(lookup_config(config_tree, "ClampMSS"), &choice);
498 myself->options |= OPTION_CLAMP_MSS;
500 get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
501 get_config_bool(lookup_config(config_tree, "DecrementTTL"), &decrement_ttl);
502 if(get_config_string(lookup_config(config_tree, "Broadcast"), &mode)) {
503 if(!strcasecmp(mode, "no"))
504 broadcast_mode = BMODE_NONE;
505 else if(!strcasecmp(mode, "yes") || !strcasecmp(mode, "mst"))
506 broadcast_mode = BMODE_MST;
507 else if(!strcasecmp(mode, "direct"))
508 broadcast_mode = BMODE_DIRECT;
510 logger(LOG_ERR, "Invalid broadcast mode!");
516 #if !defined(SOL_IP) || !defined(IP_TOS)
517 if(priorityinheritance)
518 logger(LOG_WARNING, "%s not supported on this platform", "PriorityInheritance");
521 if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire))
524 if(get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout)) {
525 if(maxtimeout <= 0) {
526 logger(LOG_ERR, "Bogus maximum timeout!");
532 if(get_config_int(lookup_config(config_tree, "UDPRcvBuf"), &udp_rcvbuf)) {
533 if(udp_rcvbuf <= 0) {
534 logger(LOG_ERR, "UDPRcvBuf cannot be negative!");
539 if(get_config_int(lookup_config(config_tree, "UDPSndBuf"), &udp_sndbuf)) {
540 if(udp_sndbuf <= 0) {
541 logger(LOG_ERR, "UDPSndBuf cannot be negative!");
546 if(get_config_int(lookup_config(config_tree, "ReplayWindow"), &replaywin_int)) {
547 if(replaywin_int < 0) {
548 logger(LOG_ERR, "ReplayWindow cannot be negative!");
551 replaywin = (unsigned)replaywin_int;
554 if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
555 if(!strcasecmp(afname, "IPv4"))
556 addressfamily = AF_INET;
557 else if(!strcasecmp(afname, "IPv6"))
558 addressfamily = AF_INET6;
559 else if(!strcasecmp(afname, "any"))
560 addressfamily = AF_UNSPEC;
562 logger(LOG_ERR, "Invalid address family!");
568 get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
570 /* Generate packet encryption key */
573 (lookup_config(config_tree, "Cipher"), &cipher)) {
574 if(!strcasecmp(cipher, "none")) {
575 myself->incipher = NULL;
577 myself->incipher = EVP_get_cipherbyname(cipher);
579 if(!myself->incipher) {
580 logger(LOG_ERR, "Unrecognized cipher type!");
585 myself->incipher = EVP_bf_cbc();
588 myself->inkeylength = myself->incipher->key_len + myself->incipher->iv_len;
590 myself->inkeylength = 1;
592 myself->connection->outcipher = EVP_bf_ofb();
594 if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
597 keyexpires = now + keylifetime;
599 /* Check if we want to use message authentication codes... */
601 if(get_config_string(lookup_config(config_tree, "Digest"), &digest)) {
602 if(!strcasecmp(digest, "none")) {
603 myself->indigest = NULL;
605 myself->indigest = EVP_get_digestbyname(digest);
607 if(!myself->indigest) {
608 logger(LOG_ERR, "Unrecognized digest type!");
613 myself->indigest = EVP_sha1();
615 myself->connection->outdigest = EVP_sha1();
617 if(get_config_int(lookup_config(config_tree, "MACLength"), &myself->inmaclength)) {
618 if(myself->indigest) {
619 if(myself->inmaclength > myself->indigest->md_size) {
620 logger(LOG_ERR, "MAC length exceeds size of digest!");
622 } else if(myself->inmaclength < 0) {
623 logger(LOG_ERR, "Bogus MAC length!");
628 myself->inmaclength = 4;
630 myself->connection->outmaclength = 0;
634 if(get_config_int(lookup_config(config_tree, "Compression"), &myself->incompression)) {
635 if(myself->incompression < 0 || myself->incompression > 11) {
636 logger(LOG_ERR, "Bogus compression level!");
640 myself->incompression = 0;
642 myself->connection->outcompression = 0;
646 myself->nexthop = myself;
647 myself->via = myself;
648 myself->status.reachable = true;
660 if(get_config_string(lookup_config(config_tree, "DeviceType"), &type)) {
661 if(!strcasecmp(type, "dummy"))
662 devops = dummy_devops;
663 else if(!strcasecmp(type, "raw_socket"))
664 devops = raw_socket_devops;
665 else if(!strcasecmp(type, "multicast"))
666 devops = multicast_devops;
668 else if(!strcasecmp(type, "uml"))
672 else if(!strcasecmp(type, "vde"))
680 /* Run tinc-up script to further initialize the tap interface */
681 xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
682 xasprintf(&envp[1], "DEVICE=%s", device ? : "");
683 xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
684 xasprintf(&envp[3], "NAME=%s", myself->name);
687 execute_script("tinc-up", envp);
689 for(i = 0; i < 5; i++)
692 /* Run subnet-up scripts for our own subnets */
694 subnet_update(myself, NULL, true);
698 if(!do_detach && getenv("LISTEN_FDS")) {
702 listen_sockets = atoi(getenv("LISTEN_FDS"));
704 unsetenv("LISTEN_FDS");
707 if(listen_sockets > MAXSOCKETS) {
708 logger(LOG_ERR, "Too many listening sockets");
712 for(i = 0; i < listen_sockets; i++) {
714 if(getsockname(i + 3, &sa.sa, &salen) < 0) {
715 logger(LOG_ERR, "Could not get address of listen fd %d: %s", i + 3, sockstrerror(errno));
719 listen_socket[i].tcp = i + 3;
722 fcntl(i + 3, F_SETFD, FD_CLOEXEC);
725 listen_socket[i].udp = setup_vpn_in_socket(&sa);
726 if(listen_socket[i].udp < 0)
729 ifdebug(CONNECTIONS) {
730 hostname = sockaddr2hostname(&sa);
731 logger(LOG_NOTICE, "Listening on %s", hostname);
735 memcpy(&listen_socket[i].sa, &sa, salen);
739 cfg = lookup_config(config_tree, "BindToAddress");
742 get_config_string(cfg, &address);
744 cfg = lookup_config_next(config_tree, cfg);
749 char *space = strchr(address, ' ');
755 if(!strcmp(address, "*"))
759 hint.ai_family = addressfamily;
760 hint.ai_socktype = SOCK_STREAM;
761 hint.ai_protocol = IPPROTO_TCP;
762 hint.ai_flags = AI_PASSIVE;
764 err = getaddrinfo(address && *address ? address : NULL, port, &hint, &ai);
768 logger(LOG_ERR, "System call `%s' failed: %s", "getaddrinfo",
773 for(aip = ai; aip; aip = aip->ai_next) {
774 if(listen_sockets >= MAXSOCKETS) {
775 logger(LOG_ERR, "Too many listening sockets");
779 listen_socket[listen_sockets].tcp =
780 setup_listen_socket((sockaddr_t *) aip->ai_addr);
782 if(listen_socket[listen_sockets].tcp < 0)
785 listen_socket[listen_sockets].udp =
786 setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
788 if(listen_socket[listen_sockets].udp < 0)
791 ifdebug(CONNECTIONS) {
792 hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
793 logger(LOG_NOTICE, "Listening on %s", hostname);
797 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
806 logger(LOG_NOTICE, "Ready");
808 logger(LOG_ERR, "Unable to create any listening socket!");
818 bool setup_network(void) {
828 if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
829 if(pinginterval < 1) {
830 pinginterval = 86400;
835 if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
837 if(pingtimeout < 1 || pingtimeout > pinginterval)
838 pingtimeout = pinginterval;
840 if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize))
841 maxoutbufsize = 10 * MTU;
850 close all open network connections
852 void close_network_connections(void) {
853 avl_node_t *node, *next;
858 for(node = connection_tree->head; node; node = next) {
862 terminate_connection(c, false);
865 for(list_node_t *node = outgoing_list->head; node; node = node->next) {
866 outgoing_t *outgoing = node->data;
869 event_del(outgoing->event);
872 list_delete_list(outgoing_list);
874 if(myself && myself->connection) {
875 subnet_update(myself, NULL, false);
876 terminate_connection(myself->connection, false);
877 free_connection(myself->connection);
880 for(i = 0; i < listen_sockets; i++) {
881 close(listen_socket[i].tcp);
882 close(listen_socket[i].udp);
885 xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
886 xasprintf(&envp[1], "DEVICE=%s", device ? : "");
887 xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
888 xasprintf(&envp[3], "NAME=%s", myself->name);
898 execute_script("tinc-down", envp);
900 if(myport) free(myport);
902 for(i = 0; i < 4; i++)