2 protocol_auth.c -- handle the meta-protocol, authentication
3 Copyright (C) 1999-2005 Ivo Timmermans,
4 2000-2012 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"
42 static bool send_proxyrequest(connection_t *c) {
48 sockaddr2str(&c->address, &host, &port);
49 send_request(c, "CONNECT %s:%s HTTP/1.1\r\n\r", host, port);
55 if(c->address.sa.sa_family != AF_INET) {
56 logger(LOG_ERR, "Cannot connect to an IPv6 host through a SOCKS 4 proxy!");
59 char s4req[9 + (proxyuser ? strlen(proxyuser) : 0)];
62 memcpy(s4req + 2, &c->address.in.sin_port, 2);
63 memcpy(s4req + 4, &c->address.in.sin_addr, 4);
65 strcpy(s4req + 8, proxyuser);
66 s4req[sizeof s4req - 1] = 0;
68 return send_meta(c, s4req, sizeof s4req);
71 int len = 3 + 6 + (c->address.sa.sa_family == AF_INET ? 4 : 16);
74 len += 3 + strlen(proxyuser) + strlen(proxypass);
82 s5req[i++] = strlen(proxyuser);
83 strcpy(s5req + i, proxyuser);
84 i += strlen(proxyuser);
85 s5req[i++] = strlen(proxypass);
86 strcpy(s5req + i, proxypass);
87 i += strlen(proxypass);
95 if(c->address.sa.sa_family == AF_INET) {
97 memcpy(s5req + i, &c->address.in.sin_addr, 4);
99 memcpy(s5req + i, &c->address.in.sin_port, 2);
102 } else if(c->address.sa.sa_family == AF_INET6) {
104 memcpy(s5req + i, &c->address.in6.sin6_addr, 16);
106 memcpy(s5req + i, &c->address.in6.sin6_port, 2);
110 logger(LOG_ERR, "Address family %hx not supported for SOCKS 5 proxies!", c->address.sa.sa_family);
115 return send_meta(c, s5req, sizeof s5req);
118 logger(LOG_ERR, "Proxy type not implemented yet");
123 logger(LOG_ERR, "Unknown proxy type");
128 bool send_id(connection_t *c) {
130 if(!send_proxyrequest(c))
133 return send_request(c, "%d %s %d", ID, myself->connection->name,
134 myself->connection->protocol_version);
137 bool id_h(connection_t *c) {
138 char name[MAX_STRING_SIZE];
140 if(sscanf(c->buffer, "%*d " MAX_STRING " %d", name, &c->protocol_version) != 2) {
141 logger(LOG_ERR, "Got bad %s from %s (%s)", "ID", c->name,
146 /* Check if identity is a valid name */
148 if(!check_id(name)) {
149 logger(LOG_ERR, "Got bad %s from %s (%s): %s", "ID", c->name,
150 c->hostname, "invalid name");
154 /* If this is an outgoing connection, make sure we are connected to the right host */
157 if(strcmp(c->name, name)) {
158 logger(LOG_ERR, "Peer %s is %s instead of %s", c->hostname, name,
165 c->name = xstrdup(name);
168 /* Check if version matches */
170 if(c->protocol_version != myself->connection->protocol_version) {
171 logger(LOG_ERR, "Peer %s (%s) uses incompatible version %d",
172 c->name, c->hostname, c->protocol_version);
176 if(bypass_security) {
178 init_configuration(&c->config_tree);
179 c->allow_request = ACK;
183 if(!c->config_tree) {
184 init_configuration(&c->config_tree);
186 if(!read_connection_config(c)) {
187 logger(LOG_ERR, "Peer %s had unknown identity (%s)", c->hostname,
193 if(!read_rsa_public_key(c)) {
197 c->allow_request = METAKEY;
199 return send_metakey(c);
202 bool send_metakey(connection_t *c) {
205 int len = RSA_size(c->rsa_key);
207 /* Allocate buffers for the meta key */
209 char buffer[2 * len + 1];
211 c->outkey = xrealloc(c->outkey, len);
214 c->outctx = xmalloc_and_zero(sizeof(*c->outctx));
216 /* Copy random data to the buffer */
218 RAND_pseudo_bytes((unsigned char *)c->outkey, len);
220 /* The message we send must be smaller than the modulus of the RSA key.
221 By definition, for a key of k bits, the following formula holds:
223 2^(k-1) <= modulus < 2^(k)
225 Where ^ means "to the power of", not "xor".
226 This means that to be sure, we must choose our message < 2^(k-1).
227 This can be done by setting the most significant bit to zero.
230 c->outkey[0] &= 0x7F;
232 ifdebug(SCARY_THINGS) {
233 bin2hex(c->outkey, buffer, len);
234 buffer[len * 2] = '\0';
235 logger(LOG_DEBUG, "Generated random meta key (unencrypted): %s",
239 /* Encrypt the random data
241 We do not use one of the PKCS padding schemes here.
242 This is allowed, because we encrypt a totally random string
243 with a length equal to that of the modulus of the RSA key.
246 if(RSA_public_encrypt(len, (unsigned char *)c->outkey, (unsigned char *)buffer, c->rsa_key, RSA_NO_PADDING) != len) {
247 logger(LOG_ERR, "Error during encryption of meta key for %s (%s)",
248 c->name, c->hostname);
252 /* Convert the encrypted random data to a hexadecimal formatted string */
254 bin2hex(buffer, buffer, len);
255 buffer[len * 2] = '\0';
257 /* Send the meta key */
259 x = send_request(c, "%d %d %d %d %d %s", METAKEY,
260 c->outcipher ? c->outcipher->nid : 0,
261 c->outdigest ? c->outdigest->type : 0, c->outmaclength,
262 c->outcompression, buffer);
264 /* Further outgoing requests are encrypted with the key we just generated */
267 if(!EVP_EncryptInit(c->outctx, c->outcipher,
268 (unsigned char *)c->outkey + len - c->outcipher->key_len,
269 (unsigned char *)c->outkey + len - c->outcipher->key_len -
270 c->outcipher->iv_len)) {
271 logger(LOG_ERR, "Error during initialisation of cipher for %s (%s): %s",
272 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
276 c->status.encryptout = true;
282 bool metakey_h(connection_t *c) {
283 char buffer[MAX_STRING_SIZE];
284 int cipher, digest, maclength, compression;
287 if(sscanf(c->buffer, "%*d %d %d %d %d " MAX_STRING, &cipher, &digest, &maclength, &compression, buffer) != 5) {
288 logger(LOG_ERR, "Got bad %s from %s (%s)", "METAKEY", c->name,
293 len = RSA_size(myself->connection->rsa_key);
295 /* Check if the length of the meta key is all right */
297 if(strlen(buffer) != len * 2) {
298 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong keylength");
302 /* Allocate buffers for the meta key */
304 c->inkey = xrealloc(c->inkey, len);
307 c->inctx = xmalloc_and_zero(sizeof(*c->inctx));
309 /* Convert the challenge from hexadecimal back to binary */
311 hex2bin(buffer, buffer, len);
313 /* Decrypt the meta key */
315 if(RSA_private_decrypt(len, (unsigned char *)buffer, (unsigned char *)c->inkey, myself->connection->rsa_key, RSA_NO_PADDING) != len) { /* See challenge() */
316 logger(LOG_ERR, "Error during decryption of meta key for %s (%s)",
317 c->name, c->hostname);
321 ifdebug(SCARY_THINGS) {
322 bin2hex(c->inkey, buffer, len);
323 buffer[len * 2] = '\0';
324 logger(LOG_DEBUG, "Received random meta key (unencrypted): %s", buffer);
327 /* All incoming requests will now be encrypted. */
329 /* Check and lookup cipher and digest algorithms */
332 c->incipher = EVP_get_cipherbynid(cipher);
335 logger(LOG_ERR, "%s (%s) uses unknown cipher!", c->name, c->hostname);
339 if(!EVP_DecryptInit(c->inctx, c->incipher,
340 (unsigned char *)c->inkey + len - c->incipher->key_len,
341 (unsigned char *)c->inkey + len - c->incipher->key_len -
342 c->incipher->iv_len)) {
343 logger(LOG_ERR, "Error during initialisation of cipher from %s (%s): %s",
344 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
348 c->status.decryptin = true;
353 c->inmaclength = maclength;
356 c->indigest = EVP_get_digestbynid(digest);
359 logger(LOG_ERR, "Node %s (%s) uses unknown digest!", c->name, c->hostname);
363 if(c->inmaclength > c->indigest->md_size || c->inmaclength < 0) {
364 logger(LOG_ERR, "%s (%s) uses bogus MAC length!", c->name, c->hostname);
371 c->incompression = compression;
373 c->allow_request = CHALLENGE;
375 return send_challenge(c);
378 bool send_challenge(connection_t *c) {
379 /* CHECKME: what is most reasonable value for len? */
381 int len = RSA_size(c->rsa_key);
383 /* Allocate buffers for the challenge */
385 char buffer[2 * len + 1];
387 c->hischallenge = xrealloc(c->hischallenge, len);
389 /* Copy random data to the buffer */
391 RAND_pseudo_bytes((unsigned char *)c->hischallenge, len);
395 bin2hex(c->hischallenge, buffer, len);
396 buffer[len * 2] = '\0';
398 /* Send the challenge */
400 return send_request(c, "%d %s", CHALLENGE, buffer);
403 bool challenge_h(connection_t *c) {
404 char buffer[MAX_STRING_SIZE];
407 if(sscanf(c->buffer, "%*d " MAX_STRING, buffer) != 1) {
408 logger(LOG_ERR, "Got bad %s from %s (%s)", "CHALLENGE", c->name,
413 len = RSA_size(myself->connection->rsa_key);
415 /* Check if the length of the challenge is all right */
417 if(strlen(buffer) != len * 2) {
418 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name,
419 c->hostname, "wrong challenge length");
423 /* Allocate buffers for the challenge */
425 c->mychallenge = xrealloc(c->mychallenge, len);
427 /* Convert the challenge from hexadecimal back to binary */
429 hex2bin(buffer, c->mychallenge, len);
431 c->allow_request = CHAL_REPLY;
433 /* Rest is done by send_chal_reply() */
435 return send_chal_reply(c);
438 bool send_chal_reply(connection_t *c) {
439 char hash[EVP_MAX_MD_SIZE * 2 + 1];
442 /* Calculate the hash from the challenge we received */
444 if(!EVP_DigestInit(&ctx, c->indigest)
445 || !EVP_DigestUpdate(&ctx, c->mychallenge, RSA_size(myself->connection->rsa_key))
446 || !EVP_DigestFinal(&ctx, (unsigned char *)hash, NULL)) {
447 logger(LOG_ERR, "Error during calculation of response for %s (%s): %s",
448 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
452 /* Convert the hash to a hexadecimal formatted string */
454 bin2hex(hash, hash, c->indigest->md_size);
455 hash[c->indigest->md_size * 2] = '\0';
459 return send_request(c, "%d %s", CHAL_REPLY, hash);
462 bool chal_reply_h(connection_t *c) {
463 char hishash[MAX_STRING_SIZE];
464 char myhash[EVP_MAX_MD_SIZE];
467 if(sscanf(c->buffer, "%*d " MAX_STRING, hishash) != 1) {
468 logger(LOG_ERR, "Got bad %s from %s (%s)", "CHAL_REPLY", c->name,
473 /* Check if the length of the hash is all right */
475 if(strlen(hishash) != c->outdigest->md_size * 2) {
476 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name,
477 c->hostname, "wrong challenge reply length");
481 /* Convert the hash to binary format */
483 hex2bin(hishash, hishash, c->outdigest->md_size);
485 /* Calculate the hash from the challenge we sent */
487 if(!EVP_DigestInit(&ctx, c->outdigest)
488 || !EVP_DigestUpdate(&ctx, c->hischallenge, RSA_size(c->rsa_key))
489 || !EVP_DigestFinal(&ctx, (unsigned char *)myhash, NULL)) {
490 logger(LOG_ERR, "Error during calculation of response from %s (%s): %s",
491 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
495 /* Verify the incoming hash with the calculated hash */
497 if(memcmp(hishash, myhash, c->outdigest->md_size)) {
498 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name,
499 c->hostname, "wrong challenge reply");
501 ifdebug(SCARY_THINGS) {
502 bin2hex(myhash, hishash, SHA_DIGEST_LENGTH);
503 hishash[SHA_DIGEST_LENGTH * 2] = '\0';
504 logger(LOG_DEBUG, "Expected challenge reply: %s", hishash);
510 /* Identity has now been positively verified.
511 Send an acknowledgement with the rest of the information needed.
514 c->allow_request = ACK;
519 bool send_ack(connection_t *c) {
520 /* ACK message contains rest of the information the other end needs
521 to create node_t and edge_t structures. */
526 /* Estimate weight */
528 gettimeofday(&now, NULL);
529 c->estimated_weight = (now.tv_sec - c->start.tv_sec) * 1000 + (now.tv_usec - c->start.tv_usec) / 1000;
531 /* Check some options */
533 if((get_config_bool(lookup_config(c->config_tree, "IndirectData"), &choice) && choice) || myself->options & OPTION_INDIRECT)
534 c->options |= OPTION_INDIRECT;
536 if((get_config_bool(lookup_config(c->config_tree, "TCPOnly"), &choice) && choice) || myself->options & OPTION_TCPONLY)
537 c->options |= OPTION_TCPONLY | OPTION_INDIRECT;
539 if(myself->options & OPTION_PMTU_DISCOVERY)
540 c->options |= OPTION_PMTU_DISCOVERY;
542 choice = myself->options & OPTION_CLAMP_MSS;
543 get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice);
545 c->options |= OPTION_CLAMP_MSS;
547 get_config_int(lookup_config(c->config_tree, "Weight"), &c->estimated_weight);
549 return send_request(c, "%d %s %d %x", ACK, myport, c->estimated_weight, c->options);
552 static void send_everything(connection_t *c) {
553 avl_node_t *node, *node2;
558 /* Send all known subnets and edges */
561 for(node = myself->subnet_tree->head; node; node = node->next) {
563 send_add_subnet(c, s);
569 for(node = node_tree->head; node; node = node->next) {
572 for(node2 = n->subnet_tree->head; node2; node2 = node2->next) {
574 send_add_subnet(c, s);
577 for(node2 = n->edge_tree->head; node2; node2 = node2->next) {
584 bool ack_h(connection_t *c) {
585 char hisport[MAX_STRING_SIZE];
592 if(sscanf(c->buffer, "%*d " MAX_STRING " %d %x", hisport, &weight, &options) != 3) {
593 logger(LOG_ERR, "Got bad %s from %s (%s)", "ACK", c->name,
598 /* Check if we already have a node_t for him */
600 n = lookup_node(c->name);
604 n->name = xstrdup(c->name);
608 /* Oh dear, we already have a connection to this node. */
609 ifdebug(CONNECTIONS) logger(LOG_DEBUG, "Established a second connection with %s (%s), closing old connection",
610 n->name, n->hostname);
611 terminate_connection(n->connection, false);
612 /* Run graph algorithm to purge key and make sure up/down scripts are rerun with new IP addresses and stuff */
619 if(!(c->options & options & OPTION_PMTU_DISCOVERY)) {
620 c->options &= ~OPTION_PMTU_DISCOVERY;
621 options &= ~OPTION_PMTU_DISCOVERY;
623 c->options |= options;
625 if(get_config_int(lookup_config(c->config_tree, "PMTU"), &mtu) && mtu < n->mtu)
628 if(get_config_int(lookup_config(config_tree, "PMTU"), &mtu) && mtu < n->mtu)
631 if(get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice)) {
633 c->options |= OPTION_CLAMP_MSS;
635 c->options &= ~OPTION_CLAMP_MSS;
638 /* Activate this connection */
640 c->allow_request = ALL;
641 c->status.active = true;
643 ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Connection with %s (%s) activated", c->name,
646 /* Send him everything we know */
650 /* Create an edge_t for this connection */
652 c->edge = new_edge();
653 c->edge->from = myself;
655 sockaddr2str(&c->address, &hisaddress, NULL);
656 c->edge->address = str2sockaddr(hisaddress, hisport);
658 c->edge->weight = (weight + c->estimated_weight) / 2;
659 c->edge->connection = c;
660 c->edge->options = c->options;
664 /* Notify everyone of the new edge */
667 send_add_edge(c, c->edge);
669 send_add_edge(everyone, c->edge);
671 /* Run MST and SSSP algorithms */