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