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