2 protocol_auth.c -- handle the meta-protocol, authentication
3 Copyright (C) 1999-2005 Ivo Timmermans,
4 2000-2015 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)
45 if(!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,
80 c->name = xstrdup(name);
83 /* Check if version matches */
85 if(c->protocol_version != myself->connection->protocol_version) {
86 logger(LOG_ERR, "Peer %s (%s) uses incompatible version %d",
87 c->name, c->hostname, c->protocol_version);
93 init_configuration(&c->config_tree);
94 c->allow_request = ACK;
99 init_configuration(&c->config_tree);
101 if(!read_connection_config(c)) {
102 logger(LOG_ERR, "Peer %s had unknown identity (%s)", c->hostname,
108 if(!read_rsa_public_key(c)) {
112 c->allow_request = METAKEY;
114 return send_metakey(c);
117 bool send_metakey(connection_t *c) {
120 int len = RSA_size(c->rsa_key);
122 /* Allocate buffers for the meta key */
124 char buffer[2 * len + 1];
126 c->outkey = xrealloc(c->outkey, len);
129 c->outctx = xmalloc_and_zero(sizeof(*c->outctx));
131 /* Copy random data to the buffer */
133 if (1 != RAND_bytes((unsigned char *)c->outkey, len)) {
134 int err = ERR_get_error();
135 logger(LOG_ERR, "Failed to generate meta key (%s)", ERR_error_string(err, NULL));
140 /* The message we send must be smaller than the modulus of the RSA key.
141 By definition, for a key of k bits, the following formula holds:
143 2^(k-1) <= modulus < 2^(k)
145 Where ^ means "to the power of", not "xor".
146 This means that to be sure, we must choose our message < 2^(k-1).
147 This can be done by setting the most significant bit to zero.
150 c->outkey[0] &= 0x7F;
152 ifdebug(SCARY_THINGS) {
153 bin2hex(c->outkey, buffer, len);
154 buffer[len * 2] = '\0';
155 logger(LOG_DEBUG, "Generated random meta key (unencrypted): %s",
159 /* Encrypt the random data
161 We do not use one of the PKCS padding schemes here.
162 This is allowed, because we encrypt a totally random string
163 with a length equal to that of the modulus of the RSA key.
166 if(RSA_public_encrypt(len, (unsigned char *)c->outkey, (unsigned char *)buffer, c->rsa_key, RSA_NO_PADDING) != len) {
167 logger(LOG_ERR, "Error during encryption of meta key for %s (%s): %s",
168 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
172 /* Convert the encrypted random data to a hexadecimal formatted string */
174 bin2hex(buffer, buffer, len);
175 buffer[len * 2] = '\0';
177 /* Send the meta key */
179 x = send_request(c, "%d %d %d %d %d %s", METAKEY,
180 c->outcipher ? c->outcipher->nid : 0,
181 c->outdigest ? c->outdigest->type : 0, c->outmaclength,
182 c->outcompression, buffer);
184 /* Further outgoing requests are encrypted with the key we just generated */
187 if(!EVP_EncryptInit(c->outctx, c->outcipher,
188 (unsigned char *)c->outkey + len - c->outcipher->key_len,
189 (unsigned char *)c->outkey + len - c->outcipher->key_len -
190 c->outcipher->iv_len)) {
191 logger(LOG_ERR, "Error during initialisation of cipher for %s (%s): %s",
192 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
196 c->status.encryptout = true;
202 bool metakey_h(connection_t *c) {
203 char buffer[MAX_STRING_SIZE];
204 int cipher, digest, maclength, compression;
207 if(sscanf(c->buffer, "%*d %d %d %d %d " MAX_STRING, &cipher, &digest, &maclength, &compression, buffer) != 5) {
208 logger(LOG_ERR, "Got bad %s from %s (%s)", "METAKEY", c->name,
213 len = RSA_size(myself->connection->rsa_key);
215 /* Check if the length of the meta key is all right */
217 if(strlen(buffer) != len * 2) {
218 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong keylength");
222 /* Allocate buffers for the meta key */
224 c->inkey = xrealloc(c->inkey, len);
227 c->inctx = xmalloc_and_zero(sizeof(*c->inctx));
229 /* Convert the challenge from hexadecimal back to binary */
231 if(!hex2bin(buffer, buffer, len)) {
232 logger(LOG_ERR, "Got bad %s from %s(%s): %s", "METAKEY", c->name, c->hostname, "invalid key");
236 /* Decrypt the meta key */
238 if(RSA_private_decrypt(len, (unsigned char *)buffer, (unsigned char *)c->inkey, myself->connection->rsa_key, RSA_NO_PADDING) != len) { /* See challenge() */
239 logger(LOG_ERR, "Error during decryption of meta key for %s (%s): %s",
240 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
244 ifdebug(SCARY_THINGS) {
245 bin2hex(c->inkey, buffer, len);
246 buffer[len * 2] = '\0';
247 logger(LOG_DEBUG, "Received random meta key (unencrypted): %s", buffer);
250 /* All incoming requests will now be encrypted. */
252 /* Check and lookup cipher and digest algorithms */
255 c->incipher = EVP_get_cipherbynid(cipher);
258 logger(LOG_ERR, "%s (%s) uses unknown cipher!", c->name, c->hostname);
262 if(!EVP_DecryptInit(c->inctx, c->incipher,
263 (unsigned char *)c->inkey + len - c->incipher->key_len,
264 (unsigned char *)c->inkey + len - c->incipher->key_len -
265 c->incipher->iv_len)) {
266 logger(LOG_ERR, "Error during initialisation of cipher from %s (%s): %s",
267 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
271 c->status.decryptin = true;
276 c->inmaclength = maclength;
279 c->indigest = EVP_get_digestbynid(digest);
282 logger(LOG_ERR, "Node %s (%s) uses unknown digest!", c->name, c->hostname);
286 if(c->inmaclength > c->indigest->md_size || c->inmaclength < 0) {
287 logger(LOG_ERR, "%s (%s) uses bogus MAC length!", c->name, c->hostname);
294 c->incompression = compression;
296 c->allow_request = CHALLENGE;
298 return send_challenge(c);
301 bool send_challenge(connection_t *c) {
302 /* CHECKME: what is most reasonable value for len? */
304 int len = RSA_size(c->rsa_key);
306 /* Allocate buffers for the challenge */
308 char buffer[2 * len + 1];
310 c->hischallenge = xrealloc(c->hischallenge, len);
312 /* Copy random data to the buffer */
314 if (1 != RAND_bytes((unsigned char *)c->hischallenge, len)) {
315 int err = ERR_get_error();
316 logger(LOG_ERR, "Failed to generate challenge (%s)", ERR_error_string(err, NULL));
317 return false; // Do not send predictable challenges, let connection attempt fail.
322 bin2hex(c->hischallenge, buffer, len);
323 buffer[len * 2] = '\0';
325 /* Send the challenge */
327 return send_request(c, "%d %s", CHALLENGE, buffer);
330 bool challenge_h(connection_t *c) {
331 char buffer[MAX_STRING_SIZE];
334 if(sscanf(c->buffer, "%*d " MAX_STRING, buffer) != 1) {
335 logger(LOG_ERR, "Got bad %s from %s (%s)", "CHALLENGE", c->name,
340 len = RSA_size(myself->connection->rsa_key);
342 /* Check if the length of the challenge is all right */
344 if(strlen(buffer) != len * 2) {
345 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name,
346 c->hostname, "wrong challenge length");
350 /* Allocate buffers for the challenge */
352 c->mychallenge = xrealloc(c->mychallenge, len);
354 /* Convert the challenge from hexadecimal back to binary */
356 if(!hex2bin(buffer, c->mychallenge, len)) {
357 logger(LOG_ERR, "Got bad %s from %s(%s): %s", "CHALLENGE", c->name, c->hostname, "invalid challenge");
361 c->allow_request = CHAL_REPLY;
363 /* Rest is done by send_chal_reply() */
365 return send_chal_reply(c);
368 bool send_chal_reply(connection_t *c) {
369 char hash[EVP_MAX_MD_SIZE * 2 + 1];
372 /* Calculate the hash from the challenge we received */
374 if(!EVP_DigestInit(&ctx, c->indigest)
375 || !EVP_DigestUpdate(&ctx, c->mychallenge, RSA_size(myself->connection->rsa_key))
376 || !EVP_DigestFinal(&ctx, (unsigned char *)hash, NULL)) {
377 logger(LOG_ERR, "Error during calculation of response for %s (%s): %s",
378 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
382 /* Convert the hash to a hexadecimal formatted string */
384 bin2hex(hash, hash, c->indigest->md_size);
385 hash[c->indigest->md_size * 2] = '\0';
389 return send_request(c, "%d %s", CHAL_REPLY, hash);
392 bool chal_reply_h(connection_t *c) {
393 char hishash[MAX_STRING_SIZE];
394 char myhash[EVP_MAX_MD_SIZE];
397 if(sscanf(c->buffer, "%*d " MAX_STRING, hishash) != 1) {
398 logger(LOG_ERR, "Got bad %s from %s (%s)", "CHAL_REPLY", c->name,
403 /* Check if the length of the hash is all right */
405 if(strlen(hishash) != c->outdigest->md_size * 2) {
406 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name,
407 c->hostname, "wrong challenge reply length");
411 /* Convert the hash to binary format */
413 if(!hex2bin(hishash, hishash, c->outdigest->md_size)) {
414 logger(LOG_ERR, "Got bad %s from %s(%s): %s", "CHAL_REPLY", c->name, c->hostname, "invalid hash");
418 /* Calculate the hash from the challenge we sent */
420 if(!EVP_DigestInit(&ctx, c->outdigest)
421 || !EVP_DigestUpdate(&ctx, c->hischallenge, RSA_size(c->rsa_key))
422 || !EVP_DigestFinal(&ctx, (unsigned char *)myhash, NULL)) {
423 logger(LOG_ERR, "Error during calculation of response from %s (%s): %s",
424 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
428 /* Verify the incoming hash with the calculated hash */
430 if(memcmp(hishash, myhash, c->outdigest->md_size)) {
431 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name,
432 c->hostname, "wrong challenge reply");
434 ifdebug(SCARY_THINGS) {
435 bin2hex(myhash, hishash, SHA_DIGEST_LENGTH);
436 hishash[SHA_DIGEST_LENGTH * 2] = '\0';
437 logger(LOG_DEBUG, "Expected challenge reply: %s", hishash);
443 /* Identity has now been positively verified.
444 Send an acknowledgement with the rest of the information needed.
447 c->allow_request = ACK;
452 bool send_ack(connection_t *c) {
453 /* ACK message contains rest of the information the other end needs
454 to create node_t and edge_t structures. */
459 /* Estimate weight */
461 gettimeofday(&now, NULL);
462 c->estimated_weight = (now.tv_sec - c->start.tv_sec) * 1000 + (now.tv_usec - c->start.tv_usec) / 1000;
464 /* Check some options */
466 if((get_config_bool(lookup_config(c->config_tree, "IndirectData"), &choice) && choice) || myself->options & OPTION_INDIRECT)
467 c->options |= OPTION_INDIRECT;
469 if((get_config_bool(lookup_config(c->config_tree, "TCPOnly"), &choice) && choice) || myself->options & OPTION_TCPONLY)
470 c->options |= OPTION_TCPONLY | OPTION_INDIRECT;
472 if(myself->options & OPTION_PMTU_DISCOVERY)
473 c->options |= OPTION_PMTU_DISCOVERY;
475 choice = myself->options & OPTION_CLAMP_MSS;
476 get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice);
478 c->options |= OPTION_CLAMP_MSS;
480 get_config_int(lookup_config(c->config_tree, "Weight"), &c->estimated_weight);
482 return send_request(c, "%d %s %d %x", ACK, myport, c->estimated_weight, c->options);
485 static void send_everything(connection_t *c) {
486 avl_node_t *node, *node2;
491 /* Send all known subnets and edges */
494 for(node = myself->subnet_tree->head; node; node = node->next) {
496 send_add_subnet(c, s);
502 for(node = node_tree->head; node; node = node->next) {
505 for(node2 = n->subnet_tree->head; node2; node2 = node2->next) {
507 send_add_subnet(c, s);
510 for(node2 = n->edge_tree->head; node2; node2 = node2->next) {
517 bool ack_h(connection_t *c) {
518 char hisport[MAX_STRING_SIZE];
525 if(sscanf(c->buffer, "%*d " MAX_STRING " %d %x", hisport, &weight, &options) != 3) {
526 logger(LOG_ERR, "Got bad %s from %s (%s)", "ACK", c->name,
531 /* Check if we already have a node_t for him */
533 n = lookup_node(c->name);
537 n->name = xstrdup(c->name);
541 /* Oh dear, we already have a connection to this node. */
542 ifdebug(CONNECTIONS) logger(LOG_DEBUG, "Established a second connection with %s (%s), closing old connection",
543 n->name, n->hostname);
544 terminate_connection(n->connection, false);
545 /* Run graph algorithm to purge key and make sure up/down scripts are rerun with new IP addresses and stuff */
552 if(!(c->options & options & OPTION_PMTU_DISCOVERY)) {
553 c->options &= ~OPTION_PMTU_DISCOVERY;
554 options &= ~OPTION_PMTU_DISCOVERY;
556 c->options |= options;
558 if(get_config_int(lookup_config(c->config_tree, "PMTU"), &mtu) && mtu < n->mtu)
561 if(get_config_int(lookup_config(config_tree, "PMTU"), &mtu) && mtu < n->mtu)
564 if(get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice)) {
566 c->options |= OPTION_CLAMP_MSS;
568 c->options &= ~OPTION_CLAMP_MSS;
571 /* Activate this connection */
573 c->allow_request = ALL;
574 c->status.active = true;
576 ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Connection with %s (%s) activated", c->name,
579 /* Send him everything we know */
583 /* Create an edge_t for this connection */
585 c->edge = new_edge();
586 c->edge->from = myself;
588 sockaddr2str(&c->address, &hisaddress, NULL);
589 c->edge->address = str2sockaddr(hisaddress, hisport);
591 c->edge->weight = (weight + c->estimated_weight) / 2;
592 c->edge->connection = c;
593 c->edge->options = c->options;
597 /* Notify everyone of the new edge */
600 send_add_edge(c, c->edge);
602 send_add_edge(everyone, c->edge);
604 /* Run MST and SSSP algorithms */