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