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