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 int addressfamily = AF_UNSPEC;
38 char *get_my_hostname() {
39 char *hostname = NULL;
41 char *hostport = NULL;
42 char *name = get_my_name(false);
43 char *filename = NULL;
45 // Use first Address statement in own host config file
47 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
48 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;
66 if(!port && !strcasecmp(line, "Port")) {
70 if(strcasecmp(line, "Address"))
72 hostname = xstrdup(q);
86 // If that doesn't work, guess externally visible hostname
87 fprintf(stderr, "Trying to discover externally visible hostname...\n");
88 struct addrinfo *ai = str2addrinfo("tinc-vpn.org", "80", SOCK_STREAM);
89 struct addrinfo *aip = ai;
90 static const char request[] = "GET http://tinc-vpn.org/host.cgi HTTP/1.0\r\n\r\n";
93 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
95 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
101 send(s, request, sizeof request - 1, 0);
102 int len = recv(s, line, sizeof line - 1, MSG_WAITALL);
105 if(line[len - 1] == '\n')
107 char *p = strrchr(line, '\n');
109 hostname = xstrdup(p + 1);
122 // Check that the hostname is reasonable
124 for(char *p = hostname; *p; p++) {
125 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
127 // If not, forget it.
135 printf("Please enter your host's external address or hostname");
137 printf(" [%s]", hostname);
141 if(!fgets(line, sizeof line, stdin)) {
142 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
154 for(char *p = line; *p; p++) {
155 if(isalnum(*p) || *p == '-' || *p == '.')
157 fprintf(stderr, "Invalid address or hostname.\n");
162 hostname = xstrdup(line);
166 FILE *f = fopen(filename, "a");
168 fprintf(f, "\nAddress = %s\n", hostname);
171 fprintf(stderr, "Could not append Address to %s: %s\n", filename, strerror(errno));
177 if(strchr(hostname, ':'))
178 xasprintf(&hostport, "[%s]:%s", hostname, port);
180 xasprintf(&hostport, "%s:%s", hostname, port);
192 static bool fcopy(FILE *out, const char *filename) {
193 FILE *in = fopen(filename, "r");
195 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
201 while((len = fread(buf, 1, sizeof buf, in)))
202 fwrite(buf, len, 1, out);
207 int cmd_invite(int argc, char *argv[]) {
209 fprintf(stderr, "Not enough arguments!\n");
213 // Check validity of the new node's name
214 if(!check_id(argv[1])) {
215 fprintf(stderr, "Invalid name for node.\n");
219 char *myname = get_my_name(true);
223 // Ensure no host configuration file with that name exists
224 char *filename = NULL;
225 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, argv[1]);
226 if(!access(filename, F_OK)) {
228 fprintf(stderr, "A host config file for %s already exists!\n", argv[1]);
233 // If a daemon is running, ensure no other nodes now about this name
235 if(connect_tincd(false)) {
236 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
238 while(recvline(fd, line, sizeof line)) {
241 if(sscanf(line, "%d %d %s", &code, &req, node) != 3)
243 if(!strcmp(node, argv[1]))
248 fprintf(stderr, "A node with name %s is already known!\n", argv[1]);
255 xasprintf(&filename, "%s" SLASH "invitations", confbase);
256 if(mkdir(filename, 0700) && errno != EEXIST) {
257 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
262 // Count the number of valid invitations, clean up old ones
263 DIR *dir = opendir(filename);
265 fprintf(stderr, "Could not read directory %s: %s\n", filename, strerror(errno));
273 time_t deadline = time(NULL) - 604800; // 1 week in the past
275 while((ent = readdir(dir))) {
276 if(strlen(ent->d_name) != 24)
280 xasprintf(&invname, "%s" SLASH "%s", filename, ent->d_name);
281 if(!stat(invname, &st)) {
282 if(deadline < st.st_mtime)
287 fprintf(stderr, "Could not stat %s: %s\n", invname, strerror(errno));
294 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
304 xasprintf(&filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", confbase);
306 // Remove the key if there are no outstanding invitations.
310 // Create a new key if necessary.
311 FILE *f = fopen(filename, "r");
313 if(errno != ENOENT) {
314 fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
319 key = ecdsa_generate();
324 f = fopen(filename, "w");
326 fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
330 chmod(filename, 0600);
331 ecdsa_write_pem_private_key(key, f);
333 key = ecdsa_read_pem_private_key(f);
335 fprintf(stderr, "Could not read private key from %s\n", filename);
342 // Create a hash of the key.
343 char *fingerprint = ecdsa_get_base64_public_key(key);
344 digest_t *digest = digest_open_by_name("sha256", 18);
347 digest_create(digest, fingerprint, strlen(fingerprint), hash);
348 b64encode_urlsafe(hash, hash, 18);
350 // Create a random cookie for this invitation.
352 randomize(cookie, 18);
354 // Create a filename that doesn't reveal the cookie itself
355 char buf[18 + strlen(fingerprint)];
357 memcpy(buf, cookie, 18);
358 memcpy(buf + 18, fingerprint, sizeof buf - 18);
359 digest_create(digest, buf, sizeof buf, cookiehash);
360 b64encode_urlsafe(cookiehash, cookiehash, 18);
362 b64encode_urlsafe(cookie, cookie, 18);
364 // Create a file containing the details of the invitation.
365 xasprintf(&filename, "%s" SLASH "invitations" SLASH "%s", confbase, cookiehash);
366 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
368 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);
385 // Copy Broadcast and Mode
386 FILE *tc = fopen(tinc_conf, "r");
389 while(fgets(buf, sizeof buf, tc)) {
390 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
391 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9])))
397 fprintf(f, "#---------------------------------------------------------------#\n");
398 fprintf(f, "Name = %s\n", myname);
401 xasprintf(&filename2, "%s" SLASH "hosts" SLASH "%s", confbase, myname);
406 // Create an URL from the local address, key hash and cookie
408 xasprintf(&url, "%s/%s%s", address, hash, cookie);
410 // Call the inviation-created script
412 xasprintf(&envp[0], "NAME=%s", myname);
413 xasprintf(&envp[1], "NETNAME=%s", netname);
414 xasprintf(&envp[2], "NODE=%s", argv[1]);
415 xasprintf(&envp[3], "INVITATION_FILE=%s", filename);
416 xasprintf(&envp[4], "INVITATION_URL=%s", url);
417 execute_script("invitation-created", envp);
418 for(int i = 0; i < 6 && envp[i]; i++)
430 static char cookie[18];
431 static sptps_t sptps;
433 static size_t datalen;
434 static bool success = false;
436 static char cookie[18], hash[18];
438 static char *get_line(const char **data) {
447 static char line[1024];
448 const char *end = strchr(*data, '\n');
449 size_t len = end ? end - *data : strlen(*data);
450 if(len >= sizeof line) {
451 fprintf(stderr, "Maximum line length exceeded!\n");
454 if(len && !isprint(**data))
457 memcpy(line, *data, len);
468 static char *get_value(const char *data, const char *var) {
469 char *line = get_line(&data);
473 char *sep = line + strcspn(line, " \t=");
474 char *val = sep + strspn(sep, " \t");
476 val += 1 + strspn(val + 1, " \t");
478 if(strcasecmp(line, var))
483 static char *grep(const char *data, const char *var) {
484 static char value[1024];
486 const char *p = data;
487 int varlen = strlen(var);
489 // Skip all lines not starting with var
490 while(strncasecmp(p, var, varlen) || !strchr(" \t=", p[varlen])) {
502 p += strspn(p, " \t");
504 p += 1 + strspn(p + 1, " \t");
506 const char *e = strchr(p, '\n');
510 if(e - p >= sizeof value) {
511 fprintf(stderr, "Maximum line length exceeded!\n");
515 memcpy(value, p, e - p);
520 static bool finalize_join(void) {
521 char *name = xstrdup(get_value(data, "Name"));
523 fprintf(stderr, "No Name found in invitation!\n");
527 if(!check_id(name)) {
528 fprintf(stderr, "Invalid Name found in invitation: %s!\n", name);
533 netname = grep(data, "NetName");
535 bool ask_netname = false;
536 char temp_netname[32];
549 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
550 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
552 if(!access(tinc_conf, F_OK)) {
553 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
554 if(!tty || confbasegiven)
557 // Generate a random netname, ask for a better one later.
559 snprintf(temp_netname, sizeof temp_netname, "join_%x", rand());
560 netname = temp_netname;
564 if(mkdir(confbase, 0777) && errno != EEXIST) {
565 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
569 if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
570 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
574 FILE *f = fopen(tinc_conf, "w");
576 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
580 fprintf(f, "Name = %s\n", name);
583 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
584 FILE *fh = fopen(filename, "w");
586 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
590 // Filter first chunk on approved keywords, split between tinc.conf and hosts/Name
591 // Other chunks go unfiltered to their respective host config files
592 const char *p = data;
595 while((l = get_line(&p))) {
600 // Split line into variable and value
601 int len = strcspn(l, "\t =");
603 value += strspn(value, "\t ");
606 value += strspn(value, "\t ");
611 if(!strcasecmp(l, "Name"))
612 if(strcmp(value, name))
616 else if(!strcasecmp(l, "NetName"))
619 // Check the list of known variables
622 for(i = 0; variables[i].name; i++) {
623 if(strcasecmp(l, variables[i].name))
629 // Ignore unknown and unsafe variables
631 fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
633 } else if(!(variables[i].type & VAR_SAFE)) {
634 fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
638 // Copy the safe variable to the right config file
639 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
645 while(l && !strcasecmp(l, "Name")) {
646 if(!check_id(value)) {
647 fprintf(stderr, "Invalid Name found in invitation.\n");
651 if(!strcmp(value, name)) {
652 fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
656 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, value);
657 f = fopen(filename, "w");
660 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
664 while((l = get_line(&p))) {
665 if(!strcmp(l, "#---------------------------------------------------------------#"))
667 int len = strcspn(l, "\t =");
668 if(len == 4 && !strncasecmp(l, "Name", 4)) {
670 value += strspn(value, "\t ");
673 value += strspn(value, "\t ");
687 // Generate our key and send a copy to the server
688 ecdsa_t *key = ecdsa_generate();
692 char *b64key = ecdsa_get_base64_public_key(key);
696 xasprintf(&filename, "%s" SLASH "ecdsa_key.priv", confbase);
697 f = fopenmask(filename, "w", 0600);
699 if(!ecdsa_write_pem_private_key(key, f)) {
700 fprintf(stderr, "Error writing private key!\n");
708 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
710 sptps_send_record(&sptps, 1, b64key, strlen(b64key));
714 rsa_t *rsa = rsa_generate(2048, 0x1001);
715 xasprintf(&filename, "%s" SLASH "rsa_key.priv", confbase);
716 f = fopenmask(filename, "w", 0600);
718 rsa_write_pem_private_key(rsa, f);
721 rsa_write_pem_public_key(rsa, fh);
731 fprintf(stderr, "Enter a new netname: ");
732 if(!fgets(line, sizeof line, stdin)) {
733 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
736 if(!*line || *line == '\n')
739 line[strlen(line) - 1] = 0;
742 xasprintf(&newbase, CONFDIR SLASH "tinc" SLASH "%s", line);
743 if(rename(confbase, newbase)) {
744 fprintf(stderr, "Error trying to rename %s to %s: %s\n", confbase, newbase, strerror(errno));
758 static bool invitation_send(void *handle, uint8_t type, const char *data, size_t len) {
760 int result = send(sock, data, len, 0);
761 if(result == -1 && errno == EINTR)
771 static bool invitation_receive(void *handle, uint8_t type, const char *msg, uint16_t len) {
773 case SPTPS_HANDSHAKE:
774 return sptps_send_record(&sptps, 0, cookie, sizeof cookie);
777 data = xrealloc(data, datalen + len + 1);
778 memcpy(data + datalen, msg, len);
784 return finalize_join();
787 fprintf(stderr, "Invitation succesfully accepted.\n");
788 shutdown(sock, SHUT_RDWR);
799 int cmd_join(int argc, char *argv[]) {
805 fprintf(stderr, "Too many arguments!\n");
809 // Make sure confbase exists and is accessible.
810 if(strcmp(confdir, confbase) && mkdir(confdir, 0755) && errno != EEXIST) {
811 fprintf(stderr, "Could not create directory %s: %s\n", confdir, strerror(errno));
815 if(mkdir(confbase, 0777) && errno != EEXIST) {
816 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
820 if(access(confbase, R_OK | W_OK | X_OK)) {
821 fprintf(stderr, "No permission to write in directory %s: %s\n", confbase, strerror(errno));
825 // If a netname or explicit configuration directory is specified, check for an existing tinc.conf.
826 if((netname || confbasegiven) && !access(tinc_conf, F_OK)) {
827 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
831 // Either read the invitation from the command line or from stdin.
835 invitation = argv[1];
838 printf("Enter invitation URL: ");
842 if(!fgets(line, sizeof line, stdin)) {
843 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
849 // Parse the invitation URL.
852 char *slash = strchr(invitation, '/');
858 if(strlen(slash) != 48)
861 char *address = invitation;
863 if(*address == '[') {
865 char *bracket = strchr(address, ']');
869 if(bracket[1] == ':')
872 port = strchr(address, ':');
880 if(!b64decode(slash, hash, 18) || !b64decode(slash + 24, cookie, 18))
883 // Generate a throw-away key for the invitation.
884 ecdsa_t *key = ecdsa_generate();
888 char *b64key = ecdsa_get_base64_public_key(key);
890 // Connect to the tinc daemon mentioned in the URL.
891 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
895 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
897 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
901 if(connect(sock, ai->ai_addr, ai->ai_addrlen)) {
902 fprintf(stderr, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
907 fprintf(stderr, "Connected to %s port %s...\n", address, port);
909 // Tell him we have an invitation, and give him our throw-away key.
910 int len = snprintf(line, sizeof line, "0 ?%s %d.%d\n", b64key, PROT_MAJOR, PROT_MINOR);
911 if(len <= 0 || len >= sizeof line)
914 if(!sendline(sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
915 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
920 char hisname[4096] = "";
921 int code, hismajor, hisminor = 0;
923 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) {
924 fprintf(stderr, "Cannot read greeting from peer\n");
929 // Check if the hash of the key he gave us matches the hash in the URL.
930 char *fingerprint = line + 2;
931 digest_t *digest = digest_open_by_name("sha256", 18);
935 if(!digest_create(digest, fingerprint, strlen(fingerprint), hishash)) {
936 fprintf(stderr, "Could not create digest\n%s\n", line + 2);
939 if(memcmp(hishash, hash, 18)) {
940 fprintf(stderr, "Peer has an invalid key!\n%s\n", line + 2);
945 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
949 // Start an SPTPS session
950 if(!sptps_start(&sptps, NULL, true, false, key, hiskey, "tinc invitation", 15, invitation_send, invitation_receive))
953 // Feed rest of input buffer to SPTPS
954 if(!sptps_receive_data(&sptps, buffer, blen))
957 while((len = recv(sock, line, sizeof line, 0))) {
961 fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
965 if(!sptps_receive_data(&sptps, line, len))
975 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
982 fprintf(stderr, "Invalid invitation URL.\n");