2 protocol_auth.c -- handle the meta-protocol, authentication
3 Copyright (C) 1999-2003 Ivo Timmermans <ivo@o2w.nl>,
4 2000-2003 Guus Sliepen <guus@sliepen.eu.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.
20 $Id: protocol_auth.c,v 1.1.4.30 2003/11/17 15:30:18 guus Exp $
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 we set c->name in advance, 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,
80 c->name = xstrdup(name);
82 /* Check if version matches */
84 if(c->protocol_version != myself->connection->protocol_version) {
85 logger(LOG_ERR, _("Peer %s (%s) uses incompatible version %d"),
86 c->name, c->hostname, c->protocol_version);
92 init_configuration(&c->config_tree);
93 c->allow_request = ACK;
98 init_configuration(&c->config_tree);
100 if(!read_connection_config(c)) {
101 logger(LOG_ERR, _("Peer %s had unknown identity (%s)"), c->hostname,
107 if(!read_rsa_public_key(c)) {
111 c->allow_request = METAKEY;
113 return send_metakey(c);
116 bool send_metakey(connection_t *c)
118 char buffer[MAX_STRING_SIZE];
124 len = RSA_size(c->rsa_key);
126 /* Allocate buffers for the meta key */
129 c->outkey = xmalloc(len);
132 c->outctx = xmalloc_and_zero(sizeof(*c->outctx));
134 /* Copy random data to the buffer */
136 RAND_pseudo_bytes(c->outkey, len);
138 /* The message we send must be smaller than the modulus of the RSA key.
139 By definition, for a key of k bits, the following formula holds:
141 2^(k-1) <= modulus < 2^(k)
143 Where ^ means "to the power of", not "xor".
144 This means that to be sure, we must choose our message < 2^(k-1).
145 This can be done by setting the most significant bit to zero.
148 c->outkey[0] &= 0x7F;
150 ifdebug(SCARY_THINGS) {
151 bin2hex(c->outkey, buffer, len);
152 buffer[len * 2] = '\0';
153 logger(LOG_DEBUG, _("Generated random meta key (unencrypted): %s"),
157 /* Encrypt the random data
159 We do not use one of the PKCS padding schemes here.
160 This is allowed, because we encrypt a totally random string
161 with a length equal to that of the modulus of the RSA key.
164 if(RSA_public_encrypt(len, c->outkey, buffer, c->rsa_key, RSA_NO_PADDING) != len) {
165 logger(LOG_ERR, _("Error during encryption of meta key for %s (%s)"),
166 c->name, c->hostname);
170 /* Convert the encrypted random data to a hexadecimal formatted string */
172 bin2hex(buffer, buffer, len);
173 buffer[len * 2] = '\0';
175 /* Send the meta key */
177 x = send_request(c, "%d %d %d %d %d %s", METAKEY,
178 c->outcipher ? c->outcipher->nid : 0,
179 c->outdigest ? c->outdigest->type : 0, c->outmaclength,
180 c->outcompression, buffer);
182 /* Further outgoing requests are encrypted with the key we just generated */
185 if(!EVP_EncryptInit(c->outctx, c->outcipher,
186 c->outkey + len - c->outcipher->key_len,
187 c->outkey + len - c->outcipher->key_len -
188 c->outcipher->iv_len)) {
189 logger(LOG_ERR, _("Error during initialisation of cipher for %s (%s): %s"),
190 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
194 c->status.encryptout = true;
200 bool metakey_h(connection_t *c)
202 char buffer[MAX_STRING_SIZE];
203 int cipher, digest, maclength, compression;
208 if(sscanf(c->buffer, "%*d %d %d %d %d " MAX_STRING, &cipher, &digest, &maclength, &compression, buffer) != 5) {
209 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "METAKEY", c->name,
214 len = RSA_size(myself->connection->rsa_key);
216 /* Check if the length of the meta key is all right */
218 if(strlen(buffer) != len * 2) {
219 logger(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name, c->hostname, "wrong keylength");
223 /* Allocate buffers for the meta key */
226 c->inkey = xmalloc(len);
229 c->inctx = xmalloc_and_zero(sizeof(*c->inctx));
231 /* Convert the challenge from hexadecimal back to binary */
233 hex2bin(buffer, buffer, len);
235 /* Decrypt the meta key */
237 if(RSA_private_decrypt(len, buffer, c->inkey, myself->connection->rsa_key, RSA_NO_PADDING) != len) { /* See challenge() */
238 logger(LOG_ERR, _("Error during encryption of meta key for %s (%s)"),
239 c->name, c->hostname);
243 ifdebug(SCARY_THINGS) {
244 bin2hex(c->inkey, buffer, len);
245 buffer[len * 2] = '\0';
246 logger(LOG_DEBUG, _("Received random meta key (unencrypted): %s"), buffer);
249 /* All incoming requests will now be encrypted. */
251 /* Check and lookup cipher and digest algorithms */
254 c->incipher = EVP_get_cipherbynid(cipher);
257 logger(LOG_ERR, _("%s (%s) uses unknown cipher!"), c->name, c->hostname);
261 if(!EVP_DecryptInit(c->inctx, c->incipher,
262 c->inkey + len - c->incipher->key_len,
263 c->inkey + len - c->incipher->key_len -
264 c->incipher->iv_len)) {
265 logger(LOG_ERR, _("Error during initialisation of cipher from %s (%s): %s"),
266 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
270 c->status.decryptin = true;
275 c->inmaclength = maclength;
278 c->indigest = EVP_get_digestbynid(digest);
281 logger(LOG_ERR, _("Node %s (%s) uses unknown digest!"), c->name, c->hostname);
285 if(c->inmaclength > c->indigest->md_size || c->inmaclength < 0) {
286 logger(LOG_ERR, _("%s (%s) uses bogus MAC length!"), c->name, c->hostname);
293 c->incompression = compression;
295 c->allow_request = CHALLENGE;
297 return send_challenge(c);
300 bool send_challenge(connection_t *c)
302 char buffer[MAX_STRING_SIZE];
307 /* CHECKME: what is most reasonable value for len? */
309 len = RSA_size(c->rsa_key);
311 /* Allocate buffers for the challenge */
314 c->hischallenge = xmalloc(len);
316 /* Copy random data to the buffer */
318 RAND_pseudo_bytes(c->hischallenge, len);
322 bin2hex(c->hischallenge, buffer, len);
323 buffer[len * 2] = '\0';
325 /* Send the challenge */
327 return send_request(c, "%d %s", CHALLENGE, buffer);
330 bool challenge_h(connection_t *c)
332 char buffer[MAX_STRING_SIZE];
337 if(sscanf(c->buffer, "%*d " MAX_STRING, buffer) != 1) {
338 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "CHALLENGE", c->name,
343 len = RSA_size(myself->connection->rsa_key);
345 /* Check if the length of the challenge is all right */
347 if(strlen(buffer) != len * 2) {
348 logger(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name,
349 c->hostname, "wrong challenge length");
353 /* Allocate buffers for the challenge */
356 c->mychallenge = xmalloc(len);
358 /* Convert the challenge from hexadecimal back to binary */
360 hex2bin(buffer, c->mychallenge, len);
362 c->allow_request = CHAL_REPLY;
364 /* Rest is done by send_chal_reply() */
366 return send_chal_reply(c);
369 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, RSA_size(myself->connection->rsa_key))
380 || !EVP_DigestFinal(&ctx, 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)
398 char hishash[MAX_STRING_SIZE];
399 char myhash[EVP_MAX_MD_SIZE];
404 if(sscanf(c->buffer, "%*d " MAX_STRING, hishash) != 1) {
405 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "CHAL_REPLY", c->name,
410 /* Check if the length of the hash is all right */
412 if(strlen(hishash) != c->outdigest->md_size * 2) {
413 logger(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name,
414 c->hostname, _("wrong challenge reply length"));
418 /* Convert the hash to binary format */
420 hex2bin(hishash, hishash, c->outdigest->md_size);
422 /* Calculate the hash from the challenge we sent */
424 if(!EVP_DigestInit(&ctx, c->outdigest)
425 || !EVP_DigestUpdate(&ctx, c->hischallenge, RSA_size(c->rsa_key))
426 || !EVP_DigestFinal(&ctx, myhash, NULL)) {
427 logger(LOG_ERR, _("Error during calculation of response from %s (%s): %s"),
428 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
432 /* Verify the incoming hash with the calculated hash */
434 if(memcmp(hishash, myhash, c->outdigest->md_size)) {
435 logger(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name,
436 c->hostname, _("wrong challenge reply"));
438 ifdebug(SCARY_THINGS) {
439 bin2hex(myhash, hishash, SHA_DIGEST_LENGTH);
440 hishash[SHA_DIGEST_LENGTH * 2] = '\0';
441 logger(LOG_DEBUG, _("Expected challenge reply: %s"), hishash);
447 /* Identity has now been positively verified.
448 Send an acknowledgement with the rest of the information needed.
451 c->allow_request = ACK;
456 bool send_ack(connection_t *c)
458 /* ACK message contains rest of the information the other end needs
459 to create node_t and edge_t structures. */
466 /* Estimate weight */
468 gettimeofday(&now, NULL);
469 c->estimated_weight = (now.tv_sec - c->start.tv_sec) * 1000 + (now.tv_usec - c->start.tv_usec) / 1000;
471 /* Check some options */
473 if((get_config_bool(lookup_config(c->config_tree, "IndirectData"), &choice) && choice) || myself->options & OPTION_INDIRECT)
474 c->options |= OPTION_INDIRECT;
476 if((get_config_bool(lookup_config(c->config_tree, "TCPOnly"), &choice) && choice) || myself->options & OPTION_TCPONLY)
477 c->options |= OPTION_TCPONLY | OPTION_INDIRECT;
479 return send_request(c, "%d %s %d %lx", ACK, myport, c->estimated_weight, c->options);
482 static void send_everything(connection_t *c)
484 avl_node_t *node, *node2;
489 /* Send all known subnets and edges */
492 for(node = myself->subnet_tree->head; node; node = node->next) {
494 send_add_subnet(c, s);
500 for(node = node_tree->head; node; node = node->next) {
503 for(node2 = n->subnet_tree->head; node2; node2 = node2->next) {
505 send_add_subnet(c, s);
508 for(node2 = n->edge_tree->head; node2; node2 = node2->next) {
515 bool ack_h(connection_t *c)
517 char hisport[MAX_STRING_SIZE];
518 char *hisaddress, *dummy;
525 if(sscanf(c->buffer, "%*d " MAX_STRING " %d %lx", hisport, &weight, &options) != 3) {
526 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "ACK", c->name,
531 /* Check if we already have a node_t for him */
533 n = lookup_node(c->name);
537 n->name = xstrdup(c->name);
541 /* Oh dear, we already have a connection to this node. */
542 ifdebug(CONNECTIONS) logger(LOG_DEBUG, _("Established a second connection with %s (%s), closing old connection"),
543 n->name, n->hostname);
544 terminate_connection(n->connection, false);
545 /* Run graph algorithm to purge key and make sure up/down scripts are rerun with new IP addresses and stuff */
552 c->options |= options;
554 /* Activate this connection */
556 c->allow_request = ALL;
557 c->status.active = true;
559 ifdebug(CONNECTIONS) logger(LOG_NOTICE, _("Connection with %s (%s) activated"), c->name,
562 /* Send him everything we know */
566 /* Create an edge_t for this connection */
568 c->edge = new_edge();
570 c->edge->from = myself;
572 sockaddr2str(&c->address, &hisaddress, &dummy);
573 c->edge->address = str2sockaddr(hisaddress, hisport);
576 c->edge->weight = (weight + c->estimated_weight) / 2;
577 c->edge->connection = c;
578 c->edge->options = c->options;
582 /* Notify everyone of the new edge */
585 send_add_edge(c, c->edge);
587 send_add_edge(broadcast, c->edge);
589 /* Run MST and SSSP algorithms */