2 invitation.c -- Create and accept invitations
3 Copyright (C) 2013-2015 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"
36 #include "ed25519/sha512.h"
38 int addressfamily = AF_UNSPEC;
40 static void scan_for_hostname(const char *filename, char **hostname, char **port) {
41 if(!filename || (*hostname && *port))
44 FILE *f = fopen(filename, "r");
48 while(fgets(line, sizeof line, f)) {
52 p += strcspn(p, "\t =");
55 q = p + strspn(p, "\t ");
57 q += 1 + strspn(q + 1, "\t ");
59 p = q + strcspn(q, "\t ");
62 p += strspn(p, "\t ");
63 p[strcspn(p, "\t ")] = 0;
65 if(!*port && !strcasecmp(line, "Port")) {
67 } else if(!*hostname && !strcasecmp(line, "Address")) {
68 *hostname = xstrdup(q);
75 if(*hostname && *port)
82 char *get_my_hostname() {
83 char *hostname = NULL;
85 char *hostport = NULL;
86 char *name = get_my_name(false);
87 char filename[PATH_MAX];
89 // Use first Address statement in own host config file
91 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
92 scan_for_hostname(filename, &hostname, &port);
93 scan_for_hostname(tinc_conf, &hostname, &port);
99 // If that doesn't work, guess externally visible hostname
100 fprintf(stderr, "Trying to discover externally visible hostname...\n");
101 struct addrinfo *ai = str2addrinfo("tinc-vpn.org", "80", SOCK_STREAM);
102 struct addrinfo *aip = ai;
103 static const char request[] = "GET http://tinc-vpn.org/host.cgi HTTP/1.0\r\n\r\n";
106 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
108 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
114 send(s, request, sizeof request - 1, 0);
115 int len = recv(s, line, sizeof line - 1, MSG_WAITALL);
118 if(line[len - 1] == '\n')
120 char *p = strrchr(line, '\n');
122 hostname = xstrdup(p + 1);
135 // Check that the hostname is reasonable
137 for(char *p = hostname; *p; p++) {
138 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
140 // If not, forget it.
149 fprintf(stderr, "Could not determine the external address or hostname. Please set Address manually.\n");
156 fprintf(stderr, "Please enter your host's external address or hostname");
158 fprintf(stderr, " [%s]", hostname);
159 fprintf(stderr, ": ");
161 if(!fgets(line, sizeof line, stdin)) {
162 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
174 for(char *p = line; *p; p++) {
175 if(isalnum(*p) || *p == '-' || *p == '.')
177 fprintf(stderr, "Invalid address or hostname.\n");
182 hostname = xstrdup(line);
186 FILE *f = fopen(filename, "a");
188 fprintf(f, "\nAddress = %s\n", hostname);
191 fprintf(stderr, "Could not append Address to %s: %s\n", filename, strerror(errno));
197 if(strchr(hostname, ':'))
198 xasprintf(&hostport, "[%s]:%s", hostname, port);
200 xasprintf(&hostport, "%s:%s", hostname, port);
202 if(strchr(hostname, ':'))
203 xasprintf(&hostport, "[%s]", hostname);
205 hostport = xstrdup(hostname);
213 static bool fcopy(FILE *out, const char *filename) {
214 FILE *in = fopen(filename, "r");
216 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
222 while((len = fread(buf, 1, sizeof buf, in)))
223 fwrite(buf, len, 1, out);
228 int cmd_invite(int argc, char *argv[]) {
230 fprintf(stderr, "Not enough arguments!\n");
234 // Check validity of the new node's name
235 if(!check_id(argv[1])) {
236 fprintf(stderr, "Invalid name for node.\n");
240 char *myname = get_my_name(true);
244 // Ensure no host configuration file with that name exists
245 char filename[PATH_MAX];
246 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", confbase, argv[1]);
247 if(!access(filename, F_OK)) {
248 fprintf(stderr, "A host config file for %s already exists!\n", argv[1]);
252 // If a daemon is running, ensure no other nodes know about this name
254 if(connect_tincd(false)) {
255 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
257 while(recvline(fd, line, sizeof line)) {
260 if(sscanf(line, "%d %d %s", &code, &req, node) != 3)
262 if(!strcmp(node, argv[1]))
267 fprintf(stderr, "A node with name %s is already known!\n", argv[1]);
272 snprintf(filename, sizeof filename, "%s" SLASH "invitations", confbase);
273 if(mkdir(filename, 0700) && errno != EEXIST) {
274 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));
288 time_t deadline = time(NULL) - 604800; // 1 week in the past
290 while((ent = readdir(dir))) {
291 if(strlen(ent->d_name) != 24)
293 char invname[PATH_MAX];
295 snprintf(invname, sizeof 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));
310 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
315 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "ed25519_key.priv", confbase);
317 // Remove the key if there are no outstanding invitations.
321 // Create a new key if necessary.
322 FILE *f = fopen(filename, "r");
324 if(errno != ENOENT) {
325 fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
329 key = ecdsa_generate();
332 f = fopen(filename, "w");
334 fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
337 chmod(filename, 0600);
338 ecdsa_write_pem_private_key(key, f);
341 if(connect_tincd(false))
342 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
344 key = ecdsa_read_pem_private_key(f);
347 fprintf(stderr, "Could not read private key from %s\n", filename);
353 // Create a hash of the key.
355 char *fingerprint = ecdsa_get_base64_public_key(key);
356 sha512(fingerprint, strlen(fingerprint), hash);
357 b64encode_urlsafe(hash, hash, 18);
359 // Create a random cookie for this invitation.
361 randomize(cookie, 18);
363 // Create a filename that doesn't reveal the cookie itself
364 char buf[18 + strlen(fingerprint)];
366 memcpy(buf, cookie, 18);
367 memcpy(buf + 18, fingerprint, sizeof buf - 18);
368 sha512(buf, sizeof buf, cookiehash);
369 b64encode_urlsafe(cookiehash, cookiehash, 18);
371 b64encode_urlsafe(cookie, cookie, 18);
373 // Create a file containing the details of the invitation.
374 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "%s", confbase, cookiehash);
375 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
377 fprintf(stderr, "Could not create invitation file %s: %s\n", filename, strerror(errno));
380 f = fdopen(ifd, "w");
384 // Get the local address
385 char *address = get_my_hostname();
387 // Fill in the details.
388 fprintf(f, "Name = %s\n", argv[1]);
390 fprintf(f, "NetName = %s\n", netname);
391 fprintf(f, "ConnectTo = %s\n", myname);
393 // Copy Broadcast and Mode
394 FILE *tc = fopen(tinc_conf, "r");
397 while(fgets(buf, sizeof buf, tc)) {
398 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
399 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
401 // Make sure there is a newline character.
402 if(!strchr(buf, '\n'))
409 fprintf(f, "#---------------------------------------------------------------#\n");
410 fprintf(f, "Name = %s\n", myname);
412 char filename2[PATH_MAX];
413 snprintf(filename2, sizeof filename2, "%s" SLASH "hosts" SLASH "%s", confbase, myname);
417 // Create an URL from the local address, key hash and cookie
419 xasprintf(&url, "%s/%s%s", address, hash, cookie);
421 // Call the inviation-created script
423 xasprintf(&envp[0], "NAME=%s", myname);
424 xasprintf(&envp[1], "NETNAME=%s", netname);
425 xasprintf(&envp[2], "NODE=%s", argv[1]);
426 xasprintf(&envp[3], "INVITATION_FILE=%s", filename);
427 xasprintf(&envp[4], "INVITATION_URL=%s", url);
428 execute_script("invitation-created", envp);
429 for(int i = 0; i < 6 && envp[i]; i++)
440 static char cookie[18];
441 static sptps_t sptps;
443 static size_t datalen;
444 static bool success = false;
446 static char cookie[18], hash[18];
448 static char *get_line(const char **data) {
457 static char line[1024];
458 const char *end = strchr(*data, '\n');
459 size_t len = end ? end - *data : strlen(*data);
460 if(len >= sizeof line) {
461 fprintf(stderr, "Maximum line length exceeded!\n");
464 if(len && !isprint(**data))
467 memcpy(line, *data, len);
478 static char *get_value(const char *data, const char *var) {
479 char *line = get_line(&data);
483 char *sep = line + strcspn(line, " \t=");
484 char *val = sep + strspn(sep, " \t");
486 val += 1 + strspn(val + 1, " \t");
488 if(strcasecmp(line, var))
493 static char *grep(const char *data, const char *var) {
494 static char value[1024];
496 const char *p = data;
497 int varlen = strlen(var);
499 // Skip all lines not starting with var
500 while(strncasecmp(p, var, varlen) || !strchr(" \t=", p[varlen])) {
512 p += strspn(p, " \t");
514 p += 1 + strspn(p + 1, " \t");
516 const char *e = strchr(p, '\n');
520 if(e - p >= sizeof value) {
521 fprintf(stderr, "Maximum line length exceeded!\n");
525 memcpy(value, p, e - p);
530 static bool finalize_join(void) {
531 char *name = xstrdup(get_value(data, "Name"));
533 fprintf(stderr, "No Name found in invitation!\n");
537 if(!check_id(name)) {
538 fprintf(stderr, "Invalid Name found in invitation: %s!\n", name);
543 netname = grep(data, "NetName");
545 bool ask_netname = false;
546 char temp_netname[32];
559 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
560 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
562 if(!access(tinc_conf, F_OK)) {
563 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
567 // Generate a random netname, ask for a better one later.
569 snprintf(temp_netname, sizeof temp_netname, "join_%x", rand());
570 netname = temp_netname;
574 if(mkdir(confbase, 0777) && errno != EEXIST) {
575 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
579 if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
580 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
584 FILE *f = fopen(tinc_conf, "w");
586 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
590 fprintf(f, "Name = %s\n", name);
592 char filename[PATH_MAX];
593 snprintf(filename, sizeof filename, "%s" SLASH "%s", hosts_dir, name);
594 FILE *fh = fopen(filename, "w");
596 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
601 // Filter first chunk on approved keywords, split between tinc.conf and hosts/Name
602 // Other chunks go unfiltered to their respective host config files
603 const char *p = data;
606 while((l = get_line(&p))) {
611 // Split line into variable and value
612 int len = strcspn(l, "\t =");
614 value += strspn(value, "\t ");
617 value += strspn(value, "\t ");
622 if(!strcasecmp(l, "Name"))
623 if(strcmp(value, name))
627 else if(!strcasecmp(l, "NetName"))
630 // Check the list of known variables
633 for(i = 0; variables[i].name; i++) {
634 if(strcasecmp(l, variables[i].name))
640 // Ignore unknown and unsafe variables
642 fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
644 } else if(!(variables[i].type & VAR_SAFE)) {
645 fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
649 // Copy the safe variable to the right config file
650 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
655 while(l && !strcasecmp(l, "Name")) {
656 if(!check_id(value)) {
657 fprintf(stderr, "Invalid Name found in invitation.\n");
661 if(!strcmp(value, name)) {
662 fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
666 snprintf(filename, sizeof filename, "%s" SLASH "%s", hosts_dir, value);
667 f = fopen(filename, "w");
670 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
674 while((l = get_line(&p))) {
675 if(!strcmp(l, "#---------------------------------------------------------------#"))
677 int len = strcspn(l, "\t =");
678 if(len == 4 && !strncasecmp(l, "Name", 4)) {
680 value += strspn(value, "\t ");
683 value += strspn(value, "\t ");
696 // Generate our key and send a copy to the server
697 ecdsa_t *key = ecdsa_generate();
701 char *b64key = ecdsa_get_base64_public_key(key);
705 snprintf(filename, sizeof filename, "%s" SLASH "ed25519_key.priv", confbase);
706 f = fopenmask(filename, "w", 0600);
708 if(!ecdsa_write_pem_private_key(key, f)) {
709 fprintf(stderr, "Error writing private key!\n");
717 fprintf(fh, "Ed25519PublicKey = %s\n", b64key);
719 sptps_send_record(&sptps, 1, b64key, strlen(b64key));
723 #ifndef DISABLE_LEGACY
724 rsa_t *rsa = rsa_generate(2048, 0x1001);
725 snprintf(filename, sizeof filename, "%s" SLASH "rsa_key.priv", confbase);
726 f = fopenmask(filename, "w", 0600);
728 rsa_write_pem_private_key(rsa, f);
731 rsa_write_pem_public_key(rsa, fh);
740 if(ask_netname && tty) {
741 fprintf(stderr, "Enter a new netname: ");
742 if(!fgets(line, sizeof line, stdin)) {
743 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
746 if(!*line || *line == '\n')
749 line[strlen(line) - 1] = 0;
751 char newbase[PATH_MAX];
752 snprintf(newbase, sizeof newbase, CONFDIR SLASH "tinc" SLASH "%s", line);
753 if(rename(confbase, newbase)) {
754 fprintf(stderr, "Error trying to rename %s to %s: %s\n", confbase, newbase, strerror(errno));
762 fprintf(stderr, "Configuration stored in: %s\n", confbase);
768 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
770 int result = send(sock, data, len, 0);
771 if(result == -1 && errno == EINTR)
781 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
783 case SPTPS_HANDSHAKE:
784 return sptps_send_record(&sptps, 0, cookie, sizeof cookie);
787 data = xrealloc(data, datalen + len + 1);
788 memcpy(data + datalen, msg, len);
794 return finalize_join();
797 fprintf(stderr, "Invitation succesfully accepted.\n");
798 shutdown(sock, SHUT_RDWR);
809 int cmd_join(int argc, char *argv[]) {
815 fprintf(stderr, "Too many arguments!\n");
819 // Make sure confbase exists and is accessible.
820 if(!confbase_given && mkdir(confdir, 0755) && errno != EEXIST) {
821 fprintf(stderr, "Could not create directory %s: %s\n", confdir, strerror(errno));
825 if(mkdir(confbase, 0777) && errno != EEXIST) {
826 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
830 if(access(confbase, R_OK | W_OK | X_OK)) {
831 fprintf(stderr, "No permission to write in directory %s: %s\n", confbase, strerror(errno));
835 // If a netname or explicit configuration directory is specified, check for an existing tinc.conf.
836 if((netname || confbasegiven) && !access(tinc_conf, F_OK)) {
837 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
841 // Either read the invitation from the command line or from stdin.
845 invitation = argv[1];
848 fprintf(stderr, "Enter invitation URL: ");
850 if(!fgets(line, sizeof line, stdin)) {
851 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
857 // Parse the invitation URL.
860 char *slash = strchr(invitation, '/');
866 if(strlen(slash) != 48)
869 char *address = invitation;
871 if(*address == '[') {
873 char *bracket = strchr(address, ']');
877 if(bracket[1] == ':')
880 port = strchr(address, ':');
888 if(!b64decode(slash, hash, 24) || !b64decode(slash + 24, cookie, 24))
891 // Generate a throw-away key for the invitation.
892 ecdsa_t *key = ecdsa_generate();
896 char *b64key = ecdsa_get_base64_public_key(key);
898 // Connect to the tinc daemon mentioned in the URL.
899 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
903 struct addrinfo *aip = NULL;
914 sock = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
916 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
920 if(connect(sock, aip->ai_addr, aip->ai_addrlen)) {
921 char *addrstr, *portstr;
922 sockaddr2str((sockaddr_t *)aip->ai_addr, &addrstr, &portstr);
923 fprintf(stderr, "Could not connect to %s port %s: %s\n", addrstr, portstr, strerror(errno));
930 fprintf(stderr, "Connected to %s port %s...\n", address, port);
932 // Tell him we have an invitation, and give him our throw-away key.
933 int len = snprintf(line, sizeof line, "0 ?%s %d.%d\n", b64key, PROT_MAJOR, PROT_MINOR);
934 if(len <= 0 || len >= sizeof line)
937 if(!sendline(sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
938 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
943 char hisname[4096] = "";
944 int code, hismajor, hisminor = 0;
946 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) {
947 fprintf(stderr, "Cannot read greeting from peer\n");
952 // Check if the hash of the key he gave us matches the hash in the URL.
953 char *fingerprint = line + 2;
955 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
956 fprintf(stderr, "Could not create digest\n%s\n", line + 2);
959 if(memcmp(hishash, hash, 18)) {
960 fprintf(stderr, "Peer has an invalid key!\n%s\n", line + 2);
965 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
969 // Start an SPTPS session
970 if(!sptps_start(&sptps, NULL, true, false, key, hiskey, "tinc invitation", 15, invitation_send, invitation_receive))
973 // Feed rest of input buffer to SPTPS
974 if(!sptps_receive_data(&sptps, buffer, blen))
977 while((len = recv(sock, line, sizeof line, 0))) {
981 fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
987 int done = sptps_receive_data(&sptps, p, len);
1001 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
1008 fprintf(stderr, "Invalid invitation URL.\n");