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"
36 #define SCRIPTEXTENSION ".bat"
38 #define SCRIPTEXTENSION ""
41 int addressfamily = AF_UNSPEC;
43 char *get_my_hostname() {
44 char *hostname = NULL;
46 char *hostport = NULL;
47 char *name = get_my_name(false);
48 char *filename = NULL;
50 // Use first Address statement in own host config file
52 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
53 FILE *f = fopen(filename, "r");
55 while(fgets(line, sizeof line, f)) {
59 p += strcspn(p, "\t =");
62 q = p + strspn(p, "\t ");
64 q += 1 + strspn(q + 1, "\t ");
66 p = q + strcspn(q, "\t ");
69 p += strspn(p, "\t ");
70 p[strcspn(p, "\t ")] = 0;
71 if(!port && !strcasecmp(line, "Port")) {
75 if(strcasecmp(line, "Address"))
77 hostname = xstrdup(q);
91 // If that doesn't work, guess externally visible hostname
92 fprintf(stderr, "Trying to discover externally visible hostname...\n");
93 struct addrinfo *ai = str2addrinfo("ifconfig.me", "80", SOCK_STREAM);
94 static const char request[] = "GET /host HTTP/1.0\r\n\r\n";
96 int s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
98 if(connect(s, ai->ai_addr, ai->ai_addrlen)) {
104 send(s, request, sizeof request - 1, 0);
105 int len = recv(s, line, sizeof line - 1, MSG_WAITALL);
108 if(line[len - 1] == '\n')
110 char *p = strrchr(line, '\n');
112 hostname = xstrdup(p + 1);
119 // Check that the hostname is reasonable
121 for(char *p = hostname; *p; p++) {
122 if(isalnum(*p) || *p == '-' || *p == '.')
124 // If not, forget it.
132 printf("Please enter your host's external address or hostname");
134 printf(" [%s]", hostname);
138 if(!fgets(line, sizeof line, stdin)) {
139 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
151 for(char *p = line; *p; p++) {
152 if(isalnum(*p) || *p == '-' || *p == '.')
154 fprintf(stderr, "Invalid address or hostname.\n");
159 hostname = xstrdup(line);
163 FILE *f = fopen(filename, "a");
165 fprintf(f, "\nAddress = %s\n", hostname);
168 fprintf(stderr, "Could not append Address to %s: %s\n", filename, strerror(errno));
174 if(strchr(hostname, ':'))
175 xasprintf(&hostport, "[%s]:%s", hostname, port);
177 xasprintf(&hostport, "%s:%s", hostname, port);
189 static bool fcopy(FILE *out, const char *filename) {
190 FILE *in = fopen(filename, "r");
192 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
198 while((len = fread(buf, 1, sizeof buf, in)))
199 fwrite(buf, len, 1, out);
204 int cmd_invite(int argc, char *argv[]) {
206 fprintf(stderr, "Not enough arguments!\n");
210 // Check validity of the new node's name
211 if(!check_id(argv[1])) {
212 fprintf(stderr, "Invalid name for node.\n");
216 char *myname = get_my_name(true);
220 // Ensure no host configuration file with that name exists
221 char *filename = NULL;
222 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, argv[1]);
223 if(!access(filename, F_OK)) {
225 fprintf(stderr, "A host config file for %s already exists!\n", argv[1]);
230 // If a daemon is running, ensure no other nodes now about this name
232 if(connect_tincd(false)) {
233 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
235 while(recvline(fd, line, sizeof line)) {
238 if(sscanf(line, "%d %d %s", &code, &req, node) != 3)
240 if(!strcmp(node, argv[1]))
245 fprintf(stderr, "A node with name %s is already known!\n", argv[1]);
252 xasprintf(&filename, "%s" SLASH "invitations", confbase);
253 if(mkdir(filename, 0700) && errno != EEXIST) {
254 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
259 // Count the number of valid invitations, clean up old ones
260 DIR *dir = opendir(filename);
262 fprintf(stderr, "Could not read directory %s: %s\n", filename, strerror(errno));
270 time_t deadline = time(NULL) - 604800; // 1 week in the past
272 while((ent = readdir(dir))) {
273 if(strlen(ent->d_name) != 24)
277 xasprintf(&invname, "%s" SLASH "%s", filename, ent->d_name);
278 if(!stat(invname, &st)) {
279 if(deadline < st.st_mtime)
284 fprintf(stderr, "Could not stat %s: %s\n", invname, strerror(errno));
291 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
301 xasprintf(&filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", confbase);
303 // Remove the key if there are no outstanding invitations.
307 // Create a new key if necessary.
308 FILE *f = fopen(filename, "r");
310 if(errno != ENOENT) {
311 fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
316 key = ecdsa_generate();
321 f = fopen(filename, "w");
323 fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
327 chmod(filename, 0600);
328 ecdsa_write_pem_private_key(key, f);
330 key = ecdsa_read_pem_private_key(f);
332 fprintf(stderr, "Could not read private key from %s\n", filename);
339 // Create a hash of the key.
340 char *fingerprint = ecdsa_get_base64_public_key(key);
341 digest_t *digest = digest_open_by_name("sha256", 18);
344 digest_create(digest, fingerprint, strlen(fingerprint), hash);
345 b64encode_urlsafe(hash, hash, 18);
347 // Create a random cookie for this invitation.
349 randomize(cookie, 18);
350 b64encode_urlsafe(cookie, cookie, 18);
352 // Create a file containing the details of the invitation.
353 xasprintf(&filename, "%s" SLASH "invitations" SLASH "%s", confbase, cookie);
354 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
356 fprintf(stderr, "Could not create invitation file %s: %s\n", filename, strerror(errno));
361 f = fdopen(ifd, "w");
365 // Fill in the details.
366 fprintf(f, "Name = %s\n", argv[1]);
368 fprintf(f, "NetName = %s\n", netname);
369 fprintf(f, "ConnectTo = %s\n", myname);
370 // TODO: copy Broadcast and Mode
371 fprintf(f, "#---------------------------------------------------------------#\n");
372 fprintf(f, "Name = %s\n", myname);
374 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, myname);
378 // Create an URL from the local address, key hash and cookie
379 char *address = get_my_hostname();
380 printf("%s/%s%s\n", address, hash, cookie);
388 static char cookie[18];
389 static sptps_t sptps;
391 static size_t datalen;
392 static bool success = false;
394 static char cookie[18], hash[18];
396 static char *get_line(const char **data) {
405 static char line[1024];
406 const char *end = strchr(*data, '\n');
407 size_t len = end ? end - *data : strlen(*data);
408 if(len >= sizeof line) {
409 fprintf(stderr, "Maximum line length exceeded!\n");
412 if(len && !isprint(**data))
415 memcpy(line, *data, len);
426 static char *get_value(const char *data, const char *var) {
427 char *line = get_line(&data);
431 char *sep = line + strcspn(line, " \t=");
432 char *val = sep + strspn(sep, " \t");
434 val += 1 + strspn(val + 1, " \t");
436 if(strcasecmp(line, var))
441 static char *grep(const char *data, const char *var) {
442 static char value[1024];
444 const char *p = data;
445 int varlen = strlen(var);
447 // Skip all lines not starting with var
448 while(strncasecmp(p, var, varlen) || !strchr(" \t=", p[varlen])) {
460 p += strspn(p, " \t");
462 p += 1 + strspn(p + 1, " \t");
464 const char *e = strchr(p, '\n');
468 if(e - p >= sizeof value) {
469 fprintf(stderr, "Maximum line length exceeded!\n");
473 memcpy(value, p, e - p);
478 static bool finalize_join(void) {
479 char *name = xstrdup(get_value(data, "Name"));
481 fprintf(stderr, "No Name found in invitation!\n");
485 if(!check_id(name)) {
486 fprintf(stderr, "Invalid Name found in invitation: %s!\n", name);
491 netname = grep(data, "NetName");
504 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
505 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
507 if(!access(tinc_conf, F_OK)) {
508 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
509 if(!tty || confbasegiven)
512 fprintf(stderr, "Enter a new netname: ");
513 if(!fgets(line, sizeof line, stdin)) {
514 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
517 if(!*line || *line == '\n')
520 line[strlen(line) - 1] = 0;
525 if(mkdir(confbase, 0755) && errno != EEXIST) {
526 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
530 if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
531 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
535 FILE *f = fopen(tinc_conf, "w");
537 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
541 fprintf(f, "Name = %s\n", name);
544 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
545 FILE *fh = fopen(filename, "w");
547 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
551 // Filter first chunk on approved keywords, split between tinc.conf and hosts/Name
552 // Other chunks go unfiltered to their respective host config files
553 const char *p = data;
556 while((l = get_line(&p))) {
561 // Split line into variable and value
562 int len = strcspn(l, "\t =");
564 value += strspn(value, "\t ");
567 value += strspn(value, "\t ");
572 if(!strcasecmp(l, "Name"))
573 if(strcmp(value, name))
577 else if(!strcasecmp(l, "NetName"))
580 // Check the list of known variables
583 for(i = 0; variables[i].name; i++) {
584 if(strcasecmp(l, variables[i].name))
590 // Ignore unknown and unsafe variables
592 fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
594 } else if(!(variables[i].type & VAR_SAFE)) {
595 fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
599 // Copy the safe variable to the right config file
600 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
606 while(l && !strcasecmp(l, "Name")) {
607 if(!check_id(value)) {
608 fprintf(stderr, "Invalid Name found in invitation.\n");
612 if(!strcmp(value, name)) {
613 fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
617 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, value);
618 f = fopen(filename, "w");
621 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
625 while((l = get_line(&p))) {
626 if(!strcmp(l, "#---------------------------------------------------------------#"))
628 int len = strcspn(l, "\t =");
629 if(len == 4 && !strncasecmp(l, "Name", 4)) {
631 value += strspn(value, "\t ");
634 value += strspn(value, "\t ");
648 // Generate our key and send a copy to the server
649 ecdsa_t *key = ecdsa_generate();
653 char *b64key = ecdsa_get_base64_public_key(key);
657 xasprintf(&filename, "%s" SLASH "ecdsa_key.priv", confbase);
658 f = fopen(filename, "w");
661 /* Make it unreadable for others. */
662 fchmod(fileno(f), 0600);
665 if(!ecdsa_write_pem_private_key(key, f)) {
666 fprintf(stderr, "Error writing private key!\n");
674 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
676 sptps_send_record(&sptps, 1, b64key, strlen(b64key));
680 rsa_t *rsa = rsa_generate(2048, 0x1001);
681 xasprintf(&filename, "%s" SLASH "rsa_key.priv", confbase);
682 f = fopen(filename, "w");
685 /* Make it unreadable for others. */
686 fchmod(fileno(f), 0600);
689 rsa_write_pem_private_key(rsa, f);
692 rsa_write_pem_public_key(rsa, fh);
700 fprintf(stderr, "Invitation succesfully accepted.\n");
701 shutdown(sock, SHUT_RDWR);
707 static bool invitation_send(void *handle, uint8_t type, const char *data, size_t len) {
709 int result = send(sock, data, len, 0);
710 if(result == -1 && errno == EINTR)
720 static bool invitation_receive(void *handle, uint8_t type, const char *msg, uint16_t len) {
722 case SPTPS_HANDSHAKE:
723 return sptps_send_record(&sptps, 0, cookie, sizeof cookie);
726 data = xrealloc(data, datalen + len + 1);
727 memcpy(data + datalen, msg, len);
733 return finalize_join();
742 int cmd_join(int argc, char *argv[]) {
748 fprintf(stderr, "Too many arguments!\n");
752 // Make sure confdir exists.
753 if(mkdir(confdir, 0755) && errno != EEXIST) {
754 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
758 // Either read the invitation from the command line or from stdin.
762 invitation = argv[1];
765 printf("Enter invitation URL: ");
769 if(!fgets(line, sizeof line, stdin)) {
770 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
776 // Parse the invitation URL.
779 char *slash = strchr(invitation, '/');
785 if(strlen(slash) != 48)
788 char *address = invitation;
790 if(*address == '[') {
792 char *bracket = strchr(address, ']');
796 if(bracket[1] == ':')
799 port = strchr(address, ':');
807 if(!b64decode(slash, hash, 18) || !b64decode(slash + 24, cookie, 18))
810 // Generate a throw-away key for the invitation.
811 ecdsa_t *key = ecdsa_generate();
815 char *b64key = ecdsa_get_base64_public_key(key);
817 // Connect to the tinc daemon mentioned in the URL.
818 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
822 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
824 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
828 if(connect(sock, ai->ai_addr, ai->ai_addrlen)) {
829 fprintf(stderr, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
834 fprintf(stderr, "Connected to %s port %s...\n", address, port);
836 // Tell him we have an invitation, and give him our throw-away key.
837 int len = snprintf(line, sizeof line, "0 ?%s %d.%d\n", b64key, PROT_MAJOR, PROT_MINOR);
838 if(len <= 0 || len >= sizeof line)
841 if(!sendline(sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
842 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
847 char hisname[4096] = "";
848 int code, hismajor, hisminor = 0;
850 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) {
851 fprintf(stderr, "Cannot read greeting from peer\n");
856 // Check if the hash of the key he have us matches the hash in the URL.
857 char *fingerprint = line + 2;
858 digest_t *digest = digest_open_by_name("sha256", 18);
862 if(!digest_create(digest, fingerprint, strlen(fingerprint), hishash)) {
863 fprintf(stderr, "Could not create digest\n%s\n", line + 2);
866 if(memcmp(hishash, hash, 18)) {
867 fprintf(stderr, "Peer has an invalid key!\n%s\n", line + 2);
872 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
876 // Start an SPTPS session
877 if(!sptps_start(&sptps, NULL, true, false, key, hiskey, "tinc invitation", 15, invitation_send, invitation_receive))
880 // Feed rest of input buffer to SPTPS
881 if(!sptps_receive_data(&sptps, buffer, blen))
884 while((len = recv(sock, line, sizeof line, 0))) {
888 fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
892 if(!sptps_receive_data(&sptps, line, len))
902 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
909 fprintf(stderr, "Invalid invitation URL.\n");