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"
36 int addressfamily = AF_UNSPEC;
38 static void scan_for_hostname(const char *filename, char **hostname, char **port) {
39 if(!filename || (*hostname && *port))
42 FILE *f = fopen(filename, "r");
46 while(fgets(line, sizeof line, f)) {
50 p += strcspn(p, "\t =");
53 q = p + strspn(p, "\t ");
55 q += 1 + strspn(q + 1, "\t ");
57 p = q + strcspn(q, "\t ");
60 p += strspn(p, "\t ");
61 p[strcspn(p, "\t ")] = 0;
63 if(!*port && !strcasecmp(line, "Port")) {
65 } else if(!*hostname && !strcasecmp(line, "Address")) {
66 *hostname = xstrdup(q);
73 if(*hostname && *port)
80 char *get_my_hostname() {
81 char *hostname = NULL;
83 char *hostport = NULL;
84 char *name = get_my_name(false);
85 char *filename = NULL;
87 // Use first Address statement in own host config file
89 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
90 scan_for_hostname(filename, &hostname, &port);
91 scan_for_hostname(tinc_conf, &hostname, &port);
97 // If that doesn't work, guess externally visible hostname
98 fprintf(stderr, "Trying to discover externally visible hostname...\n");
99 struct addrinfo *ai = str2addrinfo("tinc-vpn.org", "80", SOCK_STREAM);
100 struct addrinfo *aip = ai;
101 static const char request[] = "GET http://tinc-vpn.org/host.cgi HTTP/1.0\r\n\r\n";
104 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
106 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
112 send(s, request, sizeof request - 1, 0);
113 int len = recv(s, line, sizeof line - 1, MSG_WAITALL);
116 if(line[len - 1] == '\n')
118 char *p = strrchr(line, '\n');
120 hostname = xstrdup(p + 1);
133 // Check that the hostname is reasonable
135 for(char *p = hostname; *p; p++) {
136 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
138 // If not, forget it.
147 fprintf(stderr, "Could not determine the external address or hostname. Please set Address manually.\n");
154 fprintf(stderr, "Please enter your host's external address or hostname");
156 fprintf(stderr, " [%s]", hostname);
157 fprintf(stderr, ": ");
159 if(!fgets(line, sizeof line, stdin)) {
160 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
172 for(char *p = line; *p; p++) {
173 if(isalnum(*p) || *p == '-' || *p == '.')
175 fprintf(stderr, "Invalid address or hostname.\n");
180 hostname = xstrdup(line);
184 FILE *f = fopen(filename, "a");
186 fprintf(f, "\nAddress = %s\n", hostname);
189 fprintf(stderr, "Could not append Address to %s: %s\n", filename, strerror(errno));
195 if(strchr(hostname, ':'))
196 xasprintf(&hostport, "[%s]:%s", hostname, port);
198 xasprintf(&hostport, "%s:%s", hostname, port);
210 static bool fcopy(FILE *out, const char *filename) {
211 FILE *in = fopen(filename, "r");
213 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
219 while((len = fread(buf, 1, sizeof buf, in)))
220 fwrite(buf, len, 1, out);
225 int cmd_invite(int argc, char *argv[]) {
227 fprintf(stderr, "Not enough arguments!\n");
231 // Check validity of the new node's name
232 if(!check_id(argv[1])) {
233 fprintf(stderr, "Invalid name for node.\n");
237 char *myname = get_my_name(true);
241 // Ensure no host configuration file with that name exists
242 char *filename = NULL;
243 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, argv[1]);
244 if(!access(filename, F_OK)) {
246 fprintf(stderr, "A host config file for %s already exists!\n", argv[1]);
251 // If a daemon is running, ensure no other nodes now about this name
253 if(connect_tincd(false)) {
254 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
256 while(recvline(fd, line, sizeof line)) {
259 if(sscanf(line, "%d %d %s", &code, &req, node) != 3)
261 if(!strcmp(node, argv[1]))
266 fprintf(stderr, "A node with name %s is already known!\n", argv[1]);
273 xasprintf(&filename, "%s" SLASH "invitations", confbase);
274 if(mkdir(filename, 0700) && errno != EEXIST) {
275 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));
291 time_t deadline = time(NULL) - 604800; // 1 week in the past
293 while((ent = readdir(dir))) {
294 if(strlen(ent->d_name) != 24)
298 xasprintf(&invname, "%s" SLASH "%s", filename, ent->d_name);
299 if(!stat(invname, &st)) {
300 if(deadline < st.st_mtime)
305 fprintf(stderr, "Could not stat %s: %s\n", invname, strerror(errno));
312 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
322 xasprintf(&filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", confbase);
324 // Remove the key if there are no outstanding invitations.
328 // Create a new key if necessary.
329 FILE *f = fopen(filename, "r");
331 if(errno != ENOENT) {
332 fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
337 key = ecdsa_generate();
342 f = fopen(filename, "w");
344 fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
348 chmod(filename, 0600);
349 ecdsa_write_pem_private_key(key, f);
352 if(connect_tincd(false))
353 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
355 key = ecdsa_read_pem_private_key(f);
358 fprintf(stderr, "Could not read private key from %s\n", filename);
365 // Create a hash of the key.
366 char *fingerprint = ecdsa_get_base64_public_key(key);
367 digest_t *digest = digest_open_by_name("sha256", 18);
370 digest_create(digest, fingerprint, strlen(fingerprint), hash);
371 b64encode_urlsafe(hash, hash, 18);
373 // Create a random cookie for this invitation.
375 randomize(cookie, 18);
377 // Create a filename that doesn't reveal the cookie itself
378 char buf[18 + strlen(fingerprint)];
380 memcpy(buf, cookie, 18);
381 memcpy(buf + 18, fingerprint, sizeof buf - 18);
382 digest_create(digest, buf, sizeof buf, cookiehash);
383 b64encode_urlsafe(cookiehash, cookiehash, 18);
385 b64encode_urlsafe(cookie, cookie, 18);
387 // Create a file containing the details of the invitation.
388 xasprintf(&filename, "%s" SLASH "invitations" SLASH "%s", confbase, cookiehash);
389 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
391 fprintf(stderr, "Could not create invitation file %s: %s\n", filename, strerror(errno));
395 f = fdopen(ifd, "w");
399 // Get the local address
400 char *address = get_my_hostname();
402 // Fill in the details.
403 fprintf(f, "Name = %s\n", argv[1]);
405 fprintf(f, "NetName = %s\n", netname);
406 fprintf(f, "ConnectTo = %s\n", myname);
408 // Copy Broadcast and Mode
409 FILE *tc = fopen(tinc_conf, "r");
412 while(fgets(buf, sizeof buf, tc)) {
413 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
414 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
416 // Make sure there is a newline character.
417 if(!strchr(buf, '\n'))
424 fprintf(f, "#---------------------------------------------------------------#\n");
425 fprintf(f, "Name = %s\n", myname);
428 xasprintf(&filename2, "%s" SLASH "hosts" SLASH "%s", confbase, myname);
433 // Create an URL from the local address, key hash and cookie
435 xasprintf(&url, "%s/%s%s", address, hash, cookie);
437 // Call the inviation-created script
439 xasprintf(&envp[0], "NAME=%s", myname);
440 xasprintf(&envp[1], "NETNAME=%s", netname);
441 xasprintf(&envp[2], "NODE=%s", argv[1]);
442 xasprintf(&envp[3], "INVITATION_FILE=%s", filename);
443 xasprintf(&envp[4], "INVITATION_URL=%s", url);
444 execute_script("invitation-created", envp);
445 for(int i = 0; i < 6 && envp[i]; i++)
457 static char cookie[18];
458 static sptps_t sptps;
460 static size_t datalen;
461 static bool success = false;
463 static char cookie[18], hash[18];
465 static char *get_line(const char **data) {
474 static char line[1024];
475 const char *end = strchr(*data, '\n');
476 size_t len = end ? end - *data : strlen(*data);
477 if(len >= sizeof line) {
478 fprintf(stderr, "Maximum line length exceeded!\n");
481 if(len && !isprint(**data))
484 memcpy(line, *data, len);
495 static char *get_value(const char *data, const char *var) {
496 char *line = get_line(&data);
500 char *sep = line + strcspn(line, " \t=");
501 char *val = sep + strspn(sep, " \t");
503 val += 1 + strspn(val + 1, " \t");
505 if(strcasecmp(line, var))
510 static char *grep(const char *data, const char *var) {
511 static char value[1024];
513 const char *p = data;
514 int varlen = strlen(var);
516 // Skip all lines not starting with var
517 while(strncasecmp(p, var, varlen) || !strchr(" \t=", p[varlen])) {
529 p += strspn(p, " \t");
531 p += 1 + strspn(p + 1, " \t");
533 const char *e = strchr(p, '\n');
537 if(e - p >= sizeof value) {
538 fprintf(stderr, "Maximum line length exceeded!\n");
542 memcpy(value, p, e - p);
547 static bool finalize_join(void) {
548 char *name = xstrdup(get_value(data, "Name"));
550 fprintf(stderr, "No Name found in invitation!\n");
554 if(!check_id(name)) {
555 fprintf(stderr, "Invalid Name found in invitation: %s!\n", name);
560 netname = grep(data, "NetName");
562 bool ask_netname = false;
563 char temp_netname[32];
576 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
577 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
579 if(!access(tinc_conf, F_OK)) {
580 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
584 // Generate a random netname, ask for a better one later.
586 snprintf(temp_netname, sizeof temp_netname, "join_%x", rand());
587 netname = temp_netname;
591 if(mkdir(confbase, 0777) && errno != EEXIST) {
592 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
596 if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
597 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
601 FILE *f = fopen(tinc_conf, "w");
603 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
607 fprintf(f, "Name = %s\n", name);
610 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
611 FILE *fh = fopen(filename, "w");
613 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
617 // Filter first chunk on approved keywords, split between tinc.conf and hosts/Name
618 // Other chunks go unfiltered to their respective host config files
619 const char *p = data;
622 while((l = get_line(&p))) {
627 // Split line into variable and value
628 int len = strcspn(l, "\t =");
630 value += strspn(value, "\t ");
633 value += strspn(value, "\t ");
638 if(!strcasecmp(l, "Name"))
639 if(strcmp(value, name))
643 else if(!strcasecmp(l, "NetName"))
646 // Check the list of known variables
649 for(i = 0; variables[i].name; i++) {
650 if(strcasecmp(l, variables[i].name))
656 // Ignore unknown and unsafe variables
658 fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
660 } else if(!(variables[i].type & VAR_SAFE)) {
661 fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
665 // Copy the safe variable to the right config file
666 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
672 while(l && !strcasecmp(l, "Name")) {
673 if(!check_id(value)) {
674 fprintf(stderr, "Invalid Name found in invitation.\n");
678 if(!strcmp(value, name)) {
679 fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
683 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, value);
684 f = fopen(filename, "w");
687 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
691 while((l = get_line(&p))) {
692 if(!strcmp(l, "#---------------------------------------------------------------#"))
694 int len = strcspn(l, "\t =");
695 if(len == 4 && !strncasecmp(l, "Name", 4)) {
697 value += strspn(value, "\t ");
700 value += strspn(value, "\t ");
714 // Generate our key and send a copy to the server
715 ecdsa_t *key = ecdsa_generate();
719 char *b64key = ecdsa_get_base64_public_key(key);
723 xasprintf(&filename, "%s" SLASH "ecdsa_key.priv", confbase);
724 f = fopenmask(filename, "w", 0600);
726 if(!ecdsa_write_pem_private_key(key, f)) {
727 fprintf(stderr, "Error writing private key!\n");
735 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
737 sptps_send_record(&sptps, 1, b64key, strlen(b64key));
741 rsa_t *rsa = rsa_generate(2048, 0x1001);
742 xasprintf(&filename, "%s" SLASH "rsa_key.priv", confbase);
743 f = fopenmask(filename, "w", 0600);
745 rsa_write_pem_private_key(rsa, f);
748 rsa_write_pem_public_key(rsa, fh);
757 if(ask_netname && tty) {
758 fprintf(stderr, "Enter a new netname: ");
759 if(!fgets(line, sizeof line, stdin)) {
760 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
763 if(!*line || *line == '\n')
766 line[strlen(line) - 1] = 0;
769 xasprintf(&newbase, CONFDIR SLASH "tinc" SLASH "%s", line);
770 if(rename(confbase, newbase)) {
771 fprintf(stderr, "Error trying to rename %s to %s: %s\n", confbase, newbase, strerror(errno));
781 fprintf(stderr, "Configuration stored in: %s\n", confbase);
787 static bool invitation_send(void *handle, uint8_t type, const char *data, size_t len) {
789 int result = send(sock, data, len, 0);
790 if(result == -1 && errno == EINTR)
800 static bool invitation_receive(void *handle, uint8_t type, const char *msg, uint16_t len) {
802 case SPTPS_HANDSHAKE:
803 return sptps_send_record(&sptps, 0, cookie, sizeof cookie);
806 data = xrealloc(data, datalen + len + 1);
807 memcpy(data + datalen, msg, len);
813 return finalize_join();
816 fprintf(stderr, "Invitation succesfully accepted.\n");
817 shutdown(sock, SHUT_RDWR);
828 int cmd_join(int argc, char *argv[]) {
834 fprintf(stderr, "Too many arguments!\n");
838 // Make sure confbase exists and is accessible.
839 if(!confbase_given && mkdir(confdir, 0755) && errno != EEXIST) {
840 fprintf(stderr, "Could not create directory %s: %s\n", confdir, strerror(errno));
844 if(mkdir(confbase, 0777) && errno != EEXIST) {
845 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
849 if(access(confbase, R_OK | W_OK | X_OK)) {
850 fprintf(stderr, "No permission to write in directory %s: %s\n", confbase, strerror(errno));
854 // If a netname or explicit configuration directory is specified, check for an existing tinc.conf.
855 if((netname || confbasegiven) && !access(tinc_conf, F_OK)) {
856 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
860 // Either read the invitation from the command line or from stdin.
864 invitation = argv[1];
867 fprintf(stderr, "Enter invitation URL: ");
869 if(!fgets(line, sizeof line, stdin)) {
870 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
876 // Parse the invitation URL.
879 char *slash = strchr(invitation, '/');
885 if(strlen(slash) != 48)
888 char *address = invitation;
890 if(*address == '[') {
892 char *bracket = strchr(address, ']');
896 if(bracket[1] == ':')
899 port = strchr(address, ':');
907 if(!b64decode(slash, hash, 18) || !b64decode(slash + 24, cookie, 18))
910 // Generate a throw-away key for the invitation.
911 ecdsa_t *key = ecdsa_generate();
915 char *b64key = ecdsa_get_base64_public_key(key);
917 // Connect to the tinc daemon mentioned in the URL.
918 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
922 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
924 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
928 if(connect(sock, ai->ai_addr, ai->ai_addrlen)) {
929 fprintf(stderr, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
934 fprintf(stderr, "Connected to %s port %s...\n", address, port);
936 // Tell him we have an invitation, and give him our throw-away key.
937 int len = snprintf(line, sizeof line, "0 ?%s %d.%d\n", b64key, PROT_MAJOR, PROT_MINOR);
938 if(len <= 0 || len >= sizeof line)
941 if(!sendline(sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
942 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
947 char hisname[4096] = "";
948 int code, hismajor, hisminor = 0;
950 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) {
951 fprintf(stderr, "Cannot read greeting from peer\n");
956 // Check if the hash of the key he gave us matches the hash in the URL.
957 char *fingerprint = line + 2;
958 digest_t *digest = digest_open_by_name("sha256", 18);
962 if(!digest_create(digest, fingerprint, strlen(fingerprint), hishash)) {
963 fprintf(stderr, "Could not create digest\n%s\n", line + 2);
966 if(memcmp(hishash, hash, 18)) {
967 fprintf(stderr, "Peer has an invalid key!\n%s\n", line + 2);
972 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
976 // Start an SPTPS session
977 if(!sptps_start(&sptps, NULL, true, false, key, hiskey, "tinc invitation", 15, invitation_send, invitation_receive))
980 // Feed rest of input buffer to SPTPS
981 if(!sptps_receive_data(&sptps, buffer, blen))
984 while((len = recv(sock, line, sizeof line, 0))) {
988 fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
992 if(!sptps_receive_data(&sptps, line, len))
1002 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
1009 fprintf(stderr, "Invalid invitation URL.\n");