Update copyrights, links, email addresses and let Subversion update $Id$ keywords.
[oweals/tinc.git] / src / protocol_auth.c
1 /*
2     protocol_auth.c -- handle the meta-protocol, authentication
3     Copyright (C) 1999-2004 Ivo Timmermans <ivo@tinc-vpn.org>,
4                   2000-2004 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                 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 false;
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                 if(!read_connection_config(c)) {
101                         logger(LOG_ERR, _("Peer %s had unknown identity (%s)"), c->hostname,
102                                    c->name);
103                         return false;
104                 }
105         }
106
107         if(!read_rsa_public_key(c)) {
108                 return false;
109         }
110
111         c->allow_request = METAKEY;
112
113         return send_metakey(c);
114 }
115
116 bool send_metakey(connection_t *c)
117 {
118         char buffer[MAX_STRING_SIZE];
119         int len;
120         bool x;
121
122         cp();
123
124         len = RSA_size(c->rsa_key);
125
126         /* Allocate buffers for the meta key */
127
128         if(!c->outkey)
129                 c->outkey = xmalloc(len);
130
131         if(!c->outctx)
132                 c->outctx = xmalloc_and_zero(sizeof(*c->outctx));
133         cp();
134         /* Copy random data to the buffer */
135
136         RAND_pseudo_bytes(c->outkey, len);
137
138         /* The message we send must be smaller than the modulus of the RSA key.
139            By definition, for a key of k bits, the following formula holds:
140
141            2^(k-1) <= modulus < 2^(k)
142
143            Where ^ means "to the power of", not "xor".
144            This means that to be sure, we must choose our message < 2^(k-1).
145            This can be done by setting the most significant bit to zero.
146          */
147
148         c->outkey[0] &= 0x7F;
149
150         ifdebug(SCARY_THINGS) {
151                 bin2hex(c->outkey, buffer, len);
152                 buffer[len * 2] = '\0';
153                 logger(LOG_DEBUG, _("Generated random meta key (unencrypted): %s"),
154                            buffer);
155         }
156
157         /* Encrypt the random data
158
159            We do not use one of the PKCS padding schemes here.
160            This is allowed, because we encrypt a totally random string
161            with a length equal to that of the modulus of the RSA key.
162          */
163
164         if(RSA_public_encrypt(len, c->outkey, buffer, c->rsa_key, RSA_NO_PADDING) != len) {
165                 logger(LOG_ERR, _("Error during encryption of meta key for %s (%s)"),
166                            c->name, c->hostname);
167                 return false;
168         }
169
170         /* Convert the encrypted random data to a hexadecimal formatted string */
171
172         bin2hex(buffer, buffer, len);
173         buffer[len * 2] = '\0';
174
175         /* Send the meta key */
176
177         x = send_request(c, "%d %d %d %d %d %s", METAKEY,
178                                          c->outcipher ? c->outcipher->nid : 0,
179                                          c->outdigest ? c->outdigest->type : 0, c->outmaclength,
180                                          c->outcompression, buffer);
181
182         /* Further outgoing requests are encrypted with the key we just generated */
183
184         if(c->outcipher) {
185                 if(!EVP_EncryptInit(c->outctx, c->outcipher,
186                                         c->outkey + len - c->outcipher->key_len,
187                                         c->outkey + len - c->outcipher->key_len -
188                                         c->outcipher->iv_len)) {
189                         logger(LOG_ERR, _("Error during initialisation of cipher for %s (%s): %s"),
190                                         c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
191                         return false;
192                 }
193
194                 c->status.encryptout = true;
195         }
196
197         return x;
198 }
199
200 bool metakey_h(connection_t *c)
201 {
202         char buffer[MAX_STRING_SIZE];
203         int cipher, digest, maclength, compression;
204         int len;
205
206         cp();
207
208         if(sscanf(c->buffer, "%*d %d %d %d %d " MAX_STRING, &cipher, &digest, &maclength, &compression, buffer) != 5) {
209                 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "METAKEY", c->name,
210                            c->hostname);
211                 return false;
212         }
213
214         len = RSA_size(myself->connection->rsa_key);
215
216         /* Check if the length of the meta key is all right */
217
218         if(strlen(buffer) != len * 2) {
219                 logger(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name, c->hostname, "wrong keylength");
220                 return false;
221         }
222
223         /* Allocate buffers for the meta key */
224
225         if(!c->inkey)
226                 c->inkey = xmalloc(len);
227
228         if(!c->inctx)
229                 c->inctx = xmalloc_and_zero(sizeof(*c->inctx));
230
231         /* Convert the challenge from hexadecimal back to binary */
232
233         hex2bin(buffer, buffer, len);
234
235         /* Decrypt the meta key */
236
237         if(RSA_private_decrypt(len, buffer, c->inkey, myself->connection->rsa_key, RSA_NO_PADDING) != len) {    /* See challenge() */
238                 logger(LOG_ERR, _("Error during encryption of meta key for %s (%s)"),
239                            c->name, c->hostname);
240                 return false;
241         }
242
243         ifdebug(SCARY_THINGS) {
244                 bin2hex(c->inkey, buffer, len);
245                 buffer[len * 2] = '\0';
246                 logger(LOG_DEBUG, _("Received random meta key (unencrypted): %s"), buffer);
247         }
248
249         /* All incoming requests will now be encrypted. */
250
251         /* Check and lookup cipher and digest algorithms */
252
253         if(cipher) {
254                 c->incipher = EVP_get_cipherbynid(cipher);
255                 
256                 if(!c->incipher) {
257                         logger(LOG_ERR, _("%s (%s) uses unknown cipher!"), c->name, c->hostname);
258                         return false;
259                 }
260
261                 if(!EVP_DecryptInit(c->inctx, c->incipher,
262                                         c->inkey + len - c->incipher->key_len,
263                                         c->inkey + len - c->incipher->key_len -
264                                         c->incipher->iv_len)) {
265                         logger(LOG_ERR, _("Error during initialisation of cipher from %s (%s): %s"),
266                                         c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
267                         return false;
268                 }
269
270                 c->status.decryptin = true;
271         } else {
272                 c->incipher = NULL;
273         }
274
275         c->inmaclength = maclength;
276
277         if(digest) {
278                 c->indigest = EVP_get_digestbynid(digest);
279
280                 if(!c->indigest) {
281                         logger(LOG_ERR, _("Node %s (%s) uses unknown digest!"), c->name, c->hostname);
282                         return false;
283                 }
284
285                 if(c->inmaclength > c->indigest->md_size || c->inmaclength < 0) {
286                         logger(LOG_ERR, _("%s (%s) uses bogus MAC length!"), c->name, c->hostname);
287                         return false;
288                 }
289         } else {
290                 c->indigest = NULL;
291         }
292
293         c->incompression = compression;
294
295         c->allow_request = CHALLENGE;
296
297         return send_challenge(c);
298 }
299
300 bool send_challenge(connection_t *c)
301 {
302         char buffer[MAX_STRING_SIZE];
303         int len;
304
305         cp();
306
307         /* CHECKME: what is most reasonable value for len? */
308
309         len = RSA_size(c->rsa_key);
310
311         /* Allocate buffers for the challenge */
312
313         if(!c->hischallenge)
314                 c->hischallenge = xmalloc(len);
315
316         /* Copy random data to the buffer */
317
318         RAND_pseudo_bytes(c->hischallenge, len);
319
320         /* Convert to hex */
321
322         bin2hex(c->hischallenge, buffer, len);
323         buffer[len * 2] = '\0';
324
325         /* Send the challenge */
326
327         return send_request(c, "%d %s", CHALLENGE, buffer);
328 }
329
330 bool challenge_h(connection_t *c)
331 {
332         char buffer[MAX_STRING_SIZE];
333         int len;
334
335         cp();
336
337         if(sscanf(c->buffer, "%*d " MAX_STRING, buffer) != 1) {
338                 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "CHALLENGE", c->name,
339                            c->hostname);
340                 return false;
341         }
342
343         len = RSA_size(myself->connection->rsa_key);
344
345         /* Check if the length of the challenge is all right */
346
347         if(strlen(buffer) != len * 2) {
348                 logger(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name,
349                            c->hostname, "wrong challenge length");
350                 return false;
351         }
352
353         /* Allocate buffers for the challenge */
354
355         if(!c->mychallenge)
356                 c->mychallenge = xmalloc(len);
357
358         /* Convert the challenge from hexadecimal back to binary */
359
360         hex2bin(buffer, c->mychallenge, len);
361
362         c->allow_request = CHAL_REPLY;
363
364         /* Rest is done by send_chal_reply() */
365
366         return send_chal_reply(c);
367 }
368
369 bool send_chal_reply(connection_t *c)
370 {
371         char hash[EVP_MAX_MD_SIZE * 2 + 1];
372         EVP_MD_CTX ctx;
373
374         cp();
375
376         /* Calculate the hash from the challenge we received */
377
378         if(!EVP_DigestInit(&ctx, c->indigest)
379                         || !EVP_DigestUpdate(&ctx, c->mychallenge, RSA_size(myself->connection->rsa_key))
380                         || !EVP_DigestFinal(&ctx, hash, NULL)) {
381                 logger(LOG_ERR, _("Error during calculation of response for %s (%s): %s"),
382                         c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
383                 return false;
384         }
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 bool 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 false;
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 false;
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         if(!EVP_DigestInit(&ctx, c->outdigest)
425                         || !EVP_DigestUpdate(&ctx, c->hischallenge, RSA_size(c->rsa_key))
426                         || !EVP_DigestFinal(&ctx, myhash, NULL)) {
427                 logger(LOG_ERR, _("Error during calculation of response from %s (%s): %s"),
428                         c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
429                 return false;
430         }
431
432         /* Verify the incoming hash with the calculated hash */
433
434         if(memcmp(hishash, myhash, c->outdigest->md_size)) {
435                 logger(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name,
436                            c->hostname, _("wrong challenge reply"));
437
438                 ifdebug(SCARY_THINGS) {
439                         bin2hex(myhash, hishash, SHA_DIGEST_LENGTH);
440                         hishash[SHA_DIGEST_LENGTH * 2] = '\0';
441                         logger(LOG_DEBUG, _("Expected challenge reply: %s"), hishash);
442                 }
443
444                 return false;
445         }
446
447         /* Identity has now been positively verified.
448            Send an acknowledgement with the rest of the information needed.
449          */
450
451         c->allow_request = ACK;
452
453         return send_ack(c);
454 }
455
456 bool send_ack(connection_t *c)
457 {
458         /* ACK message contains rest of the information the other end needs
459            to create node_t and edge_t structures. */
460
461         struct timeval now;
462         bool choice;
463
464         cp();
465
466         /* Estimate weight */
467
468         gettimeofday(&now, NULL);
469         c->estimated_weight = (now.tv_sec - c->start.tv_sec) * 1000 + (now.tv_usec - c->start.tv_usec) / 1000;
470
471         /* Check some options */
472
473         if((get_config_bool(lookup_config(c->config_tree, "IndirectData"), &choice) && choice) || myself->options & OPTION_INDIRECT)
474                 c->options |= OPTION_INDIRECT;
475
476         if((get_config_bool(lookup_config(c->config_tree, "TCPOnly"), &choice) && choice) || myself->options & OPTION_TCPONLY)
477                 c->options |= OPTION_TCPONLY | OPTION_INDIRECT;
478
479         if((get_config_bool(lookup_config(c->config_tree, "PMTUDiscovery"), &choice) && choice) || myself->options & OPTION_PMTU_DISCOVERY)
480                 c->options |= OPTION_PMTU_DISCOVERY;
481
482         get_config_int(lookup_config(c->config_tree, "Weight"), &c->estimated_weight);
483
484         return send_request(c, "%d %s %d %lx", ACK, myport, c->estimated_weight, c->options);
485 }
486
487 static void send_everything(connection_t *c)
488 {
489         avl_node_t *node, *node2;
490         node_t *n;
491         subnet_t *s;
492         edge_t *e;
493
494         /* Send all known subnets and edges */
495
496         if(tunnelserver) {
497                 for(node = myself->subnet_tree->head; node; node = node->next) {
498                         s = node->data;
499                         send_add_subnet(c, s);
500                 }
501
502                 return;
503         }
504
505         for(node = node_tree->head; node; node = node->next) {
506                 n = node->data;
507
508                 for(node2 = n->subnet_tree->head; node2; node2 = node2->next) {
509                         s = node2->data;
510                         send_add_subnet(c, s);
511                 }
512
513                 for(node2 = n->edge_tree->head; node2; node2 = node2->next) {
514                         e = node2->data;
515                         send_add_edge(c, e);
516                 }
517         }
518 }
519
520 bool ack_h(connection_t *c)
521 {
522         char hisport[MAX_STRING_SIZE];
523         char *hisaddress, *dummy;
524         int weight, mtu;
525         long int options;
526         node_t *n;
527
528         cp();
529
530         if(sscanf(c->buffer, "%*d " MAX_STRING " %d %lx", hisport, &weight, &options) != 3) {
531                 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "ACK", c->name,
532                            c->hostname);
533                 return false;
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                         ifdebug(CONNECTIONS) logger(LOG_DEBUG, _("Established a second connection with %s (%s), closing old connection"),
548                                            n->name, n->hostname);
549                         terminate_connection(n->connection, false);
550                         /* Run graph algorithm to purge key and make sure up/down scripts are rerun with new IP addresses and stuff */
551                         graph();
552                 }
553         }
554
555         n->connection = c;
556         c->node = n;
557         c->options |= options;
558
559         if(get_config_int(lookup_config(c->config_tree, "PMTU"), &mtu) && mtu < n->mtu)
560                 n->mtu = mtu;
561
562         if(get_config_int(lookup_config(myself->connection->config_tree, "PMTU"), &mtu) && mtu < n->mtu)
563                 n->mtu = mtu;
564
565         /* Activate this connection */
566
567         c->allow_request = ALL;
568         c->status.active = true;
569
570         ifdebug(CONNECTIONS) logger(LOG_NOTICE, _("Connection with %s (%s) activated"), c->name,
571                            c->hostname);
572
573         /* Send him everything we know */
574
575         send_everything(c);
576
577         /* Create an edge_t for this connection */
578
579         c->edge = new_edge();
580         cp();
581         c->edge->from = myself;
582         c->edge->to = n;
583         sockaddr2str(&c->address, &hisaddress, &dummy);
584         c->edge->address = str2sockaddr(hisaddress, hisport);
585         free(hisaddress);
586         free(dummy);
587         c->edge->weight = (weight + c->estimated_weight) / 2;
588         c->edge->connection = c;
589         c->edge->options = c->options;
590
591         edge_add(c->edge);
592
593         /* Notify everyone of the new edge */
594
595         if(tunnelserver)
596                 send_add_edge(c, c->edge);
597         else
598                 send_add_edge(broadcast, c->edge);
599
600         /* Run MST and SSSP algorithms */
601
602         graph();
603
604         return true;
605 }