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[PATH_MAX];
84 // Use first Address statement in own host config file
86 snprintf(filename,PATH_MAX, "%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);
206 static bool fcopy(FILE *out, const char *filename) {
207 FILE *in = fopen(filename, "r");
209 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
215 while((len = fread(buf, 1, sizeof buf, in)))
216 fwrite(buf, len, 1, out);
221 int cmd_invite(int argc, char *argv[]) {
223 fprintf(stderr, "Not enough arguments!\n");
227 // Check validity of the new node's name
228 if(!check_id(argv[1])) {
229 fprintf(stderr, "Invalid name for node.\n");
233 char *myname = get_my_name(true);
237 // Ensure no host configuration file with that name exists
238 char filename [PATH_MAX];
239 snprintf(filename,PATH_MAX, "%s" SLASH "hosts" SLASH "%s", confbase, argv[1]);
240 if(!access(filename, F_OK)) {
241 fprintf(stderr, "A host config file for %s already exists!\n", argv[1]);
245 // If a daemon is running, ensure no other nodes now about this name
247 if(connect_tincd(false)) {
248 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
250 while(recvline(fd, line, sizeof line)) {
253 if(sscanf(line, "%d %d %s", &code, &req, node) != 3)
255 if(!strcmp(node, argv[1]))
260 fprintf(stderr, "A node with name %s is already known!\n", argv[1]);
267 snprintf(filename,PATH_MAX, "%s" SLASH "invitations", confbase);
268 if(mkdir(filename, 0700) && errno != EEXIST) {
269 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
273 // Count the number of valid invitations, clean up old ones
274 DIR *dir = opendir(filename);
276 fprintf(stderr, "Could not read directory %s: %s\n", filename, strerror(errno));
283 time_t deadline = time(NULL) - 604800; // 1 week in the past
285 while((ent = readdir(dir))) {
286 if(strlen(ent->d_name) != 24)
288 char invname[PATH_MAX];
290 snprintf(invname,PATH_MAX, "%s" SLASH "%s", filename, ent->d_name);
291 if(!stat(invname, &st)) {
292 if(deadline < st.st_mtime)
297 fprintf(stderr, "Could not stat %s: %s\n", invname, strerror(errno));
303 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
311 snprintf(filename,PATH_MAX, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", confbase);
313 // Remove the key if there are no outstanding invitations.
317 // Create a new key if necessary.
318 FILE *f = fopen(filename, "r");
320 if(errno != ENOENT) {
321 fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
325 key = ecdsa_generate();
329 f = fopen(filename, "w");
331 fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
334 chmod(filename, 0600);
335 ecdsa_write_pem_private_key(key, f);
338 if(connect_tincd(false))
339 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
341 key = ecdsa_read_pem_private_key(f);
344 fprintf(stderr, "Could not read private key from %s\n", filename);
350 // Create a hash of the key.
351 char *fingerprint = ecdsa_get_base64_public_key(key);
352 sha512(fingerprint, strlen(fingerprint), hash);
353 b64encode_urlsafe(hash, hash, 18);
355 // Create a random cookie for this invitation.
357 randomize(cookie, 18);
359 // Create a filename that doesn't reveal the cookie itself
360 char buf[18 + strlen(fingerprint)];
362 memcpy(buf, cookie, 18);
363 memcpy(buf + 18, fingerprint, sizeof buf - 18);
364 sha512(buf, sizeof buf, cookiehash);
365 b64encode_urlsafe(cookiehash, cookiehash, 18);
367 b64encode_urlsafe(cookie, cookie, 18);
369 // Create a file containing the details of the invitation.
370 snprintf(filename,PATH_MAX, "%s" SLASH "invitations" SLASH "%s", confbase, cookiehash);
371 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
373 fprintf(stderr, "Could not create invitation file %s: %s\n", filename, strerror(errno));
376 f = fdopen(ifd, "w");
380 // Get the local address
381 char *address = get_my_hostname();
383 // Fill in the details.
384 fprintf(f, "Name = %s\n", argv[1]);
386 fprintf(f, "NetName = %s\n", netname);
387 fprintf(f, "ConnectTo = %s\n", myname);
389 // Copy Broadcast and Mode
390 FILE *tc = fopen(tinc_conf, "r");
393 while(fgets(buf, sizeof buf, tc)) {
394 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
395 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
397 // Make sure there is a newline character.
398 if(!strchr(buf, '\n'))
405 fprintf(f, "#---------------------------------------------------------------#\n");
406 fprintf(f, "Name = %s\n", myname);
408 char filename2[PATH_MAX];
409 snsprintf(filename2,PATH_MAX, "%s" SLASH "hosts" SLASH "%s", confbase, myname);
413 // Create an URL from the local address, key hash and cookie
415 xasprintf(&url, "%s/%s%s", address, hash, cookie);
421 static char cookie[18];
422 static sptps_t sptps;
424 static size_t datalen;
425 static bool success = false;
427 static char cookie[18], hash[18];
429 static char *get_line(const char **data) {
438 static char line[1024];
439 const char *end = strchr(*data, '\n');
440 size_t len = end ? end - *data : strlen(*data);
441 if(len >= sizeof line) {
442 fprintf(stderr, "Maximum line length exceeded!\n");
445 if(len && !isprint(**data))
448 memcpy(line, *data, len);
459 static char *get_value(const char *data, const char *var) {
460 char *line = get_line(&data);
464 char *sep = line + strcspn(line, " \t=");
465 char *val = sep + strspn(sep, " \t");
467 val += 1 + strspn(val + 1, " \t");
469 if(strcasecmp(line, var))
474 static char *grep(const char *data, const char *var) {
475 static char value[1024];
477 const char *p = data;
478 int varlen = strlen(var);
480 // Skip all lines not starting with var
481 while(strncasecmp(p, var, varlen) || !strchr(" \t=", p[varlen])) {
493 p += strspn(p, " \t");
495 p += 1 + strspn(p + 1, " \t");
497 const char *e = strchr(p, '\n');
501 if(e - p >= sizeof value) {
502 fprintf(stderr, "Maximum line length exceeded!\n");
506 memcpy(value, p, e - p);
511 static bool finalize_join(void) {
512 char *name = xstrdup(get_value(data, "Name"));
514 fprintf(stderr, "No Name found in invitation!\n");
518 if(!check_id(name)) {
519 fprintf(stderr, "Invalid Name found in invitation: %s!\n", name);
524 netname = grep(data, "NetName");
526 bool ask_netname = false;
527 char temp_netname[32];
533 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
534 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
536 if(!access(tinc_conf, F_OK)) {
537 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
541 // Generate a random netname, ask for a better one later.
543 snprintf(temp_netname, sizeof temp_netname, "join_%x", rand());
544 netname = temp_netname;
548 if(mkdir(confbase, 0777) && errno != EEXIST) {
549 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
553 if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
554 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
558 FILE *f = fopen(tinc_conf, "w");
560 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
564 fprintf(f, "Name = %s\n", name);
566 char filename[PATH_MAX];
567 snprintf(filename,PATH_MAX, "%s" SLASH "%s", hosts_dir, name);
568 FILE *fh = fopen(filename, "w");
570 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
574 // Filter first chunk on approved keywords, split between tinc.conf and hosts/Name
575 // Other chunks go unfiltered to their respective host config files
576 const char *p = data;
579 while((l = get_line(&p))) {
584 // Split line into variable and value
585 int len = strcspn(l, "\t =");
587 value += strspn(value, "\t ");
590 value += strspn(value, "\t ");
595 if(!strcasecmp(l, "Name"))
596 if(strcmp(value, name))
600 else if(!strcasecmp(l, "NetName"))
603 // Check the list of known variables
606 for(i = 0; variables[i].name; i++) {
607 if(strcasecmp(l, variables[i].name))
613 // Ignore unknown and unsafe variables
615 fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
617 } else if(!(variables[i].type & VAR_SAFE)) {
618 fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
622 // Copy the safe variable to the right config file
623 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
628 while(l && !strcasecmp(l, "Name")) {
629 if(!check_id(value)) {
630 fprintf(stderr, "Invalid Name found in invitation.\n");
634 if(!strcmp(value, name)) {
635 fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
639 snprintf(filename,PATH_MAX, "%s" SLASH "%s", hosts_dir, value);
640 f = fopen(filename, "w");
643 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
647 while((l = get_line(&p))) {
648 if(!strcmp(l, "#---------------------------------------------------------------#"))
650 int len = strcspn(l, "\t =");
651 if(len == 4 && !strncasecmp(l, "Name", 4)) {
653 value += strspn(value, "\t ");
656 value += strspn(value, "\t ");
669 // Generate our key and send a copy to the server
670 ecdsa_t *key = ecdsa_generate();
674 char *b64key = ecdsa_get_base64_public_key(key);
678 snprintf(filename,PATH_MAX, "%s" SLASH "ecdsa_key.priv", confbase);
679 f = fopenmask(filename, "w", 0600);
681 if(!ecdsa_write_pem_private_key(key, f)) {
682 fprintf(stderr, "Error writing private key!\n");
690 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
692 sptps_send_record(&sptps, 1, b64key, strlen(b64key));
700 if(ask_netname && tty) {
701 fprintf(stderr, "Enter a new netname: ");
702 if(!fgets(line, sizeof line, stdin)) {
703 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
706 if(!*line || *line == '\n')
709 line[strlen(line) - 1] = 0;
712 xasprintf(&newbase, CONFDIR SLASH "tinc" SLASH "%s", line);
713 if(rename(confbase, newbase)) {
714 fprintf(stderr, "Error trying to rename %s to %s: %s\n", confbase, newbase, strerror(errno));
723 fprintf(stderr, "Configuration stored in: %s\n", confbase);
729 static bool invitation_send(void *handle, uint8_t type, const char *data, size_t len) {
731 int result = send(sock, data, len, 0);
732 if(result == -1 && errno == EINTR)
742 static bool invitation_receive(void *handle, uint8_t type, const char *msg, uint16_t len) {
744 case SPTPS_HANDSHAKE:
745 return sptps_send_record(&sptps, 0, cookie, sizeof cookie);
748 data = xrealloc(data, datalen + len + 1);
749 memcpy(data + datalen, msg, len);
755 return finalize_join();
758 fprintf(stderr, "Invitation succesfully accepted.\n");
759 shutdown(sock, SHUT_RDWR);
770 int cmd_join(int argc, char *argv[]) {
776 fprintf(stderr, "Too many arguments!\n");
780 // Make sure confbase exists and is accessible.
781 if(mkdir(confbase, 0777) && errno != EEXIST) {
782 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
786 if(access(confbase, R_OK | W_OK | X_OK)) {
787 fprintf(stderr, "No permission to write in directory %s: %s\n", confbase, strerror(errno));
791 // If a netname or explicit configuration directory is specified, check for an existing tinc.conf.
792 if((netname || confbasegiven) && !access(tinc_conf, F_OK)) {
793 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
797 // Either read the invitation from the command line or from stdin.
801 invitation = argv[1];
804 fprintf(stderr, "Enter invitation URL: ");
806 if(!fgets(line, sizeof line, stdin)) {
807 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
813 // Parse the invitation URL.
816 char *slash = strchr(invitation, '/');
822 if(strlen(slash) != 48)
825 char *address = invitation;
827 if(*address == '[') {
829 char *bracket = strchr(address, ']');
833 if(bracket[1] == ':')
836 port = strchr(address, ':');
844 if(!b64decode(slash, hash, 18) || !b64decode(slash + 24, cookie, 18))
847 // Generate a throw-away key for the invitation.
848 ecdsa_t *key = ecdsa_generate();
852 char *b64key = ecdsa_get_base64_public_key(key);
854 // Connect to the tinc daemon mentioned in the URL.
855 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
859 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
861 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
865 if(connect(sock, ai->ai_addr, ai->ai_addrlen)) {
866 fprintf(stderr, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
871 fprintf(stderr, "Connected to %s port %s...\n", address, port);
873 // Tell him we have an invitation, and give him our throw-away key.
874 int len = snprintf(line, sizeof line, "0 ?%s %d.%d\n", b64key, PROT_MAJOR, PROT_MINOR);
875 if(len <= 0 || len >= sizeof line)
878 if(!sendline(sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
879 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
884 char hisname[4096] = "";
885 int code, hismajor, hisminor = 0;
887 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) {
888 fprintf(stderr, "Cannot read greeting from peer\n");
893 // Check if the hash of the key he gave us matches the hash in the URL.
894 char *fingerprint = line + 2;
896 if(!sha512(fingerprint, strlen(fingerprint), hishash)) {
897 fprintf(stderr, "Could not create hash\n%s\n", line + 2);
900 if(memcmp(hishash, hash, 18)) {
901 fprintf(stderr, "Peer has an invalid key!\n%s\n", line + 2);
906 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
910 // Start an SPTPS session
911 if(!sptps_start(&sptps, NULL, true, false, key, hiskey, "tinc invitation", 15, invitation_send, invitation_receive))
914 // Feed rest of input buffer to SPTPS
915 if(!sptps_receive_data(&sptps, buffer, blen))
918 while((len = recv(sock, line, sizeof line, 0))) {
922 fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
926 if(!sptps_receive_data(&sptps, line, len))
936 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
943 fprintf(stderr, "Invalid invitation URL.\n");