2 protocol_auth.c -- handle the meta-protocol, authentication
3 Copyright (C) 1999-2005 Ivo Timmermans,
4 2000-2007 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
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25 #include <openssl/sha.h>
26 #include <openssl/rand.h>
27 #include <openssl/err.h>
28 #include <openssl/evp.h>
30 #include "splay_tree.h"
32 #include "connection.h"
44 bool send_id(connection_t *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, char *request) {
52 char name[MAX_STRING_SIZE];
56 if(sscanf(request, "%*d " MAX_STRING " %d", name, &c->protocol_version) != 2) {
57 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "ID", c->name,
62 /* Check if identity is a valid name */
65 logger(LOG_ERR, _("Got bad %s from %s (%s): %s"), "ID", c->name,
66 c->hostname, "invalid name");
70 /* If this is an outgoing connection, make sure we are connected to the right host */
73 if(strcmp(c->name, name)) {
74 logger(LOG_ERR, _("Peer %s is %s instead of %s"), c->hostname, name,
81 c->name = xstrdup(name);
84 /* Check if version matches */
86 if(c->protocol_version != myself->connection->protocol_version) {
87 logger(LOG_ERR, _("Peer %s (%s) uses incompatible version %d"),
88 c->name, c->hostname, c->protocol_version);
94 init_configuration(&c->config_tree);
95 c->allow_request = ACK;
100 init_configuration(&c->config_tree);
102 if(!read_connection_config(c)) {
103 logger(LOG_ERR, _("Peer %s had unknown identity (%s)"), c->hostname,
109 if(!read_rsa_public_key(c)) {
113 c->allow_request = METAKEY;
115 return send_metakey(c);
118 bool send_metakey(connection_t *c) {
125 len = get_rsa_size(&c->rsa_key);
127 /* Allocate buffers for the meta key */
129 buffer = alloca(2 * len + 1);
132 c->outkey = xmalloc(len);
135 c->outctx = xmalloc_and_zero(sizeof(*c->outctx));
137 /* Copy random data to the buffer */
139 RAND_pseudo_bytes((unsigned char *)c->outkey, len);
141 /* The message we send must be smaller than the modulus of the RSA key.
142 By definition, for a key of k bits, the following formula holds:
144 2^(k-1) <= modulus < 2^(k)
146 Where ^ means "to the power of", not "xor".
147 This means that to be sure, we must choose our message < 2^(k-1).
148 This can be done by setting the most significant bit to zero.
151 c->outkey[0] &= 0x7F;
153 ifdebug(SCARY_THINGS) {
154 bin2hex(c->outkey, buffer, len);
155 buffer[len * 2] = '\0';
156 logger(LOG_DEBUG, _("Generated random meta key (unencrypted): %s"),
160 /* Encrypt the random data
162 We do not use one of the PKCS padding schemes here.
163 This is allowed, because we encrypt a totally random string
164 with a length equal to that of the modulus of the RSA key.
167 if(!rsa_public_encrypt(len, (unsigned char *)c->outkey, (unsigned char *)buffer, &c->rsa_key)) {
168 logger(LOG_ERR, _("Error during encryption of meta key for %s (%s)"),
169 c->name, c->hostname);
173 /* Convert the encrypted random data to a hexadecimal formatted string */
175 bin2hex(buffer, buffer, len);
176 buffer[len * 2] = '\0';
178 /* Send the meta key */
180 x = send_request(c, "%d %d %d %d %d %s", METAKEY,
181 c->outcipher ? c->outcipher->nid : 0,
182 c->outdigest ? c->outdigest->type : 0, c->outmaclength,
183 c->outcompression, buffer);
185 /* Further outgoing requests are encrypted with the key we just generated */
188 if(!EVP_EncryptInit(c->outctx, c->outcipher,
189 (unsigned char *)c->outkey + len - c->outcipher->key_len,
190 (unsigned char *)c->outkey + len - c->outcipher->key_len -
191 c->outcipher->iv_len)) {
192 logger(LOG_ERR, _("Error during initialisation of cipher for %s (%s): %s"),
193 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
197 c->status.encryptout = true;
203 bool metakey_h(connection_t *c, char *request) {
204 char buffer[MAX_STRING_SIZE];
205 int cipher, digest, maclength, compression;
210 if(sscanf(request, "%*d %d %d %d %d " MAX_STRING, &cipher, &digest, &maclength, &compression, buffer) != 5) {
211 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "METAKEY", c->name,
216 len = get_rsa_size(&myself->connection->rsa_key);
218 /* Check if the length of the meta key is all right */
220 if(strlen(buffer) != len * 2) {
221 logger(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name, c->hostname, "wrong keylength");
225 /* Allocate buffers for the meta key */
228 c->inkey = xmalloc(len);
231 c->inctx = xmalloc_and_zero(sizeof(*c->inctx));
233 /* Convert the challenge from hexadecimal back to binary */
235 hex2bin(buffer, buffer, len);
237 /* Decrypt the meta key */
239 if(!rsa_private_decrypt(len, (unsigned char *)buffer, (unsigned char *)c->inkey, &myself->connection->rsa_key)) {
240 logger(LOG_ERR, _("Error during encryption of meta key for %s (%s)"), c->name, c->hostname);
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) {
307 /* CHECKME: what is most reasonable value for len? */
309 len = get_rsa_size(&c->rsa_key);
311 /* Allocate buffers for the challenge */
313 buffer = alloca(2 * len + 1);
316 c->hischallenge = xmalloc(len);
318 /* Copy random data to the buffer */
320 RAND_pseudo_bytes((unsigned char *)c->hischallenge, len);
324 bin2hex(c->hischallenge, buffer, len);
325 buffer[len * 2] = '\0';
327 /* Send the challenge */
329 return send_request(c, "%d %s", CHALLENGE, buffer);
332 bool challenge_h(connection_t *c, char *request) {
333 char buffer[MAX_STRING_SIZE];
338 if(sscanf(request, "%*d " MAX_STRING, buffer) != 1) {
339 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "CHALLENGE", c->name,
344 len = get_rsa_size(&myself->connection->rsa_key);
346 /* Check if the length of the challenge is all right */
348 if(strlen(buffer) != len * 2) {
349 logger(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name,
350 c->hostname, "wrong challenge length");
354 /* Allocate buffers for the challenge */
357 c->mychallenge = xmalloc(len);
359 /* Convert the challenge from hexadecimal back to binary */
361 hex2bin(buffer, c->mychallenge, len);
363 c->allow_request = CHAL_REPLY;
365 /* Rest is done by send_chal_reply() */
367 return send_chal_reply(c);
370 bool send_chal_reply(connection_t *c) {
371 char hash[EVP_MAX_MD_SIZE * 2 + 1];
376 /* Calculate the hash from the challenge we received */
378 if(!EVP_DigestInit(&ctx, c->indigest)
379 || !EVP_DigestUpdate(&ctx, c->mychallenge, get_rsa_size(&myself->connection->rsa_key))
380 || !EVP_DigestFinal(&ctx, (unsigned char *)hash, NULL)) {
381 logger(LOG_ERR, _("Error during calculation of response for %s (%s): %s"),
382 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
386 /* Convert the hash to a hexadecimal formatted string */
388 bin2hex(hash, hash, c->indigest->md_size);
389 hash[c->indigest->md_size * 2] = '\0';
393 return send_request(c, "%d %s", CHAL_REPLY, hash);
396 bool chal_reply_h(connection_t *c, char *request) {
397 char hishash[MAX_STRING_SIZE];
398 char myhash[EVP_MAX_MD_SIZE];
403 if(sscanf(request, "%*d " MAX_STRING, hishash) != 1) {
404 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "CHAL_REPLY", c->name,
409 /* Check if the length of the hash is all right */
411 if(strlen(hishash) != c->outdigest->md_size * 2) {
412 logger(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name,
413 c->hostname, _("wrong challenge reply length"));
417 /* Convert the hash to binary format */
419 hex2bin(hishash, hishash, c->outdigest->md_size);
421 /* Calculate the hash from the challenge we sent */
423 if(!EVP_DigestInit(&ctx, c->outdigest)
424 || !EVP_DigestUpdate(&ctx, c->hischallenge, get_rsa_size(&c->rsa_key))
425 || !EVP_DigestFinal(&ctx, (unsigned char *)myhash, NULL)) {
426 logger(LOG_ERR, _("Error during calculation of response from %s (%s): %s"),
427 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
431 /* Verify the incoming hash with the calculated hash */
433 if(memcmp(hishash, myhash, c->outdigest->md_size)) {
434 logger(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name,
435 c->hostname, _("wrong challenge reply"));
437 ifdebug(SCARY_THINGS) {
438 bin2hex(myhash, hishash, SHA_DIGEST_LENGTH);
439 hishash[SHA_DIGEST_LENGTH * 2] = '\0';
440 logger(LOG_DEBUG, _("Expected challenge reply: %s"), hishash);
446 /* Identity has now been positively verified.
447 Send an acknowledgement with the rest of the information needed.
450 c->allow_request = ACK;
455 bool send_ack(connection_t *c) {
456 /* ACK message contains rest of the information the other end needs
457 to create node_t and edge_t structures. */
464 /* Estimate weight */
466 gettimeofday(&now, NULL);
467 c->estimated_weight = (now.tv_sec - c->start.tv_sec) * 1000 + (now.tv_usec - c->start.tv_usec) / 1000;
469 /* Check some options */
471 if((get_config_bool(lookup_config(c->config_tree, "IndirectData"), &choice) && choice) || myself->options & OPTION_INDIRECT)
472 c->options |= OPTION_INDIRECT;
474 if((get_config_bool(lookup_config(c->config_tree, "TCPOnly"), &choice) && choice) || myself->options & OPTION_TCPONLY)
475 c->options |= OPTION_TCPONLY | OPTION_INDIRECT;
477 if((get_config_bool(lookup_config(c->config_tree, "PMTUDiscovery"), &choice) && choice) || myself->options & OPTION_PMTU_DISCOVERY)
478 c->options |= OPTION_PMTU_DISCOVERY;
480 get_config_int(lookup_config(c->config_tree, "Weight"), &c->estimated_weight);
482 return send_request(c, "%d %s %d %lx", ACK, myport, c->estimated_weight, c->options);
485 static void send_everything(connection_t *c) {
486 splay_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, char *request) {
518 char hisport[MAX_STRING_SIZE];
519 char *hisaddress, *dummy;
526 if(sscanf(request, "%*d " MAX_STRING " %d %lx", hisport, &weight, &options) != 3) {
527 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "ACK", c->name,
532 /* Check if we already have a node_t for him */
534 n = lookup_node(c->name);
538 n->name = xstrdup(c->name);
542 /* Oh dear, we already have a connection to this node. */
543 ifdebug(CONNECTIONS) logger(LOG_DEBUG, _("Established a second connection with %s (%s), closing old connection"), n->connection->name, n->connection->hostname);
545 if(n->connection->outgoing) {
547 logger(LOG_WARNING, _("Two outgoing connections to the same node!"));
549 c->outgoing = n->connection->outgoing;
551 n->connection->outgoing = NULL;
554 terminate_connection(n->connection, false);
555 /* Run graph algorithm to purge key and make sure up/down scripts are rerun with new IP addresses and stuff */
562 c->options |= options;
564 if(get_config_int(lookup_config(c->config_tree, "PMTU"), &mtu) && mtu < n->mtu)
567 if(get_config_int(lookup_config(myself->connection->config_tree, "PMTU"), &mtu) && mtu < n->mtu)
570 /* Activate this connection */
572 c->allow_request = ALL;
573 c->status.active = true;
575 ifdebug(CONNECTIONS) logger(LOG_NOTICE, _("Connection with %s (%s) activated"), c->name,
578 /* Send him everything we know */
582 /* Create an edge_t for this connection */
584 c->edge = new_edge();
586 c->edge->from = myself;
588 sockaddr2str(&c->address, &hisaddress, &dummy);
589 c->edge->address = str2sockaddr(hisaddress, hisport);
592 c->edge->weight = (weight + c->estimated_weight) / 2;
593 c->edge->connection = c;
594 c->edge->options = c->options;
598 /* Notify everyone of the new edge */
601 send_add_edge(c, c->edge);
603 send_add_edge(broadcast, c->edge);
605 /* Run MST and SSSP algorithms */