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