2 invitation.c -- Create and accept invitations
3 Copyright (C) 2014 Guus Sliepen <guus@meshlink.io>
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"
33 int addressfamily = AF_UNSPEC;
35 static void scan_for_hostname(const char *filename, char **hostname, char **port) {
36 if(!filename || (*hostname && *port))
39 FILE *f = fopen(filename, "r");
43 while(fgets(line, sizeof line, f)) {
47 p += strcspn(p, "\t =");
50 q = p + strspn(p, "\t ");
52 q += 1 + strspn(q + 1, "\t ");
54 p = q + strcspn(q, "\t ");
57 p += strspn(p, "\t ");
58 p[strcspn(p, "\t ")] = 0;
60 if(!*port && !strcasecmp(line, "Port")) {
62 } else if(!*hostname && !strcasecmp(line, "Address")) {
63 *hostname = xstrdup(q);
70 if(*hostname && *port)
77 char *get_my_hostname() {
78 char *hostname = NULL;
80 char *hostport = NULL;
81 char *name = get_my_name(false);
82 char *filename = NULL;
84 // Use first Address statement in own host config file
86 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
87 scan_for_hostname(filename, &hostname, &port);
88 scan_for_hostname(tinc_conf, &hostname, &port);
94 // If that doesn't work, guess externally visible hostname
95 fprintf(stderr, "Trying to discover externally visible hostname...\n");
96 struct addrinfo *ai = str2addrinfo("tinc-vpn.org", "80", SOCK_STREAM);
97 struct addrinfo *aip = ai;
98 static const char request[] = "GET http://tinc-vpn.org/host.cgi HTTP/1.0\r\n\r\n";
101 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
103 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
109 send(s, request, sizeof request - 1, 0);
110 int len = recv(s, line, sizeof line - 1, MSG_WAITALL);
113 if(line[len - 1] == '\n')
115 char *p = strrchr(line, '\n');
117 hostname = xstrdup(p + 1);
130 // Check that the hostname is reasonable
132 for(char *p = hostname; *p; p++) {
133 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
135 // If not, forget it.
144 fprintf(stderr, "Could not determine the external address or hostname. Please set Address manually.\n");
151 fprintf(stderr, "Please enter your host's external address or hostname");
153 fprintf(stderr, " [%s]", hostname);
154 fprintf(stderr, ": ");
156 if(!fgets(line, sizeof line, stdin)) {
157 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
169 for(char *p = line; *p; p++) {
170 if(isalnum(*p) || *p == '-' || *p == '.')
172 fprintf(stderr, "Invalid address or hostname.\n");
177 hostname = xstrdup(line);
181 FILE *f = fopen(filename, "a");
183 fprintf(f, "\nAddress = %s\n", hostname);
186 fprintf(stderr, "Could not append Address to %s: %s\n", filename, strerror(errno));
192 if(strchr(hostname, ':'))
193 xasprintf(&hostport, "[%s]:%s", hostname, port);
195 xasprintf(&hostport, "%s:%s", hostname, port);
207 static bool fcopy(FILE *out, const char *filename) {
208 FILE *in = fopen(filename, "r");
210 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
216 while((len = fread(buf, 1, sizeof buf, in)))
217 fwrite(buf, len, 1, out);
222 int cmd_invite(int argc, char *argv[]) {
224 fprintf(stderr, "Not enough arguments!\n");
228 // Check validity of the new node's name
229 if(!check_id(argv[1])) {
230 fprintf(stderr, "Invalid name for node.\n");
234 char *myname = get_my_name(true);
238 // Ensure no host configuration file with that name exists
239 char *filename = NULL;
240 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, argv[1]);
241 if(!access(filename, F_OK)) {
243 fprintf(stderr, "A host config file for %s already exists!\n", argv[1]);
248 // If a daemon is running, ensure no other nodes now about this name
250 if(connect_tincd(false)) {
251 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
253 while(recvline(fd, line, sizeof line)) {
256 if(sscanf(line, "%d %d %s", &code, &req, node) != 3)
258 if(!strcmp(node, argv[1]))
263 fprintf(stderr, "A node with name %s is already known!\n", argv[1]);
270 xasprintf(&filename, "%s" SLASH "invitations", confbase);
271 if(mkdir(filename, 0700) && errno != EEXIST) {
272 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
277 // Count the number of valid invitations, clean up old ones
278 DIR *dir = opendir(filename);
280 fprintf(stderr, "Could not read directory %s: %s\n", filename, strerror(errno));
288 time_t deadline = time(NULL) - 604800; // 1 week in the past
290 while((ent = readdir(dir))) {
291 if(strlen(ent->d_name) != 24)
295 xasprintf(&invname, "%s" SLASH "%s", filename, ent->d_name);
296 if(!stat(invname, &st)) {
297 if(deadline < st.st_mtime)
302 fprintf(stderr, "Could not stat %s: %s\n", invname, strerror(errno));
309 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
319 xasprintf(&filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", confbase);
321 // Remove the key if there are no outstanding invitations.
325 // Create a new key if necessary.
326 FILE *f = fopen(filename, "r");
328 if(errno != ENOENT) {
329 fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
334 key = ecdsa_generate();
339 f = fopen(filename, "w");
341 fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
345 chmod(filename, 0600);
346 ecdsa_write_pem_private_key(key, f);
349 if(connect_tincd(false))
350 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
352 key = ecdsa_read_pem_private_key(f);
355 fprintf(stderr, "Could not read private key from %s\n", filename);
362 // Create a hash of the key.
363 char *fingerprint = ecdsa_get_base64_public_key(key);
364 sha512(fingerprint, strlen(fingerprint), hash);
365 b64encode_urlsafe(hash, hash, 18);
367 // Create a random cookie for this invitation.
369 randomize(cookie, 18);
371 // Create a filename that doesn't reveal the cookie itself
372 char buf[18 + strlen(fingerprint)];
374 memcpy(buf, cookie, 18);
375 memcpy(buf + 18, fingerprint, sizeof buf - 18);
376 sha512(buf, sizeof buf, cookiehash);
377 b64encode_urlsafe(cookiehash, cookiehash, 18);
379 b64encode_urlsafe(cookie, cookie, 18);
381 // Create a file containing the details of the invitation.
382 xasprintf(&filename, "%s" SLASH "invitations" SLASH "%s", confbase, cookiehash);
383 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
385 fprintf(stderr, "Could not create invitation file %s: %s\n", filename, strerror(errno));
389 f = fdopen(ifd, "w");
393 // Get the local address
394 char *address = get_my_hostname();
396 // Fill in the details.
397 fprintf(f, "Name = %s\n", argv[1]);
399 fprintf(f, "NetName = %s\n", netname);
400 fprintf(f, "ConnectTo = %s\n", myname);
402 // Copy Broadcast and Mode
403 FILE *tc = fopen(tinc_conf, "r");
406 while(fgets(buf, sizeof buf, tc)) {
407 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
408 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
410 // Make sure there is a newline character.
411 if(!strchr(buf, '\n'))
418 fprintf(f, "#---------------------------------------------------------------#\n");
419 fprintf(f, "Name = %s\n", myname);
422 xasprintf(&filename2, "%s" SLASH "hosts" SLASH "%s", confbase, myname);
427 // Create an URL from the local address, key hash and cookie
429 xasprintf(&url, "%s/%s%s", address, hash, cookie);
435 static char cookie[18];
436 static sptps_t sptps;
438 static size_t datalen;
439 static bool success = false;
441 static char cookie[18], hash[18];
443 static char *get_line(const char **data) {
452 static char line[1024];
453 const char *end = strchr(*data, '\n');
454 size_t len = end ? end - *data : strlen(*data);
455 if(len >= sizeof line) {
456 fprintf(stderr, "Maximum line length exceeded!\n");
459 if(len && !isprint(**data))
462 memcpy(line, *data, len);
473 static char *get_value(const char *data, const char *var) {
474 char *line = get_line(&data);
478 char *sep = line + strcspn(line, " \t=");
479 char *val = sep + strspn(sep, " \t");
481 val += 1 + strspn(val + 1, " \t");
483 if(strcasecmp(line, var))
488 static char *grep(const char *data, const char *var) {
489 static char value[1024];
491 const char *p = data;
492 int varlen = strlen(var);
494 // Skip all lines not starting with var
495 while(strncasecmp(p, var, varlen) || !strchr(" \t=", p[varlen])) {
507 p += strspn(p, " \t");
509 p += 1 + strspn(p + 1, " \t");
511 const char *e = strchr(p, '\n');
515 if(e - p >= sizeof value) {
516 fprintf(stderr, "Maximum line length exceeded!\n");
520 memcpy(value, p, e - p);
525 static bool finalize_join(void) {
526 char *name = xstrdup(get_value(data, "Name"));
528 fprintf(stderr, "No Name found in invitation!\n");
532 if(!check_id(name)) {
533 fprintf(stderr, "Invalid Name found in invitation: %s!\n", name);
538 netname = grep(data, "NetName");
540 bool ask_netname = false;
541 char temp_netname[32];
547 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
548 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
550 if(!access(tinc_conf, F_OK)) {
551 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
555 // Generate a random netname, ask for a better one later.
557 snprintf(temp_netname, sizeof temp_netname, "join_%x", rand());
558 netname = temp_netname;
562 if(mkdir(confbase, 0777) && errno != EEXIST) {
563 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
567 if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
568 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
572 FILE *f = fopen(tinc_conf, "w");
574 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
578 fprintf(f, "Name = %s\n", name);
581 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
582 FILE *fh = fopen(filename, "w");
584 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
588 // Filter first chunk on approved keywords, split between tinc.conf and hosts/Name
589 // Other chunks go unfiltered to their respective host config files
590 const char *p = data;
593 while((l = get_line(&p))) {
598 // Split line into variable and value
599 int len = strcspn(l, "\t =");
601 value += strspn(value, "\t ");
604 value += strspn(value, "\t ");
609 if(!strcasecmp(l, "Name"))
610 if(strcmp(value, name))
614 else if(!strcasecmp(l, "NetName"))
617 // Check the list of known variables
620 for(i = 0; variables[i].name; i++) {
621 if(strcasecmp(l, variables[i].name))
627 // Ignore unknown and unsafe variables
629 fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
631 } else if(!(variables[i].type & VAR_SAFE)) {
632 fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
636 // Copy the safe variable to the right config file
637 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
643 while(l && !strcasecmp(l, "Name")) {
644 if(!check_id(value)) {
645 fprintf(stderr, "Invalid Name found in invitation.\n");
649 if(!strcmp(value, name)) {
650 fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
654 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, value);
655 f = fopen(filename, "w");
658 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
662 while((l = get_line(&p))) {
663 if(!strcmp(l, "#---------------------------------------------------------------#"))
665 int len = strcspn(l, "\t =");
666 if(len == 4 && !strncasecmp(l, "Name", 4)) {
668 value += strspn(value, "\t ");
671 value += strspn(value, "\t ");
685 // Generate our key and send a copy to the server
686 ecdsa_t *key = ecdsa_generate();
690 char *b64key = ecdsa_get_base64_public_key(key);
694 xasprintf(&filename, "%s" SLASH "ecdsa_key.priv", confbase);
695 f = fopenmask(filename, "w", 0600);
697 if(!ecdsa_write_pem_private_key(key, f)) {
698 fprintf(stderr, "Error writing private key!\n");
706 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
708 sptps_send_record(&sptps, 1, b64key, strlen(b64key));
716 if(ask_netname && tty) {
717 fprintf(stderr, "Enter a new netname: ");
718 if(!fgets(line, sizeof line, stdin)) {
719 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
722 if(!*line || *line == '\n')
725 line[strlen(line) - 1] = 0;
728 xasprintf(&newbase, CONFDIR SLASH "tinc" SLASH "%s", line);
729 if(rename(confbase, newbase)) {
730 fprintf(stderr, "Error trying to rename %s to %s: %s\n", confbase, newbase, strerror(errno));
739 fprintf(stderr, "Configuration stored in: %s\n", confbase);
745 static bool invitation_send(void *handle, uint8_t type, const char *data, size_t len) {
747 int result = send(sock, data, len, 0);
748 if(result == -1 && errno == EINTR)
758 static bool invitation_receive(void *handle, uint8_t type, const char *msg, uint16_t len) {
760 case SPTPS_HANDSHAKE:
761 return sptps_send_record(&sptps, 0, cookie, sizeof cookie);
764 data = xrealloc(data, datalen + len + 1);
765 memcpy(data + datalen, msg, len);
771 return finalize_join();
774 fprintf(stderr, "Invitation succesfully accepted.\n");
775 shutdown(sock, SHUT_RDWR);
786 int cmd_join(int argc, char *argv[]) {
792 fprintf(stderr, "Too many arguments!\n");
796 // Make sure confbase exists and is accessible.
797 if(mkdir(confbase, 0777) && errno != EEXIST) {
798 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
802 if(access(confbase, R_OK | W_OK | X_OK)) {
803 fprintf(stderr, "No permission to write in directory %s: %s\n", confbase, strerror(errno));
807 // If a netname or explicit configuration directory is specified, check for an existing tinc.conf.
808 if((netname || confbasegiven) && !access(tinc_conf, F_OK)) {
809 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
813 // Either read the invitation from the command line or from stdin.
817 invitation = argv[1];
820 fprintf(stderr, "Enter invitation URL: ");
822 if(!fgets(line, sizeof line, stdin)) {
823 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
829 // Parse the invitation URL.
832 char *slash = strchr(invitation, '/');
838 if(strlen(slash) != 48)
841 char *address = invitation;
843 if(*address == '[') {
845 char *bracket = strchr(address, ']');
849 if(bracket[1] == ':')
852 port = strchr(address, ':');
860 if(!b64decode(slash, hash, 18) || !b64decode(slash + 24, cookie, 18))
863 // Generate a throw-away key for the invitation.
864 ecdsa_t *key = ecdsa_generate();
868 char *b64key = ecdsa_get_base64_public_key(key);
870 // Connect to the tinc daemon mentioned in the URL.
871 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
875 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
877 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
881 if(connect(sock, ai->ai_addr, ai->ai_addrlen)) {
882 fprintf(stderr, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
887 fprintf(stderr, "Connected to %s port %s...\n", address, port);
889 // Tell him we have an invitation, and give him our throw-away key.
890 int len = snprintf(line, sizeof line, "0 ?%s %d.%d\n", b64key, PROT_MAJOR, PROT_MINOR);
891 if(len <= 0 || len >= sizeof line)
894 if(!sendline(sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
895 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
900 char hisname[4096] = "";
901 int code, hismajor, hisminor = 0;
903 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) {
904 fprintf(stderr, "Cannot read greeting from peer\n");
909 // Check if the hash of the key he gave us matches the hash in the URL.
910 char *fingerprint = line + 2;
912 if(!sha512(fingerprint, strlen(fingerprint), hishash)) {
913 fprintf(stderr, "Could not create hash\n%s\n", line + 2);
916 if(memcmp(hishash, hash, 18)) {
917 fprintf(stderr, "Peer has an invalid key!\n%s\n", line + 2);
922 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
926 // Start an SPTPS session
927 if(!sptps_start(&sptps, NULL, true, false, key, hiskey, "tinc invitation", 15, invitation_send, invitation_receive))
930 // Feed rest of input buffer to SPTPS
931 if(!sptps_receive_data(&sptps, buffer, blen))
934 while((len = recv(sock, line, sizeof line, 0))) {
938 fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
942 if(!sptps_receive_data(&sptps, line, len))
952 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
959 fprintf(stderr, "Invalid invitation URL.\n");