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