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
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>
32 #include "connection.h"
43 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)
53 char name[MAX_STRING_SIZE];
57 if(sscanf(c->buffer, "%*d " MAX_STRING " %d", name, &c->protocol_version) != 2) {
58 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "ID", c->name,
63 /* Check if identity is a valid name */
66 logger(LOG_ERR, _("Got bad %s from %s (%s): %s"), "ID", c->name,
67 c->hostname, "invalid name");
71 /* If this is an outgoing connection, make sure we are connected to the right host */
74 if(strcmp(c->name, name)) {
75 logger(LOG_ERR, _("Peer %s is %s instead of %s"), c->hostname, name,
82 c->name = xstrdup(name);
85 /* Check if version matches */
87 if(c->protocol_version != myself->connection->protocol_version) {
88 logger(LOG_ERR, _("Peer %s (%s) uses incompatible version %d"),
89 c->name, c->hostname, c->protocol_version);
95 init_configuration(&c->config_tree);
96 c->allow_request = ACK;
100 if(!c->config_tree) {
101 init_configuration(&c->config_tree);
103 if(!read_connection_config(c)) {
104 logger(LOG_ERR, _("Peer %s had unknown identity (%s)"), c->hostname,
110 if(!read_rsa_public_key(c)) {
114 c->allow_request = METAKEY;
116 return send_metakey(c);
119 bool send_metakey(connection_t *c)
127 len = RSA_size(c->rsa_key);
129 /* Allocate buffers for the meta key */
131 buffer = alloca(2 * len + 1);
133 c->outkey = xrealloc(c->outkey, len);
136 c->outctx = xmalloc_and_zero(sizeof(*c->outctx));
138 /* Copy random data to the buffer */
140 RAND_pseudo_bytes((unsigned char *)c->outkey, len);
142 /* The message we send must be smaller than the modulus of the RSA key.
143 By definition, for a key of k bits, the following formula holds:
145 2^(k-1) <= modulus < 2^(k)
147 Where ^ means "to the power of", not "xor".
148 This means that to be sure, we must choose our message < 2^(k-1).
149 This can be done by setting the most significant bit to zero.
152 c->outkey[0] &= 0x7F;
154 ifdebug(SCARY_THINGS) {
155 bin2hex(c->outkey, buffer, len);
156 buffer[len * 2] = '\0';
157 logger(LOG_DEBUG, _("Generated random meta key (unencrypted): %s"),
161 /* Encrypt the random data
163 We do not use one of the PKCS padding schemes here.
164 This is allowed, because we encrypt a totally random string
165 with a length equal to that of the modulus of the RSA key.
168 if(RSA_public_encrypt(len, (unsigned char *)c->outkey, (unsigned char *)buffer, c->rsa_key, RSA_NO_PADDING) != len) {
169 logger(LOG_ERR, _("Error during encryption of meta key for %s (%s)"),
170 c->name, c->hostname);
174 /* Convert the encrypted random data to a hexadecimal formatted string */
176 bin2hex(buffer, buffer, len);
177 buffer[len * 2] = '\0';
179 /* Send the meta key */
181 x = send_request(c, "%d %d %d %d %d %s", METAKEY,
182 c->outcipher ? c->outcipher->nid : 0,
183 c->outdigest ? c->outdigest->type : 0, c->outmaclength,
184 c->outcompression, buffer);
186 /* Further outgoing requests are encrypted with the key we just generated */
189 if(!EVP_EncryptInit(c->outctx, c->outcipher,
190 (unsigned char *)c->outkey + len - c->outcipher->key_len,
191 (unsigned char *)c->outkey + len - c->outcipher->key_len -
192 c->outcipher->iv_len)) {
193 logger(LOG_ERR, _("Error during initialisation of cipher for %s (%s): %s"),
194 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
198 c->status.encryptout = true;
204 bool metakey_h(connection_t *c)
206 char buffer[MAX_STRING_SIZE];
207 int cipher, digest, maclength, compression;
212 if(sscanf(c->buffer, "%*d %d %d %d %d " MAX_STRING, &cipher, &digest, &maclength, &compression, buffer) != 5) {
213 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "METAKEY", c->name,
218 len = RSA_size(myself->connection->rsa_key);
220 /* Check if the length of the meta key is all right */
222 if(strlen(buffer) != len * 2) {
223 logger(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name, c->hostname, "wrong keylength");
227 /* Allocate buffers for the meta key */
229 c->inkey = xrealloc(c->inkey, len);
232 c->inctx = xmalloc_and_zero(sizeof(*c->inctx));
234 /* Convert the challenge from hexadecimal back to binary */
236 hex2bin(buffer, buffer, len);
238 /* Decrypt the meta key */
240 if(RSA_private_decrypt(len, (unsigned char *)buffer, (unsigned char *)c->inkey, myself->connection->rsa_key, RSA_NO_PADDING) != len) { /* See challenge() */
241 logger(LOG_ERR, _("Error during decryption of meta key for %s (%s)"),
242 c->name, c->hostname);
246 ifdebug(SCARY_THINGS) {
247 bin2hex(c->inkey, buffer, len);
248 buffer[len * 2] = '\0';
249 logger(LOG_DEBUG, _("Received random meta key (unencrypted): %s"), buffer);
252 /* All incoming requests will now be encrypted. */
254 /* Check and lookup cipher and digest algorithms */
257 c->incipher = EVP_get_cipherbynid(cipher);
260 logger(LOG_ERR, _("%s (%s) uses unknown cipher!"), c->name, c->hostname);
264 if(!EVP_DecryptInit(c->inctx, c->incipher,
265 (unsigned char *)c->inkey + len - c->incipher->key_len,
266 (unsigned char *)c->inkey + len - c->incipher->key_len -
267 c->incipher->iv_len)) {
268 logger(LOG_ERR, _("Error during initialisation of cipher from %s (%s): %s"),
269 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
273 c->status.decryptin = true;
278 c->inmaclength = maclength;
281 c->indigest = EVP_get_digestbynid(digest);
284 logger(LOG_ERR, _("Node %s (%s) uses unknown digest!"), c->name, c->hostname);
288 if(c->inmaclength > c->indigest->md_size || c->inmaclength < 0) {
289 logger(LOG_ERR, _("%s (%s) uses bogus MAC length!"), c->name, c->hostname);
296 c->incompression = compression;
298 c->allow_request = CHALLENGE;
300 return send_challenge(c);
303 bool send_challenge(connection_t *c)
310 /* CHECKME: what is most reasonable value for len? */
312 len = RSA_size(c->rsa_key);
314 /* Allocate buffers for the challenge */
316 buffer = alloca(2 * len + 1);
318 c->hischallenge = xrealloc(c->hischallenge, len);
320 /* Copy random data to the buffer */
322 RAND_pseudo_bytes((unsigned char *)c->hischallenge, len);
326 bin2hex(c->hischallenge, buffer, len);
327 buffer[len * 2] = '\0';
329 /* Send the challenge */
331 return send_request(c, "%d %s", CHALLENGE, buffer);
334 bool challenge_h(connection_t *c)
336 char buffer[MAX_STRING_SIZE];
341 if(sscanf(c->buffer, "%*d " MAX_STRING, buffer) != 1) {
342 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "CHALLENGE", c->name,
347 len = RSA_size(myself->connection->rsa_key);
349 /* Check if the length of the challenge is all right */
351 if(strlen(buffer) != len * 2) {
352 logger(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name,
353 c->hostname, "wrong challenge length");
357 /* Allocate buffers for the challenge */
359 c->mychallenge = xrealloc(c->mychallenge, len);
361 /* Convert the challenge from hexadecimal back to binary */
363 hex2bin(buffer, c->mychallenge, len);
365 c->allow_request = CHAL_REPLY;
367 /* Rest is done by send_chal_reply() */
369 return send_chal_reply(c);
372 bool send_chal_reply(connection_t *c)
374 char hash[EVP_MAX_MD_SIZE * 2 + 1];
379 /* Calculate the hash from the challenge we received */
381 if(!EVP_DigestInit(&ctx, c->indigest)
382 || !EVP_DigestUpdate(&ctx, c->mychallenge, RSA_size(myself->connection->rsa_key))
383 || !EVP_DigestFinal(&ctx, (unsigned char *)hash, NULL)) {
384 logger(LOG_ERR, _("Error during calculation of response for %s (%s): %s"),
385 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
389 /* Convert the hash to a hexadecimal formatted string */
391 bin2hex(hash, hash, c->indigest->md_size);
392 hash[c->indigest->md_size * 2] = '\0';
396 return send_request(c, "%d %s", CHAL_REPLY, hash);
399 bool chal_reply_h(connection_t *c)
401 char hishash[MAX_STRING_SIZE];
402 char myhash[EVP_MAX_MD_SIZE];
407 if(sscanf(c->buffer, "%*d " MAX_STRING, hishash) != 1) {
408 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "CHAL_REPLY", c->name,
413 /* Check if the length of the hash is all right */
415 if(strlen(hishash) != c->outdigest->md_size * 2) {
416 logger(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name,
417 c->hostname, _("wrong challenge reply length"));
421 /* Convert the hash to binary format */
423 hex2bin(hishash, hishash, c->outdigest->md_size);
425 /* Calculate the hash from the challenge we sent */
427 if(!EVP_DigestInit(&ctx, c->outdigest)
428 || !EVP_DigestUpdate(&ctx, c->hischallenge, RSA_size(c->rsa_key))
429 || !EVP_DigestFinal(&ctx, (unsigned char *)myhash, NULL)) {
430 logger(LOG_ERR, _("Error during calculation of response from %s (%s): %s"),
431 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
435 /* Verify the incoming hash with the calculated hash */
437 if(memcmp(hishash, myhash, c->outdigest->md_size)) {
438 logger(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name,
439 c->hostname, _("wrong challenge reply"));
441 ifdebug(SCARY_THINGS) {
442 bin2hex(myhash, hishash, SHA_DIGEST_LENGTH);
443 hishash[SHA_DIGEST_LENGTH * 2] = '\0';
444 logger(LOG_DEBUG, _("Expected challenge reply: %s"), hishash);
450 /* Identity has now been positively verified.
451 Send an acknowledgement with the rest of the information needed.
454 c->allow_request = ACK;
459 bool send_ack(connection_t *c)
461 /* ACK message contains rest of the information the other end needs
462 to create node_t and edge_t structures. */
469 /* Estimate weight */
471 gettimeofday(&now, NULL);
472 c->estimated_weight = (now.tv_sec - c->start.tv_sec) * 1000 + (now.tv_usec - c->start.tv_usec) / 1000;
474 /* Check some options */
476 if((get_config_bool(lookup_config(c->config_tree, "IndirectData"), &choice) && choice) || myself->options & OPTION_INDIRECT)
477 c->options |= OPTION_INDIRECT;
479 if((get_config_bool(lookup_config(c->config_tree, "TCPOnly"), &choice) && choice) || myself->options & OPTION_TCPONLY)
480 c->options |= OPTION_TCPONLY | OPTION_INDIRECT;
482 if(myself->options & OPTION_PMTU_DISCOVERY)
483 c->options |= OPTION_PMTU_DISCOVERY;
485 get_config_int(lookup_config(c->config_tree, "Weight"), &c->estimated_weight);
487 return send_request(c, "%d %s %d %lx", ACK, myport, c->estimated_weight, c->options);
490 static void send_everything(connection_t *c)
492 avl_node_t *node, *node2;
497 /* Send all known subnets and edges */
500 for(node = myself->subnet_tree->head; node; node = node->next) {
502 send_add_subnet(c, s);
508 for(node = node_tree->head; node; node = node->next) {
511 for(node2 = n->subnet_tree->head; node2; node2 = node2->next) {
513 send_add_subnet(c, s);
516 for(node2 = n->edge_tree->head; node2; node2 = node2->next) {
523 bool ack_h(connection_t *c)
525 char hisport[MAX_STRING_SIZE];
526 char *hisaddress, *dummy;
533 if(sscanf(c->buffer, "%*d " MAX_STRING " %d %lx", hisport, &weight, &options) != 3) {
534 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "ACK", c->name,
539 /* Check if we already have a node_t for him */
541 n = lookup_node(c->name);
545 n->name = xstrdup(c->name);
549 /* Oh dear, we already have a connection to this node. */
550 ifdebug(CONNECTIONS) logger(LOG_DEBUG, _("Established a second connection with %s (%s), closing old connection"),
551 n->name, n->hostname);
552 terminate_connection(n->connection, false);
553 /* Run graph algorithm to purge key and make sure up/down scripts are rerun with new IP addresses and stuff */
560 if(!(c->options & options & OPTION_PMTU_DISCOVERY)) {
561 c->options &= ~OPTION_PMTU_DISCOVERY;
562 options &= ~OPTION_PMTU_DISCOVERY;
564 c->options |= options;
566 if(get_config_int(lookup_config(c->config_tree, "PMTU"), &mtu) && mtu < n->mtu)
569 if(get_config_int(lookup_config(myself->connection->config_tree, "PMTU"), &mtu) && mtu < n->mtu)
572 /* Activate this connection */
574 c->allow_request = ALL;
575 c->status.active = true;
577 ifdebug(CONNECTIONS) logger(LOG_NOTICE, _("Connection with %s (%s) activated"), c->name,
580 /* Send him everything we know */
584 /* Create an edge_t for this connection */
586 c->edge = new_edge();
588 c->edge->from = myself;
590 sockaddr2str(&c->address, &hisaddress, &dummy);
591 c->edge->address = str2sockaddr(hisaddress, hisport);
594 c->edge->weight = (weight + c->estimated_weight) / 2;
595 c->edge->connection = c;
596 c->edge->options = c->options;
600 /* Notify everyone of the new edge */
603 send_add_edge(c, c->edge);
605 send_add_edge(broadcast, c->edge);
607 /* Run MST and SSSP algorithms */