Big header file cleanup: everything that has to do with standard system
[tinc] / 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.24 2003/07/17 15:06:26 guus Exp $
21 */
22
23 #include "system.h"
24
25 #include <openssl/sha.h>
26 #include <openssl/rand.h>
27 #include <openssl/evp.h>
28
29 #include "avl_tree.h"
30 #include "conf.h"
31 #include "connection.h"
32 #include "edge.h"
33 #include "graph.h"
34 #include "logger.h"
35 #include "net.h"
36 #include "netutl.h"
37 #include "node.h"
38 #include "protocol.h"
39 #include "utils.h"
40 #include "xalloc.h"
41
42 int send_id(connection_t *c)
43 {
44         cp();
45
46         return send_request(c, "%d %s %d", ID, myself->connection->name,
47                                                 myself->connection->protocol_version);
48 }
49
50 int id_h(connection_t *c)
51 {
52         char name[MAX_STRING_SIZE];
53         int bla;
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 -1;
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 -1;
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 -1;
78                 }
79         } else
80                 c->name = xstrdup(name);
81
82         /* Check if version matches */
83
84         if(c->protocol_version != myself->connection->protocol_version) {
85                 logger(LOG_ERR, _("Peer %s (%s) uses incompatible version %d"),
86                            c->name, c->hostname, c->protocol_version);
87                 return -1;
88         }
89
90         if(bypass_security) {
91                 if(!c->config_tree)
92                         init_configuration(&c->config_tree);
93                 c->allow_request = ACK;
94                 return send_ack(c);
95         }
96
97         if(!c->config_tree) {
98                 init_configuration(&c->config_tree);
99
100                 bla = read_connection_config(c);
101
102                 if(bla) {
103                         logger(LOG_ERR, _("Peer %s had unknown identity (%s)"), c->hostname,
104                                    c->name);
105                         return -1;
106                 }
107         }
108
109         if(read_rsa_public_key(c)) {
110                 return -1;
111         }
112
113         /* Check some options */
114
115         if((get_config_bool(lookup_config(c->config_tree, "IndirectData"), &bla) && bla) || myself->options & OPTION_INDIRECT)
116                 c->options |= OPTION_INDIRECT;
117
118         if((get_config_bool(lookup_config(c->config_tree, "TCPOnly"), &bla) && bla) || myself->options & OPTION_TCPONLY)
119                 c->options |= OPTION_TCPONLY | OPTION_INDIRECT;
120
121         c->allow_request = METAKEY;
122
123         return send_metakey(c);
124 }
125
126 int send_metakey(connection_t *c)
127 {
128         char buffer[MAX_STRING_SIZE];
129         int len, x;
130
131         cp();
132
133         len = RSA_size(c->rsa_key);
134
135         /* Allocate buffers for the meta key */
136
137         if(!c->outkey)
138                 c->outkey = xmalloc(len);
139
140         if(!c->outctx)
141                 c->outctx = xmalloc_and_zero(sizeof(*c->outctx));
142         cp();
143         /* Copy random data to the buffer */
144
145         RAND_bytes(c->outkey, len);
146
147         /* The message we send must be smaller than the modulus of the RSA key.
148            By definition, for a key of k bits, the following formula holds:
149
150            2^(k-1) <= modulus < 2^(k)
151
152            Where ^ means "to the power of", not "xor".
153            This means that to be sure, we must choose our message < 2^(k-1).
154            This can be done by setting the most significant bit to zero.
155          */
156
157         c->outkey[0] &= 0x7F;
158
159         ifdebug(SCARY_THINGS) {
160                 bin2hex(c->outkey, buffer, len);
161                 buffer[len * 2] = '\0';
162                 logger(LOG_DEBUG, _("Generated random meta key (unencrypted): %s"),
163                            buffer);
164         }
165
166         /* Encrypt the random data
167
168            We do not use one of the PKCS padding schemes here.
169            This is allowed, because we encrypt a totally random string
170            with a length equal to that of the modulus of the RSA key.
171          */
172
173         if(RSA_public_encrypt(len, c->outkey, buffer, c->rsa_key, RSA_NO_PADDING) != len) {
174                 logger(LOG_ERR, _("Error during encryption of meta key for %s (%s)"),
175                            c->name, c->hostname);
176                 return -1;
177         }
178
179         /* Convert the encrypted random data to a hexadecimal formatted string */
180
181         bin2hex(buffer, buffer, len);
182         buffer[len * 2] = '\0';
183
184         /* Send the meta key */
185
186         x = send_request(c, "%d %d %d %d %d %s", METAKEY,
187                                          c->outcipher ? c->outcipher->nid : 0,
188                                          c->outdigest ? c->outdigest->type : 0, c->outmaclength,
189                                          c->outcompression, buffer);
190
191         /* Further outgoing requests are encrypted with the key we just generated */
192
193         if(c->outcipher) {
194                 EVP_EncryptInit(c->outctx, c->outcipher,
195                                                 c->outkey + len - c->outcipher->key_len,
196                                                 c->outkey + len - c->outcipher->key_len -
197                                                 c->outcipher->iv_len);
198
199                 c->status.encryptout = 1;
200         }
201
202         return x;
203 }
204
205 int 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 -1;
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 -1;
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, buffer, 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 -1;
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 -1;
264                 }
265
266                 EVP_DecryptInit(c->inctx, c->incipher,
267                                                 c->inkey + len - c->incipher->key_len,
268                                                 c->inkey + len - c->incipher->key_len -
269                                                 c->incipher->iv_len);
270
271                 c->status.decryptin = 1;
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 -1;
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 -1;
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 int send_challenge(connection_t *c)
302 {
303         char buffer[MAX_STRING_SIZE];
304         int len, x;
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         if(!c->hischallenge)
315                 c->hischallenge = xmalloc(len);
316
317         /* Copy random data to the buffer */
318
319         RAND_bytes(c->hischallenge, len);
320
321         /* Convert to hex */
322
323         bin2hex(c->hischallenge, buffer, len);
324         buffer[len * 2] = '\0';
325
326         /* Send the challenge */
327
328         x = send_request(c, "%d %s", CHALLENGE, buffer);
329
330         return x;
331 }
332
333 int challenge_h(connection_t *c)
334 {
335         char buffer[MAX_STRING_SIZE];
336         int len;
337
338         cp();
339
340         if(sscanf(c->buffer, "%*d " MAX_STRING, buffer) != 1) {
341                 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "CHALLENGE", c->name,
342                            c->hostname);
343                 return -1;
344         }
345
346         len = RSA_size(myself->connection->rsa_key);
347
348         /* Check if the length of the challenge is all right */
349
350         if(strlen(buffer) != len * 2) {
351                 logger(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name,
352                            c->hostname, "wrong challenge length");
353                 return -1;
354         }
355
356         /* Allocate buffers for the challenge */
357
358         if(!c->mychallenge)
359                 c->mychallenge = xmalloc(len);
360
361         /* Convert the challenge from hexadecimal back to binary */
362
363         hex2bin(buffer, c->mychallenge, len);
364
365         c->allow_request = CHAL_REPLY;
366
367         /* Rest is done by send_chal_reply() */
368
369         return send_chal_reply(c);
370 }
371
372 int send_chal_reply(connection_t *c)
373 {
374         char hash[EVP_MAX_MD_SIZE * 2 + 1];
375         EVP_MD_CTX ctx;
376
377         cp();
378
379         /* Calculate the hash from the challenge we received */
380
381         EVP_DigestInit(&ctx, c->indigest);
382         EVP_DigestUpdate(&ctx, c->mychallenge,
383                                          RSA_size(myself->connection->rsa_key));
384         EVP_DigestFinal(&ctx, hash, NULL);
385
386         /* Convert the hash to a hexadecimal formatted string */
387
388         bin2hex(hash, hash, c->indigest->md_size);
389         hash[c->indigest->md_size * 2] = '\0';
390
391         /* Send the reply */
392
393         return send_request(c, "%d %s", CHAL_REPLY, hash);
394 }
395
396 int chal_reply_h(connection_t *c)
397 {
398         char hishash[MAX_STRING_SIZE];
399         char myhash[EVP_MAX_MD_SIZE];
400         EVP_MD_CTX ctx;
401
402         cp();
403
404         if(sscanf(c->buffer, "%*d " MAX_STRING, hishash) != 1) {
405                 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "CHAL_REPLY", c->name,
406                            c->hostname);
407                 return -1;
408         }
409
410         /* Check if the length of the hash is all right */
411
412         if(strlen(hishash) != c->outdigest->md_size * 2) {
413                 logger(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name,
414                            c->hostname, _("wrong challenge reply length"));
415                 return -1;
416         }
417
418         /* Convert the hash to binary format */
419
420         hex2bin(hishash, hishash, c->outdigest->md_size);
421
422         /* Calculate the hash from the challenge we sent */
423
424         EVP_DigestInit(&ctx, c->outdigest);
425         EVP_DigestUpdate(&ctx, c->hischallenge, RSA_size(c->rsa_key));
426         EVP_DigestFinal(&ctx, myhash, NULL);
427
428         /* Verify the incoming hash with the calculated hash */
429
430         if(memcmp(hishash, myhash, c->outdigest->md_size)) {
431                 logger(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name,
432                            c->hostname, _("wrong challenge reply"));
433
434                 ifdebug(SCARY_THINGS) {
435                         bin2hex(myhash, hishash, SHA_DIGEST_LENGTH);
436                         hishash[SHA_DIGEST_LENGTH * 2] = '\0';
437                         logger(LOG_DEBUG, _("Expected challenge reply: %s"), hishash);
438                 }
439
440                 return -1;
441         }
442
443         /* Identity has now been positively verified.
444            Send an acknowledgement with the rest of the information needed.
445          */
446
447         c->allow_request = ACK;
448
449         return send_ack(c);
450 }
451
452 int send_ack(connection_t *c)
453 {
454         /* ACK message contains rest of the information the other end needs
455            to create node_t and edge_t structures. */
456
457         int x;
458         struct timeval now;
459
460         cp();
461
462         /* Estimate weight */
463
464         gettimeofday(&now, NULL);
465         c->estimated_weight =
466                 (now.tv_sec - c->start.tv_sec) * 1000 + (now.tv_usec -
467                                                                                                  c->start.tv_usec) / 1000;
468         x = send_request(c, "%d %s %d %lx", ACK, myport, c->estimated_weight,
469                                          c->options);
470
471         return x;
472 }
473
474 static void send_everything(connection_t *c)
475 {
476         avl_node_t *node, *node2;
477         node_t *n;
478         subnet_t *s;
479         edge_t *e;
480
481         /* Send all known subnets and edges */
482
483         for(node = node_tree->head; node; node = node->next) {
484                 n = (node_t *) node->data;
485
486                 for(node2 = n->subnet_tree->head; node2; node2 = node2->next) {
487                         s = (subnet_t *) node2->data;
488                         send_add_subnet(c, s);
489                 }
490
491                 for(node2 = n->edge_tree->head; node2; node2 = node2->next) {
492                         e = (edge_t *) node2->data;
493                         send_add_edge(c, e);
494                 }
495         }
496 }
497
498 int ack_h(connection_t *c)
499 {
500         char hisport[MAX_STRING_SIZE];
501         char *hisaddress, *dummy;
502         int weight;
503         long int options;
504         node_t *n;
505
506         cp();
507
508         if(sscanf(c->buffer, "%*d " MAX_STRING " %d %lx", hisport, &weight, &options) != 3) {
509                 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "ACK", c->name,
510                            c->hostname);
511                 return -1;
512         }
513
514         /* Check if we already have a node_t for him */
515
516         n = lookup_node(c->name);
517
518         if(!n) {
519                 n = new_node();
520                 n->name = xstrdup(c->name);
521                 node_add(n);
522         } else {
523                 if(n->connection) {
524                         /* Oh dear, we already have a connection to this node. */
525                         ifdebug(CONNECTIONS) logger(LOG_DEBUG, _("Established a second connection with %s (%s), closing old connection"),
526                                            n->name, n->hostname);
527                         terminate_connection(n->connection, 0);
528                         /* Run graph algorithm to purge key and make sure up/down scripts are rerun with new IP addresses and stuff */
529                         graph();
530                 }
531         }
532
533         n->connection = c;
534         c->node = n;
535         c->options |= options;
536
537         /* Activate this connection */
538
539         c->allow_request = ALL;
540         c->status.active = 1;
541
542         ifdebug(CONNECTIONS) logger(LOG_NOTICE, _("Connection with %s (%s) activated"), c->name,
543                            c->hostname);
544
545         /* Send him everything we know */
546
547         send_everything(c);
548
549         /* Create an edge_t for this connection */
550
551         c->edge = new_edge();
552         cp();
553         c->edge->from = myself;
554         c->edge->to = n;
555         sockaddr2str(&c->address, &hisaddress, &dummy);
556         c->edge->address = str2sockaddr(hisaddress, hisport);
557         free(hisaddress);
558         free(dummy);
559         c->edge->weight = (weight + c->estimated_weight) / 2;
560         c->edge->connection = c;
561         c->edge->options = c->options;
562
563         edge_add(c->edge);
564
565         /* Notify everyone of the new edge */
566
567         send_add_edge(broadcast, c->edge);
568
569         /* Run MST and SSSP algorithms */
570
571         graph();
572
573         return 0;
574 }