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