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);
47 return send_request(c, "%d %s %d", ID, myself->connection->name,
48 myself->connection->protocol_version);
51 bool id_h(connection_t *c) {
52 char name[MAX_STRING_SIZE];
54 if(sscanf(c->buffer, "%*d " MAX_STRING " %d", name, &c->protocol_version) != 2) {
55 logger(LOG_ERR, "Got bad %s from %s (%s)", "ID", c->name,
60 /* Check if identity is a valid name */
63 logger(LOG_ERR, "Got bad %s from %s (%s): %s", "ID", c->name,
64 c->hostname, "invalid name");
68 /* If this is an outgoing connection, make sure we are connected to the right host */
71 if(strcmp(c->name, name)) {
72 logger(LOG_ERR, "Peer %s is %s instead of %s", c->hostname, name,
79 c->name = xstrdup(name);
82 /* Check if version matches */
84 if(c->protocol_version != myself->connection->protocol_version) {
85 logger(LOG_ERR, "Peer %s (%s) uses incompatible version %d",
86 c->name, c->hostname, c->protocol_version);
92 init_configuration(&c->config_tree);
93 c->allow_request = ACK;
98 init_configuration(&c->config_tree);
100 if(!read_connection_config(c)) {
101 logger(LOG_ERR, "Peer %s had unknown identity (%s)", c->hostname,
107 if(!read_rsa_public_key(c)) {
111 c->allow_request = METAKEY;
113 return send_metakey(c);
116 static uint64_t byte_budget(const EVP_CIPHER *cipher) {
117 /* Hopefully some failsafe way to calculate the maximum amount of bytes to
118 send/receive with a given cipher before we might run into birthday paradox
119 attacks. Because we might use different modes, the block size of the mode
120 might be 1 byte. In that case, use the IV length. Ensure the whole thing
121 is limited to what can be represented with a 64 bits integer.
124 int ivlen = EVP_CIPHER_iv_length(cipher);
125 int blklen = EVP_CIPHER_block_size(cipher);
126 int len = blklen > 1 ? blklen : ivlen > 1 ? ivlen : 8;
127 int bits = len * 4 - 1;
128 return bits < 64 ? UINT64_C(1) << bits : UINT64_MAX;
131 bool send_metakey(connection_t *c) {
134 int len = RSA_size(c->rsa_key);
136 /* Allocate buffers for the meta key */
138 char buffer[2 * len + 1];
140 c->outkey = xrealloc(c->outkey, len);
143 c->outctx = EVP_CIPHER_CTX_new();
148 /* Copy random data to the buffer */
150 if (1 != RAND_bytes((unsigned char *)c->outkey, len)) {
151 int err = ERR_get_error();
152 logger(LOG_ERR, "Failed to generate meta key (%s)", ERR_error_string(err, NULL));
157 /* The message we send must be smaller than the modulus of the RSA key.
158 By definition, for a key of k bits, the following formula holds:
160 2^(k-1) <= modulus < 2^(k)
162 Where ^ means "to the power of", not "xor".
163 This means that to be sure, we must choose our message < 2^(k-1).
164 This can be done by setting the most significant bit to zero.
167 c->outkey[0] &= 0x7F;
169 ifdebug(SCARY_THINGS) {
170 bin2hex(c->outkey, buffer, len);
171 buffer[len * 2] = '\0';
172 logger(LOG_DEBUG, "Generated random meta key (unencrypted): %s",
176 /* Encrypt the random data
178 We do not use one of the PKCS padding schemes here.
179 This is allowed, because we encrypt a totally random string
180 with a length equal to that of the modulus of the RSA key.
183 if(RSA_public_encrypt(len, (unsigned char *)c->outkey, (unsigned char *)buffer, c->rsa_key, RSA_NO_PADDING) != len) {
184 logger(LOG_ERR, "Error during encryption of meta key for %s (%s): %s",
185 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
189 /* Convert the encrypted random data to a hexadecimal formatted string */
191 bin2hex(buffer, buffer, len);
192 buffer[len * 2] = '\0';
194 /* Send the meta key */
196 x = send_request(c, "%d %d %d %d %d %s", METAKEY,
197 c->outcipher ? EVP_CIPHER_nid(c->outcipher) : 0,
198 c->outdigest ? EVP_MD_type(c->outdigest) : 0, c->outmaclength,
199 c->outcompression, buffer);
201 /* Further outgoing requests are encrypted with the key we just generated */
204 if(!EVP_EncryptInit(c->outctx, c->outcipher,
205 (unsigned char *)c->outkey + len - EVP_CIPHER_key_length(c->outcipher),
206 (unsigned char *)c->outkey + len - EVP_CIPHER_key_length(c->outcipher) -
207 EVP_CIPHER_iv_length(c->outcipher))) {
208 logger(LOG_ERR, "Error during initialisation of cipher for %s (%s): %s",
209 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
213 c->outbudget = byte_budget(c->outcipher);
214 c->status.encryptout = true;
220 bool metakey_h(connection_t *c) {
221 char buffer[MAX_STRING_SIZE];
222 int cipher, digest, maclength, compression;
225 if(sscanf(c->buffer, "%*d %d %d %d %d " MAX_STRING, &cipher, &digest, &maclength, &compression, buffer) != 5) {
226 logger(LOG_ERR, "Got bad %s from %s (%s)", "METAKEY", c->name,
231 len = RSA_size(myself->connection->rsa_key);
233 /* Check if the length of the meta key is all right */
235 if(strlen(buffer) != len * 2) {
236 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong keylength");
240 /* Allocate buffers for the meta key */
242 c->inkey = xrealloc(c->inkey, len);
245 c->inctx = EVP_CIPHER_CTX_new();
250 /* Convert the challenge from hexadecimal back to binary */
252 if(!hex2bin(buffer, buffer, len)) {
253 logger(LOG_ERR, "Got bad %s from %s(%s): %s", "METAKEY", c->name, c->hostname, "invalid key");
257 /* Decrypt the meta key */
259 if(RSA_private_decrypt(len, (unsigned char *)buffer, (unsigned char *)c->inkey, myself->connection->rsa_key, RSA_NO_PADDING) != len) { /* See challenge() */
260 logger(LOG_ERR, "Error during decryption of meta key for %s (%s): %s",
261 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
265 ifdebug(SCARY_THINGS) {
266 bin2hex(c->inkey, buffer, len);
267 buffer[len * 2] = '\0';
268 logger(LOG_DEBUG, "Received random meta key (unencrypted): %s", buffer);
271 /* All incoming requests will now be encrypted. */
273 /* Check and lookup cipher and digest algorithms */
276 c->incipher = EVP_get_cipherbynid(cipher);
279 logger(LOG_ERR, "%s (%s) uses unknown cipher!", c->name, c->hostname);
283 if(!EVP_DecryptInit(c->inctx, c->incipher,
284 (unsigned char *)c->inkey + len - EVP_CIPHER_key_length(c->incipher),
285 (unsigned char *)c->inkey + len - EVP_CIPHER_key_length(c->incipher) -
286 EVP_CIPHER_iv_length(c->incipher))) {
287 logger(LOG_ERR, "Error during initialisation of cipher from %s (%s): %s",
288 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
292 c->inbudget = byte_budget(c->incipher);
293 c->status.decryptin = true;
298 c->inmaclength = maclength;
301 c->indigest = EVP_get_digestbynid(digest);
304 logger(LOG_ERR, "Node %s (%s) uses unknown digest!", c->name, c->hostname);
308 if(c->inmaclength > EVP_MD_size(c->indigest) || c->inmaclength < 0) {
309 logger(LOG_ERR, "%s (%s) uses bogus MAC length!", c->name, c->hostname);
316 c->incompression = compression;
318 c->allow_request = CHALLENGE;
320 return send_challenge(c);
323 bool send_challenge(connection_t *c) {
324 /* CHECKME: what is most reasonable value for len? */
326 int len = RSA_size(c->rsa_key);
328 /* Allocate buffers for the challenge */
330 char buffer[2 * len + 1];
332 c->hischallenge = xrealloc(c->hischallenge, len);
334 /* Copy random data to the buffer */
336 if (1 != RAND_bytes((unsigned char *)c->hischallenge, len)) {
337 int err = ERR_get_error();
338 logger(LOG_ERR, "Failed to generate challenge (%s)", ERR_error_string(err, NULL));
339 return false; // Do not send predictable challenges, let connection attempt fail.
344 bin2hex(c->hischallenge, buffer, len);
345 buffer[len * 2] = '\0';
347 /* Send the challenge */
349 return send_request(c, "%d %s", CHALLENGE, buffer);
352 bool challenge_h(connection_t *c) {
353 char buffer[MAX_STRING_SIZE];
356 if(sscanf(c->buffer, "%*d " MAX_STRING, buffer) != 1) {
357 logger(LOG_ERR, "Got bad %s from %s (%s)", "CHALLENGE", c->name,
362 len = RSA_size(myself->connection->rsa_key);
364 /* Check if the length of the challenge is all right */
366 if(strlen(buffer) != len * 2) {
367 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name,
368 c->hostname, "wrong challenge length");
372 /* Allocate buffers for the challenge */
374 c->mychallenge = xrealloc(c->mychallenge, len);
376 /* Convert the challenge from hexadecimal back to binary */
378 if(!hex2bin(buffer, c->mychallenge, len)) {
379 logger(LOG_ERR, "Got bad %s from %s(%s): %s", "CHALLENGE", c->name, c->hostname, "invalid challenge");
383 c->allow_request = CHAL_REPLY;
385 /* Rest is done by send_chal_reply() */
387 return send_chal_reply(c);
390 bool send_chal_reply(connection_t *c) {
391 char hash[EVP_MAX_MD_SIZE * 2 + 1];
394 /* Calculate the hash from the challenge we received */
396 ctx = EVP_MD_CTX_create();
400 if(!EVP_DigestInit(ctx, c->indigest)
401 || !EVP_DigestUpdate(ctx, c->mychallenge, RSA_size(myself->connection->rsa_key))
402 || !EVP_DigestFinal(ctx, (unsigned char *)hash, NULL)) {
403 EVP_MD_CTX_destroy(ctx);
404 logger(LOG_ERR, "Error during calculation of response for %s (%s): %s",
405 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
409 EVP_MD_CTX_destroy(ctx);
411 /* Convert the hash to a hexadecimal formatted string */
413 bin2hex(hash, hash, EVP_MD_size(c->indigest));
414 hash[EVP_MD_size(c->indigest) * 2] = '\0';
418 return send_request(c, "%d %s", CHAL_REPLY, hash);
421 bool chal_reply_h(connection_t *c) {
422 char hishash[MAX_STRING_SIZE];
423 char myhash[EVP_MAX_MD_SIZE];
426 if(sscanf(c->buffer, "%*d " MAX_STRING, hishash) != 1) {
427 logger(LOG_ERR, "Got bad %s from %s (%s)", "CHAL_REPLY", c->name,
432 /* Check if the length of the hash is all right */
434 if(strlen(hishash) != EVP_MD_size(c->outdigest) * 2) {
435 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name,
436 c->hostname, "wrong challenge reply length");
440 /* Convert the hash to binary format */
442 if(!hex2bin(hishash, hishash, EVP_MD_size(c->outdigest))) {
443 logger(LOG_ERR, "Got bad %s from %s(%s): %s", "CHAL_REPLY", c->name, c->hostname, "invalid hash");
447 /* Calculate the hash from the challenge we sent */
449 ctx = EVP_MD_CTX_create();
453 if(!EVP_DigestInit(ctx, c->outdigest)
454 || !EVP_DigestUpdate(ctx, c->hischallenge, RSA_size(c->rsa_key))
455 || !EVP_DigestFinal(ctx, (unsigned char *)myhash, NULL)) {
456 EVP_MD_CTX_destroy(ctx);
457 logger(LOG_ERR, "Error during calculation of response from %s (%s): %s",
458 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
462 EVP_MD_CTX_destroy(ctx);
464 /* Verify the incoming hash with the calculated hash */
466 if(memcmp(hishash, myhash, EVP_MD_size(c->outdigest))) {
467 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name,
468 c->hostname, "wrong challenge reply");
470 ifdebug(SCARY_THINGS) {
471 bin2hex(myhash, hishash, SHA_DIGEST_LENGTH);
472 hishash[SHA_DIGEST_LENGTH * 2] = '\0';
473 logger(LOG_DEBUG, "Expected challenge reply: %s", hishash);
479 /* Identity has now been positively verified.
480 Send an acknowledgement with the rest of the information needed.
483 c->allow_request = ACK;
488 bool send_ack(connection_t *c) {
489 /* ACK message contains rest of the information the other end needs
490 to create node_t and edge_t structures. */
495 /* Estimate weight */
497 gettimeofday(&now, NULL);
498 c->estimated_weight = (now.tv_sec - c->start.tv_sec) * 1000 + (now.tv_usec - c->start.tv_usec) / 1000;
500 /* Check some options */
502 if((get_config_bool(lookup_config(c->config_tree, "IndirectData"), &choice) && choice) || myself->options & OPTION_INDIRECT)
503 c->options |= OPTION_INDIRECT;
505 if((get_config_bool(lookup_config(c->config_tree, "TCPOnly"), &choice) && choice) || myself->options & OPTION_TCPONLY)
506 c->options |= OPTION_TCPONLY | OPTION_INDIRECT;
508 if(myself->options & OPTION_PMTU_DISCOVERY)
509 c->options |= OPTION_PMTU_DISCOVERY;
511 choice = myself->options & OPTION_CLAMP_MSS;
512 get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice);
514 c->options |= OPTION_CLAMP_MSS;
516 get_config_int(lookup_config(c->config_tree, "Weight"), &c->estimated_weight);
518 return send_request(c, "%d %s %d %x", ACK, myport, c->estimated_weight, c->options);
521 static void send_everything(connection_t *c) {
522 avl_node_t *node, *node2;
527 /* Send all known subnets and edges */
530 for(node = myself->subnet_tree->head; node; node = node->next) {
532 send_add_subnet(c, s);
538 for(node = node_tree->head; node; node = node->next) {
541 for(node2 = n->subnet_tree->head; node2; node2 = node2->next) {
543 send_add_subnet(c, s);
546 for(node2 = n->edge_tree->head; node2; node2 = node2->next) {
553 bool ack_h(connection_t *c) {
554 char hisport[MAX_STRING_SIZE];
560 if(sscanf(c->buffer, "%*d " MAX_STRING " %d %x", hisport, &weight, &options) != 3) {
561 logger(LOG_ERR, "Got bad %s from %s (%s)", "ACK", c->name,
566 /* Check if we already have a node_t for him */
568 n = lookup_node(c->name);
572 n->name = xstrdup(c->name);
576 /* Oh dear, we already have a connection to this node. */
577 ifdebug(CONNECTIONS) logger(LOG_DEBUG, "Established a second connection with %s (%s), closing old connection",
578 n->name, n->hostname);
579 terminate_connection(n->connection, false);
580 /* Run graph algorithm to purge key and make sure up/down scripts are rerun with new IP addresses and stuff */
587 if(!(c->options & options & OPTION_PMTU_DISCOVERY)) {
588 c->options &= ~OPTION_PMTU_DISCOVERY;
589 options &= ~OPTION_PMTU_DISCOVERY;
591 c->options |= options;
593 if(get_config_int(lookup_config(c->config_tree, "PMTU"), &mtu) && mtu < n->mtu)
596 if(get_config_int(lookup_config(config_tree, "PMTU"), &mtu) && mtu < n->mtu)
599 if(get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice)) {
601 c->options |= OPTION_CLAMP_MSS;
603 c->options &= ~OPTION_CLAMP_MSS;
606 /* Activate this connection */
608 c->allow_request = ALL;
609 c->status.active = true;
611 ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Connection with %s (%s) activated", c->name,
614 /* Send him everything we know */
618 /* Create an edge_t for this connection */
620 c->edge = new_edge();
621 c->edge->from = myself;
623 sockaddrcpy(&c->edge->address, &c->address);
624 sockaddr_setport(&c->edge->address, hisport);
625 c->edge->weight = (weight + c->estimated_weight) / 2;
626 c->edge->connection = c;
627 c->edge->options = c->options;
631 /* Notify everyone of the new edge */
634 send_add_edge(c, c->edge);
636 send_add_edge(everyone, c->edge);
638 /* Run MST and SSSP algorithms */