Don't initialise a CIPHER_CTX if cipher == NULL.
[tinc] / src / protocol_auth.c
1 /*
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>
5
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.
10
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.
15
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.
19
20     $Id: protocol_auth.c,v 1.1.4.25 2003/07/22 20:55:20 guus Exp $
21 */
22
23 #include "system.h"
24
25 #include <openssl/sha.h>
26 #include <openssl/rand.h>
27 #include <openssl/evp.h>
28
29 #include "avl_tree.h"
30 #include "conf.h"
31 #include "connection.h"
32 #include "edge.h"
33 #include "graph.h"
34 #include "logger.h"
35 #include "net.h"
36 #include "netutl.h"
37 #include "node.h"
38 #include "protocol.h"
39 #include "utils.h"
40 #include "xalloc.h"
41
42 bool send_id(connection_t *c)
43 {
44         cp();
45
46         return send_request(c, "%d %s %d", ID, myself->connection->name,
47                                                 myself->connection->protocol_version);
48 }
49
50 bool id_h(connection_t *c)
51 {
52         char name[MAX_STRING_SIZE];
53         bool choice;
54
55         cp();
56
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,
59                            c->hostname);
60                 return false;
61         }
62
63         /* Check if identity is a valid name */
64
65         if(!check_id(name)) {
66                 logger(LOG_ERR, _("Got bad %s from %s (%s): %s"), "ID", c->name,
67                            c->hostname, "invalid name");
68                 return false;
69         }
70
71         /* If we set c->name in advance, make sure we are connected to the right host */
72
73         if(c->name) {
74                 if(strcmp(c->name, name)) {
75                         logger(LOG_ERR, _("Peer %s is %s instead of %s"), c->hostname, name,
76                                    c->name);
77                         return false;
78                 }
79         } else
80                 c->name = xstrdup(name);
81
82         /* Check if version matches */
83
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);
87                 return false;
88         }
89
90         if(bypass_security) {
91                 if(!c->config_tree)
92                         init_configuration(&c->config_tree);
93                 c->allow_request = ACK;
94                 return send_ack(c);
95         }
96
97         if(!c->config_tree) {
98                 init_configuration(&c->config_tree);
99
100                 if(!read_connection_config(c)) {
101                         logger(LOG_ERR, _("Peer %s had unknown identity (%s)"), c->hostname,
102                                    c->name);
103                         return false;
104                 }
105         }
106
107         if(!read_rsa_public_key(c)) {
108                 return false;
109         }
110
111         /* Check some options */
112
113         if((get_config_bool(lookup_config(c->config_tree, "IndirectData"), &choice) && choice) || myself->options & OPTION_INDIRECT)
114                 c->options |= OPTION_INDIRECT;
115
116         if((get_config_bool(lookup_config(c->config_tree, "TCPOnly"), &choice) && choice) || myself->options & OPTION_TCPONLY)
117                 c->options |= OPTION_TCPONLY | OPTION_INDIRECT;
118
119         c->allow_request = METAKEY;
120
121         return send_metakey(c);
122 }
123
124 bool send_metakey(connection_t *c)
125 {
126         char buffer[MAX_STRING_SIZE];
127         int len;
128         bool x;
129
130         cp();
131
132         len = RSA_size(c->rsa_key);
133
134         /* Allocate buffers for the meta key */
135
136         if(!c->outkey)
137                 c->outkey = xmalloc(len);
138
139         if(!c->outctx)
140                 c->outctx = xmalloc_and_zero(sizeof(*c->outctx));
141         cp();
142         /* Copy random data to the buffer */
143
144         RAND_bytes(c->outkey, len);
145
146         /* The message we send must be smaller than the modulus of the RSA key.
147            By definition, for a key of k bits, the following formula holds:
148
149            2^(k-1) <= modulus < 2^(k)
150
151            Where ^ means "to the power of", not "xor".
152            This means that to be sure, we must choose our message < 2^(k-1).
153            This can be done by setting the most significant bit to zero.
154          */
155
156         c->outkey[0] &= 0x7F;
157
158         ifdebug(SCARY_THINGS) {
159                 bin2hex(c->outkey, buffer, len);
160                 buffer[len * 2] = '\0';
161                 logger(LOG_DEBUG, _("Generated random meta key (unencrypted): %s"),
162                            buffer);
163         }
164
165         /* Encrypt the random data
166
167            We do not use one of the PKCS padding schemes here.
168            This is allowed, because we encrypt a totally random string
169            with a length equal to that of the modulus of the RSA key.
170          */
171
172         if(RSA_public_encrypt(len, c->outkey, buffer, c->rsa_key, RSA_NO_PADDING) != len) {
173                 logger(LOG_ERR, _("Error during encryption of meta key for %s (%s)"),
174                            c->name, c->hostname);
175                 return false;
176         }
177
178         /* Convert the encrypted random data to a hexadecimal formatted string */
179
180         bin2hex(buffer, buffer, len);
181         buffer[len * 2] = '\0';
182
183         /* Send the meta key */
184
185         x = send_request(c, "%d %d %d %d %d %s", METAKEY,
186                                          c->outcipher ? c->outcipher->nid : 0,
187                                          c->outdigest ? c->outdigest->type : 0, c->outmaclength,
188                                          c->outcompression, buffer);
189
190         /* Further outgoing requests are encrypted with the key we just generated */
191
192         if(c->outcipher) {
193                 EVP_EncryptInit(c->outctx, c->outcipher,
194                                                 c->outkey + len - c->outcipher->key_len,
195                                                 c->outkey + len - c->outcipher->key_len -
196                                                 c->outcipher->iv_len);
197
198                 c->status.encryptout = true;
199         }
200
201         return x;
202 }
203
204 bool metakey_h(connection_t *c)
205 {
206         char buffer[MAX_STRING_SIZE];
207         int cipher, digest, maclength, compression;
208         int len;
209
210         cp();
211
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,
214                            c->hostname);
215                 return false;
216         }
217
218         len = RSA_size(myself->connection->rsa_key);
219
220         /* Check if the length of the meta key is all right */
221
222         if(strlen(buffer) != len * 2) {
223                 logger(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name, c->hostname, "wrong keylength");
224                 return false;
225         }
226
227         /* Allocate buffers for the meta key */
228
229         if(!c->inkey)
230                 c->inkey = xmalloc(len);
231
232         if(!c->inctx)
233                 c->inctx = xmalloc_and_zero(sizeof(*c->inctx));
234
235         /* Convert the challenge from hexadecimal back to binary */
236
237         hex2bin(buffer, buffer, len);
238
239         /* Decrypt the meta key */
240
241         if(RSA_private_decrypt(len, buffer, c->inkey, myself->connection->rsa_key, RSA_NO_PADDING) != len) {    /* See challenge() */
242                 logger(LOG_ERR, _("Error during encryption of meta key for %s (%s)"),
243                            c->name, c->hostname);
244                 return false;
245         }
246
247         ifdebug(SCARY_THINGS) {
248                 bin2hex(c->inkey, buffer, len);
249                 buffer[len * 2] = '\0';
250                 logger(LOG_DEBUG, _("Received random meta key (unencrypted): %s"), buffer);
251         }
252
253         /* All incoming requests will now be encrypted. */
254
255         /* Check and lookup cipher and digest algorithms */
256
257         if(cipher) {
258                 c->incipher = EVP_get_cipherbynid(cipher);
259                 
260                 if(!c->incipher) {
261                         logger(LOG_ERR, _("%s (%s) uses unknown cipher!"), c->name, c->hostname);
262                         return false;
263                 }
264
265                 EVP_DecryptInit(c->inctx, c->incipher,
266                                                 c->inkey + len - c->incipher->key_len,
267                                                 c->inkey + len - c->incipher->key_len -
268                                                 c->incipher->iv_len);
269
270                 c->status.decryptin = true;
271         } else {
272                 c->incipher = NULL;
273         }
274
275         c->inmaclength = maclength;
276
277         if(digest) {
278                 c->indigest = EVP_get_digestbynid(digest);
279
280                 if(!c->indigest) {
281                         logger(LOG_ERR, _("Node %s (%s) uses unknown digest!"), c->name, c->hostname);
282                         return false;
283                 }
284
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);
287                         return false;
288                 }
289         } else {
290                 c->indigest = NULL;
291         }
292
293         c->incompression = compression;
294
295         c->allow_request = CHALLENGE;
296
297         return send_challenge(c);
298 }
299
300 bool send_challenge(connection_t *c)
301 {
302         char buffer[MAX_STRING_SIZE];
303         int len;
304
305         cp();
306
307         /* CHECKME: what is most reasonable value for len? */
308
309         len = RSA_size(c->rsa_key);
310
311         /* Allocate buffers for the challenge */
312
313         if(!c->hischallenge)
314                 c->hischallenge = xmalloc(len);
315
316         /* Copy random data to the buffer */
317
318         RAND_bytes(c->hischallenge, len);
319
320         /* Convert to hex */
321
322         bin2hex(c->hischallenge, buffer, len);
323         buffer[len * 2] = '\0';
324
325         /* Send the challenge */
326
327         return send_request(c, "%d %s", CHALLENGE, buffer);
328 }
329
330 bool challenge_h(connection_t *c)
331 {
332         char buffer[MAX_STRING_SIZE];
333         int len;
334
335         cp();
336
337         if(sscanf(c->buffer, "%*d " MAX_STRING, buffer) != 1) {
338                 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "CHALLENGE", c->name,
339                            c->hostname);
340                 return false;
341         }
342
343         len = RSA_size(myself->connection->rsa_key);
344
345         /* Check if the length of the challenge is all right */
346
347         if(strlen(buffer) != len * 2) {
348                 logger(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name,
349                            c->hostname, "wrong challenge length");
350                 return false;
351         }
352
353         /* Allocate buffers for the challenge */
354
355         if(!c->mychallenge)
356                 c->mychallenge = xmalloc(len);
357
358         /* Convert the challenge from hexadecimal back to binary */
359
360         hex2bin(buffer, c->mychallenge, len);
361
362         c->allow_request = CHAL_REPLY;
363
364         /* Rest is done by send_chal_reply() */
365
366         return send_chal_reply(c);
367 }
368
369 bool send_chal_reply(connection_t *c)
370 {
371         char hash[EVP_MAX_MD_SIZE * 2 + 1];
372         EVP_MD_CTX ctx;
373
374         cp();
375
376         /* Calculate the hash from the challenge we received */
377
378         EVP_DigestInit(&ctx, c->indigest);
379         EVP_DigestUpdate(&ctx, c->mychallenge,
380                                          RSA_size(myself->connection->rsa_key));
381         EVP_DigestFinal(&ctx, hash, NULL);
382
383         /* Convert the hash to a hexadecimal formatted string */
384
385         bin2hex(hash, hash, c->indigest->md_size);
386         hash[c->indigest->md_size * 2] = '\0';
387
388         /* Send the reply */
389
390         return send_request(c, "%d %s", CHAL_REPLY, hash);
391 }
392
393 bool chal_reply_h(connection_t *c)
394 {
395         char hishash[MAX_STRING_SIZE];
396         char myhash[EVP_MAX_MD_SIZE];
397         EVP_MD_CTX ctx;
398
399         cp();
400
401         if(sscanf(c->buffer, "%*d " MAX_STRING, hishash) != 1) {
402                 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "CHAL_REPLY", c->name,
403                            c->hostname);
404                 return false;
405         }
406
407         /* Check if the length of the hash is all right */
408
409         if(strlen(hishash) != c->outdigest->md_size * 2) {
410                 logger(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name,
411                            c->hostname, _("wrong challenge reply length"));
412                 return false;
413         }
414
415         /* Convert the hash to binary format */
416
417         hex2bin(hishash, hishash, c->outdigest->md_size);
418
419         /* Calculate the hash from the challenge we sent */
420
421         EVP_DigestInit(&ctx, c->outdigest);
422         EVP_DigestUpdate(&ctx, c->hischallenge, RSA_size(c->rsa_key));
423         EVP_DigestFinal(&ctx, myhash, NULL);
424
425         /* Verify the incoming hash with the calculated hash */
426
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"));
430
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);
435                 }
436
437                 return false;
438         }
439
440         /* Identity has now been positively verified.
441            Send an acknowledgement with the rest of the information needed.
442          */
443
444         c->allow_request = ACK;
445
446         return send_ack(c);
447 }
448
449 bool send_ack(connection_t *c)
450 {
451         /* ACK message contains rest of the information the other end needs
452            to create node_t and edge_t structures. */
453
454         struct timeval now;
455
456         cp();
457
458         /* Estimate weight */
459
460         gettimeofday(&now, NULL);
461         c->estimated_weight = (now.tv_sec - c->start.tv_sec) * 1000 + (now.tv_usec - c->start.tv_usec) / 1000;
462
463         return send_request(c, "%d %s %d %lx", ACK, myport, c->estimated_weight, c->options);
464 }
465
466 static void send_everything(connection_t *c)
467 {
468         avl_node_t *node, *node2;
469         node_t *n;
470         subnet_t *s;
471         edge_t *e;
472
473         /* Send all known subnets and edges */
474
475         for(node = node_tree->head; node; node = node->next) {
476                 n = (node_t *) node->data;
477
478                 for(node2 = n->subnet_tree->head; node2; node2 = node2->next) {
479                         s = (subnet_t *) node2->data;
480                         send_add_subnet(c, s);
481                 }
482
483                 for(node2 = n->edge_tree->head; node2; node2 = node2->next) {
484                         e = (edge_t *) node2->data;
485                         send_add_edge(c, e);
486                 }
487         }
488 }
489
490 bool ack_h(connection_t *c)
491 {
492         char hisport[MAX_STRING_SIZE];
493         char *hisaddress, *dummy;
494         int weight;
495         long int options;
496         node_t *n;
497
498         cp();
499
500         if(sscanf(c->buffer, "%*d " MAX_STRING " %d %lx", hisport, &weight, &options) != 3) {
501                 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "ACK", c->name,
502                            c->hostname);
503                 return false;
504         }
505
506         /* Check if we already have a node_t for him */
507
508         n = lookup_node(c->name);
509
510         if(!n) {
511                 n = new_node();
512                 n->name = xstrdup(c->name);
513                 node_add(n);
514         } else {
515                 if(n->connection) {
516                         /* Oh dear, we already have a connection to this node. */
517                         ifdebug(CONNECTIONS) logger(LOG_DEBUG, _("Established a second connection with %s (%s), closing old connection"),
518                                            n->name, n->hostname);
519                         terminate_connection(n->connection, false);
520                         /* Run graph algorithm to purge key and make sure up/down scripts are rerun with new IP addresses and stuff */
521                         graph();
522                 }
523         }
524
525         n->connection = c;
526         c->node = n;
527         c->options |= options;
528
529         /* Activate this connection */
530
531         c->allow_request = ALL;
532         c->status.active = true;
533
534         ifdebug(CONNECTIONS) logger(LOG_NOTICE, _("Connection with %s (%s) activated"), c->name,
535                            c->hostname);
536
537         /* Send him everything we know */
538
539         send_everything(c);
540
541         /* Create an edge_t for this connection */
542
543         c->edge = new_edge();
544         cp();
545         c->edge->from = myself;
546         c->edge->to = n;
547         sockaddr2str(&c->address, &hisaddress, &dummy);
548         c->edge->address = str2sockaddr(hisaddress, hisport);
549         free(hisaddress);
550         free(dummy);
551         c->edge->weight = (weight + c->estimated_weight) / 2;
552         c->edge->connection = c;
553         c->edge->options = c->options;
554
555         edge_add(c->edge);
556
557         /* Notify everyone of the new edge */
558
559         send_add_edge(broadcast, c->edge);
560
561         /* Run MST and SSSP algorithms */
562
563         graph();
564
565         return true;
566 }