2 protocol_auth.c -- handle the meta-protocol, authentication
3 Copyright (C) 1999-2005 Ivo Timmermans,
4 2000-2013 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) {
129 if(proxytype && c->outgoing)
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): %s",
248 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
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 if(!hex2bin(buffer, buffer, len)) {
312 logger(LOG_ERR, "Got bad %s from %s(%s): %s", "METAKEY", c->name, c->hostname, "invalid key");
316 /* Decrypt the meta key */
318 if(RSA_private_decrypt(len, (unsigned char *)buffer, (unsigned char *)c->inkey, myself->connection->rsa_key, RSA_NO_PADDING) != len) { /* See challenge() */
319 logger(LOG_ERR, "Error during decryption of meta key for %s (%s): %s",
320 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
324 ifdebug(SCARY_THINGS) {
325 bin2hex(c->inkey, buffer, len);
326 buffer[len * 2] = '\0';
327 logger(LOG_DEBUG, "Received random meta key (unencrypted): %s", buffer);
330 /* All incoming requests will now be encrypted. */
332 /* Check and lookup cipher and digest algorithms */
335 c->incipher = EVP_get_cipherbynid(cipher);
338 logger(LOG_ERR, "%s (%s) uses unknown cipher!", c->name, c->hostname);
342 if(!EVP_DecryptInit(c->inctx, c->incipher,
343 (unsigned char *)c->inkey + len - c->incipher->key_len,
344 (unsigned char *)c->inkey + len - c->incipher->key_len -
345 c->incipher->iv_len)) {
346 logger(LOG_ERR, "Error during initialisation of cipher from %s (%s): %s",
347 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
351 c->status.decryptin = true;
356 c->inmaclength = maclength;
359 c->indigest = EVP_get_digestbynid(digest);
362 logger(LOG_ERR, "Node %s (%s) uses unknown digest!", c->name, c->hostname);
366 if(c->inmaclength > c->indigest->md_size || c->inmaclength < 0) {
367 logger(LOG_ERR, "%s (%s) uses bogus MAC length!", c->name, c->hostname);
374 c->incompression = compression;
376 c->allow_request = CHALLENGE;
378 return send_challenge(c);
381 bool send_challenge(connection_t *c) {
382 /* CHECKME: what is most reasonable value for len? */
384 int len = RSA_size(c->rsa_key);
386 /* Allocate buffers for the challenge */
388 char buffer[2 * len + 1];
390 c->hischallenge = xrealloc(c->hischallenge, len);
392 /* Copy random data to the buffer */
394 RAND_pseudo_bytes((unsigned char *)c->hischallenge, len);
398 bin2hex(c->hischallenge, buffer, len);
399 buffer[len * 2] = '\0';
401 /* Send the challenge */
403 return send_request(c, "%d %s", CHALLENGE, buffer);
406 bool challenge_h(connection_t *c) {
407 char buffer[MAX_STRING_SIZE];
410 if(sscanf(c->buffer, "%*d " MAX_STRING, buffer) != 1) {
411 logger(LOG_ERR, "Got bad %s from %s (%s)", "CHALLENGE", c->name,
416 len = RSA_size(myself->connection->rsa_key);
418 /* Check if the length of the challenge is all right */
420 if(strlen(buffer) != len * 2) {
421 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name,
422 c->hostname, "wrong challenge length");
426 /* Allocate buffers for the challenge */
428 c->mychallenge = xrealloc(c->mychallenge, len);
430 /* Convert the challenge from hexadecimal back to binary */
432 if(!hex2bin(buffer, c->mychallenge, len)) {
433 logger(LOG_ERR, "Got bad %s from %s(%s): %s", "CHALLENGE", c->name, c->hostname, "invalid challenge");
437 c->allow_request = CHAL_REPLY;
439 /* Rest is done by send_chal_reply() */
441 return send_chal_reply(c);
444 bool send_chal_reply(connection_t *c) {
445 char hash[EVP_MAX_MD_SIZE * 2 + 1];
448 /* Calculate the hash from the challenge we received */
450 if(!EVP_DigestInit(&ctx, c->indigest)
451 || !EVP_DigestUpdate(&ctx, c->mychallenge, RSA_size(myself->connection->rsa_key))
452 || !EVP_DigestFinal(&ctx, (unsigned char *)hash, NULL)) {
453 logger(LOG_ERR, "Error during calculation of response for %s (%s): %s",
454 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
458 /* Convert the hash to a hexadecimal formatted string */
460 bin2hex(hash, hash, c->indigest->md_size);
461 hash[c->indigest->md_size * 2] = '\0';
465 return send_request(c, "%d %s", CHAL_REPLY, hash);
468 bool chal_reply_h(connection_t *c) {
469 char hishash[MAX_STRING_SIZE];
470 char myhash[EVP_MAX_MD_SIZE];
473 if(sscanf(c->buffer, "%*d " MAX_STRING, hishash) != 1) {
474 logger(LOG_ERR, "Got bad %s from %s (%s)", "CHAL_REPLY", c->name,
479 /* Check if the length of the hash is all right */
481 if(strlen(hishash) != c->outdigest->md_size * 2) {
482 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name,
483 c->hostname, "wrong challenge reply length");
487 /* Convert the hash to binary format */
489 if(!hex2bin(hishash, hishash, c->outdigest->md_size)) {
490 logger(LOG_ERR, "Got bad %s from %s(%s): %s", "CHAL_REPLY", c->name, c->hostname, "invalid hash");
494 /* Calculate the hash from the challenge we sent */
496 if(!EVP_DigestInit(&ctx, c->outdigest)
497 || !EVP_DigestUpdate(&ctx, c->hischallenge, RSA_size(c->rsa_key))
498 || !EVP_DigestFinal(&ctx, (unsigned char *)myhash, NULL)) {
499 logger(LOG_ERR, "Error during calculation of response from %s (%s): %s",
500 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
504 /* Verify the incoming hash with the calculated hash */
506 if(memcmp(hishash, myhash, c->outdigest->md_size)) {
507 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name,
508 c->hostname, "wrong challenge reply");
510 ifdebug(SCARY_THINGS) {
511 bin2hex(myhash, hishash, SHA_DIGEST_LENGTH);
512 hishash[SHA_DIGEST_LENGTH * 2] = '\0';
513 logger(LOG_DEBUG, "Expected challenge reply: %s", hishash);
519 /* Identity has now been positively verified.
520 Send an acknowledgement with the rest of the information needed.
523 c->allow_request = ACK;
528 bool send_ack(connection_t *c) {
529 /* ACK message contains rest of the information the other end needs
530 to create node_t and edge_t structures. */
535 /* Estimate weight */
537 gettimeofday(&now, NULL);
538 c->estimated_weight = (now.tv_sec - c->start.tv_sec) * 1000 + (now.tv_usec - c->start.tv_usec) / 1000;
540 /* Check some options */
542 if((get_config_bool(lookup_config(c->config_tree, "IndirectData"), &choice) && choice) || myself->options & OPTION_INDIRECT)
543 c->options |= OPTION_INDIRECT;
545 if((get_config_bool(lookup_config(c->config_tree, "TCPOnly"), &choice) && choice) || myself->options & OPTION_TCPONLY)
546 c->options |= OPTION_TCPONLY | OPTION_INDIRECT;
548 if(myself->options & OPTION_PMTU_DISCOVERY)
549 c->options |= OPTION_PMTU_DISCOVERY;
551 choice = myself->options & OPTION_CLAMP_MSS;
552 get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice);
554 c->options |= OPTION_CLAMP_MSS;
556 get_config_int(lookup_config(c->config_tree, "Weight"), &c->estimated_weight);
558 return send_request(c, "%d %s %d %x", ACK, myport, c->estimated_weight, c->options);
561 static void send_everything(connection_t *c) {
562 avl_node_t *node, *node2;
567 /* Send all known subnets and edges */
570 for(node = myself->subnet_tree->head; node; node = node->next) {
572 send_add_subnet(c, s);
578 for(node = node_tree->head; node; node = node->next) {
581 for(node2 = n->subnet_tree->head; node2; node2 = node2->next) {
583 send_add_subnet(c, s);
586 for(node2 = n->edge_tree->head; node2; node2 = node2->next) {
593 bool ack_h(connection_t *c) {
594 char hisport[MAX_STRING_SIZE];
601 if(sscanf(c->buffer, "%*d " MAX_STRING " %d %x", hisport, &weight, &options) != 3) {
602 logger(LOG_ERR, "Got bad %s from %s (%s)", "ACK", c->name,
607 /* Check if we already have a node_t for him */
609 n = lookup_node(c->name);
613 n->name = xstrdup(c->name);
617 /* Oh dear, we already have a connection to this node. */
618 ifdebug(CONNECTIONS) logger(LOG_DEBUG, "Established a second connection with %s (%s), closing old connection",
619 n->name, n->hostname);
620 terminate_connection(n->connection, false);
621 /* Run graph algorithm to purge key and make sure up/down scripts are rerun with new IP addresses and stuff */
628 if(!(c->options & options & OPTION_PMTU_DISCOVERY)) {
629 c->options &= ~OPTION_PMTU_DISCOVERY;
630 options &= ~OPTION_PMTU_DISCOVERY;
632 c->options |= options;
634 if(get_config_int(lookup_config(c->config_tree, "PMTU"), &mtu) && mtu < n->mtu)
637 if(get_config_int(lookup_config(config_tree, "PMTU"), &mtu) && mtu < n->mtu)
640 if(get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice)) {
642 c->options |= OPTION_CLAMP_MSS;
644 c->options &= ~OPTION_CLAMP_MSS;
647 /* Activate this connection */
649 c->allow_request = ALL;
650 c->status.active = true;
652 ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Connection with %s (%s) activated", c->name,
655 /* Send him everything we know */
659 /* Create an edge_t for this connection */
661 c->edge = new_edge();
662 c->edge->from = myself;
664 sockaddr2str(&c->address, &hisaddress, NULL);
665 c->edge->address = str2sockaddr(hisaddress, hisport);
667 c->edge->weight = (weight + c->estimated_weight) / 2;
668 c->edge->connection = c;
669 c->edge->options = c->options;
673 /* Notify everyone of the new edge */
676 send_add_edge(c, c->edge);
678 send_add_edge(everyone, c->edge);
680 /* Run MST and SSSP algorithms */