2 invitation.c -- Create and accept invitations
3 Copyright (C) 2013-2014 Guus Sliepen <guus@tinc-vpn.org>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 #include "control_common.h"
26 #include "invitation.h"
34 int addressfamily = AF_UNSPEC;
36 static void scan_for_hostname(const char *filename, char **hostname, char **port) {
37 if(!filename || (*hostname && *port))
40 FILE *f = fopen(filename, "r");
44 while(fgets(line, sizeof line, f)) {
48 p += strcspn(p, "\t =");
51 q = p + strspn(p, "\t ");
53 q += 1 + strspn(q + 1, "\t ");
55 p = q + strcspn(q, "\t ");
58 p += strspn(p, "\t ");
59 p[strcspn(p, "\t ")] = 0;
61 if(!*port && !strcasecmp(line, "Port")) {
63 } else if(!*hostname && !strcasecmp(line, "Address")) {
64 *hostname = xstrdup(q);
71 if(*hostname && *port)
78 char *get_my_hostname() {
79 char *hostname = NULL;
81 char *hostport = NULL;
82 char *name = get_my_name(false);
83 char *filename = NULL;
85 // Use first Address statement in own host config file
87 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
88 scan_for_hostname(filename, &hostname, &port);
89 scan_for_hostname(tinc_conf, &hostname, &port);
95 // If that doesn't work, guess externally visible hostname
96 fprintf(stderr, "Trying to discover externally visible hostname...\n");
97 struct addrinfo *ai = str2addrinfo("tinc-vpn.org", "80", SOCK_STREAM);
98 struct addrinfo *aip = ai;
99 static const char request[] = "GET http://tinc-vpn.org/host.cgi HTTP/1.0\r\n\r\n";
102 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
104 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
110 send(s, request, sizeof request - 1, 0);
111 int len = recv(s, line, sizeof line - 1, MSG_WAITALL);
114 if(line[len - 1] == '\n')
116 char *p = strrchr(line, '\n');
118 hostname = xstrdup(p + 1);
131 // Check that the hostname is reasonable
133 for(char *p = hostname; *p; p++) {
134 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
136 // If not, forget it.
145 fprintf(stderr, "Could not determine the external address or hostname. Please set Address manually.\n");
152 fprintf(stderr, "Please enter your host's external address or hostname");
154 fprintf(stderr, " [%s]", hostname);
155 fprintf(stderr, ": ");
157 if(!fgets(line, sizeof line, stdin)) {
158 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
170 for(char *p = line; *p; p++) {
171 if(isalnum(*p) || *p == '-' || *p == '.')
173 fprintf(stderr, "Invalid address or hostname.\n");
178 hostname = xstrdup(line);
182 FILE *f = fopen(filename, "a");
184 fprintf(f, "\nAddress = %s\n", hostname);
187 fprintf(stderr, "Could not append Address to %s: %s\n", filename, strerror(errno));
193 if(strchr(hostname, ':'))
194 xasprintf(&hostport, "[%s]:%s", hostname, port);
196 xasprintf(&hostport, "%s:%s", hostname, port);
208 static bool fcopy(FILE *out, const char *filename) {
209 FILE *in = fopen(filename, "r");
211 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
217 while((len = fread(buf, 1, sizeof buf, in)))
218 fwrite(buf, len, 1, out);
223 int cmd_invite(int argc, char *argv[]) {
225 fprintf(stderr, "Not enough arguments!\n");
229 // Check validity of the new node's name
230 if(!check_id(argv[1])) {
231 fprintf(stderr, "Invalid name for node.\n");
235 char *myname = get_my_name(true);
239 // Ensure no host configuration file with that name exists
240 char *filename = NULL;
241 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, argv[1]);
242 if(!access(filename, F_OK)) {
244 fprintf(stderr, "A host config file for %s already exists!\n", argv[1]);
249 // If a daemon is running, ensure no other nodes now about this name
251 if(connect_tincd(false)) {
252 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
254 while(recvline(fd, line, sizeof line)) {
257 if(sscanf(line, "%d %d %s", &code, &req, node) != 3)
259 if(!strcmp(node, argv[1]))
264 fprintf(stderr, "A node with name %s is already known!\n", argv[1]);
271 xasprintf(&filename, "%s" SLASH "invitations", confbase);
272 if(mkdir(filename, 0700) && errno != EEXIST) {
273 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
278 // Count the number of valid invitations, clean up old ones
279 DIR *dir = opendir(filename);
281 fprintf(stderr, "Could not read directory %s: %s\n", filename, strerror(errno));
289 time_t deadline = time(NULL) - 604800; // 1 week in the past
291 while((ent = readdir(dir))) {
292 if(strlen(ent->d_name) != 24)
296 xasprintf(&invname, "%s" SLASH "%s", filename, ent->d_name);
297 if(!stat(invname, &st)) {
298 if(deadline < st.st_mtime)
303 fprintf(stderr, "Could not stat %s: %s\n", invname, strerror(errno));
310 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
320 xasprintf(&filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", confbase);
322 // Remove the key if there are no outstanding invitations.
326 // Create a new key if necessary.
327 FILE *f = fopen(filename, "r");
329 if(errno != ENOENT) {
330 fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
335 key = ecdsa_generate();
340 f = fopen(filename, "w");
342 fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
346 chmod(filename, 0600);
347 ecdsa_write_pem_private_key(key, f);
350 if(connect_tincd(false))
351 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
353 key = ecdsa_read_pem_private_key(f);
356 fprintf(stderr, "Could not read private key from %s\n", filename);
363 // Create a hash of the key.
364 char *fingerprint = ecdsa_get_base64_public_key(key);
365 digest_t *digest = digest_open_by_name("sha256", 18);
368 digest_create(digest, fingerprint, strlen(fingerprint), hash);
369 b64encode_urlsafe(hash, hash, 18);
371 // Create a random cookie for this invitation.
373 randomize(cookie, 18);
375 // Create a filename that doesn't reveal the cookie itself
376 char buf[18 + strlen(fingerprint)];
378 memcpy(buf, cookie, 18);
379 memcpy(buf + 18, fingerprint, sizeof buf - 18);
380 digest_create(digest, buf, sizeof buf, cookiehash);
381 b64encode_urlsafe(cookiehash, cookiehash, 18);
383 b64encode_urlsafe(cookie, cookie, 18);
385 // Create a file containing the details of the invitation.
386 xasprintf(&filename, "%s" SLASH "invitations" SLASH "%s", confbase, cookiehash);
387 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
389 fprintf(stderr, "Could not create invitation file %s: %s\n", filename, strerror(errno));
393 f = fdopen(ifd, "w");
397 // Get the local address
398 char *address = get_my_hostname();
400 // Fill in the details.
401 fprintf(f, "Name = %s\n", argv[1]);
403 fprintf(f, "NetName = %s\n", netname);
404 fprintf(f, "ConnectTo = %s\n", myname);
406 // Copy Broadcast and Mode
407 FILE *tc = fopen(tinc_conf, "r");
410 while(fgets(buf, sizeof buf, tc)) {
411 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
412 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
414 // Make sure there is a newline character.
415 if(!strchr(buf, '\n'))
422 fprintf(f, "#---------------------------------------------------------------#\n");
423 fprintf(f, "Name = %s\n", myname);
426 xasprintf(&filename2, "%s" SLASH "hosts" SLASH "%s", confbase, myname);
431 // Create an URL from the local address, key hash and cookie
433 xasprintf(&url, "%s/%s%s", address, hash, cookie);
439 static char cookie[18];
440 static sptps_t sptps;
442 static size_t datalen;
443 static bool success = false;
445 static char cookie[18], hash[18];
447 static char *get_line(const char **data) {
456 static char line[1024];
457 const char *end = strchr(*data, '\n');
458 size_t len = end ? end - *data : strlen(*data);
459 if(len >= sizeof line) {
460 fprintf(stderr, "Maximum line length exceeded!\n");
463 if(len && !isprint(**data))
466 memcpy(line, *data, len);
477 static char *get_value(const char *data, const char *var) {
478 char *line = get_line(&data);
482 char *sep = line + strcspn(line, " \t=");
483 char *val = sep + strspn(sep, " \t");
485 val += 1 + strspn(val + 1, " \t");
487 if(strcasecmp(line, var))
492 static char *grep(const char *data, const char *var) {
493 static char value[1024];
495 const char *p = data;
496 int varlen = strlen(var);
498 // Skip all lines not starting with var
499 while(strncasecmp(p, var, varlen) || !strchr(" \t=", p[varlen])) {
511 p += strspn(p, " \t");
513 p += 1 + strspn(p + 1, " \t");
515 const char *e = strchr(p, '\n');
519 if(e - p >= sizeof value) {
520 fprintf(stderr, "Maximum line length exceeded!\n");
524 memcpy(value, p, e - p);
529 static bool finalize_join(void) {
530 char *name = xstrdup(get_value(data, "Name"));
532 fprintf(stderr, "No Name found in invitation!\n");
536 if(!check_id(name)) {
537 fprintf(stderr, "Invalid Name found in invitation: %s!\n", name);
542 netname = grep(data, "NetName");
544 bool ask_netname = false;
545 char temp_netname[32];
551 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
552 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
554 if(!access(tinc_conf, F_OK)) {
555 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
559 // Generate a random netname, ask for a better one later.
561 snprintf(temp_netname, sizeof temp_netname, "join_%x", rand());
562 netname = temp_netname;
566 if(mkdir(confbase, 0777) && errno != EEXIST) {
567 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
571 if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
572 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
576 FILE *f = fopen(tinc_conf, "w");
578 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
582 fprintf(f, "Name = %s\n", name);
585 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
586 FILE *fh = fopen(filename, "w");
588 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
592 // Filter first chunk on approved keywords, split between tinc.conf and hosts/Name
593 // Other chunks go unfiltered to their respective host config files
594 const char *p = data;
597 while((l = get_line(&p))) {
602 // Split line into variable and value
603 int len = strcspn(l, "\t =");
605 value += strspn(value, "\t ");
608 value += strspn(value, "\t ");
613 if(!strcasecmp(l, "Name"))
614 if(strcmp(value, name))
618 else if(!strcasecmp(l, "NetName"))
621 // Check the list of known variables
624 for(i = 0; variables[i].name; i++) {
625 if(strcasecmp(l, variables[i].name))
631 // Ignore unknown and unsafe variables
633 fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
635 } else if(!(variables[i].type & VAR_SAFE)) {
636 fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
640 // Copy the safe variable to the right config file
641 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
647 while(l && !strcasecmp(l, "Name")) {
648 if(!check_id(value)) {
649 fprintf(stderr, "Invalid Name found in invitation.\n");
653 if(!strcmp(value, name)) {
654 fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
658 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, value);
659 f = fopen(filename, "w");
662 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
666 while((l = get_line(&p))) {
667 if(!strcmp(l, "#---------------------------------------------------------------#"))
669 int len = strcspn(l, "\t =");
670 if(len == 4 && !strncasecmp(l, "Name", 4)) {
672 value += strspn(value, "\t ");
675 value += strspn(value, "\t ");
689 // Generate our key and send a copy to the server
690 ecdsa_t *key = ecdsa_generate();
694 char *b64key = ecdsa_get_base64_public_key(key);
698 xasprintf(&filename, "%s" SLASH "ecdsa_key.priv", confbase);
699 f = fopenmask(filename, "w", 0600);
701 if(!ecdsa_write_pem_private_key(key, f)) {
702 fprintf(stderr, "Error writing private key!\n");
710 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
712 sptps_send_record(&sptps, 1, b64key, strlen(b64key));
716 rsa_t *rsa = rsa_generate(2048, 0x1001);
717 xasprintf(&filename, "%s" SLASH "rsa_key.priv", confbase);
718 f = fopenmask(filename, "w", 0600);
720 rsa_write_pem_private_key(rsa, f);
723 rsa_write_pem_public_key(rsa, fh);
732 if(ask_netname && tty) {
733 fprintf(stderr, "Enter a new netname: ");
734 if(!fgets(line, sizeof line, stdin)) {
735 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
738 if(!*line || *line == '\n')
741 line[strlen(line) - 1] = 0;
744 xasprintf(&newbase, CONFDIR SLASH "tinc" SLASH "%s", line);
745 if(rename(confbase, newbase)) {
746 fprintf(stderr, "Error trying to rename %s to %s: %s\n", confbase, newbase, strerror(errno));
755 fprintf(stderr, "Configuration stored in: %s\n", confbase);
761 static bool invitation_send(void *handle, uint8_t type, const char *data, size_t len) {
763 int result = send(sock, data, len, 0);
764 if(result == -1 && errno == EINTR)
774 static bool invitation_receive(void *handle, uint8_t type, const char *msg, uint16_t len) {
776 case SPTPS_HANDSHAKE:
777 return sptps_send_record(&sptps, 0, cookie, sizeof cookie);
780 data = xrealloc(data, datalen + len + 1);
781 memcpy(data + datalen, msg, len);
787 return finalize_join();
790 fprintf(stderr, "Invitation succesfully accepted.\n");
791 shutdown(sock, SHUT_RDWR);
802 int cmd_join(int argc, char *argv[]) {
808 fprintf(stderr, "Too many arguments!\n");
812 // Make sure confbase exists and is accessible.
813 if(mkdir(confbase, 0777) && errno != EEXIST) {
814 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
818 if(access(confbase, R_OK | W_OK | X_OK)) {
819 fprintf(stderr, "No permission to write in directory %s: %s\n", confbase, strerror(errno));
823 // If a netname or explicit configuration directory is specified, check for an existing tinc.conf.
824 if((netname || confbasegiven) && !access(tinc_conf, F_OK)) {
825 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
829 // Either read the invitation from the command line or from stdin.
833 invitation = argv[1];
836 fprintf(stderr, "Enter invitation URL: ");
838 if(!fgets(line, sizeof line, stdin)) {
839 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
845 // Parse the invitation URL.
848 char *slash = strchr(invitation, '/');
854 if(strlen(slash) != 48)
857 char *address = invitation;
859 if(*address == '[') {
861 char *bracket = strchr(address, ']');
865 if(bracket[1] == ':')
868 port = strchr(address, ':');
876 if(!b64decode(slash, hash, 18) || !b64decode(slash + 24, cookie, 18))
879 // Generate a throw-away key for the invitation.
880 ecdsa_t *key = ecdsa_generate();
884 char *b64key = ecdsa_get_base64_public_key(key);
886 // Connect to the tinc daemon mentioned in the URL.
887 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
891 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
893 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
897 if(connect(sock, ai->ai_addr, ai->ai_addrlen)) {
898 fprintf(stderr, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
903 fprintf(stderr, "Connected to %s port %s...\n", address, port);
905 // Tell him we have an invitation, and give him our throw-away key.
906 int len = snprintf(line, sizeof line, "0 ?%s %d.%d\n", b64key, PROT_MAJOR, PROT_MINOR);
907 if(len <= 0 || len >= sizeof line)
910 if(!sendline(sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
911 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
916 char hisname[4096] = "";
917 int code, hismajor, hisminor = 0;
919 if(!recvline(sock, line, sizeof line) || sscanf(line, "%d %s %d.%d", &code, hisname, &hismajor, &hisminor) < 3 || code != 0 || hismajor != PROT_MAJOR || !check_id(hisname) || !recvline(sock, line, sizeof line) || !rstrip(line) || sscanf(line, "%d ", &code) != 1 || code != ACK || strlen(line) < 3) {
920 fprintf(stderr, "Cannot read greeting from peer\n");
925 // Check if the hash of the key he gave us matches the hash in the URL.
926 char *fingerprint = line + 2;
927 digest_t *digest = digest_open_by_name("sha256", 18);
931 if(!digest_create(digest, fingerprint, strlen(fingerprint), hishash)) {
932 fprintf(stderr, "Could not create digest\n%s\n", line + 2);
935 if(memcmp(hishash, hash, 18)) {
936 fprintf(stderr, "Peer has an invalid key!\n%s\n", line + 2);
941 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
945 // Start an SPTPS session
946 if(!sptps_start(&sptps, NULL, true, false, key, hiskey, "tinc invitation", 15, invitation_send, invitation_receive))
949 // Feed rest of input buffer to SPTPS
950 if(!sptps_receive_data(&sptps, buffer, blen))
953 while((len = recv(sock, line, sizeof line, 0))) {
957 fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
961 if(!sptps_receive_data(&sptps, line, len))
971 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
978 fprintf(stderr, "Invalid invitation URL.\n");