2 invitation.c -- Create and accept invitations
3 Copyright (C) 2013-2017 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"
27 #include "invitation.h"
38 #include "ed25519/sha512.h"
40 int addressfamily = AF_UNSPEC;
42 static void scan_for_hostname(const char *filename, char **hostname, char **port) {
43 if(!filename || (*hostname && *port))
46 FILE *f = fopen(filename, "r");
50 while(fgets(line, sizeof(line), f)) {
54 p += strcspn(p, "\t =");
57 q = p + strspn(p, "\t ");
59 q += 1 + strspn(q + 1, "\t ");
61 p = q + strcspn(q, "\t ");
64 p += strspn(p, "\t ");
65 p[strcspn(p, "\t ")] = 0;
67 if(!*port && !strcasecmp(line, "Port")) {
69 } else if(!*hostname && !strcasecmp(line, "Address")) {
70 *hostname = xstrdup(q);
77 if(*hostname && *port)
84 char *get_my_hostname() {
85 char *hostname = NULL;
87 char *hostport = NULL;
88 char *name = get_my_name(false);
89 char filename[PATH_MAX] = {0};
91 // Use first Address statement in own host config file
93 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", confbase, name);
94 scan_for_hostname(filename, &hostname, &port);
95 scan_for_hostname(tinc_conf, &hostname, &port);
101 // If that doesn't work, guess externally visible hostname
102 fprintf(stderr, "Trying to discover externally visible hostname...\n");
103 struct addrinfo *ai = str2addrinfo("tinc-vpn.org", "80", SOCK_STREAM);
104 struct addrinfo *aip = ai;
105 static const char request[] = "GET http://tinc-vpn.org/host.cgi HTTP/1.0\r\n\r\n";
108 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
110 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
116 send(s, request, sizeof(request) - 1, 0);
117 int len = recv(s, line, sizeof(line) - 1, MSG_WAITALL);
120 if(line[len - 1] == '\n')
122 char *p = strrchr(line, '\n');
124 hostname = xstrdup(p + 1);
137 // Check that the hostname is reasonable
139 for(char *p = hostname; *p; p++) {
140 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
142 // If not, forget it.
151 fprintf(stderr, "Could not determine the external address or hostname. Please set Address manually.\n");
158 fprintf(stderr, "Please enter your host's external address or hostname");
160 fprintf(stderr, " [%s]", hostname);
161 fprintf(stderr, ": ");
163 if(!fgets(line, sizeof(line), stdin)) {
164 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
176 for(char *p = line; *p; p++) {
177 if(isalnum(*p) || *p == '-' || *p == '.')
179 fprintf(stderr, "Invalid address or hostname.\n");
184 hostname = xstrdup(line);
188 FILE *f = fopen(filename, "a");
190 fprintf(f, "\nAddress = %s\n", hostname);
193 fprintf(stderr, "Could not append Address to %s: %s\n", filename, strerror(errno));
199 if(strchr(hostname, ':'))
200 xasprintf(&hostport, "[%s]:%s", hostname, port);
202 xasprintf(&hostport, "%s:%s", hostname, port);
204 if(strchr(hostname, ':'))
205 xasprintf(&hostport, "[%s]", hostname);
207 hostport = xstrdup(hostname);
215 static bool fcopy(FILE *out, const char *filename) {
216 FILE *in = fopen(filename, "r");
218 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
224 while((len = fread(buf, 1, sizeof(buf), in)))
225 fwrite(buf, len, 1, out);
230 int cmd_invite(int argc, char *argv[]) {
232 fprintf(stderr, "Not enough arguments!\n");
236 // Check validity of the new node's name
237 if(!check_id(argv[1])) {
238 fprintf(stderr, "Invalid name for node.\n");
242 myname = get_my_name(true);
246 // Ensure no host configuration file with that name exists
247 char filename[PATH_MAX];
248 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", confbase, argv[1]);
249 if(!access(filename, F_OK)) {
250 fprintf(stderr, "A host config file for %s already exists!\n", argv[1]);
254 // If a daemon is running, ensure no other nodes know about this name
255 if(connect_tincd(false)) {
257 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
259 while(recvline(fd, line, sizeof(line))) {
262 if(sscanf(line, "%d %d %4095s", &code, &req, node) != 3)
264 if(!strcmp(node, argv[1]))
269 fprintf(stderr, "A node with name %s is already known!\n", argv[1]);
274 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", confbase);
275 if(mkdir(filename, 0700) && errno != EEXIST) {
276 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
280 // Count the number of valid invitations, clean up old ones
281 DIR *dir = opendir(filename);
283 fprintf(stderr, "Could not read directory %s: %s\n", filename, strerror(errno));
290 time_t deadline = time(NULL) - 604800; // 1 week in the past
292 while((ent = readdir(dir))) {
293 if(strlen(ent->d_name) != 24)
295 char invname[PATH_MAX];
297 snprintf(invname, sizeof(invname), "%s" SLASH "%s", filename, ent->d_name);
298 if(!stat(invname, &st)) {
299 if(deadline < st.st_mtime)
304 fprintf(stderr, "Could not stat %s: %s\n", invname, strerror(errno));
312 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
317 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "ed25519_key.priv", confbase);
319 // Remove the key if there are no outstanding invitations.
323 // Create a new key if necessary.
324 FILE *f = fopen(filename, "r");
326 if(errno != ENOENT) {
327 fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
331 key = ecdsa_generate();
334 f = fopen(filename, "w");
336 fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
339 chmod(filename, 0600);
340 if(!ecdsa_write_pem_private_key(key, f)) {
341 fprintf(stderr, "Could not write ECDSA private key\n");
347 if(connect_tincd(false))
348 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
350 key = ecdsa_read_pem_private_key(f);
353 fprintf(stderr, "Could not read private key from %s\n", filename);
359 // Create a hash of the key.
361 char *fingerprint = ecdsa_get_base64_public_key(key);
362 sha512(fingerprint, strlen(fingerprint), hash);
363 b64encode_urlsafe(hash, hash, 18);
365 // Create a random cookie for this invitation.
367 randomize(cookie, 18);
369 // Create a filename that doesn't reveal the cookie itself
370 char buf[18 + strlen(fingerprint)];
372 memcpy(buf, cookie, 18);
373 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
374 sha512(buf, sizeof(buf), cookiehash);
375 b64encode_urlsafe(cookiehash, cookiehash, 18);
377 b64encode_urlsafe(cookie, cookie, 18);
379 // Create a file containing the details of the invitation.
380 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", confbase, cookiehash);
381 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
383 fprintf(stderr, "Could not create invitation file %s: %s\n", filename, strerror(errno));
386 f = fdopen(ifd, "w");
390 // Get the local address
391 char *address = get_my_hostname();
393 // Fill in the details.
394 fprintf(f, "Name = %s\n", argv[1]);
395 if(check_netname(netname, true))
396 fprintf(f, "NetName = %s\n", netname);
397 fprintf(f, "ConnectTo = %s\n", myname);
399 // Copy Broadcast and Mode
400 FILE *tc = fopen(tinc_conf, "r");
403 while(fgets(buf, sizeof(buf), tc)) {
404 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
405 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
407 // Make sure there is a newline character.
408 if(!strchr(buf, '\n'))
415 fprintf(f, "#---------------------------------------------------------------#\n");
416 fprintf(f, "Name = %s\n", myname);
418 char filename2[PATH_MAX];
419 snprintf(filename2, sizeof(filename2), "%s" SLASH "hosts" SLASH "%s", confbase, myname);
423 // Create an URL from the local address, key hash and cookie
425 xasprintf(&url, "%s/%s%s", address, hash, cookie);
427 // Call the inviation-created script
429 environment_init(&env);
430 environment_add(&env, "NODE=%s", argv[1]);
431 environment_add(&env, "INVITATION_FILE=%s", filename);
432 environment_add(&env, "INVITATION_URL=%s", url);
433 execute_script("invitation-created", &env);
434 environment_exit(&env);
444 static char cookie[18];
445 static sptps_t sptps;
447 static size_t datalen;
448 static bool success = false;
450 static char cookie[18], hash[18];
452 static char *get_line(const char **data) {
461 static char line[1024];
462 const char *end = strchr(*data, '\n');
463 size_t len = end ? end - *data : strlen(*data);
464 if(len >= sizeof(line)) {
465 fprintf(stderr, "Maximum line length exceeded!\n");
468 if(len && !isprint(**data))
471 memcpy(line, *data, len);
482 static char *get_value(const char *data, const char *var) {
483 char *line = get_line(&data);
487 char *sep = line + strcspn(line, " \t=");
488 char *val = sep + strspn(sep, " \t");
490 val += 1 + strspn(val + 1, " \t");
492 if(strcasecmp(line, var))
497 static char *grep(const char *data, const char *var) {
498 static char value[1024];
500 const char *p = data;
501 int varlen = strlen(var);
503 // Skip all lines not starting with var
504 while(strncasecmp(p, var, varlen) || !strchr(" \t=", p[varlen])) {
516 p += strspn(p, " \t");
518 p += 1 + strspn(p + 1, " \t");
520 const char *e = strchr(p, '\n');
524 if(e - p >= sizeof(value)) {
525 fprintf(stderr, "Maximum line length exceeded!\n");
529 memcpy(value, p, e - p);
534 static bool finalize_join(void) {
535 char *name = xstrdup(get_value(data, "Name"));
537 fprintf(stderr, "No Name found in invitation!\n");
541 if(!check_id(name)) {
542 fprintf(stderr, "Invalid Name found in invitation!\n");
547 netname = grep(data, "NetName");
548 if(netname && !check_netname(netname, true)) {
549 fprintf(stderr, "Unsafe NetName found in invitation!\n");
554 bool ask_netname = false;
555 char temp_netname[32];
568 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
569 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
571 if(!access(tinc_conf, F_OK)) {
572 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
576 // Generate a random netname, ask for a better one later.
578 snprintf(temp_netname, sizeof(temp_netname), "join_%x", rand());
579 netname = temp_netname;
583 if(mkdir(confbase, 0777) && errno != EEXIST) {
584 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
588 if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
589 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
593 FILE *f = fopen(tinc_conf, "w");
595 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
599 fprintf(f, "Name = %s\n", name);
601 char filename[PATH_MAX];
602 snprintf(filename, sizeof(filename), "%s" SLASH "%s", hosts_dir, name);
603 FILE *fh = fopen(filename, "w");
605 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
610 snprintf(filename, sizeof(filename), "%s" SLASH "invitation-data", confbase);
611 FILE *finv = fopen(filename, "w");
612 if(!finv || fwrite(data, datalen, 1, finv) != 1) {
613 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
621 snprintf(filename, sizeof(filename), "%s" SLASH "tinc-up.invitation", confbase);
622 FILE *fup = fopen(filename, "w");
624 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
630 ifconfig_header(fup);
632 // Filter first chunk on approved keywords, split between tinc.conf and hosts/Name
633 // Generate a tinc-up script from Ifconfig and Route keywords.
634 // Other chunks go unfiltered to their respective host config files
635 const char *p = data;
638 while((l = get_line(&p))) {
643 // Split line into variable and value
644 int len = strcspn(l, "\t =");
646 value += strspn(value, "\t ");
649 value += strspn(value, "\t ");
654 if(!strcasecmp(l, "Name"))
655 if(strcmp(value, name))
659 else if(!strcasecmp(l, "NetName"))
662 // Check the list of known variables
665 for(i = 0; variables[i].name; i++) {
666 if(strcasecmp(l, variables[i].name))
672 // Handle Ifconfig and Route statements
674 if(!strcasecmp(l, "Ifconfig")) {
675 if(!strcasecmp(value, "dhcp"))
677 else if(!strcasecmp(value, "dhcp6"))
679 else if(!strcasecmp(value, "slaac"))
682 ifconfig_address(fup, value);
684 } else if(!strcasecmp(l, "Route")) {
685 ifconfig_route(fup, value);
690 // Ignore unknown and unsafe variables
692 fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
694 } else if(!(variables[i].type & VAR_SAFE)) {
695 fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
699 // Copy the safe variable to the right config file
700 fprintf((variables[i].type & VAR_HOST) ? fh : f, "%s = %s\n", l, value);
704 bool valid_tinc_up = ifconfig_footer(fup);
707 while(l && !strcasecmp(l, "Name")) {
708 if(!check_id(value)) {
709 fprintf(stderr, "Invalid Name found in invitation.\n");
713 if(!strcmp(value, name)) {
714 fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
718 snprintf(filename, sizeof(filename), "%s" SLASH "%s", hosts_dir, value);
719 f = fopen(filename, "w");
722 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
726 while((l = get_line(&p))) {
727 if(!strcmp(l, "#---------------------------------------------------------------#"))
729 int len = strcspn(l, "\t =");
730 if(len == 4 && !strncasecmp(l, "Name", 4)) {
732 value += strspn(value, "\t ");
735 value += strspn(value, "\t ");
748 // Generate our key and send a copy to the server
749 ecdsa_t *key = ecdsa_generate();
753 char *b64key = ecdsa_get_base64_public_key(key);
757 snprintf(filename, sizeof(filename), "%s" SLASH "ed25519_key.priv", confbase);
758 f = fopenmask(filename, "w", 0600);
762 if(!ecdsa_write_pem_private_key(key, f)) {
763 fprintf(stderr, "Error writing private key!\n");
771 fprintf(fh, "Ed25519PublicKey = %s\n", b64key);
773 sptps_send_record(&sptps, 1, b64key, strlen(b64key));
777 #ifndef DISABLE_LEGACY
778 rsa_t *rsa = rsa_generate(2048, 0x1001);
779 snprintf(filename, sizeof(filename), "%s" SLASH "rsa_key.priv", confbase);
780 f = fopenmask(filename, "w", 0600);
782 if(!f || !rsa_write_pem_private_key(rsa, f)) {
783 fprintf(stderr, "Could not write private RSA key\n");
784 } else if(!rsa_write_pem_public_key(rsa, fh)) {
785 fprintf(stderr, "Could not write public RSA key\n");
798 if(ask_netname && tty) {
799 fprintf(stderr, "Enter a new netname: ");
800 if(!fgets(line, sizeof(line), stdin)) {
801 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
804 if(!*line || *line == '\n')
807 line[strlen(line) - 1] = 0;
809 char newbase[PATH_MAX];
810 snprintf(newbase, sizeof(newbase), CONFDIR SLASH "tinc" SLASH "%s", line);
811 if(rename(confbase, newbase)) {
812 fprintf(stderr, "Error trying to rename %s to %s: %s\n", confbase, newbase, strerror(errno));
820 char filename2[PATH_MAX];
821 snprintf(filename, sizeof(filename), "%s" SLASH "tinc-up.invitation", confbase);
822 snprintf(filename2, sizeof(filename2), "%s" SLASH "tinc-up", confbase);
826 FILE *fup = fopen(filename, "r");
828 fprintf(stderr, "\nPlease review the following tinc-up script:\n\n");
831 while(fgets(buf, sizeof(buf), fup))
837 fprintf(stderr, "\nDo you want to use this script [y]es/[n]o/[e]dit? ");
838 response = tolower(getchar());
839 } while(!strchr("yne", response));
841 fprintf(stderr, "\n");
843 if(response == 'e') {
846 xasprintf(&command, "\"%s\" \"%s\"", getenv("VISUAL") ?: getenv("EDITOR") ?: "vi", filename);
848 xasprintf(&command, "edit \"%s\"", filename);
857 if(response == 'y') {
858 rename(filename, filename2);
859 chmod(filename2, 0755);
860 fprintf(stderr, "tinc-up enabled.\n");
862 fprintf(stderr, "tinc-up has been left disabled.\n");
866 fprintf(stderr, "A tinc-up script was generated, but has been left disabled.\n");
869 // A placeholder was generated.
870 rename(filename, filename2);
871 chmod(filename2, 0755);
874 fprintf(stderr, "Configuration stored in: %s\n", confbase);
880 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
882 int result = send(sock, data, len, 0);
883 if(result == -1 && errno == EINTR)
893 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
895 case SPTPS_HANDSHAKE:
896 return sptps_send_record(&sptps, 0, cookie, sizeof(cookie));
899 data = xrealloc(data, datalen + len + 1);
900 memcpy(data + datalen, msg, len);
906 return finalize_join();
909 fprintf(stderr, "Invitation succesfully accepted.\n");
910 shutdown(sock, SHUT_RDWR);
921 int cmd_join(int argc, char *argv[]) {
927 fprintf(stderr, "Too many arguments!\n");
931 // Make sure confbase exists and is accessible.
932 if(!confbase_given && mkdir(confdir, 0755) && errno != EEXIST) {
933 fprintf(stderr, "Could not create directory %s: %s\n", confdir, strerror(errno));
937 if(mkdir(confbase, 0777) && errno != EEXIST) {
938 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
942 if(access(confbase, R_OK | W_OK | X_OK)) {
943 fprintf(stderr, "No permission to write in directory %s: %s\n", confbase, strerror(errno));
947 // If a netname or explicit configuration directory is specified, check for an existing tinc.conf.
948 if((netname || confbasegiven) && !access(tinc_conf, F_OK)) {
949 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
953 // Either read the invitation from the command line or from stdin.
957 invitation = argv[1];
960 fprintf(stderr, "Enter invitation URL: ");
962 if(!fgets(line, sizeof(line), stdin)) {
963 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
969 // Parse the invitation URL.
972 char *slash = strchr(invitation, '/');
978 if(strlen(slash) != 48)
981 char *address = invitation;
983 if(*address == '[') {
985 char *bracket = strchr(address, ']');
989 if(bracket[1] == ':')
992 port = strchr(address, ':');
1000 if(!b64decode(slash, hash, 24) || !b64decode(slash + 24, cookie, 24))
1003 // Generate a throw-away key for the invitation.
1004 ecdsa_t *key = ecdsa_generate();
1008 char *b64key = ecdsa_get_base64_public_key(key);
1010 // Connect to the tinc daemon mentioned in the URL.
1011 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1015 struct addrinfo *aip = NULL;
1026 sock = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
1028 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
1032 if(connect(sock, aip->ai_addr, aip->ai_addrlen)) {
1033 char *addrstr, *portstr;
1034 sockaddr2str((sockaddr_t *)aip->ai_addr, &addrstr, &portstr);
1035 fprintf(stderr, "Could not connect to %s port %s: %s\n", addrstr, portstr, strerror(errno));
1042 fprintf(stderr, "Connected to %s port %s...\n", address, port);
1044 // Tell him we have an invitation, and give him our throw-away key.
1045 int len = snprintf(line, sizeof(line), "0 ?%s %d.%d\n", b64key, PROT_MAJOR, PROT_MINOR);
1046 if(len <= 0 || len >= sizeof(line))
1049 if(!sendline(sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1050 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1055 char hisname[4096] = "";
1056 int code, hismajor, hisminor = 0;
1058 if(!recvline(sock, line, sizeof(line)) || sscanf(line, "%d %4095s %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) {
1059 fprintf(stderr, "Cannot read greeting from peer\n");
1064 // Check if the hash of the key he gave us matches the hash in the URL.
1065 char *fingerprint = line + 2;
1067 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1068 fprintf(stderr, "Could not create digest\n%s\n", line + 2);
1071 if(memcmp(hishash, hash, 18)) {
1072 fprintf(stderr, "Peer has an invalid key!\n%s\n", line + 2);
1077 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1081 // Start an SPTPS session
1082 if(!sptps_start(&sptps, NULL, true, false, key, hiskey, "tinc invitation", 15, invitation_send, invitation_receive))
1085 // Feed rest of input buffer to SPTPS
1086 if(!sptps_receive_data(&sptps, buffer, blen))
1089 while((len = recv(sock, line, sizeof(line), 0))) {
1093 fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1099 int done = sptps_receive_data(&sptps, p, len);
1113 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
1120 fprintf(stderr, "Invalid invitation URL.\n");