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("ifconfig.me", "80", SOCK_STREAM);
88 static const char request[] = "GET /host HTTP/1.0\r\n\r\n";
90 int s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
92 if(connect(s, ai->ai_addr, ai->ai_addrlen)) {
98 send(s, request, sizeof request - 1, 0);
99 int len = recv(s, line, sizeof line - 1, MSG_WAITALL);
102 if(line[len - 1] == '\n')
104 char *p = strrchr(line, '\n');
106 hostname = xstrdup(p + 1);
113 // Check that the hostname is reasonable
115 for(char *p = hostname; *p; p++) {
116 if(isalnum(*p) || *p == '-' || *p == '.')
118 // If not, forget it.
126 printf("Please enter your host's external address or hostname");
128 printf(" [%s]", hostname);
132 if(!fgets(line, sizeof line, stdin)) {
133 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
145 for(char *p = line; *p; p++) {
146 if(isalnum(*p) || *p == '-' || *p == '.')
148 fprintf(stderr, "Invalid address or hostname.\n");
153 hostname = xstrdup(line);
157 FILE *f = fopen(filename, "a");
159 fprintf(f, "\nAddress = %s\n", hostname);
162 fprintf(stderr, "Could not append Address to %s: %s\n", filename, strerror(errno));
168 if(strchr(hostname, ':'))
169 xasprintf(&hostport, "[%s]:%s", hostname, port);
171 xasprintf(&hostport, "%s:%s", hostname, port);
183 static bool fcopy(FILE *out, const char *filename) {
184 FILE *in = fopen(filename, "r");
186 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
192 while((len = fread(buf, 1, sizeof buf, in)))
193 fwrite(buf, len, 1, out);
198 int cmd_invite(int argc, char *argv[]) {
200 fprintf(stderr, "Not enough arguments!\n");
204 // Check validity of the new node's name
205 if(!check_id(argv[1])) {
206 fprintf(stderr, "Invalid name for node.\n");
210 char *myname = get_my_name(true);
214 // Ensure no host configuration file with that name exists
215 char *filename = NULL;
216 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, argv[1]);
217 if(!access(filename, F_OK)) {
219 fprintf(stderr, "A host config file for %s already exists!\n", argv[1]);
224 // If a daemon is running, ensure no other nodes now about this name
226 if(connect_tincd(false)) {
227 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
229 while(recvline(fd, line, sizeof line)) {
232 if(sscanf(line, "%d %d %s", &code, &req, node) != 3)
234 if(!strcmp(node, argv[1]))
239 fprintf(stderr, "A node with name %s is already known!\n", argv[1]);
246 xasprintf(&filename, "%s" SLASH "invitations", confbase);
247 if(mkdir(filename, 0700) && errno != EEXIST) {
248 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
253 // Count the number of valid invitations, clean up old ones
254 DIR *dir = opendir(filename);
256 fprintf(stderr, "Could not read directory %s: %s\n", filename, strerror(errno));
264 time_t deadline = time(NULL) - 604800; // 1 week in the past
266 while((ent = readdir(dir))) {
267 if(strlen(ent->d_name) != 24)
271 xasprintf(&invname, "%s" SLASH "%s", filename, ent->d_name);
272 if(!stat(invname, &st)) {
273 if(deadline < st.st_mtime)
278 fprintf(stderr, "Could not stat %s: %s\n", invname, strerror(errno));
285 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
295 xasprintf(&filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", confbase);
297 // Remove the key if there are no outstanding invitations.
301 // Create a new key if necessary.
302 FILE *f = fopen(filename, "r");
304 if(errno != ENOENT) {
305 fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
310 key = ecdsa_generate();
315 f = fopen(filename, "w");
317 fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
321 chmod(filename, 0600);
322 ecdsa_write_pem_private_key(key, f);
324 key = ecdsa_read_pem_private_key(f);
326 fprintf(stderr, "Could not read private key from %s\n", filename);
333 // Create a hash of the key.
334 char *fingerprint = ecdsa_get_base64_public_key(key);
335 digest_t *digest = digest_open_by_name("sha256", 18);
338 digest_create(digest, fingerprint, strlen(fingerprint), hash);
339 b64encode_urlsafe(hash, hash, 18);
341 // Create a random cookie for this invitation.
343 randomize(cookie, 18);
344 b64encode_urlsafe(cookie, cookie, 18);
346 // Create a file containing the details of the invitation.
347 xasprintf(&filename, "%s" SLASH "invitations" SLASH "%s", confbase, cookie);
348 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
350 fprintf(stderr, "Could not create invitation file %s: %s\n", filename, strerror(errno));
355 f = fdopen(ifd, "w");
359 // Get the local address
360 char *address = get_my_hostname();
362 // Fill in the details.
363 fprintf(f, "Name = %s\n", argv[1]);
365 fprintf(f, "NetName = %s\n", netname);
366 fprintf(f, "ConnectTo = %s\n", myname);
367 // TODO: copy Broadcast and Mode
368 fprintf(f, "#---------------------------------------------------------------#\n");
369 fprintf(f, "Name = %s\n", myname);
371 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, myname);
375 // Create an URL from the local address, key hash and cookie
376 printf("%s/%s%s\n", address, hash, cookie);
384 static char cookie[18];
385 static sptps_t sptps;
387 static size_t datalen;
388 static bool success = false;
390 static char cookie[18], hash[18];
392 static char *get_line(const char **data) {
401 static char line[1024];
402 const char *end = strchr(*data, '\n');
403 size_t len = end ? end - *data : strlen(*data);
404 if(len >= sizeof line) {
405 fprintf(stderr, "Maximum line length exceeded!\n");
408 if(len && !isprint(**data))
411 memcpy(line, *data, len);
422 static char *get_value(const char *data, const char *var) {
423 char *line = get_line(&data);
427 char *sep = line + strcspn(line, " \t=");
428 char *val = sep + strspn(sep, " \t");
430 val += 1 + strspn(val + 1, " \t");
432 if(strcasecmp(line, var))
437 static char *grep(const char *data, const char *var) {
438 static char value[1024];
440 const char *p = data;
441 int varlen = strlen(var);
443 // Skip all lines not starting with var
444 while(strncasecmp(p, var, varlen) || !strchr(" \t=", p[varlen])) {
456 p += strspn(p, " \t");
458 p += 1 + strspn(p + 1, " \t");
460 const char *e = strchr(p, '\n');
464 if(e - p >= sizeof value) {
465 fprintf(stderr, "Maximum line length exceeded!\n");
469 memcpy(value, p, e - p);
474 static bool finalize_join(void) {
475 char *name = xstrdup(get_value(data, "Name"));
477 fprintf(stderr, "No Name found in invitation!\n");
481 if(!check_id(name)) {
482 fprintf(stderr, "Invalid Name found in invitation: %s!\n", name);
487 netname = grep(data, "NetName");
489 bool ask_netname = false;
490 char temp_netname[32];
503 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
504 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
506 if(!access(tinc_conf, F_OK)) {
507 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
508 if(!tty || confbasegiven)
511 // Generate a random netname, ask for a better one later.
513 snprintf(temp_netname, sizeof temp_netname, "join_%x", rand());
514 netname = temp_netname;
518 if(mkdir(confbase, 0777) && errno != EEXIST) {
519 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
523 if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
524 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
528 FILE *f = fopen(tinc_conf, "w");
530 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
534 fprintf(f, "Name = %s\n", name);
537 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
538 FILE *fh = fopen(filename, "w");
540 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
544 // Filter first chunk on approved keywords, split between tinc.conf and hosts/Name
545 // Other chunks go unfiltered to their respective host config files
546 const char *p = data;
549 while((l = get_line(&p))) {
554 // Split line into variable and value
555 int len = strcspn(l, "\t =");
557 value += strspn(value, "\t ");
560 value += strspn(value, "\t ");
565 if(!strcasecmp(l, "Name"))
566 if(strcmp(value, name))
570 else if(!strcasecmp(l, "NetName"))
573 // Check the list of known variables
576 for(i = 0; variables[i].name; i++) {
577 if(strcasecmp(l, variables[i].name))
583 // Ignore unknown and unsafe variables
585 fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
587 } else if(!(variables[i].type & VAR_SAFE)) {
588 fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
592 // Copy the safe variable to the right config file
593 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
599 while(l && !strcasecmp(l, "Name")) {
600 if(!check_id(value)) {
601 fprintf(stderr, "Invalid Name found in invitation.\n");
605 if(!strcmp(value, name)) {
606 fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
610 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, value);
611 f = fopen(filename, "w");
614 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
618 while((l = get_line(&p))) {
619 if(!strcmp(l, "#---------------------------------------------------------------#"))
621 int len = strcspn(l, "\t =");
622 if(len == 4 && !strncasecmp(l, "Name", 4)) {
624 value += strspn(value, "\t ");
627 value += strspn(value, "\t ");
641 // Generate our key and send a copy to the server
642 ecdsa_t *key = ecdsa_generate();
646 char *b64key = ecdsa_get_base64_public_key(key);
650 xasprintf(&filename, "%s" SLASH "ecdsa_key.priv", confbase);
651 f = fopenmask(filename, "w", 0600);
653 if(!ecdsa_write_pem_private_key(key, f)) {
654 fprintf(stderr, "Error writing private key!\n");
662 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
664 sptps_send_record(&sptps, 1, b64key, strlen(b64key));
668 rsa_t *rsa = rsa_generate(2048, 0x1001);
669 xasprintf(&filename, "%s" SLASH "rsa_key.priv", confbase);
670 f = fopenmask(filename, "w", 0600);
672 rsa_write_pem_private_key(rsa, f);
675 rsa_write_pem_public_key(rsa, fh);
683 fprintf(stderr, "Invitation succesfully accepted.\n");
684 shutdown(sock, SHUT_RDWR);
689 fprintf(stderr, "Enter a new netname: ");
690 if(!fgets(line, sizeof line, stdin)) {
691 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
694 if(!*line || *line == '\n')
697 line[strlen(line) - 1] = 0;
700 xasprintf(&newbase, CONFDIR SLASH "tinc" SLASH "%s", line);
701 if(rename(confbase, newbase)) {
702 fprintf(stderr, "Error trying to rename %s to %s: %s\n", confbase, newbase, strerror(errno));
715 static bool invitation_send(void *handle, uint8_t type, const char *data, size_t len) {
717 int result = send(sock, data, len, 0);
718 if(result == -1 && errno == EINTR)
728 static bool invitation_receive(void *handle, uint8_t type, const char *msg, uint16_t len) {
730 case SPTPS_HANDSHAKE:
731 return sptps_send_record(&sptps, 0, cookie, sizeof cookie);
734 data = xrealloc(data, datalen + len + 1);
735 memcpy(data + datalen, msg, len);
741 return finalize_join();
750 int cmd_join(int argc, char *argv[]) {
756 fprintf(stderr, "Too many arguments!\n");
760 // Make sure confbase exists and is accessible.
761 if(strcmp(confdir, confbase) && mkdir(confdir, 0755) && errno != EEXIST) {
762 fprintf(stderr, "Could not create directory %s: %s\n", confdir, strerror(errno));
766 if(mkdir(confbase, 0777) && errno != EEXIST) {
767 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
771 if(access(confbase, R_OK | W_OK | X_OK)) {
772 fprintf(stderr, "No permission to write in directory %s: %s\n", confbase, strerror(errno));
776 // If a netname or explicit configuration directory is specified, check for an existing tinc.conf.
777 if((netname || confbasegiven) && !access(tinc_conf, F_OK)) {
778 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
782 // Either read the invitation from the command line or from stdin.
786 invitation = argv[1];
789 printf("Enter invitation URL: ");
793 if(!fgets(line, sizeof line, stdin)) {
794 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
800 // Parse the invitation URL.
803 char *slash = strchr(invitation, '/');
809 if(strlen(slash) != 48)
812 char *address = invitation;
814 if(*address == '[') {
816 char *bracket = strchr(address, ']');
820 if(bracket[1] == ':')
823 port = strchr(address, ':');
831 if(!b64decode(slash, hash, 18) || !b64decode(slash + 24, cookie, 18))
834 // Generate a throw-away key for the invitation.
835 ecdsa_t *key = ecdsa_generate();
839 char *b64key = ecdsa_get_base64_public_key(key);
841 // Connect to the tinc daemon mentioned in the URL.
842 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
846 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
848 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
852 if(connect(sock, ai->ai_addr, ai->ai_addrlen)) {
853 fprintf(stderr, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
858 fprintf(stderr, "Connected to %s port %s...\n", address, port);
860 // Tell him we have an invitation, and give him our throw-away key.
861 int len = snprintf(line, sizeof line, "0 ?%s %d.%d\n", b64key, PROT_MAJOR, PROT_MINOR);
862 if(len <= 0 || len >= sizeof line)
865 if(!sendline(sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
866 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
871 char hisname[4096] = "";
872 int code, hismajor, hisminor = 0;
874 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) {
875 fprintf(stderr, "Cannot read greeting from peer\n");
880 // Check if the hash of the key he gave us matches the hash in the URL.
881 char *fingerprint = line + 2;
882 digest_t *digest = digest_open_by_name("sha256", 18);
886 if(!digest_create(digest, fingerprint, strlen(fingerprint), hishash)) {
887 fprintf(stderr, "Could not create digest\n%s\n", line + 2);
890 if(memcmp(hishash, hash, 18)) {
891 fprintf(stderr, "Peer has an invalid key!\n%s\n", line + 2);
896 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
900 // Start an SPTPS session
901 if(!sptps_start(&sptps, NULL, true, false, key, hiskey, "tinc invitation", 15, invitation_send, invitation_receive))
904 // Feed rest of input buffer to SPTPS
905 if(!sptps_receive_data(&sptps, buffer, blen))
908 while((len = recv(sock, line, sizeof line, 0))) {
912 fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
916 if(!sptps_receive_data(&sptps, line, len))
926 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
933 fprintf(stderr, "Invalid invitation URL.\n");