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