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.28 2003/10/11 12:28:48 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];
58 if(sscanf(c->buffer, "%*d " MAX_STRING " %d", name, &c->protocol_version) != 2) {
59 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "ID", c->name,
64 /* Check if identity is a valid name */
67 logger(LOG_ERR, _("Got bad %s from %s (%s): %s"), "ID", c->name,
68 c->hostname, "invalid name");
72 /* If we set c->name in advance, make sure we are connected to the right host */
75 if(strcmp(c->name, name)) {
76 logger(LOG_ERR, _("Peer %s is %s instead of %s"), c->hostname, name,
81 c->name = xstrdup(name);
83 /* Check if version matches */
85 if(c->protocol_version != myself->connection->protocol_version) {
86 logger(LOG_ERR, _("Peer %s (%s) uses incompatible version %d"),
87 c->name, c->hostname, c->protocol_version);
93 init_configuration(&c->config_tree);
94 c->allow_request = ACK;
99 init_configuration(&c->config_tree);
101 if(!read_connection_config(c)) {
102 logger(LOG_ERR, _("Peer %s had unknown identity (%s)"), c->hostname,
108 if(!read_rsa_public_key(c)) {
112 /* Check some options */
114 if((get_config_bool(lookup_config(c->config_tree, "IndirectData"), &choice) && choice) || myself->options & OPTION_INDIRECT)
115 c->options |= OPTION_INDIRECT;
117 if((get_config_bool(lookup_config(c->config_tree, "TCPOnly"), &choice) && choice) || myself->options & OPTION_TCPONLY)
118 c->options |= OPTION_TCPONLY | OPTION_INDIRECT;
120 c->allow_request = METAKEY;
122 return send_metakey(c);
125 bool send_metakey(connection_t *c)
127 char buffer[MAX_STRING_SIZE];
133 len = RSA_size(c->rsa_key);
135 /* Allocate buffers for the meta key */
138 c->outkey = xmalloc(len);
141 c->outctx = xmalloc_and_zero(sizeof(*c->outctx));
143 /* Copy random data to the buffer */
145 RAND_pseudo_bytes(c->outkey, len);
147 /* The message we send must be smaller than the modulus of the RSA key.
148 By definition, for a key of k bits, the following formula holds:
150 2^(k-1) <= modulus < 2^(k)
152 Where ^ means "to the power of", not "xor".
153 This means that to be sure, we must choose our message < 2^(k-1).
154 This can be done by setting the most significant bit to zero.
157 c->outkey[0] &= 0x7F;
159 ifdebug(SCARY_THINGS) {
160 bin2hex(c->outkey, buffer, len);
161 buffer[len * 2] = '\0';
162 logger(LOG_DEBUG, _("Generated random meta key (unencrypted): %s"),
166 /* Encrypt the random data
168 We do not use one of the PKCS padding schemes here.
169 This is allowed, because we encrypt a totally random string
170 with a length equal to that of the modulus of the RSA key.
173 if(RSA_public_encrypt(len, c->outkey, buffer, c->rsa_key, RSA_NO_PADDING) != len) {
174 logger(LOG_ERR, _("Error during encryption of meta key for %s (%s)"),
175 c->name, c->hostname);
179 /* Convert the encrypted random data to a hexadecimal formatted string */
181 bin2hex(buffer, buffer, len);
182 buffer[len * 2] = '\0';
184 /* Send the meta key */
186 x = send_request(c, "%d %d %d %d %d %s", METAKEY,
187 c->outcipher ? c->outcipher->nid : 0,
188 c->outdigest ? c->outdigest->type : 0, c->outmaclength,
189 c->outcompression, buffer);
191 /* Further outgoing requests are encrypted with the key we just generated */
194 if(!EVP_EncryptInit(c->outctx, c->outcipher,
195 c->outkey + len - c->outcipher->key_len,
196 c->outkey + len - c->outcipher->key_len -
197 c->outcipher->iv_len)) {
198 logger(LOG_ERR, _("Error during initialisation of cipher for %s (%s): %s"),
199 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
203 c->status.encryptout = true;
209 bool metakey_h(connection_t *c)
211 char buffer[MAX_STRING_SIZE];
212 int cipher, digest, maclength, compression;
217 if(sscanf(c->buffer, "%*d %d %d %d %d " MAX_STRING, &cipher, &digest, &maclength, &compression, buffer) != 5) {
218 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "METAKEY", c->name,
223 len = RSA_size(myself->connection->rsa_key);
225 /* Check if the length of the meta key is all right */
227 if(strlen(buffer) != len * 2) {
228 logger(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name, c->hostname, "wrong keylength");
232 /* Allocate buffers for the meta key */
235 c->inkey = xmalloc(len);
238 c->inctx = xmalloc_and_zero(sizeof(*c->inctx));
240 /* Convert the challenge from hexadecimal back to binary */
242 hex2bin(buffer, buffer, len);
244 /* Decrypt the meta key */
246 if(RSA_private_decrypt(len, buffer, c->inkey, myself->connection->rsa_key, RSA_NO_PADDING) != len) { /* See challenge() */
247 logger(LOG_ERR, _("Error during encryption of meta key for %s (%s)"),
248 c->name, c->hostname);
252 ifdebug(SCARY_THINGS) {
253 bin2hex(c->inkey, buffer, len);
254 buffer[len * 2] = '\0';
255 logger(LOG_DEBUG, _("Received random meta key (unencrypted): %s"), buffer);
258 /* All incoming requests will now be encrypted. */
260 /* Check and lookup cipher and digest algorithms */
263 c->incipher = EVP_get_cipherbynid(cipher);
266 logger(LOG_ERR, _("%s (%s) uses unknown cipher!"), c->name, c->hostname);
270 if(!EVP_DecryptInit(c->inctx, c->incipher,
271 c->inkey + len - c->incipher->key_len,
272 c->inkey + len - c->incipher->key_len -
273 c->incipher->iv_len)) {
274 logger(LOG_ERR, _("Error during initialisation of cipher from %s (%s): %s"),
275 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
279 c->status.decryptin = true;
284 c->inmaclength = maclength;
287 c->indigest = EVP_get_digestbynid(digest);
290 logger(LOG_ERR, _("Node %s (%s) uses unknown digest!"), c->name, c->hostname);
294 if(c->inmaclength > c->indigest->md_size || c->inmaclength < 0) {
295 logger(LOG_ERR, _("%s (%s) uses bogus MAC length!"), c->name, c->hostname);
302 c->incompression = compression;
304 c->allow_request = CHALLENGE;
306 return send_challenge(c);
309 bool send_challenge(connection_t *c)
311 char buffer[MAX_STRING_SIZE];
316 /* CHECKME: what is most reasonable value for len? */
318 len = RSA_size(c->rsa_key);
320 /* Allocate buffers for the challenge */
323 c->hischallenge = xmalloc(len);
325 /* Copy random data to the buffer */
327 RAND_pseudo_bytes(c->hischallenge, len);
331 bin2hex(c->hischallenge, buffer, len);
332 buffer[len * 2] = '\0';
334 /* Send the challenge */
336 return send_request(c, "%d %s", CHALLENGE, buffer);
339 bool challenge_h(connection_t *c)
341 char buffer[MAX_STRING_SIZE];
346 if(sscanf(c->buffer, "%*d " MAX_STRING, buffer) != 1) {
347 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "CHALLENGE", c->name,
352 len = RSA_size(myself->connection->rsa_key);
354 /* Check if the length of the challenge is all right */
356 if(strlen(buffer) != len * 2) {
357 logger(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name,
358 c->hostname, "wrong challenge length");
362 /* Allocate buffers for the challenge */
365 c->mychallenge = xmalloc(len);
367 /* Convert the challenge from hexadecimal back to binary */
369 hex2bin(buffer, c->mychallenge, len);
371 c->allow_request = CHAL_REPLY;
373 /* Rest is done by send_chal_reply() */
375 return send_chal_reply(c);
378 bool send_chal_reply(connection_t *c)
380 char hash[EVP_MAX_MD_SIZE * 2 + 1];
385 /* Calculate the hash from the challenge we received */
387 if(!EVP_DigestInit(&ctx, c->indigest)
388 || !EVP_DigestUpdate(&ctx, c->mychallenge, RSA_size(myself->connection->rsa_key))
389 || !EVP_DigestFinal(&ctx, hash, NULL)) {
390 logger(LOG_ERR, _("Error during calculation of response for %s (%s): %s"),
391 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
395 /* Convert the hash to a hexadecimal formatted string */
397 bin2hex(hash, hash, c->indigest->md_size);
398 hash[c->indigest->md_size * 2] = '\0';
402 return send_request(c, "%d %s", CHAL_REPLY, hash);
405 bool chal_reply_h(connection_t *c)
407 char hishash[MAX_STRING_SIZE];
408 char myhash[EVP_MAX_MD_SIZE];
413 if(sscanf(c->buffer, "%*d " MAX_STRING, hishash) != 1) {
414 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "CHAL_REPLY", c->name,
419 /* Check if the length of the hash is all right */
421 if(strlen(hishash) != c->outdigest->md_size * 2) {
422 logger(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name,
423 c->hostname, _("wrong challenge reply length"));
427 /* Convert the hash to binary format */
429 hex2bin(hishash, hishash, c->outdigest->md_size);
431 /* Calculate the hash from the challenge we sent */
433 if(!EVP_DigestInit(&ctx, c->outdigest)
434 || !EVP_DigestUpdate(&ctx, c->hischallenge, RSA_size(c->rsa_key))
435 || !EVP_DigestFinal(&ctx, myhash, NULL)) {
436 logger(LOG_ERR, _("Error during calculation of response from %s (%s): %s"),
437 c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
441 /* Verify the incoming hash with the calculated hash */
443 if(memcmp(hishash, myhash, c->outdigest->md_size)) {
444 logger(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name,
445 c->hostname, _("wrong challenge reply"));
447 ifdebug(SCARY_THINGS) {
448 bin2hex(myhash, hishash, SHA_DIGEST_LENGTH);
449 hishash[SHA_DIGEST_LENGTH * 2] = '\0';
450 logger(LOG_DEBUG, _("Expected challenge reply: %s"), hishash);
456 /* Identity has now been positively verified.
457 Send an acknowledgement with the rest of the information needed.
460 c->allow_request = ACK;
465 bool send_ack(connection_t *c)
467 /* ACK message contains rest of the information the other end needs
468 to create node_t and edge_t structures. */
474 /* Estimate weight */
476 gettimeofday(&now, NULL);
477 c->estimated_weight = (now.tv_sec - c->start.tv_sec) * 1000 + (now.tv_usec - c->start.tv_usec) / 1000;
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 */
491 for(node = node_tree->head; node; node = node->next) {
494 for(node2 = n->subnet_tree->head; node2; node2 = node2->next) {
496 send_add_subnet(c, s);
499 for(node2 = n->edge_tree->head; node2; node2 = node2->next) {
506 bool ack_h(connection_t *c)
508 char hisport[MAX_STRING_SIZE];
509 char *hisaddress, *dummy;
516 if(sscanf(c->buffer, "%*d " MAX_STRING " %d %lx", hisport, &weight, &options) != 3) {
517 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "ACK", c->name,
522 /* Check if we already have a node_t for him */
524 n = lookup_node(c->name);
528 n->name = xstrdup(c->name);
532 /* Oh dear, we already have a connection to this node. */
533 ifdebug(CONNECTIONS) logger(LOG_DEBUG, _("Established a second connection with %s (%s), closing old connection"),
534 n->name, n->hostname);
535 terminate_connection(n->connection, false);
536 /* Run graph algorithm to purge key and make sure up/down scripts are rerun with new IP addresses and stuff */
543 c->options |= options;
545 /* Activate this connection */
547 c->allow_request = ALL;
548 c->status.active = true;
550 ifdebug(CONNECTIONS) logger(LOG_NOTICE, _("Connection with %s (%s) activated"), c->name,
553 /* Send him everything we know */
557 /* Create an edge_t for this connection */
559 c->edge = new_edge();
561 c->edge->from = myself;
563 sockaddr2str(&c->address, &hisaddress, &dummy);
564 c->edge->address = str2sockaddr(hisaddress, hisport);
567 c->edge->weight = (weight + c->estimated_weight) / 2;
568 c->edge->connection = c;
569 c->edge->options = c->options;
573 /* Notify everyone of the new edge */
575 send_add_edge(broadcast, c->edge);
577 /* Run MST and SSSP algorithms */