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