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