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