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