Remove redundant spaces.
[tinc] / 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.17 2002/09/09 22:32:59 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(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
228            (c->buffer, "%*d %d %d %d %d " MAX_STRING, &cipher, &digest, &maclength,
229                 &compression, buffer) != 5) {
230                 syslog(LOG_ERR, _("Got bad %s from %s (%s)"), "METAKEY", c->name,
231                            c->hostname);
232                 return -1;
233         }
234
235         len = RSA_size(myself->connection->rsa_key);
236
237         /* Check if the length of the meta key is all right */
238
239         if(strlen(buffer) != len * 2) {
240                 syslog(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name,
241                            c->hostname, "wrong keylength");
242                 return -1;
243         }
244
245         /* Allocate buffers for the meta key */
246
247         if(!c->inkey)
248                 c->inkey = xmalloc(len);
249
250         if(!c->inctx)
251                 c->inctx = xmalloc(sizeof(*c->inctx));
252
253         /* Convert the challenge from hexadecimal back to binary */
254
255         hex2bin(buffer, buffer, len);
256
257         /* Decrypt the meta key */
258
259         if(RSA_private_decrypt(len, buffer, c->inkey, myself->connection->rsa_key, RSA_NO_PADDING) != len) {    /* See challenge() */
260                 syslog(LOG_ERR, _("Error during encryption of meta key for %s (%s)"),
261                            c->name, c->hostname);
262                 return -1;
263         }
264
265         if(debug_lvl >= DEBUG_SCARY_THINGS) {
266                 bin2hex(c->inkey, buffer, len);
267                 buffer[len * 2] = '\0';
268                 syslog(LOG_DEBUG, _("Received random meta key (unencrypted): %s"),
269                            buffer);
270         }
271
272         /* All incoming requests will now be encrypted. */
273
274         /* Check and lookup cipher and digest algorithms */
275
276         if(cipher) {
277                 c->incipher = EVP_get_cipherbynid(cipher);
278
279                 if(!c->incipher) {
280                         syslog(LOG_ERR, _("%s (%s) uses unknown cipher!"), c->name,
281                                    c->hostname);
282                         return -1;
283                 }
284
285                 EVP_DecryptInit(c->inctx, c->incipher,
286                                                 c->inkey + len - c->incipher->key_len,
287                                                 c->inkey + len - c->incipher->key_len -
288                                                 c->incipher->iv_len);
289
290                 c->status.decryptin = 1;
291         } else {
292                 c->incipher = NULL;
293         }
294
295         c->inmaclength = maclength;
296
297         if(digest) {
298                 c->indigest = EVP_get_digestbynid(digest);
299
300                 if(!c->indigest) {
301                         syslog(LOG_ERR, _("Node %s (%s) uses unknown digest!"), c->name,
302                                    c->hostname);
303                         return -1;
304                 }
305
306                 if(c->inmaclength > c->indigest->md_size || c->inmaclength < 0) {
307                         syslog(LOG_ERR, _("%s (%s) uses bogus MAC length!"), c->name,
308                                    c->hostname);
309                         return -1;
310                 }
311         } else {
312                 c->indigest = NULL;
313         }
314
315         c->incompression = compression;
316
317         c->allow_request = CHALLENGE;
318
319         return send_challenge(c);
320 }
321
322 int send_challenge(connection_t *c)
323 {
324         char buffer[MAX_STRING_SIZE];
325         int len, x;
326
327         cp();
328
329         /* CHECKME: what is most reasonable value for len? */
330
331         len = RSA_size(c->rsa_key);
332
333         /* Allocate buffers for the challenge */
334
335         if(!c->hischallenge)
336                 c->hischallenge = xmalloc(len);
337
338         /* Copy random data to the buffer */
339
340         RAND_bytes(c->hischallenge, len);
341
342         /* Convert to hex */
343
344         bin2hex(c->hischallenge, buffer, len);
345         buffer[len * 2] = '\0';
346
347         /* Send the challenge */
348
349         x = send_request(c, "%d %s", CHALLENGE, buffer);
350
351         return x;
352 }
353
354 int challenge_h(connection_t *c)
355 {
356         char buffer[MAX_STRING_SIZE];
357         int len;
358
359         cp();
360
361         if(sscanf(c->buffer, "%*d " MAX_STRING, buffer) != 1) {
362                 syslog(LOG_ERR, _("Got bad %s from %s (%s)"), "CHALLENGE", c->name,
363                            c->hostname);
364                 return -1;
365         }
366
367         len = RSA_size(myself->connection->rsa_key);
368
369         /* Check if the length of the challenge is all right */
370
371         if(strlen(buffer) != len * 2) {
372                 syslog(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name,
373                            c->hostname, "wrong challenge length");
374                 return -1;
375         }
376
377         /* Allocate buffers for the challenge */
378
379         if(!c->mychallenge)
380                 c->mychallenge = xmalloc(len);
381
382         /* Convert the challenge from hexadecimal back to binary */
383
384         hex2bin(buffer, c->mychallenge, len);
385
386         c->allow_request = CHAL_REPLY;
387
388         /* Rest is done by send_chal_reply() */
389
390         return send_chal_reply(c);
391 }
392
393 int send_chal_reply(connection_t *c)
394 {
395         char hash[EVP_MAX_MD_SIZE * 2 + 1];
396         EVP_MD_CTX ctx;
397
398         cp();
399
400         /* Calculate the hash from the challenge we received */
401
402         EVP_DigestInit(&ctx, c->indigest);
403         EVP_DigestUpdate(&ctx, c->mychallenge,
404                                          RSA_size(myself->connection->rsa_key));
405         EVP_DigestFinal(&ctx, hash, NULL);
406
407         /* Convert the hash to a hexadecimal formatted string */
408
409         bin2hex(hash, hash, c->indigest->md_size);
410         hash[c->indigest->md_size * 2] = '\0';
411
412         /* Send the reply */
413
414         return send_request(c, "%d %s", CHAL_REPLY, hash);
415 }
416
417 int chal_reply_h(connection_t *c)
418 {
419         char hishash[MAX_STRING_SIZE];
420         char myhash[EVP_MAX_MD_SIZE];
421         EVP_MD_CTX ctx;
422
423         cp();
424
425         if(sscanf(c->buffer, "%*d " MAX_STRING, hishash) != 1) {
426                 syslog(LOG_ERR, _("Got bad %s from %s (%s)"), "CHAL_REPLY", c->name,
427                            c->hostname);
428                 return -1;
429         }
430
431         /* Check if the length of the hash is all right */
432
433         if(strlen(hishash) != c->outdigest->md_size * 2) {
434                 syslog(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name,
435                            c->hostname, _("wrong challenge reply length"));
436                 return -1;
437         }
438
439         /* Convert the hash to binary format */
440
441         hex2bin(hishash, hishash, c->outdigest->md_size);
442
443         /* Calculate the hash from the challenge we sent */
444
445         EVP_DigestInit(&ctx, c->outdigest);
446         EVP_DigestUpdate(&ctx, c->hischallenge, RSA_size(c->rsa_key));
447         EVP_DigestFinal(&ctx, myhash, NULL);
448
449         /* Verify the incoming hash with the calculated hash */
450
451         if(memcmp(hishash, myhash, c->outdigest->md_size)) {
452                 syslog(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name,
453                            c->hostname, _("wrong challenge reply"));
454
455                 if(debug_lvl >= DEBUG_SCARY_THINGS) {
456                         bin2hex(myhash, hishash, SHA_DIGEST_LENGTH);
457                         hishash[SHA_DIGEST_LENGTH * 2] = '\0';
458                         syslog(LOG_DEBUG, _("Expected challenge reply: %s"), hishash);
459                 }
460
461                 return -1;
462         }
463
464         /* Identity has now been positively verified.
465            Send an acknowledgement with the rest of the information needed.
466          */
467
468         c->allow_request = ACK;
469
470         return send_ack(c);
471 }
472
473 int send_ack(connection_t *c)
474 {
475         /* ACK message contains rest of the information the other end needs
476            to create node_t and edge_t structures. */
477
478         int x;
479         struct timeval now;
480
481         cp();
482
483         /* Estimate weight */
484
485         gettimeofday(&now, NULL);
486         c->estimated_weight =
487                 (now.tv_sec - c->start.tv_sec) * 1000 + (now.tv_usec -
488                                                                                                  c->start.tv_usec) / 1000;
489         x = send_request(c, "%d %s %d %lx", ACK, myport, c->estimated_weight,
490                                          c->options);
491
492         return x;
493 }
494
495 void send_everything(connection_t *c)
496 {
497         avl_node_t *node, *node2;
498         node_t *n;
499         subnet_t *s;
500         edge_t *e;
501
502         /* Send all known subnets and edges */
503
504         for(node = node_tree->head; node; node = node->next) {
505                 n = (node_t *) node->data;
506
507                 for(node2 = n->subnet_tree->head; node2; node2 = node2->next) {
508                         s = (subnet_t *) node2->data;
509                         send_add_subnet(c, s);
510                 }
511
512                 for(node2 = n->edge_tree->head; node2; node2 = node2->next) {
513                         e = (edge_t *) node2->data;
514                         send_add_edge(c, e);
515                 }
516         }
517 }
518
519 int ack_h(connection_t *c)
520 {
521         char hisport[MAX_STRING_SIZE];
522         char *hisaddress, *dummy;
523         int weight;
524         long int options;
525         node_t *n;
526
527         cp();
528
529         if(sscanf
530            (c->buffer, "%*d " MAX_STRING " %d %lx", hisport, &weight, &options) != 3) {
531                 syslog(LOG_ERR, _("Got bad %s from %s (%s)"), "ACK", c->name,
532                            c->hostname);
533                 return -1;
534         }
535
536         /* Check if we already have a node_t for him */
537
538         n = lookup_node(c->name);
539
540         if(!n) {
541                 n = new_node();
542                 n->name = xstrdup(c->name);
543                 node_add(n);
544         } else {
545                 if(n->connection) {
546                         /* Oh dear, we already have a connection to this node. */
547                         if(debug_lvl >= DEBUG_CONNECTIONS)
548                                 syslog(LOG_DEBUG, _("Established a second connection with %s (%s), closing old connection"),
549                                            n->name, n->hostname);
550                         terminate_connection(n->connection, 0);
551                 }
552         }
553
554         n->connection = c;
555         c->node = n;
556         c->options |= options;
557
558         /* Activate this connection */
559
560         c->allow_request = ALL;
561         c->status.active = 1;
562
563         if(debug_lvl >= DEBUG_CONNECTIONS)
564                 syslog(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         send_add_edge(broadcast, c->edge);
590
591         /* Run MST and SSSP algorithms */
592
593         graph();
594
595         return 0;
596 }