2 protocol_auth.c -- handle the meta-protocol, authentication
3 Copyright (C) 1999-2005 Ivo Timmermans,
4 2000-2016 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 along
17 with this program; if not, write to the Free Software Foundation, Inc.,
18 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 #include <openssl/sha.h>
24 #include <openssl/rand.h>
25 #include <openssl/err.h>
26 #include <openssl/evp.h>
30 #include "connection.h"
43 bool send_id(connection_t *c) {
44 if(proxytype && c->outgoing && !c->status.proxy_passed) {
45 return send_proxyrequest(c);
48 return send_request(c, "%d %s %d", ID, myself->connection->name,
49 myself->connection->protocol_version);
52 bool id_h(connection_t *c) {
53 char name[MAX_STRING_SIZE];
55 if(sscanf(c->buffer, "%*d " MAX_STRING " %d", name, &c->protocol_version) != 2) {
56 logger(LOG_ERR, "Got bad %s from %s (%s)", "ID", c->name,
61 /* Check if identity is a valid name */
63 if(!check_id(name) || !strcmp(name, myself->name)) {
64 logger(LOG_ERR, "Got bad %s from %s (%s): %s", "ID", c->name,
65 c->hostname, "invalid name");
69 /* If this is an outgoing connection, make sure we are connected to the right host */
72 if(strcmp(c->name, name)) {
73 logger(LOG_ERR, "Peer %s is %s instead of %s", c->hostname, name,
82 c->name = xstrdup(name);
85 /* Check if version matches */
87 if(c->protocol_version != myself->connection->protocol_version) {
88 logger(LOG_ERR, "Peer %s (%s) uses incompatible version %d",
89 c->name, c->hostname, c->protocol_version);
95 init_configuration(&c->config_tree);
98 c->allow_request = ACK;
107 if(!c->config_tree) {
108 init_configuration(&c->config_tree);
110 if(!read_connection_config(c)) {
111 logger(LOG_ERR, "Peer %s had unknown identity (%s)", c->hostname,
117 if(!read_rsa_public_key(c)) {
121 c->allow_request = METAKEY;
127 return send_metakey(c);
130 static uint64_t byte_budget(const EVP_CIPHER *cipher) {
131 /* Hopefully some failsafe way to calculate the maximum amount of bytes to
132 send/receive with a given cipher before we might run into birthday paradox
133 attacks. Because we might use different modes, the block size of the mode
134 might be 1 byte. In that case, use the IV length. Ensure the whole thing
135 is limited to what can be represented with a 64 bits integer.
138 int ivlen = EVP_CIPHER_iv_length(cipher);
139 int blklen = EVP_CIPHER_block_size(cipher);
140 int len = blklen > 1 ? blklen : ivlen > 1 ? ivlen : 8;
141 int bits = len * 4 - 1;
142 return bits < 64 ? UINT64_C(1) << bits : UINT64_MAX;
145 bool send_metakey(connection_t *c) {
148 int len = RSA_size(c->rsa_key);
150 /* Allocate buffers for the meta key */
152 char buffer[2 * len + 1];
154 c->outkey = xrealloc(c->outkey, len);
157 c->outctx = EVP_CIPHER_CTX_new();
164 /* Copy random data to the buffer */
166 if(1 != RAND_bytes((unsigned char *)c->outkey, len)) {
167 int err = ERR_get_error();
168 logger(LOG_ERR, "Failed to generate meta key (%s)", ERR_error_string(err, NULL));
173 /* The message we send must be smaller than the modulus of the RSA key.
174 By definition, for a key of k bits, the following formula holds:
176 2^(k-1) <= modulus < 2^(k)
178 Where ^ means "to the power of", not "xor".
179 This means that to be sure, we must choose our message < 2^(k-1).
180 This can be done by setting the most significant bit to zero.
183 c->outkey[0] &= 0x7F;
185 ifdebug(SCARY_THINGS) {
186 bin2hex(c->outkey, buffer, len);
187 buffer[len * 2] = '\0';
188 logger(LOG_DEBUG, "Generated random meta key (unencrypted): %s",
192 /* Encrypt the random data
194 We do not use one of the PKCS padding schemes here.
195 This is allowed, because we encrypt a totally random string
196 with a length equal to that of the modulus of the RSA key.
199 if(RSA_public_encrypt(len, (unsigned char *)c->outkey, (unsigned char *)buffer, c->rsa_key, RSA_NO_PADDING) != len) {
200 logger(LOG_ERR, "Error during encryption of meta key for %s (%s): %s",
201 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
205 /* Convert the encrypted random data to a hexadecimal formatted string */
207 bin2hex(buffer, buffer, len);
208 buffer[len * 2] = '\0';
210 /* Send the meta key */
212 x = send_request(c, "%d %d %d %d %d %s", METAKEY,
213 c->outcipher ? EVP_CIPHER_nid(c->outcipher) : 0,
214 c->outdigest ? EVP_MD_type(c->outdigest) : 0, c->outmaclength,
215 c->outcompression, buffer);
217 /* Further outgoing requests are encrypted with the key we just generated */
220 if(!EVP_EncryptInit(c->outctx, c->outcipher,
221 (unsigned char *)c->outkey + len - EVP_CIPHER_key_length(c->outcipher),
222 (unsigned char *)c->outkey + len - EVP_CIPHER_key_length(c->outcipher) -
223 EVP_CIPHER_iv_length(c->outcipher))) {
224 logger(LOG_ERR, "Error during initialisation of cipher for %s (%s): %s",
225 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
229 c->outbudget = byte_budget(c->outcipher);
230 c->status.encryptout = true;
236 bool metakey_h(connection_t *c) {
237 char buffer[MAX_STRING_SIZE];
238 int cipher, digest, maclength, compression;
241 if(sscanf(c->buffer, "%*d %d %d %d %d " MAX_STRING, &cipher, &digest, &maclength, &compression, buffer) != 5) {
242 logger(LOG_ERR, "Got bad %s from %s (%s)", "METAKEY", c->name,
247 len = RSA_size(myself->connection->rsa_key);
249 /* Check if the length of the meta key is all right */
251 if(strlen(buffer) != (size_t)len * 2) {
252 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong keylength");
256 /* Allocate buffers for the meta key */
258 c->inkey = xrealloc(c->inkey, len);
261 c->inctx = EVP_CIPHER_CTX_new();
268 /* Convert the challenge from hexadecimal back to binary */
270 if(!hex2bin(buffer, buffer, len)) {
271 logger(LOG_ERR, "Got bad %s from %s(%s): %s", "METAKEY", c->name, c->hostname, "invalid key");
275 /* Decrypt the meta key */
277 if(RSA_private_decrypt(len, (unsigned char *)buffer, (unsigned char *)c->inkey, myself->connection->rsa_key, RSA_NO_PADDING) != len) { /* See challenge() */
278 logger(LOG_ERR, "Error during decryption of meta key for %s (%s): %s",
279 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
283 ifdebug(SCARY_THINGS) {
284 bin2hex(c->inkey, buffer, len);
285 buffer[len * 2] = '\0';
286 logger(LOG_DEBUG, "Received random meta key (unencrypted): %s", buffer);
289 /* All incoming requests will now be encrypted. */
291 /* Check and lookup cipher and digest algorithms */
294 c->incipher = EVP_get_cipherbynid(cipher);
297 logger(LOG_ERR, "%s (%s) uses unknown cipher!", c->name, c->hostname);
301 if(!EVP_DecryptInit(c->inctx, c->incipher,
302 (unsigned char *)c->inkey + len - EVP_CIPHER_key_length(c->incipher),
303 (unsigned char *)c->inkey + len - EVP_CIPHER_key_length(c->incipher) -
304 EVP_CIPHER_iv_length(c->incipher))) {
305 logger(LOG_ERR, "Error during initialisation of cipher from %s (%s): %s",
306 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
310 c->inbudget = byte_budget(c->incipher);
311 c->status.decryptin = true;
313 logger(LOG_ERR, "%s (%s) uses null cipher!", c->name, c->hostname);
317 c->inmaclength = maclength;
320 c->indigest = EVP_get_digestbynid(digest);
323 logger(LOG_ERR, "Node %s (%s) uses unknown digest!", c->name, c->hostname);
327 if(c->inmaclength > EVP_MD_size(c->indigest) || c->inmaclength < 0) {
328 logger(LOG_ERR, "%s (%s) uses bogus MAC length!", c->name, c->hostname);
332 logger(LOG_ERR, "%s (%s) uses null digest!", c->name, c->hostname);
336 c->incompression = compression;
338 c->allow_request = CHALLENGE;
340 return send_challenge(c);
343 bool send_challenge(connection_t *c) {
344 /* CHECKME: what is most reasonable value for len? */
346 int len = RSA_size(c->rsa_key);
348 /* Allocate buffers for the challenge */
350 char buffer[2 * len + 1];
352 c->hischallenge = xrealloc(c->hischallenge, len);
354 /* Copy random data to the buffer */
356 if(1 != RAND_bytes((unsigned char *)c->hischallenge, len)) {
357 int err = ERR_get_error();
358 logger(LOG_ERR, "Failed to generate challenge (%s)", ERR_error_string(err, NULL));
359 return false; // Do not send predictable challenges, let connection attempt fail.
364 bin2hex(c->hischallenge, buffer, len);
365 buffer[len * 2] = '\0';
367 /* Send the challenge */
369 return send_request(c, "%d %s", CHALLENGE, buffer);
372 bool challenge_h(connection_t *c) {
373 char buffer[MAX_STRING_SIZE];
376 if(sscanf(c->buffer, "%*d " MAX_STRING, buffer) != 1) {
377 logger(LOG_ERR, "Got bad %s from %s (%s)", "CHALLENGE", c->name,
382 len = RSA_size(myself->connection->rsa_key);
384 /* Check if the length of the challenge is all right */
386 if(strlen(buffer) != (size_t)len * 2) {
387 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name,
388 c->hostname, "wrong challenge length");
392 /* Allocate buffers for the challenge */
394 c->mychallenge = xrealloc(c->mychallenge, len);
396 /* Convert the challenge from hexadecimal back to binary */
398 if(!hex2bin(buffer, c->mychallenge, len)) {
399 logger(LOG_ERR, "Got bad %s from %s(%s): %s", "CHALLENGE", c->name, c->hostname, "invalid challenge");
403 c->allow_request = CHAL_REPLY;
405 /* Rest is done by send_chal_reply() */
408 return send_chal_reply(c);
414 bool send_chal_reply(connection_t *c) {
415 char hash[EVP_MAX_MD_SIZE * 2 + 1];
418 /* Calculate the hash from the challenge we received */
420 ctx = EVP_MD_CTX_create();
426 if(!EVP_DigestInit(ctx, c->indigest)
427 || !EVP_DigestUpdate(ctx, c->mychallenge, RSA_size(myself->connection->rsa_key))
428 || !EVP_DigestFinal(ctx, (unsigned char *)hash, NULL)) {
429 EVP_MD_CTX_destroy(ctx);
430 logger(LOG_ERR, "Error during calculation of response for %s (%s): %s",
431 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
435 EVP_MD_CTX_destroy(ctx);
437 /* Convert the hash to a hexadecimal formatted string */
439 bin2hex(hash, hash, EVP_MD_size(c->indigest));
440 hash[EVP_MD_size(c->indigest) * 2] = '\0';
444 return send_request(c, "%d %s", CHAL_REPLY, hash);
447 bool chal_reply_h(connection_t *c) {
448 char hishash[MAX_STRING_SIZE];
449 char myhash[EVP_MAX_MD_SIZE];
452 if(sscanf(c->buffer, "%*d " MAX_STRING, hishash) != 1) {
453 logger(LOG_ERR, "Got bad %s from %s (%s)", "CHAL_REPLY", c->name,
458 /* Check if the length of the hash is all right */
460 if(strlen(hishash) != (size_t)EVP_MD_size(c->outdigest) * 2) {
461 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name,
462 c->hostname, "wrong challenge reply length");
466 /* Convert the hash to binary format */
468 if(!hex2bin(hishash, hishash, EVP_MD_size(c->outdigest))) {
469 logger(LOG_ERR, "Got bad %s from %s(%s): %s", "CHAL_REPLY", c->name, c->hostname, "invalid hash");
473 /* Calculate the hash from the challenge we sent */
475 ctx = EVP_MD_CTX_create();
481 if(!EVP_DigestInit(ctx, c->outdigest)
482 || !EVP_DigestUpdate(ctx, c->hischallenge, RSA_size(c->rsa_key))
483 || !EVP_DigestFinal(ctx, (unsigned char *)myhash, NULL)) {
484 EVP_MD_CTX_destroy(ctx);
485 logger(LOG_ERR, "Error during calculation of response from %s (%s): %s",
486 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
490 EVP_MD_CTX_destroy(ctx);
492 /* Verify the incoming hash with the calculated hash */
494 if(memcmp(hishash, myhash, EVP_MD_size(c->outdigest))) {
495 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name,
496 c->hostname, "wrong challenge reply");
498 ifdebug(SCARY_THINGS) {
499 bin2hex(myhash, hishash, SHA_DIGEST_LENGTH);
500 hishash[SHA_DIGEST_LENGTH * 2] = '\0';
501 logger(LOG_DEBUG, "Expected challenge reply: %s", hishash);
507 /* Identity has now been positively verified.
508 Send an acknowledgement with the rest of the information needed.
511 c->allow_request = ACK;
520 bool send_ack(connection_t *c) {
521 /* ACK message contains rest of the information the other end needs
522 to create node_t and edge_t structures. */
527 /* Estimate weight */
529 gettimeofday(&now, NULL);
530 c->estimated_weight = (now.tv_sec - c->start.tv_sec) * 1000 + (now.tv_usec - c->start.tv_usec) / 1000;
532 /* Check some options */
534 if((get_config_bool(lookup_config(c->config_tree, "IndirectData"), &choice) && choice) || myself->options & OPTION_INDIRECT) {
535 c->options |= OPTION_INDIRECT;
538 if((get_config_bool(lookup_config(c->config_tree, "TCPOnly"), &choice) && choice) || myself->options & OPTION_TCPONLY) {
539 c->options |= OPTION_TCPONLY | OPTION_INDIRECT;
542 if(myself->options & OPTION_PMTU_DISCOVERY && !(c->options & OPTION_TCPONLY)) {
543 c->options |= OPTION_PMTU_DISCOVERY;
546 choice = myself->options & OPTION_CLAMP_MSS;
547 get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice);
550 c->options |= OPTION_CLAMP_MSS;
553 get_config_int(lookup_config(c->config_tree, "Weight"), &c->estimated_weight);
555 return send_request(c, "%d %s %d %x", ACK, myport, c->estimated_weight, c->options);
558 static void send_everything(connection_t *c) {
559 avl_node_t *node, *node2;
564 /* Send all known subnets and edges */
567 for(node = myself->subnet_tree->head; node; node = node->next) {
569 send_add_subnet(c, s);
575 for(node = node_tree->head; node; node = node->next) {
578 for(node2 = n->subnet_tree->head; node2; node2 = node2->next) {
580 send_add_subnet(c, s);
583 for(node2 = n->edge_tree->head; node2; node2 = node2->next) {
590 bool ack_h(connection_t *c) {
591 char hisport[MAX_STRING_SIZE];
597 if(sscanf(c->buffer, "%*d " MAX_STRING " %d %x", hisport, &weight, &options) != 3) {
598 logger(LOG_ERR, "Got bad %s from %s (%s)", "ACK", c->name,
603 /* Check if we already have a node_t for him */
605 n = lookup_node(c->name);
609 n->name = xstrdup(c->name);
613 /* Oh dear, we already have a connection to this node. */
614 ifdebug(CONNECTIONS) logger(LOG_DEBUG, "Established a second connection with %s (%s), closing old connection",
615 n->name, n->hostname);
616 terminate_connection(n->connection, false);
617 /* Run graph algorithm to purge key and make sure up/down scripts are rerun with new IP addresses and stuff */
625 if(!(c->options & options & OPTION_PMTU_DISCOVERY)) {
626 c->options &= ~OPTION_PMTU_DISCOVERY;
627 options &= ~OPTION_PMTU_DISCOVERY;
630 c->options |= options;
632 if(get_config_int(lookup_config(c->config_tree, "PMTU"), &mtu) && mtu < n->mtu) {
636 if(get_config_int(lookup_config(config_tree, "PMTU"), &mtu) && mtu < n->mtu) {
640 if(get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice)) {
642 c->options |= OPTION_CLAMP_MSS;
644 c->options &= ~OPTION_CLAMP_MSS;
648 /* Activate this connection */
650 c->allow_request = ALL;
651 c->status.active = true;
653 ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Connection with %s (%s) activated", c->name,
656 /* Send him everything we know */
660 /* Create an edge_t for this connection */
662 c->edge = new_edge();
663 c->edge->from = myself;
665 sockaddrcpy(&c->edge->address, &c->address);
666 sockaddr_setport(&c->edge->address, hisport);
667 c->edge->weight = (weight + c->estimated_weight) / 2;
668 c->edge->connection = c;
669 c->edge->options = c->options;
673 /* Notify everyone of the new edge */
676 send_add_edge(c, c->edge);
678 send_add_edge(everyone, c->edge);
681 /* Run MST and SSSP algorithms */