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);
384 // TODO: copy Broadcast and Mode
385 fprintf(f, "#---------------------------------------------------------------#\n");
386 fprintf(f, "Name = %s\n", myname);
389 xasprintf(&filename2, "%s" SLASH "hosts" SLASH "%s", confbase, myname);
394 // Create an URL from the local address, key hash and cookie
396 xasprintf(&url, "%s/%s%s", address, hash, cookie);
398 // Call the inviation-created script
400 xasprintf(&envp[0], "NAME=%s", myname);
401 xasprintf(&envp[1], "NETNAME=%s", netname);
402 xasprintf(&envp[2], "NODE=%s", argv[1]);
403 xasprintf(&envp[3], "INVITATION_FILE=%s", filename);
404 xasprintf(&envp[4], "INVITATION_URL=%s", url);
405 execute_script("invitation-created", envp);
406 for(int i = 0; i < 6 && envp[i]; i++)
418 static char cookie[18];
419 static sptps_t sptps;
421 static size_t datalen;
422 static bool success = false;
424 static char cookie[18], hash[18];
426 static char *get_line(const char **data) {
435 static char line[1024];
436 const char *end = strchr(*data, '\n');
437 size_t len = end ? end - *data : strlen(*data);
438 if(len >= sizeof line) {
439 fprintf(stderr, "Maximum line length exceeded!\n");
442 if(len && !isprint(**data))
445 memcpy(line, *data, len);
456 static char *get_value(const char *data, const char *var) {
457 char *line = get_line(&data);
461 char *sep = line + strcspn(line, " \t=");
462 char *val = sep + strspn(sep, " \t");
464 val += 1 + strspn(val + 1, " \t");
466 if(strcasecmp(line, var))
471 static char *grep(const char *data, const char *var) {
472 static char value[1024];
474 const char *p = data;
475 int varlen = strlen(var);
477 // Skip all lines not starting with var
478 while(strncasecmp(p, var, varlen) || !strchr(" \t=", p[varlen])) {
490 p += strspn(p, " \t");
492 p += 1 + strspn(p + 1, " \t");
494 const char *e = strchr(p, '\n');
498 if(e - p >= sizeof value) {
499 fprintf(stderr, "Maximum line length exceeded!\n");
503 memcpy(value, p, e - p);
508 static bool finalize_join(void) {
509 char *name = xstrdup(get_value(data, "Name"));
511 fprintf(stderr, "No Name found in invitation!\n");
515 if(!check_id(name)) {
516 fprintf(stderr, "Invalid Name found in invitation: %s!\n", name);
521 netname = grep(data, "NetName");
523 bool ask_netname = false;
524 char temp_netname[32];
537 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
538 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
540 if(!access(tinc_conf, F_OK)) {
541 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
542 if(!tty || confbasegiven)
545 // Generate a random netname, ask for a better one later.
547 snprintf(temp_netname, sizeof temp_netname, "join_%x", rand());
548 netname = temp_netname;
552 if(mkdir(confbase, 0777) && errno != EEXIST) {
553 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
557 if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
558 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
562 FILE *f = fopen(tinc_conf, "w");
564 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
568 fprintf(f, "Name = %s\n", name);
571 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
572 FILE *fh = fopen(filename, "w");
574 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
578 // Filter first chunk on approved keywords, split between tinc.conf and hosts/Name
579 // Other chunks go unfiltered to their respective host config files
580 const char *p = data;
583 while((l = get_line(&p))) {
588 // Split line into variable and value
589 int len = strcspn(l, "\t =");
591 value += strspn(value, "\t ");
594 value += strspn(value, "\t ");
599 if(!strcasecmp(l, "Name"))
600 if(strcmp(value, name))
604 else if(!strcasecmp(l, "NetName"))
607 // Check the list of known variables
610 for(i = 0; variables[i].name; i++) {
611 if(strcasecmp(l, variables[i].name))
617 // Ignore unknown and unsafe variables
619 fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
621 } else if(!(variables[i].type & VAR_SAFE)) {
622 fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
626 // Copy the safe variable to the right config file
627 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
633 while(l && !strcasecmp(l, "Name")) {
634 if(!check_id(value)) {
635 fprintf(stderr, "Invalid Name found in invitation.\n");
639 if(!strcmp(value, name)) {
640 fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
644 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, value);
645 f = fopen(filename, "w");
648 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
652 while((l = get_line(&p))) {
653 if(!strcmp(l, "#---------------------------------------------------------------#"))
655 int len = strcspn(l, "\t =");
656 if(len == 4 && !strncasecmp(l, "Name", 4)) {
658 value += strspn(value, "\t ");
661 value += strspn(value, "\t ");
675 // Generate our key and send a copy to the server
676 ecdsa_t *key = ecdsa_generate();
680 char *b64key = ecdsa_get_base64_public_key(key);
684 xasprintf(&filename, "%s" SLASH "ecdsa_key.priv", confbase);
685 f = fopenmask(filename, "w", 0600);
687 if(!ecdsa_write_pem_private_key(key, f)) {
688 fprintf(stderr, "Error writing private key!\n");
696 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
698 sptps_send_record(&sptps, 1, b64key, strlen(b64key));
702 rsa_t *rsa = rsa_generate(2048, 0x1001);
703 xasprintf(&filename, "%s" SLASH "rsa_key.priv", confbase);
704 f = fopenmask(filename, "w", 0600);
706 rsa_write_pem_private_key(rsa, f);
709 rsa_write_pem_public_key(rsa, fh);
719 fprintf(stderr, "Enter a new netname: ");
720 if(!fgets(line, sizeof line, stdin)) {
721 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
724 if(!*line || *line == '\n')
727 line[strlen(line) - 1] = 0;
730 xasprintf(&newbase, CONFDIR SLASH "tinc" SLASH "%s", line);
731 if(rename(confbase, newbase)) {
732 fprintf(stderr, "Error trying to rename %s to %s: %s\n", confbase, newbase, strerror(errno));
746 static bool invitation_send(void *handle, uint8_t type, const char *data, size_t len) {
748 int result = send(sock, data, len, 0);
749 if(result == -1 && errno == EINTR)
759 static bool invitation_receive(void *handle, uint8_t type, const char *msg, uint16_t len) {
761 case SPTPS_HANDSHAKE:
762 return sptps_send_record(&sptps, 0, cookie, sizeof cookie);
765 data = xrealloc(data, datalen + len + 1);
766 memcpy(data + datalen, msg, len);
772 return finalize_join();
775 fprintf(stderr, "Invitation succesfully accepted.\n");
776 shutdown(sock, SHUT_RDWR);
787 int cmd_join(int argc, char *argv[]) {
793 fprintf(stderr, "Too many arguments!\n");
797 // Make sure confbase exists and is accessible.
798 if(strcmp(confdir, confbase) && mkdir(confdir, 0755) && errno != EEXIST) {
799 fprintf(stderr, "Could not create directory %s: %s\n", confdir, strerror(errno));
803 if(mkdir(confbase, 0777) && errno != EEXIST) {
804 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
808 if(access(confbase, R_OK | W_OK | X_OK)) {
809 fprintf(stderr, "No permission to write in directory %s: %s\n", confbase, strerror(errno));
813 // If a netname or explicit configuration directory is specified, check for an existing tinc.conf.
814 if((netname || confbasegiven) && !access(tinc_conf, F_OK)) {
815 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
819 // Either read the invitation from the command line or from stdin.
823 invitation = argv[1];
826 printf("Enter invitation URL: ");
830 if(!fgets(line, sizeof line, stdin)) {
831 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
837 // Parse the invitation URL.
840 char *slash = strchr(invitation, '/');
846 if(strlen(slash) != 48)
849 char *address = invitation;
851 if(*address == '[') {
853 char *bracket = strchr(address, ']');
857 if(bracket[1] == ':')
860 port = strchr(address, ':');
868 if(!b64decode(slash, hash, 18) || !b64decode(slash + 24, cookie, 18))
871 // Generate a throw-away key for the invitation.
872 ecdsa_t *key = ecdsa_generate();
876 char *b64key = ecdsa_get_base64_public_key(key);
878 // Connect to the tinc daemon mentioned in the URL.
879 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
883 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
885 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
889 if(connect(sock, ai->ai_addr, ai->ai_addrlen)) {
890 fprintf(stderr, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
895 fprintf(stderr, "Connected to %s port %s...\n", address, port);
897 // Tell him we have an invitation, and give him our throw-away key.
898 int len = snprintf(line, sizeof line, "0 ?%s %d.%d\n", b64key, PROT_MAJOR, PROT_MINOR);
899 if(len <= 0 || len >= sizeof line)
902 if(!sendline(sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
903 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
908 char hisname[4096] = "";
909 int code, hismajor, hisminor = 0;
911 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) {
912 fprintf(stderr, "Cannot read greeting from peer\n");
917 // Check if the hash of the key he gave us matches the hash in the URL.
918 char *fingerprint = line + 2;
919 digest_t *digest = digest_open_by_name("sha256", 18);
923 if(!digest_create(digest, fingerprint, strlen(fingerprint), hishash)) {
924 fprintf(stderr, "Could not create digest\n%s\n", line + 2);
927 if(memcmp(hishash, hash, 18)) {
928 fprintf(stderr, "Peer has an invalid key!\n%s\n", line + 2);
933 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
937 // Start an SPTPS session
938 if(!sptps_start(&sptps, NULL, true, false, key, hiskey, "tinc invitation", 15, invitation_send, invitation_receive))
941 // Feed rest of input buffer to SPTPS
942 if(!sptps_receive_data(&sptps, buffer, blen))
945 while((len = recv(sock, line, sizeof line, 0))) {
949 fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
953 if(!sptps_receive_data(&sptps, line, len))
963 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
970 fprintf(stderr, "Invalid invitation URL.\n");