Temporarily revert to old crypto code
[tinc] / src / protocol_auth.c
1 /*
2     protocol_auth.c -- handle the meta-protocol, authentication
3     Copyright (C) 1999-2005 Ivo Timmermans,
4                   2000-2007 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 "splay_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         cp();
45
46         gettimeofday(&c->start, NULL);
47
48         return send_request(c, "%d %s %d", ID, myself->connection->name,
49                                                 myself->connection->protocol_version);
50 }
51
52 bool id_h(connection_t *c, char *request) {
53         char name[MAX_STRING_SIZE];
54
55         cp();
56
57         if(sscanf(request, "%*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 this is an outgoing connection, make sure we are connected to the right host */
72
73         if(c->outgoing) {
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                 if(c->name)
81                         free(c->name);
82                 c->name = xstrdup(name);
83         }
84
85         /* Check if version matches */
86
87         if(c->protocol_version != myself->connection->protocol_version) {
88                 logger(LOG_ERR, _("Peer %s (%s) uses incompatible version %d"),
89                            c->name, c->hostname, c->protocol_version);
90                 return false;
91         }
92
93         if(bypass_security) {
94                 if(!c->config_tree)
95                         init_configuration(&c->config_tree);
96                 c->allow_request = ACK;
97                 return send_ack(c);
98         }
99
100         if(!c->config_tree) {
101                 init_configuration(&c->config_tree);
102
103                 if(!read_connection_config(c)) {
104                         logger(LOG_ERR, _("Peer %s had unknown identity (%s)"), c->hostname,
105                                    c->name);
106                         return false;
107                 }
108         }
109
110         if(!read_rsa_public_key(c)) {
111                 return false;
112         }
113
114         c->allow_request = METAKEY;
115
116         return send_metakey(c);
117 }
118
119 bool send_metakey(connection_t *c) {
120         char *buffer;
121         int len;
122         bool x;
123
124         cp();
125
126         len = RSA_size(c->rsa_key);
127
128         /* Allocate buffers for the meta key */
129
130         buffer = alloca(2 * len + 1);
131         
132         if(!c->outkey)
133                 c->outkey = xmalloc(len);
134
135         if(!c->outctx)
136                 c->outctx = xmalloc_and_zero(sizeof(*c->outctx));
137         cp();
138         /* Copy random data to the buffer */
139
140         RAND_pseudo_bytes((unsigned char *)c->outkey, len);
141
142         /* The message we send must be smaller than the modulus of the RSA key.
143            By definition, for a key of k bits, the following formula holds:
144
145            2^(k-1) <= modulus < 2^(k)
146
147            Where ^ means "to the power of", not "xor".
148            This means that to be sure, we must choose our message < 2^(k-1).
149            This can be done by setting the most significant bit to zero.
150          */
151
152         c->outkey[0] &= 0x7F;
153
154         ifdebug(SCARY_THINGS) {
155                 bin2hex(c->outkey, buffer, len);
156                 buffer[len * 2] = '\0';
157                 logger(LOG_DEBUG, _("Generated random meta key (unencrypted): %s"),
158                            buffer);
159         }
160
161         /* Encrypt the random data
162
163            We do not use one of the PKCS padding schemes here.
164            This is allowed, because we encrypt a totally random string
165            with a length equal to that of the modulus of the RSA key.
166          */
167
168         if(RSA_public_encrypt(len, (unsigned char *)c->outkey, (unsigned char *)buffer, c->rsa_key, RSA_NO_PADDING) != len) {
169                 logger(LOG_ERR, _("Error during encryption of meta key for %s (%s)"),
170                            c->name, c->hostname);
171                 return false;
172         }
173
174         /* Convert the encrypted random data to a hexadecimal formatted string */
175
176         bin2hex(buffer, buffer, len);
177         buffer[len * 2] = '\0';
178
179         /* Send the meta key */
180
181         x = send_request(c, "%d %d %d %d %d %s", METAKEY,
182                                          c->outcipher ? c->outcipher->nid : 0,
183                                          c->outdigest ? c->outdigest->type : 0, c->outmaclength,
184                                          c->outcompression, buffer);
185
186         /* Further outgoing requests are encrypted with the key we just generated */
187
188         if(c->outcipher) {
189                 if(!EVP_EncryptInit(c->outctx, c->outcipher,
190                                         (unsigned char *)c->outkey + len - c->outcipher->key_len,
191                                         (unsigned char *)c->outkey + len - c->outcipher->key_len -
192                                         c->outcipher->iv_len)) {
193                         logger(LOG_ERR, _("Error during initialisation of cipher for %s (%s): %s"),
194                                         c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
195                         return false;
196                 }
197
198                 c->status.encryptout = true;
199         }
200
201         return x;
202 }
203
204 bool metakey_h(connection_t *c, char *request) {
205         char buffer[MAX_STRING_SIZE];
206         int cipher, digest, maclength, compression;
207         int len;
208
209         cp();
210
211         if(sscanf(request, "%*d %d %d %d %d " MAX_STRING, &cipher, &digest, &maclength, &compression, buffer) != 5) {
212                 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "METAKEY", c->name,
213                            c->hostname);
214                 return false;
215         }
216
217         len = RSA_size(myself->connection->rsa_key);
218
219         /* Check if the length of the meta key is all right */
220
221         if(strlen(buffer) != len * 2) {
222                 logger(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name, c->hostname, "wrong keylength");
223                 return false;
224         }
225
226         /* Allocate buffers for the meta key */
227
228         if(!c->inkey)
229                 c->inkey = xmalloc(len);
230
231         if(!c->inctx)
232                 c->inctx = xmalloc_and_zero(sizeof(*c->inctx));
233
234         /* Convert the challenge from hexadecimal back to binary */
235
236         hex2bin(buffer, buffer, len);
237
238         /* Decrypt the meta key */
239
240         if(RSA_private_decrypt(len, (unsigned char *)buffer, (unsigned char *)c->inkey, myself->connection->rsa_key, RSA_NO_PADDING) != len) {  /* See challenge() */
241                 logger(LOG_ERR, _("Error during encryption of meta key for %s (%s)"),
242                            c->name, c->hostname);
243                 return false;
244         }
245
246         ifdebug(SCARY_THINGS) {
247                 bin2hex(c->inkey, buffer, len);
248                 buffer[len * 2] = '\0';
249                 logger(LOG_DEBUG, _("Received random meta key (unencrypted): %s"), buffer);
250         }
251
252         /* All incoming requests will now be encrypted. */
253
254         /* Check and lookup cipher and digest algorithms */
255
256         if(cipher) {
257                 c->incipher = EVP_get_cipherbynid(cipher);
258                 
259                 if(!c->incipher) {
260                         logger(LOG_ERR, _("%s (%s) uses unknown cipher!"), c->name, c->hostname);
261                         return false;
262                 }
263
264                 if(!EVP_DecryptInit(c->inctx, c->incipher,
265                                         (unsigned char *)c->inkey + len - c->incipher->key_len,
266                                         (unsigned char *)c->inkey + len - c->incipher->key_len -
267                                         c->incipher->iv_len)) {
268                         logger(LOG_ERR, _("Error during initialisation of cipher from %s (%s): %s"),
269                                         c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
270                         return false;
271                 }
272
273                 c->status.decryptin = true;
274         } else {
275                 c->incipher = NULL;
276         }
277
278         c->inmaclength = maclength;
279
280         if(digest) {
281                 c->indigest = EVP_get_digestbynid(digest);
282
283                 if(!c->indigest) {
284                         logger(LOG_ERR, _("Node %s (%s) uses unknown digest!"), c->name, c->hostname);
285                         return false;
286                 }
287
288                 if(c->inmaclength > c->indigest->md_size || c->inmaclength < 0) {
289                         logger(LOG_ERR, _("%s (%s) uses bogus MAC length!"), c->name, c->hostname);
290                         return false;
291                 }
292         } else {
293                 c->indigest = NULL;
294         }
295
296         c->incompression = compression;
297
298         c->allow_request = CHALLENGE;
299
300         return send_challenge(c);
301 }
302
303 bool send_challenge(connection_t *c) {
304         char *buffer;
305         int len;
306
307         cp();
308
309         /* CHECKME: what is most reasonable value for len? */
310
311         len = RSA_size(c->rsa_key);
312
313         /* Allocate buffers for the challenge */
314
315         buffer = alloca(2 * len + 1);
316
317         if(!c->hischallenge)
318                 c->hischallenge = xmalloc(len);
319
320         /* Copy random data to the buffer */
321
322         RAND_pseudo_bytes((unsigned char *)c->hischallenge, len);
323
324         /* Convert to hex */
325
326         bin2hex(c->hischallenge, buffer, len);
327         buffer[len * 2] = '\0';
328
329         /* Send the challenge */
330
331         return send_request(c, "%d %s", CHALLENGE, buffer);
332 }
333
334 bool challenge_h(connection_t *c, char *request) {
335         char buffer[MAX_STRING_SIZE];
336         int len;
337
338         cp();
339
340         if(sscanf(request, "%*d " MAX_STRING, buffer) != 1) {
341                 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "CHALLENGE", c->name,
342                            c->hostname);
343                 return false;
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 false;
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 bool send_chal_reply(connection_t *c) {
373         char hash[EVP_MAX_MD_SIZE * 2 + 1];
374         EVP_MD_CTX ctx;
375
376         cp();
377
378         /* Calculate the hash from the challenge we received */
379
380         if(!EVP_DigestInit(&ctx, c->indigest)
381                         || !EVP_DigestUpdate(&ctx, c->mychallenge, RSA_size(myself->connection->rsa_key))
382                         || !EVP_DigestFinal(&ctx, (unsigned char *)hash, NULL)) {
383                 logger(LOG_ERR, _("Error during calculation of response for %s (%s): %s"),
384                         c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
385                 return false;
386         }
387
388         /* Convert the hash to a hexadecimal formatted string */
389
390         bin2hex(hash, hash, c->indigest->md_size);
391         hash[c->indigest->md_size * 2] = '\0';
392
393         /* Send the reply */
394
395         return send_request(c, "%d %s", CHAL_REPLY, hash);
396 }
397
398 bool chal_reply_h(connection_t *c, char *request) {
399         char hishash[MAX_STRING_SIZE];
400         char myhash[EVP_MAX_MD_SIZE];
401         EVP_MD_CTX ctx;
402
403         cp();
404
405         if(sscanf(request, "%*d " MAX_STRING, hishash) != 1) {
406                 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "CHAL_REPLY", c->name,
407                            c->hostname);
408                 return false;
409         }
410
411         /* Check if the length of the hash is all right */
412
413         if(strlen(hishash) != c->outdigest->md_size * 2) {
414                 logger(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name,
415                            c->hostname, _("wrong challenge reply length"));
416                 return false;
417         }
418
419         /* Convert the hash to binary format */
420
421         hex2bin(hishash, hishash, c->outdigest->md_size);
422
423         /* Calculate the hash from the challenge we sent */
424
425         if(!EVP_DigestInit(&ctx, c->outdigest)
426                         || !EVP_DigestUpdate(&ctx, c->hischallenge, RSA_size(c->rsa_key))
427                         || !EVP_DigestFinal(&ctx, (unsigned char *)myhash, NULL)) {
428                 logger(LOG_ERR, _("Error during calculation of response from %s (%s): %s"),
429                         c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
430                 return false;
431         }
432
433         /* Verify the incoming hash with the calculated hash */
434
435         if(memcmp(hishash, myhash, c->outdigest->md_size)) {
436                 logger(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name,
437                            c->hostname, _("wrong challenge reply"));
438
439                 ifdebug(SCARY_THINGS) {
440                         bin2hex(myhash, hishash, SHA_DIGEST_LENGTH);
441                         hishash[SHA_DIGEST_LENGTH * 2] = '\0';
442                         logger(LOG_DEBUG, _("Expected challenge reply: %s"), hishash);
443                 }
444
445                 return false;
446         }
447
448         /* Identity has now been positively verified.
449            Send an acknowledgement with the rest of the information needed.
450          */
451
452         c->allow_request = ACK;
453
454         return send_ack(c);
455 }
456
457 bool send_ack(connection_t *c) {
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         splay_node_t *node, *node2;
489         node_t *n;
490         subnet_t *s;
491         edge_t *e;
492
493         /* Send all known subnets and edges */
494
495         if(tunnelserver) {
496                 for(node = myself->subnet_tree->head; node; node = node->next) {
497                         s = node->data;
498                         send_add_subnet(c, s);
499                 }
500
501                 return;
502         }
503
504         for(node = node_tree->head; node; node = node->next) {
505                 n = node->data;
506
507                 for(node2 = n->subnet_tree->head; node2; node2 = node2->next) {
508                         s = node2->data;
509                         send_add_subnet(c, s);
510                 }
511
512                 for(node2 = n->edge_tree->head; node2; node2 = node2->next) {
513                         e = node2->data;
514                         send_add_edge(c, e);
515                 }
516         }
517 }
518
519 bool ack_h(connection_t *c, char *request) {
520         char hisport[MAX_STRING_SIZE];
521         char *hisaddress, *dummy;
522         int weight, mtu;
523         long int options;
524         node_t *n;
525
526         cp();
527
528         if(sscanf(request, "%*d " MAX_STRING " %d %lx", hisport, &weight, &options) != 3) {
529                 logger(LOG_ERR, _("Got bad %s from %s (%s)"), "ACK", c->name,
530                            c->hostname);
531                 return false;
532         }
533
534         /* Check if we already have a node_t for him */
535
536         n = lookup_node(c->name);
537
538         if(!n) {
539                 n = new_node();
540                 n->name = xstrdup(c->name);
541                 node_add(n);
542         } else {
543                 if(n->connection) {
544                         /* Oh dear, we already have a connection to this node. */
545                         ifdebug(CONNECTIONS) logger(LOG_DEBUG, _("Established a second connection with %s (%s), closing old connection"), n->connection->name, n->connection->hostname);
546
547                         if(n->connection->outgoing) {
548                                 if(c->outgoing)
549                                         logger(LOG_WARNING, _("Two outgoing connections to the same node!"));
550                                 else
551                                         c->outgoing = n->connection->outgoing;
552
553                                 n->connection->outgoing = NULL;
554                         }
555
556                         terminate_connection(n->connection, false);
557                         /* Run graph algorithm to purge key and make sure up/down scripts are rerun with new IP addresses and stuff */
558                         graph();
559                 }
560         }
561
562         n->connection = c;
563         c->node = n;
564         c->options |= options;
565
566         if(get_config_int(lookup_config(c->config_tree, "PMTU"), &mtu) && mtu < n->mtu)
567                 n->mtu = mtu;
568
569         if(get_config_int(lookup_config(myself->connection->config_tree, "PMTU"), &mtu) && mtu < n->mtu)
570                 n->mtu = mtu;
571
572         /* Activate this connection */
573
574         c->allow_request = ALL;
575         c->status.active = true;
576
577         ifdebug(CONNECTIONS) logger(LOG_NOTICE, _("Connection with %s (%s) activated"), c->name,
578                            c->hostname);
579
580         /* Send him everything we know */
581
582         send_everything(c);
583
584         /* Create an edge_t for this connection */
585
586         c->edge = new_edge();
587         cp();
588         c->edge->from = myself;
589         c->edge->to = n;
590         sockaddr2str(&c->address, &hisaddress, &dummy);
591         c->edge->address = str2sockaddr(hisaddress, hisport);
592         free(hisaddress);
593         free(dummy);
594         c->edge->weight = (weight + c->estimated_weight) / 2;
595         c->edge->connection = c;
596         c->edge->options = c->options;
597
598         edge_add(c->edge);
599
600         /* Notify everyone of the new edge */
601
602         if(tunnelserver)
603                 send_add_edge(c, c->edge);
604         else
605                 send_add_edge(broadcast, c->edge);
606
607         /* Run MST and SSSP algorithms */
608
609         graph();
610
611         return true;
612 }