2 protocol_auth.c -- handle the meta-protocol, authentication
3 Copyright (C) 1999-2005 Ivo Timmermans,
4 2000-2014 Guus Sliepen <guus@tinc-vpn.org>
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.
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.
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.
24 #include "connection.h"
26 #include "control_common.h"
47 ecdsa_t *invitation_key = NULL;
49 static bool send_proxyrequest(connection_t *c) {
55 sockaddr2str(&c->address, &host, &port);
56 send_request(c, "CONNECT %s:%s HTTP/1.1\r\n\r", host, port);
62 if(c->address.sa.sa_family != AF_INET) {
63 logger(DEBUG_ALWAYS, LOG_ERR, "Cannot connect to an IPv6 host through a SOCKS 4 proxy!");
66 char s4req[9 + (proxyuser ? strlen(proxyuser) : 0)];
69 memcpy(s4req + 2, &c->address.in.sin_port, 2);
70 memcpy(s4req + 4, &c->address.in.sin_addr, 4);
72 memcpy(s4req + 8, proxyuser, strlen(proxyuser));
73 s4req[sizeof s4req - 1] = 0;
75 return send_meta(c, s4req, sizeof s4req);
78 int len = 3 + 6 + (c->address.sa.sa_family == AF_INET ? 4 : 16);
81 len += 3 + strlen(proxyuser) + strlen(proxypass);
89 s5req[i++] = strlen(proxyuser);
90 memcpy(s5req + i, proxyuser, strlen(proxyuser));
91 i += strlen(proxyuser);
92 s5req[i++] = strlen(proxypass);
93 memcpy(s5req + i, proxypass, strlen(proxypass));
94 i += strlen(proxypass);
102 if(c->address.sa.sa_family == AF_INET) {
104 memcpy(s5req + i, &c->address.in.sin_addr, 4);
106 memcpy(s5req + i, &c->address.in.sin_port, 2);
109 } else if(c->address.sa.sa_family == AF_INET6) {
111 memcpy(s5req + i, &c->address.in6.sin6_addr, 16);
113 memcpy(s5req + i, &c->address.in6.sin6_port, 2);
117 logger(DEBUG_ALWAYS, LOG_ERR, "Address family %hx not supported for SOCKS 5 proxies!", c->address.sa.sa_family);
122 return send_meta(c, s5req, sizeof s5req);
125 logger(DEBUG_ALWAYS, LOG_ERR, "Proxy type not implemented yet");
130 logger(DEBUG_ALWAYS, LOG_ERR, "Unknown proxy type");
135 bool send_id(connection_t *c) {
136 gettimeofday(&c->start, NULL);
141 if(c->outgoing && !read_ecdsa_public_key(c))
144 minor = myself->connection->protocol_minor;
147 if(proxytype && c->outgoing)
148 if(!send_proxyrequest(c))
151 return send_request(c, "%d %s %d.%d", ID, myself->connection->name, myself->connection->protocol_major, minor);
154 static bool finalize_invitation(connection_t *c, const char *data, uint16_t len) {
155 if(strchr(data, '\n')) {
156 logger(DEBUG_ALWAYS, LOG_ERR, "Received invalid key from invited node %s (%s)!\n", c->name, c->hostname);
160 // Create a new host config file
161 char filename[PATH_MAX];
162 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", confbase, c->name);
163 if(!access(filename, F_OK)) {
164 logger(DEBUG_ALWAYS, LOG_ERR, "Host config file for %s (%s) already exists!\n", c->name, c->hostname);
168 FILE *f = fopen(filename, "w");
170 logger(DEBUG_ALWAYS, LOG_ERR, "Error trying to create %s: %s\n", filename, strerror(errno));
174 fprintf(f, "ECDSAPublicKey = %s\n", data);
177 logger(DEBUG_CONNECTIONS, LOG_INFO, "Key succesfully received from %s (%s)", c->name, c->hostname);
179 // Call invitation-accepted script
180 char *envp[7] = {NULL};
181 char *address, *port;
183 xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
184 xasprintf(&envp[3], "NODE=%s", c->name);
185 sockaddr2str(&c->address, &address, &port);
186 xasprintf(&envp[4], "REMOTEADDRESS=%s", address);
187 xasprintf(&envp[5], "NAME=%s", myself->name);
189 execute_script("invitation-accepted", envp);
191 for(int i = 0; envp[i] && i < 7; i++)
194 sptps_send_record(&c->sptps, 2, data, 0);
198 static bool receive_invitation_sptps(void *handle, uint8_t type, const char *data, uint16_t len) {
199 connection_t *c = handle;
204 if(type == 1 && c->status.invitation_used)
205 return finalize_invitation(c, data, len);
207 if(type != 0 || len != 18 || c->status.invitation_used)
210 // Recover the filename from the cookie and the key
211 digest_t *digest = digest_open_by_name("sha256", 18);
214 char *fingerprint = ecdsa_get_base64_public_key(invitation_key);
215 char hashbuf[18 + strlen(fingerprint)];
217 memcpy(hashbuf, data, 18);
218 memcpy(hashbuf + 18, fingerprint, sizeof hashbuf - 18);
219 digest_create(digest, hashbuf, sizeof hashbuf, cookie);
220 b64encode_urlsafe(cookie, cookie, 18);
221 digest_close(digest);
224 char filename[PATH_MAX], usedname[PATH_MAX];
225 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "%s", confbase, cookie);
226 snprintf(usedname, sizeof usedname, "%s" SLASH "invitations" SLASH "%s.used", confbase, cookie);
228 // Atomically rename the invitation file
229 if(rename(filename, usedname)) {
231 logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s tried to use non-existing invitation %s\n", c->hostname, cookie);
233 logger(DEBUG_ALWAYS, LOG_ERR, "Error trying to rename invitation %s\n", cookie);
237 // Open the renamed file
238 FILE *f = fopen(usedname, "r");
240 logger(DEBUG_ALWAYS, LOG_ERR, "Error trying to open invitation %s\n", cookie);
244 // Read the new node's Name from the file
246 fgets(buf, sizeof buf, f);
248 buf[strlen(buf) - 1] = 0;
250 len = strcspn(buf, " \t=");
251 char *name = buf + len;
252 name += strspn(name, " \t");
255 name += strspn(name, " \t");
259 if(!*buf || !*name || strcasecmp(buf, "Name") || !check_id(name)) {
260 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid invitation file %s\n", cookie);
266 c->name = xstrdup(name);
268 // Send the node the contents of the invitation file
271 while((result = fread(buf, 1, sizeof buf, f)))
272 sptps_send_record(&c->sptps, 0, buf, result);
273 sptps_send_record(&c->sptps, 1, buf, 0);
277 c->status.invitation_used = true;
279 logger(DEBUG_CONNECTIONS, LOG_INFO, "Invitation %s succesfully sent to %s (%s)", cookie, c->name, c->hostname);
283 bool id_h(connection_t *c, const char *request) {
284 char name[MAX_STRING_SIZE];
286 if(sscanf(request, "%*d " MAX_STRING " %d.%d", name, &c->protocol_major, &c->protocol_minor) < 2) {
287 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "ID", c->name,
292 /* Check if this is a control connection */
294 if(name[0] == '^' && !strcmp(name + 1, controlcookie)) {
295 c->status.control = true;
296 c->allow_request = CONTROL;
297 c->last_ping_time = now.tv_sec + 3600;
300 c->name = xstrdup("<control>");
302 return send_request(c, "%d %d %d", ACK, TINC_CTL_VERSION_CURRENT, getpid());
306 if(!invitation_key) {
307 logger(DEBUG_ALWAYS, LOG_ERR, "Got invitation from %s but we don't have an invitation key", c->hostname);
311 c->ecdsa = ecdsa_set_base64_public_key(name + 1);
313 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad invitation from %s", c->hostname);
317 c->status.invitation = true;
318 char *mykey = ecdsa_get_base64_public_key(invitation_key);
321 if(!send_request(c, "%d %s", ACK, mykey))
325 c->protocol_minor = 2;
327 return sptps_start(&c->sptps, c, false, false, invitation_key, c->ecdsa, "tinc invitation", 15, send_meta_sptps, receive_invitation_sptps);
330 /* Check if identity is a valid name */
332 if(!check_id(name)) {
333 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s): %s", "ID", c->name,
334 c->hostname, "invalid name");
338 /* If this is an outgoing connection, make sure we are connected to the right host */
341 if(strcmp(c->name, name)) {
342 logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s is %s instead of %s", c->hostname, name,
349 c->name = xstrdup(name);
352 /* Check if version matches */
354 if(c->protocol_major != myself->connection->protocol_major) {
355 logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s (%s) uses incompatible version %d.%d",
356 c->name, c->hostname, c->protocol_major, c->protocol_minor);
360 if(bypass_security) {
362 init_configuration(&c->config_tree);
363 c->allow_request = ACK;
368 c->protocol_minor = 0;
370 if(!c->config_tree) {
371 init_configuration(&c->config_tree);
373 if(!read_host_config(c->config_tree, c->name)) {
374 logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s had unknown identity (%s)", c->hostname, c->name);
379 read_ecdsa_public_key(c);
381 if(c->protocol_minor && !ecdsa_active(c->ecdsa))
382 c->protocol_minor = 1;
385 /* Forbid version rollback for nodes whose ECDSA key we know */
387 if(ecdsa_active(c->ecdsa) && c->protocol_minor < 2) {
388 logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s (%s) tries to roll back protocol version to %d.%d",
389 c->name, c->hostname, c->protocol_major, c->protocol_minor);
393 c->allow_request = METAKEY;
395 if(c->protocol_minor >= 2) {
396 c->allow_request = ACK;
397 char label[25 + strlen(myself->name) + strlen(c->name)];
400 snprintf(label, sizeof label, "tinc TCP key expansion %s %s", myself->name, c->name);
402 snprintf(label, sizeof label, "tinc TCP key expansion %s %s", c->name, myself->name);
404 return sptps_start(&c->sptps, c, c->outgoing, false, myself->connection->ecdsa, c->ecdsa, label, sizeof label, send_meta_sptps, receive_meta_sptps);
406 return send_metakey(c);
410 bool send_metakey(connection_t *c) {
411 if(!read_rsa_public_key(c))
414 if(!(c->outcipher = cipher_open_blowfish_ofb()))
417 if(!(c->outdigest = digest_open_sha1(-1)))
420 size_t len = rsa_size(c->rsa);
423 char hexkey[2 * len + 1];
425 /* Create a random key */
429 /* The message we send must be smaller than the modulus of the RSA key.
430 By definition, for a key of k bits, the following formula holds:
432 2^(k-1) <= modulus < 2^(k)
434 Where ^ means "to the power of", not "xor".
435 This means that to be sure, we must choose our message < 2^(k-1).
436 This can be done by setting the most significant bit to zero.
441 if(!cipher_set_key_from_rsa(c->outcipher, key, len, true))
444 if(debug_level >= DEBUG_SCARY_THINGS) {
445 bin2hex(key, hexkey, len);
446 logger(DEBUG_SCARY_THINGS, LOG_DEBUG, "Generated random meta key (unencrypted): %s", hexkey);
449 /* Encrypt the random data
451 We do not use one of the PKCS padding schemes here.
452 This is allowed, because we encrypt a totally random string
453 with a length equal to that of the modulus of the RSA key.
456 if(!rsa_public_encrypt(c->rsa, key, len, enckey)) {
457 logger(DEBUG_ALWAYS, LOG_ERR, "Error during encryption of meta key for %s (%s)", c->name, c->hostname);
461 /* Convert the encrypted random data to a hexadecimal formatted string */
463 bin2hex(enckey, hexkey, len);
465 /* Send the meta key */
467 bool result = send_request(c, "%d %d %d %d %d %s", METAKEY,
468 cipher_get_nid(c->outcipher),
469 digest_get_nid(c->outdigest), c->outmaclength,
470 c->outcompression, hexkey);
472 c->status.encryptout = true;
476 bool metakey_h(connection_t *c, const char *request) {
477 char hexkey[MAX_STRING_SIZE];
478 int cipher, digest, maclength, compression;
479 size_t len = rsa_size(myself->connection->rsa);
483 if(sscanf(request, "%*d %d %d %d %d " MAX_STRING, &cipher, &digest, &maclength, &compression, hexkey) != 5) {
484 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "METAKEY", c->name, c->hostname);
488 /* Convert the challenge from hexadecimal back to binary */
490 int inlen = hex2bin(hexkey, enckey, sizeof enckey);
492 /* Check if the length of the meta key is all right */
495 logger(DEBUG_ALWAYS, LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong keylength");
499 /* Decrypt the meta key */
501 if(!rsa_private_decrypt(myself->connection->rsa, enckey, len, key)) {
502 logger(DEBUG_ALWAYS, LOG_ERR, "Error during decryption of meta key for %s (%s)", c->name, c->hostname);
506 if(debug_level >= DEBUG_SCARY_THINGS) {
507 bin2hex(key, hexkey, len);
508 logger(DEBUG_SCARY_THINGS, LOG_DEBUG, "Received random meta key (unencrypted): %s", hexkey);
511 /* Check and lookup cipher and digest algorithms */
513 if(!(c->incipher = cipher_open_by_nid(cipher)) || !cipher_set_key_from_rsa(c->incipher, key, len, false)) {
514 logger(DEBUG_ALWAYS, LOG_ERR, "Error during initialisation of cipher from %s (%s)", c->name, c->hostname);
518 if(!(c->indigest = digest_open_by_nid(digest, -1))) {
519 logger(DEBUG_ALWAYS, LOG_ERR, "Error during initialisation of digest from %s (%s)", c->name, c->hostname);
523 c->status.decryptin = true;
525 c->allow_request = CHALLENGE;
527 return send_challenge(c);
530 bool send_challenge(connection_t *c) {
531 size_t len = rsa_size(c->rsa);
532 char buffer[len * 2 + 1];
535 c->hischallenge = xrealloc(c->hischallenge, len);
537 /* Copy random data to the buffer */
539 randomize(c->hischallenge, len);
543 bin2hex(c->hischallenge, buffer, len);
545 /* Send the challenge */
547 return send_request(c, "%d %s", CHALLENGE, buffer);
550 bool challenge_h(connection_t *c, const char *request) {
551 char buffer[MAX_STRING_SIZE];
552 size_t len = rsa_size(myself->connection->rsa);
553 size_t digestlen = digest_length(c->indigest);
554 char digest[digestlen];
556 if(sscanf(request, "%*d " MAX_STRING, buffer) != 1) {
557 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "CHALLENGE", c->name, c->hostname);
561 /* Convert the challenge from hexadecimal back to binary */
563 int inlen = hex2bin(buffer, buffer, sizeof buffer);
565 /* Check if the length of the challenge is all right */
568 logger(DEBUG_ALWAYS, LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong challenge length");
572 /* Calculate the hash from the challenge we received */
574 if(!digest_create(c->indigest, buffer, len, digest))
577 /* Convert the hash to a hexadecimal formatted string */
579 bin2hex(digest, buffer, digestlen);
583 c->allow_request = CHAL_REPLY;
585 return send_request(c, "%d %s", CHAL_REPLY, buffer);
588 bool chal_reply_h(connection_t *c, const char *request) {
589 char hishash[MAX_STRING_SIZE];
591 if(sscanf(request, "%*d " MAX_STRING, hishash) != 1) {
592 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "CHAL_REPLY", c->name,
597 /* Convert the hash to binary format */
599 int inlen = hex2bin(hishash, hishash, sizeof hishash);
601 /* Check if the length of the hash is all right */
603 if(inlen != digest_length(c->outdigest)) {
604 logger(DEBUG_ALWAYS, LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong challenge reply length");
609 /* Verify the hash */
611 if(!digest_verify(c->outdigest, c->hischallenge, rsa_size(c->rsa), hishash)) {
612 logger(DEBUG_ALWAYS, LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong challenge reply");
616 /* Identity has now been positively verified.
617 Send an acknowledgement with the rest of the information needed.
620 free(c->hischallenge);
621 c->hischallenge = NULL;
622 c->allow_request = ACK;
627 static bool send_upgrade(connection_t *c) {
628 /* Special case when protocol_minor is 1: the other end is ECDSA capable,
629 * but doesn't know our key yet. So send it now. */
631 char *pubkey = ecdsa_get_base64_public_key(myself->connection->ecdsa);
636 bool result = send_request(c, "%d %s", ACK, pubkey);
641 bool send_ack(connection_t *c) {
642 if(c->protocol_minor == 1)
643 return send_upgrade(c);
645 /* ACK message contains rest of the information the other end needs
646 to create node_t and edge_t structures. */
651 /* Estimate weight */
653 gettimeofday(&now, NULL);
654 c->estimated_weight = (now.tv_sec - c->start.tv_sec) * 1000 + (now.tv_usec - c->start.tv_usec) / 1000;
656 /* Check some options */
658 if((get_config_bool(lookup_config(c->config_tree, "IndirectData"), &choice) && choice) || myself->options & OPTION_INDIRECT)
659 c->options |= OPTION_INDIRECT;
661 if((get_config_bool(lookup_config(c->config_tree, "TCPOnly"), &choice) && choice) || myself->options & OPTION_TCPONLY)
662 c->options |= OPTION_TCPONLY | OPTION_INDIRECT;
664 if(myself->options & OPTION_PMTU_DISCOVERY)
665 c->options |= OPTION_PMTU_DISCOVERY;
667 choice = myself->options & OPTION_CLAMP_MSS;
668 get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice);
670 c->options |= OPTION_CLAMP_MSS;
672 if(!get_config_int(lookup_config(c->config_tree, "Weight"), &c->estimated_weight))
673 get_config_int(lookup_config(config_tree, "Weight"), &c->estimated_weight);
675 return send_request(c, "%d %s %d %x", ACK, myport, c->estimated_weight, (c->options & 0xffffff) | (experimental ? (PROT_MINOR << 24) : 0));
678 static void send_everything(connection_t *c) {
679 /* Send all known subnets and edges */
682 if(disablebuggypeers) {
685 char pad[MAXBUFSIZE - MAXSIZE];
688 memset(&zeropkt, 0, sizeof zeropkt);
689 zeropkt.pkt.len = MAXBUFSIZE;
690 send_tcppacket(c, &zeropkt.pkt);
693 for splay_each(node_t, n, node_tree) {
694 for splay_each(edge_t, e, n->edge_tree)
699 static bool upgrade_h(connection_t *c, const char *request) {
700 char pubkey[MAX_STRING_SIZE];
702 if(sscanf(request, "%*d " MAX_STRING, pubkey) != 1) {
703 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "ACK", c->name, c->hostname);
707 if(ecdsa_active(c->ecdsa) || read_ecdsa_public_key(c)) {
708 logger(DEBUG_ALWAYS, LOG_INFO, "Already have ECDSA public key from %s (%s), not upgrading.", c->name, c->hostname);
712 logger(DEBUG_ALWAYS, LOG_INFO, "Got ECDSA public key from %s (%s), upgrading!", c->name, c->hostname);
713 append_config_file(c->name, "ECDSAPublicKey", pubkey);
714 c->allow_request = TERMREQ;
715 return send_termreq(c);
718 bool ack_h(connection_t *c, const char *request) {
719 if(c->protocol_minor == 1)
720 return upgrade_h(c, request);
722 char hisport[MAX_STRING_SIZE];
729 if(sscanf(request, "%*d " MAX_STRING " %d %x", hisport, &weight, &options) != 3) {
730 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "ACK", c->name,
735 /* Check if we already have a node_t for him */
737 n = lookup_node(c->name);
741 n->name = xstrdup(c->name);
745 /* Oh dear, we already have a connection to this node. */
746 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Established a second connection with %s (%s), closing old connection", n->connection->name, n->connection->hostname);
748 if(n->connection->outgoing) {
750 logger(DEBUG_ALWAYS, LOG_WARNING, "Two outgoing connections to the same node!");
752 c->outgoing = n->connection->outgoing;
754 n->connection->outgoing = NULL;
757 terminate_connection(n->connection, false);
758 /* Run graph algorithm to purge key and make sure up/down scripts are rerun with new IP addresses and stuff */
765 if(!(c->options & options & OPTION_PMTU_DISCOVERY)) {
766 c->options &= ~OPTION_PMTU_DISCOVERY;
767 options &= ~OPTION_PMTU_DISCOVERY;
769 c->options |= options;
771 if(get_config_int(lookup_config(c->config_tree, "PMTU"), &mtu) && mtu < n->mtu)
774 if(get_config_int(lookup_config(config_tree, "PMTU"), &mtu) && mtu < n->mtu)
777 if(get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice)) {
779 c->options |= OPTION_CLAMP_MSS;
781 c->options &= ~OPTION_CLAMP_MSS;
784 /* Activate this connection */
786 c->allow_request = ALL;
787 c->status.active = true;
789 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection with %s (%s) activated", c->name,
792 /* Send him everything we know */
796 /* Create an edge_t for this connection */
798 c->edge = new_edge();
799 c->edge->from = myself;
801 sockaddr2str(&c->address, &hisaddress, NULL);
802 c->edge->address = str2sockaddr(hisaddress, hisport);
804 c->edge->weight = (weight + c->estimated_weight) / 2;
805 c->edge->connection = c;
806 c->edge->options = c->options;
810 /* Notify everyone of the new edge */
813 send_add_edge(c, c->edge);
815 send_add_edge(everyone, c->edge);
817 /* Run MST and SSSP algorithms */