Don't call ERR_remove_state().
[oweals/tinc.git] / src / protocol_auth.c
1 /*
2     protocol_auth.c -- handle the meta-protocol, authentication
3     Copyright (C) 1999-2005 Ivo Timmermans,
4                   2000-2016 Guus Sliepen <guus@tinc-vpn.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 along
17     with this program; if not, write to the Free Software Foundation, Inc.,
18     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20
21 #include "system.h"
22
23 #include <openssl/sha.h>
24 #include <openssl/rand.h>
25 #include <openssl/err.h>
26 #include <openssl/evp.h>
27
28 #include "avl_tree.h"
29 #include "conf.h"
30 #include "connection.h"
31 #include "edge.h"
32 #include "graph.h"
33 #include "logger.h"
34 #include "meta.h"
35 #include "net.h"
36 #include "netutl.h"
37 #include "node.h"
38 #include "protocol.h"
39 #include "proxy.h"
40 #include "utils.h"
41 #include "xalloc.h"
42
43 bool send_id(connection_t *c) {
44         if(proxytype && c->outgoing && !c->status.proxy_passed) {
45                 return send_proxyrequest(c);
46         }
47
48         return send_request(c, "%d %s %d", ID, myself->connection->name,
49                             myself->connection->protocol_version);
50 }
51
52 bool id_h(connection_t *c) {
53         char name[MAX_STRING_SIZE];
54
55         if(sscanf(c->buffer, "%*d " MAX_STRING " %d", name, &c->protocol_version) != 2) {
56                 logger(LOG_ERR, "Got bad %s from %s (%s)", "ID", c->name,
57                        c->hostname);
58                 return false;
59         }
60
61         /* Check if identity is a valid name */
62
63         if(!check_id(name)) {
64                 logger(LOG_ERR, "Got bad %s from %s (%s): %s", "ID", c->name,
65                        c->hostname, "invalid name");
66                 return false;
67         }
68
69         /* If this is an outgoing connection, make sure we are connected to the right host */
70
71         if(c->outgoing) {
72                 if(strcmp(c->name, name)) {
73                         logger(LOG_ERR, "Peer %s is %s instead of %s", c->hostname, name,
74                                c->name);
75                         return false;
76                 }
77         } else {
78                 if(c->name) {
79                         free(c->name);
80                 }
81
82                 c->name = xstrdup(name);
83         }
84
85         /* Check if version matches */
86
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);
90                 return false;
91         }
92
93         if(bypass_security) {
94                 if(!c->config_tree) {
95                         init_configuration(&c->config_tree);
96                 }
97
98                 c->allow_request = ACK;
99                 return send_ack(c);
100         }
101
102         if(!c->config_tree) {
103                 init_configuration(&c->config_tree);
104
105                 if(!read_connection_config(c)) {
106                         logger(LOG_ERR, "Peer %s had unknown identity (%s)", c->hostname,
107                                c->name);
108                         return false;
109                 }
110         }
111
112         if(!read_rsa_public_key(c)) {
113                 return false;
114         }
115
116         c->allow_request = METAKEY;
117
118         return send_metakey(c);
119 }
120
121 static uint64_t byte_budget(const EVP_CIPHER *cipher) {
122         /* Hopefully some failsafe way to calculate the maximum amount of bytes to
123            send/receive with a given cipher before we might run into birthday paradox
124            attacks. Because we might use different modes, the block size of the mode
125            might be 1 byte. In that case, use the IV length. Ensure the whole thing
126            is limited to what can be represented with a 64 bits integer.
127          */
128
129         int ivlen = EVP_CIPHER_iv_length(cipher);
130         int blklen = EVP_CIPHER_block_size(cipher);
131         int len = blklen > 1 ? blklen : ivlen > 1 ? ivlen : 8;
132         int bits = len * 4 - 1;
133         return bits < 64 ? UINT64_C(1) << bits : UINT64_MAX;
134 }
135
136 bool send_metakey(connection_t *c) {
137         bool x;
138
139         int len = RSA_size(c->rsa_key);
140
141         /* Allocate buffers for the meta key */
142
143         char buffer[2 * len + 1];
144
145         c->outkey = xrealloc(c->outkey, len);
146
147         if(!c->outctx) {
148                 c->outctx = EVP_CIPHER_CTX_new();
149
150                 if(!c->outctx) {
151                         abort();
152                 }
153         }
154
155         /* Copy random data to the buffer */
156
157         if(1 != RAND_bytes((unsigned char *)c->outkey, len)) {
158                 int err = ERR_get_error();
159                 logger(LOG_ERR, "Failed to generate meta key (%s)", ERR_error_string(err, NULL));
160                 return false;
161         }
162
163
164         /* The message we send must be smaller than the modulus of the RSA key.
165            By definition, for a key of k bits, the following formula holds:
166
167            2^(k-1) <= modulus < 2^(k)
168
169            Where ^ means "to the power of", not "xor".
170            This means that to be sure, we must choose our message < 2^(k-1).
171            This can be done by setting the most significant bit to zero.
172          */
173
174         c->outkey[0] &= 0x7F;
175
176         ifdebug(SCARY_THINGS) {
177                 bin2hex(c->outkey, buffer, len);
178                 buffer[len * 2] = '\0';
179                 logger(LOG_DEBUG, "Generated random meta key (unencrypted): %s",
180                        buffer);
181         }
182
183         /* Encrypt the random data
184
185            We do not use one of the PKCS padding schemes here.
186            This is allowed, because we encrypt a totally random string
187            with a length equal to that of the modulus of the RSA key.
188          */
189
190         if(RSA_public_encrypt(len, (unsigned char *)c->outkey, (unsigned char *)buffer, c->rsa_key, RSA_NO_PADDING) != len) {
191                 logger(LOG_ERR, "Error during encryption of meta key for %s (%s): %s",
192                        c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
193                 return false;
194         }
195
196         /* Convert the encrypted random data to a hexadecimal formatted string */
197
198         bin2hex(buffer, buffer, len);
199         buffer[len * 2] = '\0';
200
201         /* Send the meta key */
202
203         x = send_request(c, "%d %d %d %d %d %s", METAKEY,
204                          c->outcipher ? EVP_CIPHER_nid(c->outcipher) : 0,
205                          c->outdigest ? EVP_MD_type(c->outdigest) : 0, c->outmaclength,
206                          c->outcompression, buffer);
207
208         /* Further outgoing requests are encrypted with the key we just generated */
209
210         if(c->outcipher) {
211                 if(!EVP_EncryptInit(c->outctx, c->outcipher,
212                                     (unsigned char *)c->outkey + len - EVP_CIPHER_key_length(c->outcipher),
213                                     (unsigned char *)c->outkey + len - EVP_CIPHER_key_length(c->outcipher) -
214                                     EVP_CIPHER_iv_length(c->outcipher))) {
215                         logger(LOG_ERR, "Error during initialisation of cipher for %s (%s): %s",
216                                c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
217                         return false;
218                 }
219
220                 c->outbudget = byte_budget(c->outcipher);
221                 c->status.encryptout = true;
222         }
223
224         return x;
225 }
226
227 bool metakey_h(connection_t *c) {
228         char buffer[MAX_STRING_SIZE];
229         int cipher, digest, maclength, compression;
230         int len;
231
232         if(sscanf(c->buffer, "%*d %d %d %d %d " MAX_STRING, &cipher, &digest, &maclength, &compression, buffer) != 5) {
233                 logger(LOG_ERR, "Got bad %s from %s (%s)", "METAKEY", c->name,
234                        c->hostname);
235                 return false;
236         }
237
238         len = RSA_size(myself->connection->rsa_key);
239
240         /* Check if the length of the meta key is all right */
241
242         if(strlen(buffer) != len * 2) {
243                 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong keylength");
244                 return false;
245         }
246
247         /* Allocate buffers for the meta key */
248
249         c->inkey = xrealloc(c->inkey, len);
250
251         if(!c->inctx) {
252                 c->inctx = EVP_CIPHER_CTX_new();
253
254                 if(!c->inctx) {
255                         abort();
256                 }
257         }
258
259         /* Convert the challenge from hexadecimal back to binary */
260
261         if(!hex2bin(buffer, buffer, len)) {
262                 logger(LOG_ERR, "Got bad %s from %s(%s): %s", "METAKEY", c->name, c->hostname, "invalid key");
263                 return false;
264         }
265
266         /* Decrypt the meta key */
267
268         if(RSA_private_decrypt(len, (unsigned char *)buffer, (unsigned char *)c->inkey, myself->connection->rsa_key, RSA_NO_PADDING) != len) {  /* See challenge() */
269                 logger(LOG_ERR, "Error during decryption of meta key for %s (%s): %s",
270                        c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
271                 return false;
272         }
273
274         ifdebug(SCARY_THINGS) {
275                 bin2hex(c->inkey, buffer, len);
276                 buffer[len * 2] = '\0';
277                 logger(LOG_DEBUG, "Received random meta key (unencrypted): %s", buffer);
278         }
279
280         /* All incoming requests will now be encrypted. */
281
282         /* Check and lookup cipher and digest algorithms */
283
284         if(cipher) {
285                 c->incipher = EVP_get_cipherbynid(cipher);
286
287                 if(!c->incipher) {
288                         logger(LOG_ERR, "%s (%s) uses unknown cipher!", c->name, c->hostname);
289                         return false;
290                 }
291
292                 if(!EVP_DecryptInit(c->inctx, c->incipher,
293                                     (unsigned char *)c->inkey + len - EVP_CIPHER_key_length(c->incipher),
294                                     (unsigned char *)c->inkey + len - EVP_CIPHER_key_length(c->incipher) -
295                                     EVP_CIPHER_iv_length(c->incipher))) {
296                         logger(LOG_ERR, "Error during initialisation of cipher from %s (%s): %s",
297                                c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
298                         return false;
299                 }
300
301                 c->inbudget = byte_budget(c->incipher);
302                 c->status.decryptin = true;
303         } else {
304                 c->incipher = NULL;
305         }
306
307         c->inmaclength = maclength;
308
309         if(digest) {
310                 c->indigest = EVP_get_digestbynid(digest);
311
312                 if(!c->indigest) {
313                         logger(LOG_ERR, "Node %s (%s) uses unknown digest!", c->name, c->hostname);
314                         return false;
315                 }
316
317                 if(c->inmaclength > EVP_MD_size(c->indigest) || c->inmaclength < 0) {
318                         logger(LOG_ERR, "%s (%s) uses bogus MAC length!", c->name, c->hostname);
319                         return false;
320                 }
321         } else {
322                 c->indigest = NULL;
323         }
324
325         c->incompression = compression;
326
327         c->allow_request = CHALLENGE;
328
329         return send_challenge(c);
330 }
331
332 bool send_challenge(connection_t *c) {
333         /* CHECKME: what is most reasonable value for len? */
334
335         int len = RSA_size(c->rsa_key);
336
337         /* Allocate buffers for the challenge */
338
339         char buffer[2 * len + 1];
340
341         c->hischallenge = xrealloc(c->hischallenge, len);
342
343         /* Copy random data to the buffer */
344
345         if(1 != RAND_bytes((unsigned char *)c->hischallenge, len)) {
346                 int err = ERR_get_error();
347                 logger(LOG_ERR, "Failed to generate challenge (%s)", ERR_error_string(err, NULL));
348                 return false; // Do not send predictable challenges, let connection attempt fail.
349         }
350
351         /* Convert to hex */
352
353         bin2hex(c->hischallenge, buffer, len);
354         buffer[len * 2] = '\0';
355
356         /* Send the challenge */
357
358         return send_request(c, "%d %s", CHALLENGE, buffer);
359 }
360
361 bool challenge_h(connection_t *c) {
362         char buffer[MAX_STRING_SIZE];
363         int len;
364
365         if(sscanf(c->buffer, "%*d " MAX_STRING, buffer) != 1) {
366                 logger(LOG_ERR, "Got bad %s from %s (%s)", "CHALLENGE", c->name,
367                        c->hostname);
368                 return false;
369         }
370
371         len = RSA_size(myself->connection->rsa_key);
372
373         /* Check if the length of the challenge is all right */
374
375         if(strlen(buffer) != len * 2) {
376                 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name,
377                        c->hostname, "wrong challenge length");
378                 return false;
379         }
380
381         /* Allocate buffers for the challenge */
382
383         c->mychallenge = xrealloc(c->mychallenge, len);
384
385         /* Convert the challenge from hexadecimal back to binary */
386
387         if(!hex2bin(buffer, c->mychallenge, len)) {
388                 logger(LOG_ERR, "Got bad %s from %s(%s): %s", "CHALLENGE", c->name, c->hostname, "invalid challenge");
389                 return false;
390         }
391
392         c->allow_request = CHAL_REPLY;
393
394         /* Rest is done by send_chal_reply() */
395
396         return send_chal_reply(c);
397 }
398
399 bool send_chal_reply(connection_t *c) {
400         char hash[EVP_MAX_MD_SIZE * 2 + 1];
401         EVP_MD_CTX *ctx;
402
403         /* Calculate the hash from the challenge we received */
404
405         ctx = EVP_MD_CTX_create();
406
407         if(!ctx) {
408                 abort();
409         }
410
411         if(!EVP_DigestInit(ctx, c->indigest)
412                         || !EVP_DigestUpdate(ctx, c->mychallenge, RSA_size(myself->connection->rsa_key))
413                         || !EVP_DigestFinal(ctx, (unsigned char *)hash, NULL)) {
414                 EVP_MD_CTX_destroy(ctx);
415                 logger(LOG_ERR, "Error during calculation of response for %s (%s): %s",
416                        c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
417                 return false;
418         }
419
420         EVP_MD_CTX_destroy(ctx);
421
422         /* Convert the hash to a hexadecimal formatted string */
423
424         bin2hex(hash, hash, EVP_MD_size(c->indigest));
425         hash[EVP_MD_size(c->indigest) * 2] = '\0';
426
427         /* Send the reply */
428
429         return send_request(c, "%d %s", CHAL_REPLY, hash);
430 }
431
432 bool chal_reply_h(connection_t *c) {
433         char hishash[MAX_STRING_SIZE];
434         char myhash[EVP_MAX_MD_SIZE];
435         EVP_MD_CTX *ctx;
436
437         if(sscanf(c->buffer, "%*d " MAX_STRING, hishash) != 1) {
438                 logger(LOG_ERR, "Got bad %s from %s (%s)", "CHAL_REPLY", c->name,
439                        c->hostname);
440                 return false;
441         }
442
443         /* Check if the length of the hash is all right */
444
445         if(strlen(hishash) != EVP_MD_size(c->outdigest) * 2) {
446                 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name,
447                        c->hostname, "wrong challenge reply length");
448                 return false;
449         }
450
451         /* Convert the hash to binary format */
452
453         if(!hex2bin(hishash, hishash, EVP_MD_size(c->outdigest))) {
454                 logger(LOG_ERR, "Got bad %s from %s(%s): %s", "CHAL_REPLY", c->name, c->hostname, "invalid hash");
455                 return false;
456         }
457
458         /* Calculate the hash from the challenge we sent */
459
460         ctx = EVP_MD_CTX_create();
461
462         if(!ctx) {
463                 abort();
464         }
465
466         if(!EVP_DigestInit(ctx, c->outdigest)
467                         || !EVP_DigestUpdate(ctx, c->hischallenge, RSA_size(c->rsa_key))
468                         || !EVP_DigestFinal(ctx, (unsigned char *)myhash, NULL)) {
469                 EVP_MD_CTX_destroy(ctx);
470                 logger(LOG_ERR, "Error during calculation of response from %s (%s): %s",
471                        c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
472                 return false;
473         }
474
475         EVP_MD_CTX_destroy(ctx);
476
477         /* Verify the incoming hash with the calculated hash */
478
479         if(memcmp(hishash, myhash, EVP_MD_size(c->outdigest))) {
480                 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name,
481                        c->hostname, "wrong challenge reply");
482
483                 ifdebug(SCARY_THINGS) {
484                         bin2hex(myhash, hishash, SHA_DIGEST_LENGTH);
485                         hishash[SHA_DIGEST_LENGTH * 2] = '\0';
486                         logger(LOG_DEBUG, "Expected challenge reply: %s", hishash);
487                 }
488
489                 return false;
490         }
491
492         /* Identity has now been positively verified.
493            Send an acknowledgement with the rest of the information needed.
494          */
495
496         c->allow_request = ACK;
497
498         return send_ack(c);
499 }
500
501 bool send_ack(connection_t *c) {
502         /* ACK message contains rest of the information the other end needs
503            to create node_t and edge_t structures. */
504
505         struct timeval now;
506         bool choice;
507
508         /* Estimate weight */
509
510         gettimeofday(&now, NULL);
511         c->estimated_weight = (now.tv_sec - c->start.tv_sec) * 1000 + (now.tv_usec - c->start.tv_usec) / 1000;
512
513         /* Check some options */
514
515         if((get_config_bool(lookup_config(c->config_tree, "IndirectData"), &choice) && choice) || myself->options & OPTION_INDIRECT) {
516                 c->options |= OPTION_INDIRECT;
517         }
518
519         if((get_config_bool(lookup_config(c->config_tree, "TCPOnly"), &choice) && choice) || myself->options & OPTION_TCPONLY) {
520                 c->options |= OPTION_TCPONLY | OPTION_INDIRECT;
521         }
522
523         if(myself->options & OPTION_PMTU_DISCOVERY) {
524                 c->options |= OPTION_PMTU_DISCOVERY;
525         }
526
527         choice = myself->options & OPTION_CLAMP_MSS;
528         get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice);
529
530         if(choice) {
531                 c->options |= OPTION_CLAMP_MSS;
532         }
533
534         get_config_int(lookup_config(c->config_tree, "Weight"), &c->estimated_weight);
535
536         return send_request(c, "%d %s %d %x", ACK, myport, c->estimated_weight, c->options);
537 }
538
539 static void send_everything(connection_t *c) {
540         avl_node_t *node, *node2;
541         node_t *n;
542         subnet_t *s;
543         edge_t *e;
544
545         /* Send all known subnets and edges */
546
547         if(tunnelserver) {
548                 for(node = myself->subnet_tree->head; node; node = node->next) {
549                         s = node->data;
550                         send_add_subnet(c, s);
551                 }
552
553                 return;
554         }
555
556         for(node = node_tree->head; node; node = node->next) {
557                 n = node->data;
558
559                 for(node2 = n->subnet_tree->head; node2; node2 = node2->next) {
560                         s = node2->data;
561                         send_add_subnet(c, s);
562                 }
563
564                 for(node2 = n->edge_tree->head; node2; node2 = node2->next) {
565                         e = node2->data;
566                         send_add_edge(c, e);
567                 }
568         }
569 }
570
571 bool ack_h(connection_t *c) {
572         char hisport[MAX_STRING_SIZE];
573         int weight, mtu;
574         uint32_t options;
575         node_t *n;
576         bool choice;
577
578         if(sscanf(c->buffer, "%*d " MAX_STRING " %d %x", hisport, &weight, &options) != 3) {
579                 logger(LOG_ERR, "Got bad %s from %s (%s)", "ACK", c->name,
580                        c->hostname);
581                 return false;
582         }
583
584         /* Check if we already have a node_t for him */
585
586         n = lookup_node(c->name);
587
588         if(!n) {
589                 n = new_node();
590                 n->name = xstrdup(c->name);
591                 node_add(n);
592         } else {
593                 if(n->connection) {
594                         /* Oh dear, we already have a connection to this node. */
595                         ifdebug(CONNECTIONS) logger(LOG_DEBUG, "Established a second connection with %s (%s), closing old connection",
596                                                     n->name, n->hostname);
597                         terminate_connection(n->connection, false);
598                         /* Run graph algorithm to purge key and make sure up/down scripts are rerun with new IP addresses and stuff */
599                         graph();
600                 }
601         }
602
603         n->connection = c;
604         c->node = n;
605
606         if(!(c->options & options & OPTION_PMTU_DISCOVERY)) {
607                 c->options &= ~OPTION_PMTU_DISCOVERY;
608                 options &= ~OPTION_PMTU_DISCOVERY;
609         }
610
611         c->options |= options;
612
613         if(get_config_int(lookup_config(c->config_tree, "PMTU"), &mtu) && mtu < n->mtu) {
614                 n->mtu = mtu;
615         }
616
617         if(get_config_int(lookup_config(config_tree, "PMTU"), &mtu) && mtu < n->mtu) {
618                 n->mtu = mtu;
619         }
620
621         if(get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice)) {
622                 if(choice) {
623                         c->options |= OPTION_CLAMP_MSS;
624                 } else {
625                         c->options &= ~OPTION_CLAMP_MSS;
626                 }
627         }
628
629         /* Activate this connection */
630
631         c->allow_request = ALL;
632         c->status.active = true;
633
634         ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Connection with %s (%s) activated", c->name,
635                                     c->hostname);
636
637         /* Send him everything we know */
638
639         send_everything(c);
640
641         /* Create an edge_t for this connection */
642
643         c->edge = new_edge();
644         c->edge->from = myself;
645         c->edge->to = n;
646         sockaddrcpy(&c->edge->address, &c->address);
647         sockaddr_setport(&c->edge->address, hisport);
648         c->edge->weight = (weight + c->estimated_weight) / 2;
649         c->edge->connection = c;
650         c->edge->options = c->options;
651
652         edge_add(c->edge);
653
654         /* Notify everyone of the new edge */
655
656         if(tunnelserver) {
657                 send_add_edge(c, c->edge);
658         } else {
659                 send_add_edge(everyone, c->edge);
660         }
661
662         /* Run MST and SSSP algorithms */
663
664         graph();
665
666         return true;
667 }