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