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