3 Copyright (C) 1998-2005 Ivo Timmermans,
4 2000-2006 Guus Sliepen <guus@tinc-vpn.org>
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, 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"
47 static struct event device_ev;
49 bool read_rsa_public_key(connection_t *c)
58 c->rsa_key = RSA_new();
59 // RSA_blinding_on(c->rsa_key, NULL);
62 /* First, check for simple PublicKey statement */
64 if(get_config_string(lookup_config(c->config_tree, "PublicKey"), &key)) {
65 BN_hex2bn(&c->rsa_key->n, key);
66 BN_hex2bn(&c->rsa_key->e, "FFFF");
71 /* Else, check for PublicKeyFile statement and read it */
73 if(get_config_string(lookup_config(c->config_tree, "PublicKeyFile"), &fname)) {
74 fp = fopen(fname, "r");
77 logger(LOG_ERR, _("Error reading RSA public key file `%s': %s"),
78 fname, strerror(errno));
84 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
88 return true; /* Woohoo. */
90 /* If it fails, try PEM_read_RSA_PUBKEY. */
91 fp = fopen(fname, "r");
94 logger(LOG_ERR, _("Error reading RSA public key file `%s': %s"),
95 fname, strerror(errno));
101 c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
105 // RSA_blinding_on(c->rsa_key, NULL);
109 logger(LOG_ERR, _("Reading RSA public key file `%s' failed: %s"),
110 fname, strerror(errno));
114 /* Else, check if a harnessed public key is in the config file */
116 asprintf(&fname, "%s/hosts/%s", confbase, c->name);
117 fp = fopen(fname, "r");
120 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
129 /* Try again with PEM_read_RSA_PUBKEY. */
131 asprintf(&fname, "%s/hosts/%s", confbase, c->name);
132 fp = fopen(fname, "r");
135 c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
136 // RSA_blinding_on(c->rsa_key, NULL);
145 logger(LOG_ERR, _("No public key for %s specified!"), c->name);
150 bool read_rsa_private_key(void)
153 char *fname, *key, *pubkey;
158 if(get_config_string(lookup_config(config_tree, "PrivateKey"), &key)) {
159 if(!get_config_string(lookup_config(myself->connection->config_tree, "PublicKey"), &pubkey)) {
160 logger(LOG_ERR, _("PrivateKey used but no PublicKey found!"));
163 myself->connection->rsa_key = RSA_new();
164 // RSA_blinding_on(myself->connection->rsa_key, NULL);
165 BN_hex2bn(&myself->connection->rsa_key->d, key);
166 BN_hex2bn(&myself->connection->rsa_key->n, pubkey);
167 BN_hex2bn(&myself->connection->rsa_key->e, "FFFF");
173 if(!get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname))
174 asprintf(&fname, "%s/rsa_key.priv", confbase);
176 fp = fopen(fname, "r");
179 logger(LOG_ERR, _("Error reading RSA private key file `%s': %s"),
180 fname, strerror(errno));
185 #if !defined(HAVE_MINGW) && !defined(HAVE_CYGWIN)
186 if(fstat(fileno(fp), &s)) {
187 logger(LOG_ERR, _("Could not stat RSA private key file `%s': %s'"),
188 fname, strerror(errno));
193 if(s.st_mode & ~0100700)
194 logger(LOG_WARNING, _("Warning: insecure file permissions for RSA private key file `%s'!"), fname);
197 myself->connection->rsa_key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
200 if(!myself->connection->rsa_key) {
201 logger(LOG_ERR, _("Reading RSA private key file `%s' failed: %s"),
202 fname, strerror(errno));
211 static struct event keyexpire_event;
213 static void keyexpire_handler(int fd, short events, void *data) {
217 void regenerate_key() {
218 RAND_pseudo_bytes((unsigned char *)myself->key, myself->keylength);
220 if(timeout_initialized(&keyexpire_event)) {
221 ifdebug(STATUS) logger(LOG_INFO, _("Regenerating symmetric key"));
222 event_del(&keyexpire_event);
223 send_key_changed(broadcast, myself);
225 timeout_set(&keyexpire_event, keyexpire_handler, NULL);
228 event_add(&keyexpire_event, &(struct timeval){keylifetime, 0});
231 EVP_CIPHER_CTX_init(&packet_ctx);
232 if(!EVP_DecryptInit_ex(&packet_ctx, myself->cipher, NULL, (unsigned char *)myself->key, (unsigned char *)myself->key + myself->cipher->key_len)) {
233 logger(LOG_ERR, _("Error during initialisation of cipher for %s (%s): %s"),
234 myself->name, myself->hostname, ERR_error_string(ERR_get_error(), NULL));
242 Configure node_t myself and set up the local sockets (listen only)
244 bool setup_myself(void)
248 char *name, *hostname, *mode, *afname, *cipher, *digest;
249 char *address = NULL;
251 struct addrinfo *ai, *aip, hint = {0};
258 myself->connection = new_connection();
259 init_configuration(&myself->connection->config_tree);
261 asprintf(&myself->hostname, _("MYSELF"));
262 asprintf(&myself->connection->hostname, _("MYSELF"));
264 myself->connection->options = 0;
265 myself->connection->protocol_version = PROT_CURRENT;
267 if(!get_config_string(lookup_config(config_tree, "Name"), &name)) { /* Not acceptable */
268 logger(LOG_ERR, _("Name for tinc daemon required!"));
272 if(!check_id(name)) {
273 logger(LOG_ERR, _("Invalid name for myself!"));
279 myself->connection->name = xstrdup(name);
281 if(!read_connection_config(myself->connection)) {
282 logger(LOG_ERR, _("Cannot open host configuration file for myself!"));
286 if(!read_rsa_private_key())
289 if(!get_config_string(lookup_config(myself->connection->config_tree, "Port"), &myport))
290 asprintf(&myport, "655");
292 /* Read in all the subnets specified in the host configuration file */
294 cfg = lookup_config(myself->connection->config_tree, "Subnet");
297 if(!get_config_subnet(cfg, &subnet))
300 subnet_add(myself, subnet);
302 cfg = lookup_config_next(myself->connection->config_tree, cfg);
305 /* Check some options */
307 if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice) && choice)
308 myself->options |= OPTION_INDIRECT;
310 if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice) && choice)
311 myself->options |= OPTION_TCPONLY;
313 if(get_config_bool(lookup_config(myself->connection->config_tree, "IndirectData"), &choice) && choice)
314 myself->options |= OPTION_INDIRECT;
316 if(get_config_bool(lookup_config(myself->connection->config_tree, "TCPOnly"), &choice) && choice)
317 myself->options |= OPTION_TCPONLY;
319 if(get_config_bool(lookup_config(myself->connection->config_tree, "PMTUDiscovery"), &choice) && choice)
320 myself->options |= OPTION_PMTU_DISCOVERY;
322 if(myself->options & OPTION_TCPONLY)
323 myself->options |= OPTION_INDIRECT;
325 get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
327 if(get_config_string(lookup_config(config_tree, "Mode"), &mode)) {
328 if(!strcasecmp(mode, "router"))
329 routing_mode = RMODE_ROUTER;
330 else if(!strcasecmp(mode, "switch"))
331 routing_mode = RMODE_SWITCH;
332 else if(!strcasecmp(mode, "hub"))
333 routing_mode = RMODE_HUB;
335 logger(LOG_ERR, _("Invalid routing mode!"));
340 routing_mode = RMODE_ROUTER;
342 get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
344 #if !defined(SOL_IP) || !defined(IP_TOS)
345 if(priorityinheritance)
346 logger(LOG_WARNING, _("PriorityInheritance not supported on this platform"));
349 if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire))
352 if(get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout)) {
353 if(maxtimeout <= 0) {
354 logger(LOG_ERR, _("Bogus maximum timeout!"));
360 if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
361 if(!strcasecmp(afname, "IPv4"))
362 addressfamily = AF_INET;
363 else if(!strcasecmp(afname, "IPv6"))
364 addressfamily = AF_INET6;
365 else if(!strcasecmp(afname, "any"))
366 addressfamily = AF_UNSPEC;
368 logger(LOG_ERR, _("Invalid address family!"));
374 get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
376 /* Generate packet encryption key */
379 (lookup_config(myself->connection->config_tree, "Cipher"), &cipher)) {
380 if(!strcasecmp(cipher, "none")) {
381 myself->cipher = NULL;
383 myself->cipher = EVP_get_cipherbyname(cipher);
385 if(!myself->cipher) {
386 logger(LOG_ERR, _("Unrecognized cipher type!"));
391 myself->cipher = EVP_bf_cbc();
394 myself->keylength = myself->cipher->key_len + myself->cipher->iv_len;
396 myself->keylength = 1;
398 myself->connection->outcipher = EVP_bf_ofb();
400 myself->key = xmalloc(myself->keylength);
402 if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
406 /* Check if we want to use message authentication codes... */
409 (lookup_config(myself->connection->config_tree, "Digest"), &digest)) {
410 if(!strcasecmp(digest, "none")) {
411 myself->digest = NULL;
413 myself->digest = EVP_get_digestbyname(digest);
415 if(!myself->digest) {
416 logger(LOG_ERR, _("Unrecognized digest type!"));
421 myself->digest = EVP_sha1();
423 myself->connection->outdigest = EVP_sha1();
425 if(get_config_int(lookup_config(myself->connection->config_tree, "MACLength"),
426 &myself->maclength)) {
428 if(myself->maclength > myself->digest->md_size) {
429 logger(LOG_ERR, _("MAC length exceeds size of digest!"));
431 } else if(myself->maclength < 0) {
432 logger(LOG_ERR, _("Bogus MAC length!"));
437 myself->maclength = 4;
439 myself->connection->outmaclength = 0;
443 if(get_config_int(lookup_config(myself->connection->config_tree, "Compression"),
444 &myself->compression)) {
445 if(myself->compression < 0 || myself->compression > 11) {
446 logger(LOG_ERR, _("Bogus compression level!"));
450 myself->compression = 0;
452 myself->connection->outcompression = 0;
456 myself->nexthop = myself;
457 myself->via = myself;
458 myself->status.reachable = true;
468 event_set(&device_ev, device_fd, EV_READ|EV_PERSIST,
469 handle_device_data, NULL);
470 if (event_add(&device_ev, NULL) < 0) {
471 logger(LOG_ERR, _("event_add failed: %s"), strerror(errno));
476 /* Run tinc-up script to further initialize the tap interface */
477 asprintf(&envp[0], "NETNAME=%s", netname ? : "");
478 asprintf(&envp[1], "DEVICE=%s", device ? : "");
479 asprintf(&envp[2], "INTERFACE=%s", iface ? : "");
480 asprintf(&envp[3], "NAME=%s", myself->name);
483 execute_script("tinc-up", envp);
485 for(i = 0; i < 5; i++)
488 /* Run subnet-up scripts for our own subnets */
490 subnet_update(myself, NULL, true);
494 get_config_string(lookup_config(config_tree, "BindToAddress"), &address);
496 hint.ai_family = addressfamily;
497 hint.ai_socktype = SOCK_STREAM;
498 hint.ai_protocol = IPPROTO_TCP;
499 hint.ai_flags = AI_PASSIVE;
501 err = getaddrinfo(address, myport, &hint, &ai);
504 logger(LOG_ERR, _("System call `%s' failed: %s"), "getaddrinfo",
511 for(aip = ai; aip; aip = aip->ai_next) {
512 listen_socket[listen_sockets].tcp =
513 setup_listen_socket((sockaddr_t *) aip->ai_addr);
515 if(listen_socket[listen_sockets].tcp < 0)
518 listen_socket[listen_sockets].udp =
519 setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
521 if(listen_socket[listen_sockets].udp < 0) {
522 close(listen_socket[listen_sockets].tcp);
526 event_set(&listen_socket[listen_sockets].ev_tcp,
527 listen_socket[listen_sockets].tcp,
529 handle_new_meta_connection, NULL);
530 if(event_add(&listen_socket[listen_sockets].ev_tcp, NULL) < 0) {
531 logger(LOG_WARNING, _("event_add failed: %s"), strerror(errno));
532 close(listen_socket[listen_sockets].tcp);
533 close(listen_socket[listen_sockets].udp);
537 event_set(&listen_socket[listen_sockets].ev_udp,
538 listen_socket[listen_sockets].udp,
540 handle_incoming_vpn_data, NULL);
541 if(event_add(&listen_socket[listen_sockets].ev_udp, NULL) < 0) {
542 logger(LOG_WARNING, _("event_add failed: %s"), strerror(errno));
543 close(listen_socket[listen_sockets].tcp);
544 close(listen_socket[listen_sockets].udp);
545 event_del(&listen_socket[listen_sockets].ev_tcp);
549 ifdebug(CONNECTIONS) {
550 hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
551 logger(LOG_NOTICE, _("Listening on %s"), hostname);
555 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
558 if(listen_sockets >= MAXSOCKETS) {
559 logger(LOG_WARNING, _("Maximum of %d listening sockets reached"), MAXSOCKETS);
567 logger(LOG_NOTICE, _("Ready"));
569 logger(LOG_ERR, _("Unable to create any listening socket!"));
577 setup all initial network connections
579 bool setup_network_connections(void)
589 if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
590 if(pinginterval < 1) {
591 pinginterval = 86400;
596 if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
598 if(pingtimeout < 1 || pingtimeout > pinginterval)
599 pingtimeout = pinginterval;
601 if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize))
602 maxoutbufsize = 4 * MTU;
607 try_outgoing_connections();
613 close all open network connections
615 void close_network_connections(void)
617 avl_node_t *node, *next;
624 for(node = connection_tree->head; node; node = next) {
630 freeaddrinfo(c->outgoing->ai);
631 free(c->outgoing->name);
636 terminate_connection(c, false);
639 if(myself && myself->connection) {
640 subnet_update(myself, NULL, false);
641 terminate_connection(myself->connection, false);
644 for(i = 0; i < listen_sockets; i++) {
645 event_del(&listen_socket[i].ev_tcp);
646 event_del(&listen_socket[i].ev_udp);
647 close(listen_socket[i].tcp);
648 close(listen_socket[i].udp);
651 asprintf(&envp[0], "NETNAME=%s", netname ? : "");
652 asprintf(&envp[1], "DEVICE=%s", device ? : "");
653 asprintf(&envp[2], "INTERFACE=%s", iface ? : "");
654 asprintf(&envp[3], "NAME=%s", myself->name);
663 execute_script("tinc-down", envp);
665 for(i = 0; i < 4; i++)