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");
121 logger(LOG_ERR, "Unknown proxy type");
126 bool send_id(connection_t *c) {
128 if(!send_proxyrequest(c))
131 return send_request(c, "%d %s %d", ID, myself->connection->name,
132 myself->connection->protocol_version);
135 bool id_h(connection_t *c) {
136 char name[MAX_STRING_SIZE];
138 if(sscanf(c->buffer, "%*d " MAX_STRING " %d", name, &c->protocol_version) != 2) {
139 logger(LOG_ERR, "Got bad %s from %s (%s)", "ID", c->name,
144 /* Check if identity is a valid name */
146 if(!check_id(name)) {
147 logger(LOG_ERR, "Got bad %s from %s (%s): %s", "ID", c->name,
148 c->hostname, "invalid name");
152 /* If this is an outgoing connection, make sure we are connected to the right host */
155 if(strcmp(c->name, name)) {
156 logger(LOG_ERR, "Peer %s is %s instead of %s", c->hostname, name,
163 c->name = xstrdup(name);
166 /* Check if version matches */
168 if(c->protocol_version != myself->connection->protocol_version) {
169 logger(LOG_ERR, "Peer %s (%s) uses incompatible version %d",
170 c->name, c->hostname, c->protocol_version);
174 if(bypass_security) {
176 init_configuration(&c->config_tree);
177 c->allow_request = ACK;
181 if(!c->config_tree) {
182 init_configuration(&c->config_tree);
184 if(!read_connection_config(c)) {
185 logger(LOG_ERR, "Peer %s had unknown identity (%s)", c->hostname,
191 if(!read_rsa_public_key(c)) {
195 c->allow_request = METAKEY;
197 return send_metakey(c);
200 bool send_metakey(connection_t *c) {
203 int len = RSA_size(c->rsa_key);
205 /* Allocate buffers for the meta key */
207 char buffer[2 * len + 1];
209 c->outkey = xrealloc(c->outkey, len);
212 c->outctx = xmalloc_and_zero(sizeof(*c->outctx));
214 /* Copy random data to the buffer */
216 RAND_pseudo_bytes((unsigned char *)c->outkey, len);
218 /* The message we send must be smaller than the modulus of the RSA key.
219 By definition, for a key of k bits, the following formula holds:
221 2^(k-1) <= modulus < 2^(k)
223 Where ^ means "to the power of", not "xor".
224 This means that to be sure, we must choose our message < 2^(k-1).
225 This can be done by setting the most significant bit to zero.
228 c->outkey[0] &= 0x7F;
230 ifdebug(SCARY_THINGS) {
231 bin2hex(c->outkey, buffer, len);
232 buffer[len * 2] = '\0';
233 logger(LOG_DEBUG, "Generated random meta key (unencrypted): %s",
237 /* Encrypt the random data
239 We do not use one of the PKCS padding schemes here.
240 This is allowed, because we encrypt a totally random string
241 with a length equal to that of the modulus of the RSA key.
244 if(RSA_public_encrypt(len, (unsigned char *)c->outkey, (unsigned char *)buffer, c->rsa_key, RSA_NO_PADDING) != len) {
245 logger(LOG_ERR, "Error during encryption of meta key for %s (%s)",
246 c->name, c->hostname);
250 /* Convert the encrypted random data to a hexadecimal formatted string */
252 bin2hex(buffer, buffer, len);
253 buffer[len * 2] = '\0';
255 /* Send the meta key */
257 x = send_request(c, "%d %d %d %d %d %s", METAKEY,
258 c->outcipher ? c->outcipher->nid : 0,
259 c->outdigest ? c->outdigest->type : 0, c->outmaclength,
260 c->outcompression, buffer);
262 /* Further outgoing requests are encrypted with the key we just generated */
265 if(!EVP_EncryptInit(c->outctx, c->outcipher,
266 (unsigned char *)c->outkey + len - c->outcipher->key_len,
267 (unsigned char *)c->outkey + len - c->outcipher->key_len -
268 c->outcipher->iv_len)) {
269 logger(LOG_ERR, "Error during initialisation of cipher for %s (%s): %s",
270 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
274 c->status.encryptout = true;
280 bool metakey_h(connection_t *c) {
281 char buffer[MAX_STRING_SIZE];
282 int cipher, digest, maclength, compression;
285 if(sscanf(c->buffer, "%*d %d %d %d %d " MAX_STRING, &cipher, &digest, &maclength, &compression, buffer) != 5) {
286 logger(LOG_ERR, "Got bad %s from %s (%s)", "METAKEY", c->name,
291 len = RSA_size(myself->connection->rsa_key);
293 /* Check if the length of the meta key is all right */
295 if(strlen(buffer) != len * 2) {
296 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong keylength");
300 /* Allocate buffers for the meta key */
302 c->inkey = xrealloc(c->inkey, len);
305 c->inctx = xmalloc_and_zero(sizeof(*c->inctx));
307 /* Convert the challenge from hexadecimal back to binary */
309 hex2bin(buffer, buffer, len);
311 /* Decrypt the meta key */
313 if(RSA_private_decrypt(len, (unsigned char *)buffer, (unsigned char *)c->inkey, myself->connection->rsa_key, RSA_NO_PADDING) != len) { /* See challenge() */
314 logger(LOG_ERR, "Error during decryption of meta key for %s (%s)",
315 c->name, c->hostname);
319 ifdebug(SCARY_THINGS) {
320 bin2hex(c->inkey, buffer, len);
321 buffer[len * 2] = '\0';
322 logger(LOG_DEBUG, "Received random meta key (unencrypted): %s", buffer);
325 /* All incoming requests will now be encrypted. */
327 /* Check and lookup cipher and digest algorithms */
330 c->incipher = EVP_get_cipherbynid(cipher);
333 logger(LOG_ERR, "%s (%s) uses unknown cipher!", c->name, c->hostname);
337 if(!EVP_DecryptInit(c->inctx, c->incipher,
338 (unsigned char *)c->inkey + len - c->incipher->key_len,
339 (unsigned char *)c->inkey + len - c->incipher->key_len -
340 c->incipher->iv_len)) {
341 logger(LOG_ERR, "Error during initialisation of cipher from %s (%s): %s",
342 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
346 c->status.decryptin = true;
351 c->inmaclength = maclength;
354 c->indigest = EVP_get_digestbynid(digest);
357 logger(LOG_ERR, "Node %s (%s) uses unknown digest!", c->name, c->hostname);
361 if(c->inmaclength > c->indigest->md_size || c->inmaclength < 0) {
362 logger(LOG_ERR, "%s (%s) uses bogus MAC length!", c->name, c->hostname);
369 c->incompression = compression;
371 c->allow_request = CHALLENGE;
373 return send_challenge(c);
376 bool send_challenge(connection_t *c) {
377 /* CHECKME: what is most reasonable value for len? */
379 int len = RSA_size(c->rsa_key);
381 /* Allocate buffers for the challenge */
383 char buffer[2 * len + 1];
385 c->hischallenge = xrealloc(c->hischallenge, len);
387 /* Copy random data to the buffer */
389 RAND_pseudo_bytes((unsigned char *)c->hischallenge, len);
393 bin2hex(c->hischallenge, buffer, len);
394 buffer[len * 2] = '\0';
396 /* Send the challenge */
398 return send_request(c, "%d %s", CHALLENGE, buffer);
401 bool challenge_h(connection_t *c) {
402 char buffer[MAX_STRING_SIZE];
405 if(sscanf(c->buffer, "%*d " MAX_STRING, buffer) != 1) {
406 logger(LOG_ERR, "Got bad %s from %s (%s)", "CHALLENGE", c->name,
411 len = RSA_size(myself->connection->rsa_key);
413 /* Check if the length of the challenge is all right */
415 if(strlen(buffer) != len * 2) {
416 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name,
417 c->hostname, "wrong challenge length");
421 /* Allocate buffers for the challenge */
423 c->mychallenge = xrealloc(c->mychallenge, len);
425 /* Convert the challenge from hexadecimal back to binary */
427 hex2bin(buffer, c->mychallenge, len);
429 c->allow_request = CHAL_REPLY;
431 /* Rest is done by send_chal_reply() */
433 return send_chal_reply(c);
436 bool send_chal_reply(connection_t *c) {
437 char hash[EVP_MAX_MD_SIZE * 2 + 1];
440 /* Calculate the hash from the challenge we received */
442 if(!EVP_DigestInit(&ctx, c->indigest)
443 || !EVP_DigestUpdate(&ctx, c->mychallenge, RSA_size(myself->connection->rsa_key))
444 || !EVP_DigestFinal(&ctx, (unsigned char *)hash, NULL)) {
445 logger(LOG_ERR, "Error during calculation of response for %s (%s): %s",
446 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
450 /* Convert the hash to a hexadecimal formatted string */
452 bin2hex(hash, hash, c->indigest->md_size);
453 hash[c->indigest->md_size * 2] = '\0';
457 return send_request(c, "%d %s", CHAL_REPLY, hash);
460 bool chal_reply_h(connection_t *c) {
461 char hishash[MAX_STRING_SIZE];
462 char myhash[EVP_MAX_MD_SIZE];
465 if(sscanf(c->buffer, "%*d " MAX_STRING, hishash) != 1) {
466 logger(LOG_ERR, "Got bad %s from %s (%s)", "CHAL_REPLY", c->name,
471 /* Check if the length of the hash is all right */
473 if(strlen(hishash) != c->outdigest->md_size * 2) {
474 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name,
475 c->hostname, "wrong challenge reply length");
479 /* Convert the hash to binary format */
481 hex2bin(hishash, hishash, c->outdigest->md_size);
483 /* Calculate the hash from the challenge we sent */
485 if(!EVP_DigestInit(&ctx, c->outdigest)
486 || !EVP_DigestUpdate(&ctx, c->hischallenge, RSA_size(c->rsa_key))
487 || !EVP_DigestFinal(&ctx, (unsigned char *)myhash, NULL)) {
488 logger(LOG_ERR, "Error during calculation of response from %s (%s): %s",
489 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
493 /* Verify the incoming hash with the calculated hash */
495 if(memcmp(hishash, myhash, c->outdigest->md_size)) {
496 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name,
497 c->hostname, "wrong challenge reply");
499 ifdebug(SCARY_THINGS) {
500 bin2hex(myhash, hishash, SHA_DIGEST_LENGTH);
501 hishash[SHA_DIGEST_LENGTH * 2] = '\0';
502 logger(LOG_DEBUG, "Expected challenge reply: %s", hishash);
508 /* Identity has now been positively verified.
509 Send an acknowledgement with the rest of the information needed.
512 c->allow_request = ACK;
517 bool send_ack(connection_t *c) {
518 /* ACK message contains rest of the information the other end needs
519 to create node_t and edge_t structures. */
524 /* Estimate weight */
526 gettimeofday(&now, NULL);
527 c->estimated_weight = (now.tv_sec - c->start.tv_sec) * 1000 + (now.tv_usec - c->start.tv_usec) / 1000;
529 /* Check some options */
531 if((get_config_bool(lookup_config(c->config_tree, "IndirectData"), &choice) && choice) || myself->options & OPTION_INDIRECT)
532 c->options |= OPTION_INDIRECT;
534 if((get_config_bool(lookup_config(c->config_tree, "TCPOnly"), &choice) && choice) || myself->options & OPTION_TCPONLY)
535 c->options |= OPTION_TCPONLY | OPTION_INDIRECT;
537 if(myself->options & OPTION_PMTU_DISCOVERY)
538 c->options |= OPTION_PMTU_DISCOVERY;
540 choice = myself->options & OPTION_CLAMP_MSS;
541 get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice);
543 c->options |= OPTION_CLAMP_MSS;
545 get_config_int(lookup_config(c->config_tree, "Weight"), &c->estimated_weight);
547 return send_request(c, "%d %s %d %x", ACK, myport, c->estimated_weight, c->options);
550 static void send_everything(connection_t *c) {
551 avl_node_t *node, *node2;
556 /* Send all known subnets and edges */
559 for(node = myself->subnet_tree->head; node; node = node->next) {
561 send_add_subnet(c, s);
567 for(node = node_tree->head; node; node = node->next) {
570 for(node2 = n->subnet_tree->head; node2; node2 = node2->next) {
572 send_add_subnet(c, s);
575 for(node2 = n->edge_tree->head; node2; node2 = node2->next) {
582 bool ack_h(connection_t *c) {
583 char hisport[MAX_STRING_SIZE];
590 if(sscanf(c->buffer, "%*d " MAX_STRING " %d %x", hisport, &weight, &options) != 3) {
591 logger(LOG_ERR, "Got bad %s from %s (%s)", "ACK", c->name,
596 /* Check if we already have a node_t for him */
598 n = lookup_node(c->name);
602 n->name = xstrdup(c->name);
606 /* Oh dear, we already have a connection to this node. */
607 ifdebug(CONNECTIONS) logger(LOG_DEBUG, "Established a second connection with %s (%s), closing old connection",
608 n->name, n->hostname);
609 terminate_connection(n->connection, false);
610 /* Run graph algorithm to purge key and make sure up/down scripts are rerun with new IP addresses and stuff */
617 if(!(c->options & options & OPTION_PMTU_DISCOVERY)) {
618 c->options &= ~OPTION_PMTU_DISCOVERY;
619 options &= ~OPTION_PMTU_DISCOVERY;
621 c->options |= options;
623 if(get_config_int(lookup_config(c->config_tree, "PMTU"), &mtu) && mtu < n->mtu)
626 if(get_config_int(lookup_config(config_tree, "PMTU"), &mtu) && mtu < n->mtu)
629 if(get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice)) {
631 c->options |= OPTION_CLAMP_MSS;
633 c->options &= ~OPTION_CLAMP_MSS;
636 /* Activate this connection */
638 c->allow_request = ALL;
639 c->status.active = true;
641 ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Connection with %s (%s) activated", c->name,
644 /* Send him everything we know */
648 /* Create an edge_t for this connection */
650 c->edge = new_edge();
651 c->edge->from = myself;
653 sockaddr2str(&c->address, &hisaddress, NULL);
654 c->edge->address = str2sockaddr(hisaddress, hisport);
656 c->edge->weight = (weight + c->estimated_weight) / 2;
657 c->edge->connection = c;
658 c->edge->options = c->options;
662 /* Notify everyone of the new edge */
665 send_add_edge(c, c->edge);
667 send_add_edge(everyone, c->edge);
669 /* Run MST and SSSP algorithms */