4c885623f34b755eecbc173418af4258cf24714e
[tinc] / src / protocol_auth.c
1 /*
2     protocol_auth.c -- handle the meta-protocol, authentication
3     Copyright (C) 1999-2005 Ivo Timmermans <ivo@tinc-vpn.org>,
4                   2000-2005 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
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20     $Id$
21 */
22
23 #include "system.h"
24
25 #include <openssl/sha.h>
26 #include <openssl/rand.h>
27 #include <openssl/err.h>
28 #include <openssl/evp.h>
29
30 #include "avl_tree.h"
31 #include "conf.h"
32 #include "connection.h"
33 #include "edge.h"
34 #include "graph.h"
35 #include "logger.h"
36 #include "net.h"
37 #include "netutl.h"
38 #include "node.h"
39 #include "protocol.h"
40 #include "utils.h"
41 #include "xalloc.h"
42
43 bool send_id(connection_t *c)
44 {
45         cp();
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 {
53         char name[MAX_STRING_SIZE];
54
55         cp();
56
57         if(sscanf(c->buffer, "%*d " MAX_STRING " %d", name, &c->protocol_version) != 2) {
58                 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "ID", c->name,
59                            c->hostname);
60                 return false;
61         }
62
63         /* Check if identity is a valid name */
64
65         if(!check_id(name)) {
66                 logger(LOG_ERR, _("Got bad %s from %s (%s): %s"), "ID", c->name,
67                            c->hostname, "invalid name");
68                 return false;
69         }
70
71         /* If we set c->name in advance, make sure we are connected to the right host */
72
73         if(c->name) {
74                 if(strcmp(c->name, name)) {
75                         logger(LOG_ERR, _("Peer %s is %s instead of %s"), c->hostname, name,
76                                    c->name);
77                         return false;
78                 }
79         } else {
80                 if(c->name)
81                         free(c->name);
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                 c->allow_request = ACK;
97                 return send_ack(c);
98         }
99
100         if(!c->config_tree) {
101                 init_configuration(&c->config_tree);
102
103                 if(!read_connection_config(c)) {
104                         logger(LOG_ERR, _("Peer %s had unknown identity (%s)"), c->hostname,
105                                    c->name);
106                         return false;
107                 }
108         }
109
110         if(!read_rsa_public_key(c)) {
111                 return false;
112         }
113
114         c->allow_request = METAKEY;
115
116         return send_metakey(c);
117 }
118
119 bool send_metakey(connection_t *c)
120 {
121         char *buffer;
122         int len;
123         bool x;
124
125         cp();
126
127         len = RSA_size(c->rsa_key);
128
129         /* Allocate buffers for the meta key */
130
131         buffer = alloca(2 * len + 1);
132         
133         if(!c->outkey)
134                 c->outkey = xmalloc(len);
135
136         if(!c->outctx)
137                 c->outctx = xmalloc_and_zero(sizeof(*c->outctx));
138         cp();
139         /* Copy random data to the buffer */
140
141         RAND_pseudo_bytes((unsigned char *)c->outkey, len);
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)"),
171                            c->name, c->hostname);
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 ? c->outcipher->nid : 0,
184                                          c->outdigest ? c->outdigest->type : 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 - c->outcipher->key_len,
192                                         (unsigned char *)c->outkey + len - c->outcipher->key_len -
193                                         c->outcipher->iv_len)) {
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 {
207         char buffer[MAX_STRING_SIZE];
208         int cipher, digest, maclength, compression;
209         int len;
210
211         cp();
212
213         if(sscanf(c->buffer, "%*d %d %d %d %d " MAX_STRING, &cipher, &digest, &maclength, &compression, buffer) != 5) {
214                 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "METAKEY", c->name,
215                            c->hostname);
216                 return false;
217         }
218
219         len = RSA_size(myself->connection->rsa_key);
220
221         /* Check if the length of the meta key is all right */
222
223         if(strlen(buffer) != len * 2) {
224                 logger(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name, c->hostname, "wrong keylength");
225                 return false;
226         }
227
228         /* Allocate buffers for the meta key */
229
230         if(!c->inkey)
231                 c->inkey = xmalloc(len);
232
233         if(!c->inctx)
234                 c->inctx = xmalloc_and_zero(sizeof(*c->inctx));
235
236         /* Convert the challenge from hexadecimal back to binary */
237
238         hex2bin(buffer, buffer, len);
239
240         /* Decrypt the meta key */
241
242         if(RSA_private_decrypt(len, (unsigned char *)buffer, (unsigned char *)c->inkey, myself->connection->rsa_key, RSA_NO_PADDING) != len) {  /* See challenge() */
243                 logger(LOG_ERR, _("Error during encryption of meta key for %s (%s)"),
244                            c->name, c->hostname);
245                 return false;
246         }
247
248         ifdebug(SCARY_THINGS) {
249                 bin2hex(c->inkey, buffer, len);
250                 buffer[len * 2] = '\0';
251                 logger(LOG_DEBUG, _("Received random meta key (unencrypted): %s"), buffer);
252         }
253
254         /* All incoming requests will now be encrypted. */
255
256         /* Check and lookup cipher and digest algorithms */
257
258         if(cipher) {
259                 c->incipher = EVP_get_cipherbynid(cipher);
260                 
261                 if(!c->incipher) {
262                         logger(LOG_ERR, _("%s (%s) uses unknown cipher!"), c->name, c->hostname);
263                         return false;
264                 }
265
266                 if(!EVP_DecryptInit(c->inctx, c->incipher,
267                                         (unsigned char *)c->inkey + len - c->incipher->key_len,
268                                         (unsigned char *)c->inkey + len - c->incipher->key_len -
269                                         c->incipher->iv_len)) {
270                         logger(LOG_ERR, _("Error during initialisation of cipher from %s (%s): %s"),
271                                         c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
272                         return false;
273                 }
274
275                 c->status.decryptin = true;
276         } else {
277                 c->incipher = NULL;
278         }
279
280         c->inmaclength = maclength;
281
282         if(digest) {
283                 c->indigest = EVP_get_digestbynid(digest);
284
285                 if(!c->indigest) {
286                         logger(LOG_ERR, _("Node %s (%s) uses unknown digest!"), c->name, c->hostname);
287                         return false;
288                 }
289
290                 if(c->inmaclength > c->indigest->md_size || c->inmaclength < 0) {
291                         logger(LOG_ERR, _("%s (%s) uses bogus MAC length!"), c->name, c->hostname);
292                         return false;
293                 }
294         } else {
295                 c->indigest = NULL;
296         }
297
298         c->incompression = compression;
299
300         c->allow_request = CHALLENGE;
301
302         return send_challenge(c);
303 }
304
305 bool send_challenge(connection_t *c)
306 {
307         char *buffer;
308         int len;
309
310         cp();
311
312         /* CHECKME: what is most reasonable value for len? */
313
314         len = RSA_size(c->rsa_key);
315
316         /* Allocate buffers for the challenge */
317
318         buffer = alloca(2 * len + 1);
319
320         if(!c->hischallenge)
321                 c->hischallenge = xmalloc(len);
322
323         /* Copy random data to the buffer */
324
325         RAND_pseudo_bytes((unsigned char *)c->hischallenge, len);
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 {
339         char buffer[MAX_STRING_SIZE];
340         int len;
341
342         cp();
343
344         if(sscanf(c->buffer, "%*d " MAX_STRING, buffer) != 1) {
345                 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "CHALLENGE", c->name,
346                            c->hostname);
347                 return false;
348         }
349
350         len = RSA_size(myself->connection->rsa_key);
351
352         /* Check if the length of the challenge is all right */
353
354         if(strlen(buffer) != len * 2) {
355                 logger(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name,
356                            c->hostname, "wrong challenge length");
357                 return false;
358         }
359
360         /* Allocate buffers for the challenge */
361
362         if(!c->mychallenge)
363                 c->mychallenge = xmalloc(len);
364
365         /* Convert the challenge from hexadecimal back to binary */
366
367         hex2bin(buffer, c->mychallenge, len);
368
369         c->allow_request = CHAL_REPLY;
370
371         /* Rest is done by send_chal_reply() */
372
373         return send_chal_reply(c);
374 }
375
376 bool send_chal_reply(connection_t *c)
377 {
378         char hash[EVP_MAX_MD_SIZE * 2 + 1];
379         EVP_MD_CTX ctx;
380
381         cp();
382
383         /* Calculate the hash from the challenge we received */
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                 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         /* Convert the hash to a hexadecimal formatted string */
394
395         bin2hex(hash, hash, c->indigest->md_size);
396         hash[c->indigest->md_size * 2] = '\0';
397
398         /* Send the reply */
399
400         return send_request(c, "%d %s", CHAL_REPLY, hash);
401 }
402
403 bool chal_reply_h(connection_t *c)
404 {
405         char hishash[MAX_STRING_SIZE];
406         char myhash[EVP_MAX_MD_SIZE];
407         EVP_MD_CTX ctx;
408
409         cp();
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) != c->outdigest->md_size * 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         hex2bin(hishash, hishash, c->outdigest->md_size);
428
429         /* Calculate the hash from the challenge we sent */
430
431         if(!EVP_DigestInit(&ctx, c->outdigest)
432                         || !EVP_DigestUpdate(&ctx, c->hischallenge, RSA_size(c->rsa_key))
433                         || !EVP_DigestFinal(&ctx, (unsigned char *)myhash, NULL)) {
434                 logger(LOG_ERR, _("Error during calculation of response from %s (%s): %s"),
435                         c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
436                 return false;
437         }
438
439         /* Verify the incoming hash with the calculated hash */
440
441         if(memcmp(hishash, myhash, c->outdigest->md_size)) {
442                 logger(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name,
443                            c->hostname, _("wrong challenge reply"));
444
445                 ifdebug(SCARY_THINGS) {
446                         bin2hex(myhash, hishash, SHA_DIGEST_LENGTH);
447                         hishash[SHA_DIGEST_LENGTH * 2] = '\0';
448                         logger(LOG_DEBUG, _("Expected challenge reply: %s"), hishash);
449                 }
450
451                 return false;
452         }
453
454         /* Identity has now been positively verified.
455            Send an acknowledgement with the rest of the information needed.
456          */
457
458         c->allow_request = ACK;
459
460         return send_ack(c);
461 }
462
463 bool send_ack(connection_t *c)
464 {
465         /* ACK message contains rest of the information the other end needs
466            to create node_t and edge_t structures. */
467
468         struct timeval now;
469         bool choice;
470
471         cp();
472
473         /* Estimate weight */
474
475         gettimeofday(&now, NULL);
476         c->estimated_weight = (now.tv_sec - c->start.tv_sec) * 1000 + (now.tv_usec - c->start.tv_usec) / 1000;
477
478         /* Check some options */
479
480         if((get_config_bool(lookup_config(c->config_tree, "IndirectData"), &choice) && choice) || myself->options & OPTION_INDIRECT)
481                 c->options |= OPTION_INDIRECT;
482
483         if((get_config_bool(lookup_config(c->config_tree, "TCPOnly"), &choice) && choice) || myself->options & OPTION_TCPONLY)
484                 c->options |= OPTION_TCPONLY | OPTION_INDIRECT;
485
486         if((get_config_bool(lookup_config(c->config_tree, "PMTUDiscovery"), &choice) && choice) || myself->options & OPTION_PMTU_DISCOVERY)
487                 c->options |= OPTION_PMTU_DISCOVERY;
488
489         get_config_int(lookup_config(c->config_tree, "Weight"), &c->estimated_weight);
490
491         return send_request(c, "%d %s %d %lx", ACK, myport, c->estimated_weight, c->options);
492 }
493
494 static void send_everything(connection_t *c)
495 {
496         avl_node_t *node, *node2;
497         node_t *n;
498         subnet_t *s;
499         edge_t *e;
500
501         /* Send all known subnets and edges */
502
503         if(tunnelserver) {
504                 for(node = myself->subnet_tree->head; node; node = node->next) {
505                         s = node->data;
506                         send_add_subnet(c, s);
507                 }
508
509                 return;
510         }
511
512         for(node = node_tree->head; node; node = node->next) {
513                 n = node->data;
514
515                 for(node2 = n->subnet_tree->head; node2; node2 = node2->next) {
516                         s = node2->data;
517                         send_add_subnet(c, s);
518                 }
519
520                 for(node2 = n->edge_tree->head; node2; node2 = node2->next) {
521                         e = node2->data;
522                         send_add_edge(c, e);
523                 }
524         }
525 }
526
527 bool ack_h(connection_t *c)
528 {
529         char hisport[MAX_STRING_SIZE];
530         char *hisaddress, *dummy;
531         int weight, mtu;
532         long int options;
533         node_t *n;
534
535         cp();
536
537         if(sscanf(c->buffer, "%*d " MAX_STRING " %d %lx", hisport, &weight, &options) != 3) {
538                 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "ACK", c->name,
539                            c->hostname);
540                 return false;
541         }
542
543         /* Check if we already have a node_t for him */
544
545         n = lookup_node(c->name);
546
547         if(!n) {
548                 n = new_node();
549                 n->name = xstrdup(c->name);
550                 node_add(n);
551         } else {
552                 if(n->connection) {
553                         /* Oh dear, we already have a connection to this node. */
554                         ifdebug(CONNECTIONS) logger(LOG_DEBUG, _("Established a second connection with %s (%s), closing old connection"),
555                                            n->name, n->hostname);
556                         terminate_connection(n->connection, false);
557                         /* Run graph algorithm to purge key and make sure up/down scripts are rerun with new IP addresses and stuff */
558                         graph();
559                 }
560         }
561
562         n->connection = c;
563         c->node = n;
564         c->options |= options;
565
566         if(get_config_int(lookup_config(c->config_tree, "PMTU"), &mtu) && mtu < n->mtu)
567                 n->mtu = mtu;
568
569         if(get_config_int(lookup_config(myself->connection->config_tree, "PMTU"), &mtu) && mtu < n->mtu)
570                 n->mtu = mtu;
571
572         /* Activate this connection */
573
574         c->allow_request = ALL;
575         c->status.active = true;
576
577         ifdebug(CONNECTIONS) logger(LOG_NOTICE, _("Connection with %s (%s) activated"), c->name,
578                            c->hostname);
579
580         /* Send him everything we know */
581
582         send_everything(c);
583
584         /* Create an edge_t for this connection */
585
586         c->edge = new_edge();
587         cp();
588         c->edge->from = myself;
589         c->edge->to = n;
590         sockaddr2str(&c->address, &hisaddress, &dummy);
591         c->edge->address = str2sockaddr(hisaddress, hisport);
592         free(hisaddress);
593         free(dummy);
594         c->edge->weight = (weight + c->estimated_weight) / 2;
595         c->edge->connection = c;
596         c->edge->options = c->options;
597
598         edge_add(c->edge);
599
600         /* Notify everyone of the new edge */
601
602         if(tunnelserver)
603                 send_add_edge(c, c->edge);
604         else
605                 send_add_edge(broadcast, c->edge);
606
607         /* Run MST and SSSP algorithms */
608
609         graph();
610
611         return true;
612 }