2 invitation.c -- Create and accept invitations
3 Copyright (C) 2013 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"
35 int addressfamily = AF_UNSPEC;
37 char *get_my_hostname() {
38 char *hostname = NULL;
40 char *hostport = NULL;
41 char *name = get_my_name(false);
42 char *filename = NULL;
44 // Use first Address statement in own host config file
46 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
47 FILE *f = fopen(filename, "r");
49 while(fgets(line, sizeof line, f)) {
53 p += strcspn(p, "\t =");
56 q = p + strspn(p, "\t ");
58 q += 1 + strspn(q + 1, "\t ");
60 p = q + strcspn(q, "\t ");
63 p += strspn(p, "\t ");
64 p[strcspn(p, "\t ")] = 0;
65 if(!port && !strcasecmp(line, "Port")) {
69 if(strcasecmp(line, "Address"))
71 hostname = xstrdup(q);
85 // If that doesn't work, guess externally visible hostname
86 fprintf(stderr, "Trying to discover externally visible hostname...\n");
87 struct addrinfo *ai = str2addrinfo("tinc-vpn.org", "80", SOCK_STREAM);
88 struct addrinfo *aip = ai;
89 static const char request[] = "GET http://tinc-vpn.org/host.cgi HTTP/1.0\r\n\r\n";
92 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
94 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
100 send(s, request, sizeof request - 1, 0);
101 int len = recv(s, line, sizeof line - 1, MSG_WAITALL);
104 if(line[len - 1] == '\n')
106 char *p = strrchr(line, '\n');
108 hostname = xstrdup(p + 1);
121 // Check that the hostname is reasonable
123 for(char *p = hostname; *p; p++) {
124 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
126 // If not, forget it.
134 printf("Please enter your host's external address or hostname");
136 printf(" [%s]", hostname);
140 if(!fgets(line, sizeof line, stdin)) {
141 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
153 for(char *p = line; *p; p++) {
154 if(isalnum(*p) || *p == '-' || *p == '.')
156 fprintf(stderr, "Invalid address or hostname.\n");
161 hostname = xstrdup(line);
165 FILE *f = fopen(filename, "a");
167 fprintf(f, "\nAddress = %s\n", hostname);
170 fprintf(stderr, "Could not append Address to %s: %s\n", filename, strerror(errno));
176 if(strchr(hostname, ':'))
177 xasprintf(&hostport, "[%s]:%s", hostname, port);
179 xasprintf(&hostport, "%s:%s", hostname, port);
191 static bool fcopy(FILE *out, const char *filename) {
192 FILE *in = fopen(filename, "r");
194 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
200 while((len = fread(buf, 1, sizeof buf, in)))
201 fwrite(buf, len, 1, out);
206 int cmd_invite(int argc, char *argv[]) {
208 fprintf(stderr, "Not enough arguments!\n");
212 // Check validity of the new node's name
213 if(!check_id(argv[1])) {
214 fprintf(stderr, "Invalid name for node.\n");
218 char *myname = get_my_name(true);
222 // Ensure no host configuration file with that name exists
223 char *filename = NULL;
224 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, argv[1]);
225 if(!access(filename, F_OK)) {
227 fprintf(stderr, "A host config file for %s already exists!\n", argv[1]);
232 // If a daemon is running, ensure no other nodes now about this name
234 if(connect_tincd(false)) {
235 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
237 while(recvline(fd, line, sizeof line)) {
240 if(sscanf(line, "%d %d %s", &code, &req, node) != 3)
242 if(!strcmp(node, argv[1]))
247 fprintf(stderr, "A node with name %s is already known!\n", argv[1]);
254 xasprintf(&filename, "%s" SLASH "invitations", confbase);
255 if(mkdir(filename, 0700) && errno != EEXIST) {
256 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
261 // Count the number of valid invitations, clean up old ones
262 DIR *dir = opendir(filename);
264 fprintf(stderr, "Could not read directory %s: %s\n", filename, strerror(errno));
272 time_t deadline = time(NULL) - 604800; // 1 week in the past
274 while((ent = readdir(dir))) {
275 if(strlen(ent->d_name) != 24)
279 xasprintf(&invname, "%s" SLASH "%s", filename, ent->d_name);
280 if(!stat(invname, &st)) {
281 if(deadline < st.st_mtime)
286 fprintf(stderr, "Could not stat %s: %s\n", invname, strerror(errno));
293 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
303 xasprintf(&filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", confbase);
305 // Remove the key if there are no outstanding invitations.
309 // Create a new key if necessary.
310 FILE *f = fopen(filename, "r");
312 if(errno != ENOENT) {
313 fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
318 key = ecdsa_generate();
323 f = fopen(filename, "w");
325 fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
329 chmod(filename, 0600);
330 ecdsa_write_pem_private_key(key, f);
332 key = ecdsa_read_pem_private_key(f);
334 fprintf(stderr, "Could not read private key from %s\n", filename);
341 // Create a hash of the key.
342 char *fingerprint = ecdsa_get_base64_public_key(key);
343 digest_t *digest = digest_open_by_name("sha256", 18);
346 digest_create(digest, fingerprint, strlen(fingerprint), hash);
347 b64encode_urlsafe(hash, hash, 18);
349 // Create a random cookie for this invitation.
351 randomize(cookie, 18);
353 // Create a filename that doesn't reveal the cookie itself
354 char buf[18 + strlen(fingerprint)];
356 memcpy(buf, cookie, 18);
357 memcpy(buf + 18, fingerprint, sizeof buf - 18);
358 digest_create(digest, buf, sizeof buf, cookiehash);
359 b64encode_urlsafe(cookiehash, cookiehash, 18);
361 b64encode_urlsafe(cookie, cookie, 18);
363 // Create a file containing the details of the invitation.
364 xasprintf(&filename, "%s" SLASH "invitations" SLASH "%s", confbase, cookiehash);
365 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
367 fprintf(stderr, "Could not create invitation file %s: %s\n", filename, strerror(errno));
372 f = fdopen(ifd, "w");
376 // Get the local address
377 char *address = get_my_hostname();
379 // Fill in the details.
380 fprintf(f, "Name = %s\n", argv[1]);
382 fprintf(f, "NetName = %s\n", netname);
383 fprintf(f, "ConnectTo = %s\n", myname);
384 // TODO: copy Broadcast and Mode
385 fprintf(f, "#---------------------------------------------------------------#\n");
386 fprintf(f, "Name = %s\n", myname);
388 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, myname);
392 // Create an URL from the local address, key hash and cookie
393 printf("%s/%s%s\n", address, hash, cookie);
401 static char cookie[18];
402 static sptps_t sptps;
404 static size_t datalen;
405 static bool success = false;
407 static char cookie[18], hash[18];
409 static char *get_line(const char **data) {
418 static char line[1024];
419 const char *end = strchr(*data, '\n');
420 size_t len = end ? end - *data : strlen(*data);
421 if(len >= sizeof line) {
422 fprintf(stderr, "Maximum line length exceeded!\n");
425 if(len && !isprint(**data))
428 memcpy(line, *data, len);
439 static char *get_value(const char *data, const char *var) {
440 char *line = get_line(&data);
444 char *sep = line + strcspn(line, " \t=");
445 char *val = sep + strspn(sep, " \t");
447 val += 1 + strspn(val + 1, " \t");
449 if(strcasecmp(line, var))
454 static char *grep(const char *data, const char *var) {
455 static char value[1024];
457 const char *p = data;
458 int varlen = strlen(var);
460 // Skip all lines not starting with var
461 while(strncasecmp(p, var, varlen) || !strchr(" \t=", p[varlen])) {
473 p += strspn(p, " \t");
475 p += 1 + strspn(p + 1, " \t");
477 const char *e = strchr(p, '\n');
481 if(e - p >= sizeof value) {
482 fprintf(stderr, "Maximum line length exceeded!\n");
486 memcpy(value, p, e - p);
491 static bool finalize_join(void) {
492 char *name = xstrdup(get_value(data, "Name"));
494 fprintf(stderr, "No Name found in invitation!\n");
498 if(!check_id(name)) {
499 fprintf(stderr, "Invalid Name found in invitation: %s!\n", name);
504 netname = grep(data, "NetName");
506 bool ask_netname = false;
507 char temp_netname[32];
520 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
521 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
523 if(!access(tinc_conf, F_OK)) {
524 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
525 if(!tty || confbasegiven)
528 // Generate a random netname, ask for a better one later.
530 snprintf(temp_netname, sizeof temp_netname, "join_%x", rand());
531 netname = temp_netname;
535 if(mkdir(confbase, 0777) && errno != EEXIST) {
536 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
540 if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
541 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
545 FILE *f = fopen(tinc_conf, "w");
547 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
551 fprintf(f, "Name = %s\n", name);
554 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
555 FILE *fh = fopen(filename, "w");
557 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
561 // Filter first chunk on approved keywords, split between tinc.conf and hosts/Name
562 // Other chunks go unfiltered to their respective host config files
563 const char *p = data;
566 while((l = get_line(&p))) {
571 // Split line into variable and value
572 int len = strcspn(l, "\t =");
574 value += strspn(value, "\t ");
577 value += strspn(value, "\t ");
582 if(!strcasecmp(l, "Name"))
583 if(strcmp(value, name))
587 else if(!strcasecmp(l, "NetName"))
590 // Check the list of known variables
593 for(i = 0; variables[i].name; i++) {
594 if(strcasecmp(l, variables[i].name))
600 // Ignore unknown and unsafe variables
602 fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
604 } else if(!(variables[i].type & VAR_SAFE)) {
605 fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
609 // Copy the safe variable to the right config file
610 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
616 while(l && !strcasecmp(l, "Name")) {
617 if(!check_id(value)) {
618 fprintf(stderr, "Invalid Name found in invitation.\n");
622 if(!strcmp(value, name)) {
623 fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
627 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, value);
628 f = fopen(filename, "w");
631 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
635 while((l = get_line(&p))) {
636 if(!strcmp(l, "#---------------------------------------------------------------#"))
638 int len = strcspn(l, "\t =");
639 if(len == 4 && !strncasecmp(l, "Name", 4)) {
641 value += strspn(value, "\t ");
644 value += strspn(value, "\t ");
658 // Generate our key and send a copy to the server
659 ecdsa_t *key = ecdsa_generate();
663 char *b64key = ecdsa_get_base64_public_key(key);
667 xasprintf(&filename, "%s" SLASH "ecdsa_key.priv", confbase);
668 f = fopenmask(filename, "w", 0600);
670 if(!ecdsa_write_pem_private_key(key, f)) {
671 fprintf(stderr, "Error writing private key!\n");
679 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
681 sptps_send_record(&sptps, 1, b64key, strlen(b64key));
685 rsa_t *rsa = rsa_generate(2048, 0x1001);
686 xasprintf(&filename, "%s" SLASH "rsa_key.priv", confbase);
687 f = fopenmask(filename, "w", 0600);
689 rsa_write_pem_private_key(rsa, f);
692 rsa_write_pem_public_key(rsa, fh);
702 fprintf(stderr, "Enter a new netname: ");
703 if(!fgets(line, sizeof line, stdin)) {
704 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
707 if(!*line || *line == '\n')
710 line[strlen(line) - 1] = 0;
713 xasprintf(&newbase, CONFDIR SLASH "tinc" SLASH "%s", line);
714 if(rename(confbase, newbase)) {
715 fprintf(stderr, "Error trying to rename %s to %s: %s\n", confbase, newbase, strerror(errno));
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(strcmp(confdir, confbase) && mkdir(confdir, 0755) && errno != EEXIST) {
782 fprintf(stderr, "Could not create directory %s: %s\n", confdir, strerror(errno));
786 if(mkdir(confbase, 0777) && errno != EEXIST) {
787 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
791 if(access(confbase, R_OK | W_OK | X_OK)) {
792 fprintf(stderr, "No permission to write in directory %s: %s\n", confbase, strerror(errno));
796 // If a netname or explicit configuration directory is specified, check for an existing tinc.conf.
797 if((netname || confbasegiven) && !access(tinc_conf, F_OK)) {
798 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
802 // Either read the invitation from the command line or from stdin.
806 invitation = argv[1];
809 printf("Enter invitation URL: ");
813 if(!fgets(line, sizeof line, stdin)) {
814 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
820 // Parse the invitation URL.
823 char *slash = strchr(invitation, '/');
829 if(strlen(slash) != 48)
832 char *address = invitation;
834 if(*address == '[') {
836 char *bracket = strchr(address, ']');
840 if(bracket[1] == ':')
843 port = strchr(address, ':');
851 if(!b64decode(slash, hash, 18) || !b64decode(slash + 24, cookie, 18))
854 // Generate a throw-away key for the invitation.
855 ecdsa_t *key = ecdsa_generate();
859 char *b64key = ecdsa_get_base64_public_key(key);
861 // Connect to the tinc daemon mentioned in the URL.
862 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
866 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
868 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
872 if(connect(sock, ai->ai_addr, ai->ai_addrlen)) {
873 fprintf(stderr, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
878 fprintf(stderr, "Connected to %s port %s...\n", address, port);
880 // Tell him we have an invitation, and give him our throw-away key.
881 int len = snprintf(line, sizeof line, "0 ?%s %d.%d\n", b64key, PROT_MAJOR, PROT_MINOR);
882 if(len <= 0 || len >= sizeof line)
885 if(!sendline(sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
886 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
891 char hisname[4096] = "";
892 int code, hismajor, hisminor = 0;
894 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) {
895 fprintf(stderr, "Cannot read greeting from peer\n");
900 // Check if the hash of the key he gave us matches the hash in the URL.
901 char *fingerprint = line + 2;
902 digest_t *digest = digest_open_by_name("sha256", 18);
906 if(!digest_create(digest, fingerprint, strlen(fingerprint), hishash)) {
907 fprintf(stderr, "Could not create digest\n%s\n", line + 2);
910 if(memcmp(hishash, hash, 18)) {
911 fprintf(stderr, "Peer has an invalid key!\n%s\n", line + 2);
916 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
920 // Start an SPTPS session
921 if(!sptps_start(&sptps, NULL, true, false, key, hiskey, "tinc invitation", 15, invitation_send, invitation_receive))
924 // Feed rest of input buffer to SPTPS
925 if(!sptps_receive_data(&sptps, buffer, blen))
928 while((len = recv(sock, line, sizeof line, 0))) {
932 fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
936 if(!sptps_receive_data(&sptps, line, len))
946 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
953 fprintf(stderr, "Invalid invitation URL.\n");