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 */
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;
102 if(!c->config_tree) {
103 init_configuration(&c->config_tree);
105 if(!read_connection_config(c)) {
106 logger(LOG_ERR, "Peer %s had unknown identity (%s)", c->hostname,
112 if(!read_rsa_public_key(c)) {
116 c->allow_request = METAKEY;
118 return send_metakey(c);
121 static uint64_t byte_budget(const EVP_CIPHER *cipher) {
122 /* Hopefully some failsafe way to calculate the maximum amount of bytes to
123 send/receive with a given cipher before we might run into birthday paradox
124 attacks. Because we might use different modes, the block size of the mode
125 might be 1 byte. In that case, use the IV length. Ensure the whole thing
126 is limited to what can be represented with a 64 bits integer.
129 int ivlen = EVP_CIPHER_iv_length(cipher);
130 int blklen = EVP_CIPHER_block_size(cipher);
131 int len = blklen > 1 ? blklen : ivlen > 1 ? ivlen : 8;
132 int bits = len * 4 - 1;
133 return bits < 64 ? UINT64_C(1) << bits : UINT64_MAX;
136 bool send_metakey(connection_t *c) {
139 int len = RSA_size(c->rsa_key);
141 /* Allocate buffers for the meta key */
143 char buffer[2 * len + 1];
145 c->outkey = xrealloc(c->outkey, len);
148 c->outctx = EVP_CIPHER_CTX_new();
155 /* Copy random data to the buffer */
157 if(1 != RAND_bytes((unsigned char *)c->outkey, len)) {
158 int err = ERR_get_error();
159 logger(LOG_ERR, "Failed to generate meta key (%s)", ERR_error_string(err, NULL));
164 /* The message we send must be smaller than the modulus of the RSA key.
165 By definition, for a key of k bits, the following formula holds:
167 2^(k-1) <= modulus < 2^(k)
169 Where ^ means "to the power of", not "xor".
170 This means that to be sure, we must choose our message < 2^(k-1).
171 This can be done by setting the most significant bit to zero.
174 c->outkey[0] &= 0x7F;
176 ifdebug(SCARY_THINGS) {
177 bin2hex(c->outkey, buffer, len);
178 buffer[len * 2] = '\0';
179 logger(LOG_DEBUG, "Generated random meta key (unencrypted): %s",
183 /* Encrypt the random data
185 We do not use one of the PKCS padding schemes here.
186 This is allowed, because we encrypt a totally random string
187 with a length equal to that of the modulus of the RSA key.
190 if(RSA_public_encrypt(len, (unsigned char *)c->outkey, (unsigned char *)buffer, c->rsa_key, RSA_NO_PADDING) != len) {
191 logger(LOG_ERR, "Error during encryption of meta key for %s (%s): %s",
192 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
196 /* Convert the encrypted random data to a hexadecimal formatted string */
198 bin2hex(buffer, buffer, len);
199 buffer[len * 2] = '\0';
201 /* Send the meta key */
203 x = send_request(c, "%d %d %d %d %d %s", METAKEY,
204 c->outcipher ? EVP_CIPHER_nid(c->outcipher) : 0,
205 c->outdigest ? EVP_MD_type(c->outdigest) : 0, c->outmaclength,
206 c->outcompression, buffer);
208 /* Further outgoing requests are encrypted with the key we just generated */
211 if(!EVP_EncryptInit(c->outctx, c->outcipher,
212 (unsigned char *)c->outkey + len - EVP_CIPHER_key_length(c->outcipher),
213 (unsigned char *)c->outkey + len - EVP_CIPHER_key_length(c->outcipher) -
214 EVP_CIPHER_iv_length(c->outcipher))) {
215 logger(LOG_ERR, "Error during initialisation of cipher for %s (%s): %s",
216 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
220 c->outbudget = byte_budget(c->outcipher);
221 c->status.encryptout = true;
227 bool metakey_h(connection_t *c) {
228 char buffer[MAX_STRING_SIZE];
229 int cipher, digest, maclength, compression;
232 if(sscanf(c->buffer, "%*d %d %d %d %d " MAX_STRING, &cipher, &digest, &maclength, &compression, buffer) != 5) {
233 logger(LOG_ERR, "Got bad %s from %s (%s)", "METAKEY", c->name,
238 len = RSA_size(myself->connection->rsa_key);
240 /* Check if the length of the meta key is all right */
242 if(strlen(buffer) != (size_t)len * 2) {
243 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong keylength");
247 /* Allocate buffers for the meta key */
249 c->inkey = xrealloc(c->inkey, len);
252 c->inctx = EVP_CIPHER_CTX_new();
259 /* Convert the challenge from hexadecimal back to binary */
261 if(!hex2bin(buffer, buffer, len)) {
262 logger(LOG_ERR, "Got bad %s from %s(%s): %s", "METAKEY", c->name, c->hostname, "invalid key");
266 /* Decrypt the meta key */
268 if(RSA_private_decrypt(len, (unsigned char *)buffer, (unsigned char *)c->inkey, myself->connection->rsa_key, RSA_NO_PADDING) != len) { /* See challenge() */
269 logger(LOG_ERR, "Error during decryption of meta key for %s (%s): %s",
270 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
274 ifdebug(SCARY_THINGS) {
275 bin2hex(c->inkey, buffer, len);
276 buffer[len * 2] = '\0';
277 logger(LOG_DEBUG, "Received random meta key (unencrypted): %s", buffer);
280 /* All incoming requests will now be encrypted. */
282 /* Check and lookup cipher and digest algorithms */
285 c->incipher = EVP_get_cipherbynid(cipher);
288 logger(LOG_ERR, "%s (%s) uses unknown cipher!", c->name, c->hostname);
292 if(!EVP_DecryptInit(c->inctx, c->incipher,
293 (unsigned char *)c->inkey + len - EVP_CIPHER_key_length(c->incipher),
294 (unsigned char *)c->inkey + len - EVP_CIPHER_key_length(c->incipher) -
295 EVP_CIPHER_iv_length(c->incipher))) {
296 logger(LOG_ERR, "Error during initialisation of cipher from %s (%s): %s",
297 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
301 c->inbudget = byte_budget(c->incipher);
302 c->status.decryptin = true;
307 c->inmaclength = maclength;
310 c->indigest = EVP_get_digestbynid(digest);
313 logger(LOG_ERR, "Node %s (%s) uses unknown digest!", c->name, c->hostname);
317 if(c->inmaclength > EVP_MD_size(c->indigest) || c->inmaclength < 0) {
318 logger(LOG_ERR, "%s (%s) uses bogus MAC length!", c->name, c->hostname);
325 c->incompression = compression;
327 c->allow_request = CHALLENGE;
329 return send_challenge(c);
332 bool send_challenge(connection_t *c) {
333 /* CHECKME: what is most reasonable value for len? */
335 int len = RSA_size(c->rsa_key);
337 /* Allocate buffers for the challenge */
339 char buffer[2 * len + 1];
341 c->hischallenge = xrealloc(c->hischallenge, len);
343 /* Copy random data to the buffer */
345 if(1 != RAND_bytes((unsigned char *)c->hischallenge, len)) {
346 int err = ERR_get_error();
347 logger(LOG_ERR, "Failed to generate challenge (%s)", ERR_error_string(err, NULL));
348 return false; // Do not send predictable challenges, let connection attempt fail.
353 bin2hex(c->hischallenge, buffer, len);
354 buffer[len * 2] = '\0';
356 /* Send the challenge */
358 return send_request(c, "%d %s", CHALLENGE, buffer);
361 bool challenge_h(connection_t *c) {
362 char buffer[MAX_STRING_SIZE];
365 if(sscanf(c->buffer, "%*d " MAX_STRING, buffer) != 1) {
366 logger(LOG_ERR, "Got bad %s from %s (%s)", "CHALLENGE", c->name,
371 len = RSA_size(myself->connection->rsa_key);
373 /* Check if the length of the challenge is all right */
375 if(strlen(buffer) != (size_t)len * 2) {
376 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name,
377 c->hostname, "wrong challenge length");
381 /* Allocate buffers for the challenge */
383 c->mychallenge = xrealloc(c->mychallenge, len);
385 /* Convert the challenge from hexadecimal back to binary */
387 if(!hex2bin(buffer, c->mychallenge, len)) {
388 logger(LOG_ERR, "Got bad %s from %s(%s): %s", "CHALLENGE", c->name, c->hostname, "invalid challenge");
392 c->allow_request = CHAL_REPLY;
394 /* Rest is done by send_chal_reply() */
396 return send_chal_reply(c);
399 bool send_chal_reply(connection_t *c) {
400 char hash[EVP_MAX_MD_SIZE * 2 + 1];
403 /* Calculate the hash from the challenge we received */
405 ctx = EVP_MD_CTX_create();
411 if(!EVP_DigestInit(ctx, c->indigest)
412 || !EVP_DigestUpdate(ctx, c->mychallenge, RSA_size(myself->connection->rsa_key))
413 || !EVP_DigestFinal(ctx, (unsigned char *)hash, NULL)) {
414 EVP_MD_CTX_destroy(ctx);
415 logger(LOG_ERR, "Error during calculation of response for %s (%s): %s",
416 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
420 EVP_MD_CTX_destroy(ctx);
422 /* Convert the hash to a hexadecimal formatted string */
424 bin2hex(hash, hash, EVP_MD_size(c->indigest));
425 hash[EVP_MD_size(c->indigest) * 2] = '\0';
429 return send_request(c, "%d %s", CHAL_REPLY, hash);
432 bool chal_reply_h(connection_t *c) {
433 char hishash[MAX_STRING_SIZE];
434 char myhash[EVP_MAX_MD_SIZE];
437 if(sscanf(c->buffer, "%*d " MAX_STRING, hishash) != 1) {
438 logger(LOG_ERR, "Got bad %s from %s (%s)", "CHAL_REPLY", c->name,
443 /* Check if the length of the hash is all right */
445 if(strlen(hishash) != (size_t)EVP_MD_size(c->outdigest) * 2) {
446 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name,
447 c->hostname, "wrong challenge reply length");
451 /* Convert the hash to binary format */
453 if(!hex2bin(hishash, hishash, EVP_MD_size(c->outdigest))) {
454 logger(LOG_ERR, "Got bad %s from %s(%s): %s", "CHAL_REPLY", c->name, c->hostname, "invalid hash");
458 /* Calculate the hash from the challenge we sent */
460 ctx = EVP_MD_CTX_create();
466 if(!EVP_DigestInit(ctx, c->outdigest)
467 || !EVP_DigestUpdate(ctx, c->hischallenge, RSA_size(c->rsa_key))
468 || !EVP_DigestFinal(ctx, (unsigned char *)myhash, NULL)) {
469 EVP_MD_CTX_destroy(ctx);
470 logger(LOG_ERR, "Error during calculation of response from %s (%s): %s",
471 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
475 EVP_MD_CTX_destroy(ctx);
477 /* Verify the incoming hash with the calculated hash */
479 if(memcmp(hishash, myhash, EVP_MD_size(c->outdigest))) {
480 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name,
481 c->hostname, "wrong challenge reply");
483 ifdebug(SCARY_THINGS) {
484 bin2hex(myhash, hishash, SHA_DIGEST_LENGTH);
485 hishash[SHA_DIGEST_LENGTH * 2] = '\0';
486 logger(LOG_DEBUG, "Expected challenge reply: %s", hishash);
492 /* Identity has now been positively verified.
493 Send an acknowledgement with the rest of the information needed.
496 c->allow_request = ACK;
501 bool send_ack(connection_t *c) {
502 /* ACK message contains rest of the information the other end needs
503 to create node_t and edge_t structures. */
508 /* Estimate weight */
510 gettimeofday(&now, NULL);
511 c->estimated_weight = (now.tv_sec - c->start.tv_sec) * 1000 + (now.tv_usec - c->start.tv_usec) / 1000;
513 /* Check some options */
515 if((get_config_bool(lookup_config(c->config_tree, "IndirectData"), &choice) && choice) || myself->options & OPTION_INDIRECT) {
516 c->options |= OPTION_INDIRECT;
519 if((get_config_bool(lookup_config(c->config_tree, "TCPOnly"), &choice) && choice) || myself->options & OPTION_TCPONLY) {
520 c->options |= OPTION_TCPONLY | OPTION_INDIRECT;
523 if(myself->options & OPTION_PMTU_DISCOVERY && !(c->options & OPTION_TCPONLY)) {
524 c->options |= OPTION_PMTU_DISCOVERY;
527 choice = myself->options & OPTION_CLAMP_MSS;
528 get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice);
531 c->options |= OPTION_CLAMP_MSS;
534 get_config_int(lookup_config(c->config_tree, "Weight"), &c->estimated_weight);
536 return send_request(c, "%d %s %d %x", ACK, myport, c->estimated_weight, c->options);
539 static void send_everything(connection_t *c) {
540 avl_node_t *node, *node2;
545 /* Send all known subnets and edges */
548 for(node = myself->subnet_tree->head; node; node = node->next) {
550 send_add_subnet(c, s);
556 for(node = node_tree->head; node; node = node->next) {
559 for(node2 = n->subnet_tree->head; node2; node2 = node2->next) {
561 send_add_subnet(c, s);
564 for(node2 = n->edge_tree->head; node2; node2 = node2->next) {
571 bool ack_h(connection_t *c) {
572 char hisport[MAX_STRING_SIZE];
578 if(sscanf(c->buffer, "%*d " MAX_STRING " %d %x", hisport, &weight, &options) != 3) {
579 logger(LOG_ERR, "Got bad %s from %s (%s)", "ACK", c->name,
584 /* Check if we already have a node_t for him */
586 n = lookup_node(c->name);
590 n->name = xstrdup(c->name);
594 /* Oh dear, we already have a connection to this node. */
595 ifdebug(CONNECTIONS) logger(LOG_DEBUG, "Established a second connection with %s (%s), closing old connection",
596 n->name, n->hostname);
597 terminate_connection(n->connection, false);
598 /* Run graph algorithm to purge key and make sure up/down scripts are rerun with new IP addresses and stuff */
606 if(!(c->options & options & OPTION_PMTU_DISCOVERY)) {
607 c->options &= ~OPTION_PMTU_DISCOVERY;
608 options &= ~OPTION_PMTU_DISCOVERY;
611 c->options |= options;
613 if(get_config_int(lookup_config(c->config_tree, "PMTU"), &mtu) && mtu < n->mtu) {
617 if(get_config_int(lookup_config(config_tree, "PMTU"), &mtu) && mtu < n->mtu) {
621 if(get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice)) {
623 c->options |= OPTION_CLAMP_MSS;
625 c->options &= ~OPTION_CLAMP_MSS;
629 /* Activate this connection */
631 c->allow_request = ALL;
632 c->status.active = true;
634 ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Connection with %s (%s) activated", c->name,
637 /* Send him everything we know */
641 /* Create an edge_t for this connection */
643 c->edge = new_edge();
644 c->edge->from = myself;
646 sockaddrcpy(&c->edge->address, &c->address);
647 sockaddr_setport(&c->edge->address, hisport);
648 c->edge->weight = (weight + c->estimated_weight) / 2;
649 c->edge->connection = c;
650 c->edge->options = c->options;
654 /* Notify everyone of the new edge */
657 send_add_edge(c, c->edge);
659 send_add_edge(everyone, c->edge);
662 /* Run MST and SSSP algorithms */