2 protocol_auth.c -- handle the meta-protocol, authentication
3 Copyright (C) 1999-2005 Ivo Timmermans,
4 2000-2009 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"
41 bool send_id(connection_t *c) {
44 return send_request(c, "%d %s %d", ID, myself->connection->name,
45 myself->connection->protocol_version);
48 bool id_h(connection_t *c) {
49 char name[MAX_STRING_SIZE];
53 if(sscanf(c->buffer, "%*d " MAX_STRING " %d", name, &c->protocol_version) != 2) {
54 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "ID", c->name,
59 /* Check if identity is a valid name */
62 logger(LOG_ERR, _("Got bad %s from %s (%s): %s"), "ID", c->name,
63 c->hostname, "invalid name");
67 /* If this is an outgoing connection, make sure we are connected to the right host */
70 if(strcmp(c->name, name)) {
71 logger(LOG_ERR, _("Peer %s is %s instead of %s"), c->hostname, name,
78 c->name = xstrdup(name);
81 /* Check if version matches */
83 if(c->protocol_version != myself->connection->protocol_version) {
84 logger(LOG_ERR, _("Peer %s (%s) uses incompatible version %d"),
85 c->name, c->hostname, c->protocol_version);
91 init_configuration(&c->config_tree);
92 c->allow_request = ACK;
97 init_configuration(&c->config_tree);
99 if(!read_connection_config(c)) {
100 logger(LOG_ERR, _("Peer %s had unknown identity (%s)"), c->hostname,
106 if(!read_rsa_public_key(c)) {
110 c->allow_request = METAKEY;
112 return send_metakey(c);
115 bool send_metakey(connection_t *c) {
122 len = RSA_size(c->rsa_key);
124 /* Allocate buffers for the meta key */
126 buffer = alloca(2 * len + 1);
128 c->outkey = xrealloc(c->outkey, len);
131 c->outctx = xmalloc_and_zero(sizeof(*c->outctx));
133 /* Copy random data to the buffer */
135 RAND_pseudo_bytes((unsigned char *)c->outkey, len);
137 /* The message we send must be smaller than the modulus of the RSA key.
138 By definition, for a key of k bits, the following formula holds:
140 2^(k-1) <= modulus < 2^(k)
142 Where ^ means "to the power of", not "xor".
143 This means that to be sure, we must choose our message < 2^(k-1).
144 This can be done by setting the most significant bit to zero.
147 c->outkey[0] &= 0x7F;
149 ifdebug(SCARY_THINGS) {
150 bin2hex(c->outkey, buffer, len);
151 buffer[len * 2] = '\0';
152 logger(LOG_DEBUG, _("Generated random meta key (unencrypted): %s"),
156 /* Encrypt the random data
158 We do not use one of the PKCS padding schemes here.
159 This is allowed, because we encrypt a totally random string
160 with a length equal to that of the modulus of the RSA key.
163 if(RSA_public_encrypt(len, (unsigned char *)c->outkey, (unsigned char *)buffer, c->rsa_key, RSA_NO_PADDING) != len) {
164 logger(LOG_ERR, _("Error during encryption of meta key for %s (%s)"),
165 c->name, c->hostname);
169 /* Convert the encrypted random data to a hexadecimal formatted string */
171 bin2hex(buffer, buffer, len);
172 buffer[len * 2] = '\0';
174 /* Send the meta key */
176 x = send_request(c, "%d %d %d %d %d %s", METAKEY,
177 c->outcipher ? c->outcipher->nid : 0,
178 c->outdigest ? c->outdigest->type : 0, c->outmaclength,
179 c->outcompression, buffer);
181 /* Further outgoing requests are encrypted with the key we just generated */
184 if(!EVP_EncryptInit(c->outctx, c->outcipher,
185 (unsigned char *)c->outkey + len - c->outcipher->key_len,
186 (unsigned char *)c->outkey + len - c->outcipher->key_len -
187 c->outcipher->iv_len)) {
188 logger(LOG_ERR, _("Error during initialisation of cipher for %s (%s): %s"),
189 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
193 c->status.encryptout = true;
199 bool metakey_h(connection_t *c) {
200 char buffer[MAX_STRING_SIZE];
201 int cipher, digest, maclength, compression;
206 if(sscanf(c->buffer, "%*d %d %d %d %d " MAX_STRING, &cipher, &digest, &maclength, &compression, buffer) != 5) {
207 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "METAKEY", c->name,
212 len = RSA_size(myself->connection->rsa_key);
214 /* Check if the length of the meta key is all right */
216 if(strlen(buffer) != len * 2) {
217 logger(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name, c->hostname, "wrong keylength");
221 /* Allocate buffers for the meta key */
223 c->inkey = xrealloc(c->inkey, len);
226 c->inctx = xmalloc_and_zero(sizeof(*c->inctx));
228 /* Convert the challenge from hexadecimal back to binary */
230 hex2bin(buffer, buffer, len);
232 /* Decrypt the meta key */
234 if(RSA_private_decrypt(len, (unsigned char *)buffer, (unsigned char *)c->inkey, myself->connection->rsa_key, RSA_NO_PADDING) != len) { /* See challenge() */
235 logger(LOG_ERR, _("Error during decryption of meta key for %s (%s)"),
236 c->name, c->hostname);
240 ifdebug(SCARY_THINGS) {
241 bin2hex(c->inkey, buffer, len);
242 buffer[len * 2] = '\0';
243 logger(LOG_DEBUG, _("Received random meta key (unencrypted): %s"), buffer);
246 /* All incoming requests will now be encrypted. */
248 /* Check and lookup cipher and digest algorithms */
251 c->incipher = EVP_get_cipherbynid(cipher);
254 logger(LOG_ERR, _("%s (%s) uses unknown cipher!"), c->name, c->hostname);
258 if(!EVP_DecryptInit(c->inctx, c->incipher,
259 (unsigned char *)c->inkey + len - c->incipher->key_len,
260 (unsigned char *)c->inkey + len - c->incipher->key_len -
261 c->incipher->iv_len)) {
262 logger(LOG_ERR, _("Error during initialisation of cipher from %s (%s): %s"),
263 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
267 c->status.decryptin = true;
272 c->inmaclength = maclength;
275 c->indigest = EVP_get_digestbynid(digest);
278 logger(LOG_ERR, _("Node %s (%s) uses unknown digest!"), c->name, c->hostname);
282 if(c->inmaclength > c->indigest->md_size || c->inmaclength < 0) {
283 logger(LOG_ERR, _("%s (%s) uses bogus MAC length!"), c->name, c->hostname);
290 c->incompression = compression;
292 c->allow_request = CHALLENGE;
294 return send_challenge(c);
297 bool send_challenge(connection_t *c) {
303 /* CHECKME: what is most reasonable value for len? */
305 len = RSA_size(c->rsa_key);
307 /* Allocate buffers for the challenge */
309 buffer = alloca(2 * len + 1);
311 c->hischallenge = xrealloc(c->hischallenge, len);
313 /* Copy random data to the buffer */
315 RAND_pseudo_bytes((unsigned char *)c->hischallenge, len);
319 bin2hex(c->hischallenge, buffer, len);
320 buffer[len * 2] = '\0';
322 /* Send the challenge */
324 return send_request(c, "%d %s", CHALLENGE, buffer);
327 bool challenge_h(connection_t *c) {
328 char buffer[MAX_STRING_SIZE];
333 if(sscanf(c->buffer, "%*d " MAX_STRING, buffer) != 1) {
334 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "CHALLENGE", c->name,
339 len = RSA_size(myself->connection->rsa_key);
341 /* Check if the length of the challenge is all right */
343 if(strlen(buffer) != len * 2) {
344 logger(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name,
345 c->hostname, "wrong challenge length");
349 /* Allocate buffers for the challenge */
351 c->mychallenge = xrealloc(c->mychallenge, len);
353 /* Convert the challenge from hexadecimal back to binary */
355 hex2bin(buffer, c->mychallenge, len);
357 c->allow_request = CHAL_REPLY;
359 /* Rest is done by send_chal_reply() */
361 return send_chal_reply(c);
364 bool send_chal_reply(connection_t *c) {
365 char hash[EVP_MAX_MD_SIZE * 2 + 1];
370 /* Calculate the hash from the challenge we received */
372 if(!EVP_DigestInit(&ctx, c->indigest)
373 || !EVP_DigestUpdate(&ctx, c->mychallenge, RSA_size(myself->connection->rsa_key))
374 || !EVP_DigestFinal(&ctx, (unsigned char *)hash, NULL)) {
375 logger(LOG_ERR, _("Error during calculation of response for %s (%s): %s"),
376 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
380 /* Convert the hash to a hexadecimal formatted string */
382 bin2hex(hash, hash, c->indigest->md_size);
383 hash[c->indigest->md_size * 2] = '\0';
387 return send_request(c, "%d %s", CHAL_REPLY, hash);
390 bool chal_reply_h(connection_t *c) {
391 char hishash[MAX_STRING_SIZE];
392 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 hex2bin(hishash, hishash, c->outdigest->md_size);
415 /* Calculate the hash from the challenge we sent */
417 if(!EVP_DigestInit(&ctx, c->outdigest)
418 || !EVP_DigestUpdate(&ctx, c->hischallenge, RSA_size(c->rsa_key))
419 || !EVP_DigestFinal(&ctx, (unsigned char *)myhash, NULL)) {
420 logger(LOG_ERR, _("Error during calculation of response from %s (%s): %s"),
421 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
425 /* Verify the incoming hash with the calculated hash */
427 if(memcmp(hishash, myhash, c->outdigest->md_size)) {
428 logger(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name,
429 c->hostname, _("wrong challenge reply"));
431 ifdebug(SCARY_THINGS) {
432 bin2hex(myhash, hishash, SHA_DIGEST_LENGTH);
433 hishash[SHA_DIGEST_LENGTH * 2] = '\0';
434 logger(LOG_DEBUG, _("Expected challenge reply: %s"), hishash);
440 /* Identity has now been positively verified.
441 Send an acknowledgement with the rest of the information needed.
444 c->allow_request = ACK;
449 bool send_ack(connection_t *c) {
450 /* ACK message contains rest of the information the other end needs
451 to create node_t and edge_t structures. */
458 /* Estimate weight */
460 gettimeofday(&now, NULL);
461 c->estimated_weight = (now.tv_sec - c->start.tv_sec) * 1000 + (now.tv_usec - c->start.tv_usec) / 1000;
463 /* Check some options */
465 if((get_config_bool(lookup_config(c->config_tree, "IndirectData"), &choice) && choice) || myself->options & OPTION_INDIRECT)
466 c->options |= OPTION_INDIRECT;
468 if((get_config_bool(lookup_config(c->config_tree, "TCPOnly"), &choice) && choice) || myself->options & OPTION_TCPONLY)
469 c->options |= OPTION_TCPONLY | OPTION_INDIRECT;
471 if(myself->options & OPTION_PMTU_DISCOVERY)
472 c->options |= OPTION_PMTU_DISCOVERY;
474 get_config_int(lookup_config(c->config_tree, "Weight"), &c->estimated_weight);
476 return send_request(c, "%d %s %d %lx", ACK, myport, c->estimated_weight, c->options);
479 static void send_everything(connection_t *c) {
480 avl_node_t *node, *node2;
485 /* Send all known subnets and edges */
488 for(node = myself->subnet_tree->head; node; node = node->next) {
490 send_add_subnet(c, s);
496 for(node = node_tree->head; node; node = node->next) {
499 for(node2 = n->subnet_tree->head; node2; node2 = node2->next) {
501 send_add_subnet(c, s);
504 for(node2 = n->edge_tree->head; node2; node2 = node2->next) {
511 bool ack_h(connection_t *c) {
512 char hisport[MAX_STRING_SIZE];
513 char *hisaddress, *dummy;
520 if(sscanf(c->buffer, "%*d " MAX_STRING " %d %lx", hisport, &weight, &options) != 3) {
521 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "ACK", c->name,
526 /* Check if we already have a node_t for him */
528 n = lookup_node(c->name);
532 n->name = xstrdup(c->name);
536 /* Oh dear, we already have a connection to this node. */
537 ifdebug(CONNECTIONS) logger(LOG_DEBUG, _("Established a second connection with %s (%s), closing old connection"),
538 n->name, n->hostname);
539 terminate_connection(n->connection, false);
540 /* Run graph algorithm to purge key and make sure up/down scripts are rerun with new IP addresses and stuff */
547 if(!(c->options & options & OPTION_PMTU_DISCOVERY)) {
548 c->options &= ~OPTION_PMTU_DISCOVERY;
549 options &= ~OPTION_PMTU_DISCOVERY;
551 c->options |= options;
553 if(get_config_int(lookup_config(c->config_tree, "PMTU"), &mtu) && mtu < n->mtu)
556 if(get_config_int(lookup_config(myself->connection->config_tree, "PMTU"), &mtu) && mtu < n->mtu)
559 /* Activate this connection */
561 c->allow_request = ALL;
562 c->status.active = true;
564 ifdebug(CONNECTIONS) logger(LOG_NOTICE, _("Connection with %s (%s) activated"), c->name,
567 /* Send him everything we know */
571 /* Create an edge_t for this connection */
573 c->edge = new_edge();
575 c->edge->from = myself;
577 sockaddr2str(&c->address, &hisaddress, &dummy);
578 c->edge->address = str2sockaddr(hisaddress, hisport);
581 c->edge->weight = (weight + c->estimated_weight) / 2;
582 c->edge->connection = c;
583 c->edge->options = c->options;
587 /* Notify everyone of the new edge */
590 send_add_edge(c, c->edge);
592 send_add_edge(broadcast, c->edge);
594 /* Run MST and SSSP algorithms */