Add timeouts to 'tinc join'
[tinc] / src / invitation.c
1 /*
2     invitation.c -- Create and accept invitations
3     Copyright (C) 2013-2022 Guus Sliepen <guus@tinc-vpn.org>
4
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.
9
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.
14
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.
18 */
19
20 #include "system.h"
21
22 #include "control_common.h"
23 #include "crypto.h"
24 #include "ecdsa.h"
25 #include "ecdsagen.h"
26 #include "ifconfig.h"
27 #include "invitation.h"
28 #include "names.h"
29 #include "netutl.h"
30 #include "rsagen.h"
31 #include "script.h"
32 #include "sptps.h"
33 #include "subnet.h"
34 #include "tincctl.h"
35 #include "utils.h"
36 #include "xalloc.h"
37 #include "random.h"
38 #include "pidfile.h"
39 #include "fs.h"
40
41 #include "ed25519/sha512.h"
42
43 int addressfamily = AF_UNSPEC;
44
45 static void scan_for_hostname(const char *filename, char **hostname, char **port) {
46         if(!filename || (*hostname && *port)) {
47                 return;
48         }
49
50         FILE *f = fopen(filename, "r");
51
52         if(!f) {
53                 return;
54         }
55
56         while(fgets(line, sizeof(line), f)) {
57                 if(!rstrip(line)) {
58                         continue;
59                 }
60
61                 char *p = line, *q;
62                 p += strcspn(p, "\t =");
63
64                 if(!*p) {
65                         continue;
66                 }
67
68                 q = p + strspn(p, "\t ");
69
70                 if(*q == '=') {
71                         q += 1 + strspn(q + 1, "\t ");
72                 }
73
74                 *p = 0;
75                 p = q + strcspn(q, "\t ");
76
77                 if(*p) {
78                         *p++ = 0;
79                 }
80
81                 p += strspn(p, "\t ");
82                 p[strcspn(p, "\t ")] = 0;
83
84                 if(!*port && !strcasecmp(line, "Port")) {
85                         free(*port);
86                         *port = xstrdup(q);
87                 } else if(!*hostname && !strcasecmp(line, "Address")) {
88                         free(*hostname);
89                         *hostname = xstrdup(q);
90
91                         if(*p) {
92                                 free(*port);
93                                 *port = xstrdup(p);
94                         }
95                 }
96
97                 if(*hostname && *port) {
98                         break;
99                 }
100         }
101
102         fclose(f);
103 }
104
105 static bool get_my_hostname(char **out_address, char **out_port) {
106         char *hostname = NULL;
107         char *port = NULL;
108         char *hostport = NULL;
109         char *name = get_my_name(false);
110         char filename[PATH_MAX] = {0};
111
112         // Use first Address statement in own host config file
113         if(check_id(name)) {
114                 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", confbase, name);
115                 scan_for_hostname(filename, &hostname, &port);
116                 scan_for_hostname(tinc_conf, &hostname, &port);
117         }
118
119         free(name);
120         name = NULL;
121
122         if(!port || (is_decimal(port) && atoi(port) == 0)) {
123                 pidfile_t *pidfile = read_pidfile();
124
125                 if(pidfile) {
126                         free(port);
127                         port = xstrdup(pidfile->port);
128                         free(pidfile);
129                 } else {
130                         fprintf(stderr, "tincd is using a dynamic port and is not running. Please start tincd or set the Port option to a non-zero value.\n");
131                         goto exit;
132                 }
133         }
134
135         if(hostname) {
136                 goto done;
137         }
138
139         // If that doesn't work, guess externally visible hostname
140         fprintf(stderr, "Trying to discover externally visible hostname...\n");
141         struct addrinfo *ai = str2addrinfo("tinc-vpn.org", "80", SOCK_STREAM);
142         struct addrinfo *aip = ai;
143         static const char request[] = "GET http://tinc-vpn.org/host.cgi HTTP/1.0\r\n\r\n";
144
145         while(aip) {
146                 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
147
148                 if(s >= 0) {
149                         if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
150                                 closesocket(s);
151                                 s = -1;
152                         }
153                 }
154
155                 if(s >= 0) {
156                         send(s, request, sizeof(request) - 1, 0);
157                         ssize_t len = recv(s, line, sizeof(line) - 1, MSG_WAITALL);
158
159                         if(len > 0) {
160                                 line[len] = 0;
161
162                                 if(line[len - 1] == '\n') {
163                                         line[--len] = 0;
164                                 }
165
166                                 char *p = strrchr(line, '\n');
167
168                                 if(p && p[1]) {
169                                         hostname = xstrdup(p + 1);
170                                 }
171                         }
172
173                         closesocket(s);
174
175                         if(hostname) {
176                                 break;
177                         }
178                 }
179
180                 aip = aip->ai_next;
181                 continue;
182         }
183
184         if(ai) {
185                 freeaddrinfo(ai);
186         }
187
188         // Check that the hostname is reasonable
189         if(hostname) {
190                 for(char *p = hostname; *p; p++) {
191                         if(isalnum((uint8_t) *p) || *p == '-' || *p == '.' || *p == ':') {
192                                 continue;
193                         }
194
195                         // If not, forget it.
196                         free(hostname);
197                         hostname = NULL;
198                         break;
199                 }
200         }
201
202         if(!tty) {
203                 if(!hostname) {
204                         fprintf(stderr, "Could not determine the external address or hostname. Please set Address manually.\n");
205                         free(port);
206                         return false;
207                 }
208
209                 goto save;
210         }
211
212 again:
213         fprintf(stderr, "Please enter your host's external address or hostname");
214
215         if(hostname) {
216                 fprintf(stderr, " [%s]", hostname);
217         }
218
219         fprintf(stderr, ": ");
220
221         if(!fgets(line, sizeof(line), stdin)) {
222                 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
223                 free(hostname);
224                 free(port);
225                 return false;
226         }
227
228         if(!rstrip(line)) {
229                 if(hostname) {
230                         goto save;
231                 } else {
232                         goto again;
233                 }
234         }
235
236         for(char *p = line; *p; p++) {
237                 if(isalnum((uint8_t) *p) || *p == '-' || *p == '.') {
238                         continue;
239                 }
240
241                 fprintf(stderr, "Invalid address or hostname.\n");
242                 goto again;
243         }
244
245         free(hostname);
246         hostname = xstrdup(line);
247
248 save:
249
250         if(*filename) {
251                 FILE *f = fopen(filename, "a");
252
253                 if(f) {
254                         fprintf(f, "\nAddress = %s\n", hostname);
255                         fclose(f);
256                 } else {
257                         fprintf(stderr, "Could not append Address to %s: %s\n", filename, strerror(errno));
258                 }
259         }
260
261 done:
262
263         if(port) {
264                 if(strchr(hostname, ':')) {
265                         xasprintf(&hostport, "[%s]:%s", hostname, port);
266                 } else {
267                         xasprintf(&hostport, "%s:%s", hostname, port);
268                 }
269         } else {
270                 if(strchr(hostname, ':')) {
271                         xasprintf(&hostport, "[%s]", hostname);
272                 } else {
273                         hostport = xstrdup(hostname);
274                 }
275         }
276
277 exit:
278         free(hostname);
279
280         if(hostport && port) {
281                 *out_address = hostport;
282                 *out_port = port;
283                 return true;
284         }
285
286         free(hostport);
287         free(port);
288         return false;
289 }
290
291 // Copy host configuration file, replacing Port with the value passed here. Host
292 // configs may contain this clause: `Port = 0`, which means 'ask the operating
293 // system to allocate any available port'. This obviously won't do for invitation
294 // files, so replace it with an actual port we've obtained previously.
295 static bool copy_config_replacing_port(FILE *out, const char *filename, const char *port) {
296         FILE *in = fopen(filename, "r");
297
298         if(!in) {
299                 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
300                 return false;
301         }
302
303         char line[1024];
304
305         while(fgets(line, sizeof(line), in)) {
306                 const char *var_beg = line + strspn(line, "\t ");
307                 const char *var_end = var_beg + strcspn(var_beg, "\t ");
308
309                 // Check the name of the variable we've read. If it's Port, replace it with
310                 // a port we'll use in invitation URL. Otherwise, just copy the line.
311                 if(var_end > var_beg && !strncasecmp(var_beg, "Port", var_end - var_beg)) {
312                         fprintf(out, "Port = %s\n", port);
313                 } else {
314                         fprintf(out, "%s", line);
315                 }
316         }
317
318         memzero(line, sizeof(line));
319         fclose(in);
320         return true;
321 }
322
323 static bool append_host_config(FILE *f, const char *nodename, const char *port) {
324         char path[PATH_MAX];
325         snprintf(path, sizeof(path), "%s" SLASH "hosts" SLASH "%s", confbase, nodename);
326         bool success = copy_config_replacing_port(f, path, port);
327         fclose(f);
328         return success;
329 }
330
331 int cmd_invite(int argc, char *argv[]) {
332         if(argc < 2) {
333                 fprintf(stderr, "Not enough arguments!\n");
334                 return 1;
335         }
336
337         if(argc > 2) {
338                 fprintf(stderr, "Too many arguments!\n");
339                 return 1;
340         }
341
342         // Check validity of the new node's name
343         if(!check_id(argv[1])) {
344                 fprintf(stderr, "Invalid name for node.\n");
345                 return 1;
346         }
347
348         free(myname);
349         myname = get_my_name(true);
350
351         if(!myname) {
352                 return 1;
353         }
354
355         // Ensure no host configuration file with that name exists
356         char filename[PATH_MAX];
357         snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", confbase, argv[1]);
358
359         if(!access(filename, F_OK)) {
360                 fprintf(stderr, "A host config file for %s already exists!\n", argv[1]);
361                 return 1;
362         }
363
364         // If a daemon is running, ensure no other nodes know about this name
365         if(connect_tincd(false)) {
366                 bool found = false;
367                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
368
369                 while(recvline(fd, line, sizeof(line))) {
370                         char node[4096];
371                         int code, req;
372
373                         if(sscanf(line, "%d %d %4095s", &code, &req, node) != 3) {
374                                 break;
375                         }
376
377                         if(!strcmp(node, argv[1])) {
378                                 found = true;
379                         }
380                 }
381
382                 if(found) {
383                         fprintf(stderr, "A node with name %s is already known!\n", argv[1]);
384                         return 1;
385                 }
386         }
387
388         if(!makedirs(DIR_INVITATIONS)) {
389                 return false;
390         }
391
392         snprintf(filename, sizeof(filename), "%s" SLASH "invitations", confbase);
393
394         // Count the number of valid invitations, clean up old ones
395         DIR *dir = opendir(filename);
396
397         if(!dir) {
398                 fprintf(stderr, "Could not read directory %s: %s\n", filename, strerror(errno));
399                 return 1;
400         }
401
402         errno = 0;
403         int count = 0;
404         struct dirent *ent;
405         time_t deadline = time(NULL) - 604800; // 1 week in the past
406
407         while((ent = readdir(dir))) {
408                 if(strlen(ent->d_name) != 24) {
409                         continue;
410                 }
411
412                 char invname[PATH_MAX];
413                 struct stat st;
414
415                 if((size_t)snprintf(invname, sizeof(invname), "%s" SLASH "%s", filename, ent->d_name) >= sizeof(invname)) {
416                         fprintf(stderr, "Filename too long: %s" SLASH "%s\n", filename, ent->d_name);
417                         continue;
418                 }
419
420                 if(!stat(invname, &st)) {
421                         if(deadline < st.st_mtime) {
422                                 count++;
423                         } else {
424                                 unlink(invname);
425                         }
426                 } else {
427                         fprintf(stderr, "Could not stat %s: %s\n", invname, strerror(errno));
428                         errno = 0;
429                 }
430         }
431
432         closedir(dir);
433
434         if(errno) {
435                 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
436                 return 1;
437         }
438
439         ecdsa_t *key;
440         snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "ed25519_key.priv", confbase);
441
442         // Remove the key if there are no outstanding invitations.
443         if(!count) {
444                 unlink(filename);
445         }
446
447         // Create a new key if necessary.
448         FILE *f = fopen(filename, "r");
449
450         if(!f) {
451                 if(errno != ENOENT) {
452                         fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
453                         return 1;
454                 }
455
456                 key = ecdsa_generate();
457
458                 if(!key) {
459                         return 1;
460                 }
461
462                 f = fopen(filename, "w");
463
464                 if(!f) {
465                         fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
466                         ecdsa_free(key);
467                         return 1;
468                 }
469
470                 chmod(filename, 0600);
471
472                 if(!ecdsa_write_pem_private_key(key, f)) {
473                         fprintf(stderr, "Could not write ECDSA private key\n");
474                         fclose(f);
475                         ecdsa_free(key);
476                         return 1;
477                 }
478
479                 fclose(f);
480
481                 if(connect_tincd(true)) {
482                         sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
483                 } else {
484                         fprintf(stderr, "Could not signal the tinc daemon. Please restart or reload it manually.\n");
485                 }
486         } else {
487                 key = ecdsa_read_pem_private_key(f);
488                 fclose(f);
489
490                 if(!key) {
491                         fprintf(stderr, "Could not read private key from %s\n", filename);
492                 }
493         }
494
495         if(!key) {
496                 return 1;
497         }
498
499         // Create a hash of the key.
500         char hash[64];
501         char *fingerprint = ecdsa_get_base64_public_key(key);
502         sha512(fingerprint, strlen(fingerprint), hash);
503         b64encode_tinc_urlsafe(hash, hash, 18);
504
505         ecdsa_free(key);
506
507         // Create a random cookie for this invitation.
508         char cookie[25];
509         randomize(cookie, 18);
510
511         // Create a filename that doesn't reveal the cookie itself
512         const size_t buflen = 18 + strlen(fingerprint);
513         uint8_t *buf = alloca(buflen);
514
515         char cookiehash[64];
516         memcpy(buf, cookie, 18);
517         memcpy(buf + 18, fingerprint, buflen - 18);
518         sha512(buf, buflen, cookiehash);
519         b64encode_tinc_urlsafe(cookiehash, cookiehash, 18);
520
521         free(fingerprint);
522
523         b64encode_tinc_urlsafe(cookie, cookie, 18);
524
525         // Create a file containing the details of the invitation.
526         snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", confbase, cookiehash);
527         int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
528
529         if(!ifd) {
530                 memzero(cookie, sizeof(cookie));
531                 fprintf(stderr, "Could not create invitation file %s: %s\n", filename, strerror(errno));
532                 return 1;
533         }
534
535         f = fdopen(ifd, "w");
536
537         if(!f) {
538                 abort();
539         }
540
541         // Get the local address
542         char *address = NULL;
543         char *port = NULL;
544
545         if(!get_my_hostname(&address, &port)) {
546                 memzero(cookie, sizeof(cookie));
547                 return 1;
548         }
549
550         // Create an URL from the local address, key hash and cookie
551         char *url;
552         xasprintf(&url, "%s/%s%s", address, hash, cookie);
553
554         memzero(cookie, sizeof(cookie));
555         free(address);
556
557         // Fill in the details.
558         fprintf(f, "Name = %s\n", argv[1]);
559
560         if(check_netname(netname, true)) {
561                 fprintf(f, "NetName = %s\n", netname);
562         }
563
564         fprintf(f, "ConnectTo = %s\n", myname);
565
566         // Copy Broadcast and Mode
567         FILE *tc = fopen(tinc_conf, "r");
568
569         if(tc) {
570                 char buf[1024];
571
572                 while(fgets(buf, sizeof(buf), tc)) {
573                         if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
574                                         || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
575                                 fputs(buf, f);
576
577                                 // Make sure there is a newline character.
578                                 if(!strchr(buf, '\n')) {
579                                         fputc('\n', f);
580                                 }
581                         }
582                 }
583
584                 fclose(tc);
585         }
586
587         fprintf(f, "#---------------------------------------------------------------#\n");
588         fprintf(f, "Name = %s\n", myname);
589
590         bool appended = append_host_config(f, myname, port);
591         free(port);
592
593         if(!appended) {
594                 fprintf(stderr, "Could not append my config to invitation file: %s.\n", strerror(errno));
595                 free_string(url);
596                 return 1;
597         }
598
599         // Call the inviation-created script
600         environment_t env;
601         environment_init(&env);
602         environment_add(&env, "NODE=%s", argv[1]);
603         environment_add(&env, "INVITATION_FILE=%s", filename);
604         environment_add(&env, "INVITATION_URL=%s", url);
605         execute_script("invitation-created", &env);
606         environment_exit(&env);
607
608         puts(url);
609         free_string(url);
610
611         return 0;
612 }
613
614 static int sock;
615 static char cookie[18], hash[18];
616 static sptps_t sptps;
617 static char *data;
618 static size_t datalen;
619 static bool success = false;
620
621 static char *get_line(char *line, size_t linelen, const char **data) {
622         if(!data || !*data) {
623                 return NULL;
624         }
625
626         if(! **data) {
627                 *data = NULL;
628                 return NULL;
629         }
630
631         const char *end = strchr(*data, '\n');
632         size_t len = end ? (size_t)(end - *data) : strlen(*data);
633
634         if(len >= linelen) {
635                 fprintf(stderr, "Maximum line length exceeded!\n");
636                 return NULL;
637         }
638
639         if(len && !isprint((uint8_t) **data)) {
640                 abort();
641         }
642
643         memcpy(line, *data, len);
644         line[len] = 0;
645
646         if(end) {
647                 *data = end + 1;
648         } else {
649                 *data = NULL;
650         }
651
652         return line;
653 }
654
655 static char *get_value(const char *data, const char *var) {
656         static char buf[1024];
657
658         char *line = get_line(buf, sizeof(buf), &data);
659
660         if(!line) {
661                 return NULL;
662         }
663
664         char *sep = line + strcspn(line, " \t=");
665         char *val = sep + strspn(sep, " \t");
666
667         if(*val == '=') {
668                 val += 1 + strspn(val + 1, " \t");
669         }
670
671         *sep = 0;
672
673         if(strcasecmp(line, var)) {
674                 return NULL;
675         }
676
677         return val;
678 }
679
680 static char *grep(const char *data, const char *var) {
681         char value[1024];
682
683         const char *p = data;
684         size_t varlen = strlen(var);
685
686         // Skip all lines not starting with var
687         while(strncasecmp(p, var, varlen) || !strchr(" \t=", p[varlen])) {
688                 p = strchr(p, '\n');
689
690                 if(!p) {
691                         break;
692                 } else {
693                         p++;
694                 }
695         }
696
697         if(!p) {
698                 return NULL;
699         }
700
701         p += varlen;
702         p += strspn(p, " \t");
703
704         if(*p == '=') {
705                 p += 1 + strspn(p + 1, " \t");
706         }
707
708         const char *e = strchr(p, '\n');
709
710         if(!e) {
711                 return xstrdup(p);
712         }
713
714         if((size_t)(e - p) >= sizeof(value)) {
715                 fprintf(stderr, "Maximum line length exceeded!\n");
716                 return NULL;
717         }
718
719         memcpy(value, p, e - p);
720         value[e - p] = 0;
721         return xstrdup(value);
722 }
723
724 static bool finalize_join(void) {
725         const char *name = get_value(data, "Name");
726
727         if(!name) {
728                 fprintf(stderr, "No Name found in invitation!\n");
729                 return false;
730         }
731
732         if(!check_id(name)) {
733                 fprintf(stderr, "Invalid Name found in invitation!\n");
734                 return false;
735         }
736
737         if(!netname) {
738                 char *net = grep(data, "NetName");
739
740                 if(net) {
741                         netname = net;
742
743                         if(!check_netname(netname, true)) {
744                                 fprintf(stderr, "Unsafe NetName found in invitation!\n");
745                                 return false;
746                         }
747                 }
748         }
749
750         bool ask_netname = false;
751         char temp_netname[32];
752
753 make_names:
754
755         if(!confbasegiven) {
756                 free(confbase);
757                 confbase = NULL;
758         }
759
760         make_names(false);
761
762         free(tinc_conf);
763         free(hosts_dir);
764
765         xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
766         xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
767
768         if(!access(tinc_conf, F_OK)) {
769                 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
770
771                 if(confbasegiven) {
772                         return false;
773                 }
774
775                 // Generate a random netname, ask for a better one later.
776                 ask_netname = true;
777                 snprintf(temp_netname, sizeof(temp_netname), "join_%x", prng(UINT32_MAX));
778                 netname = temp_netname;
779                 goto make_names;
780         }
781
782         if(!makedirs(DIR_HOSTS | DIR_CONFBASE | DIR_CACHE)) {
783                 return false;
784         }
785
786         FILE *f = fopen(tinc_conf, "w");
787
788         if(!f) {
789                 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
790                 return false;
791         }
792
793         fprintf(f, "Name = %s\n", name);
794
795         char filename[PATH_MAX];
796         snprintf(filename, sizeof(filename), "%s" SLASH "%s", hosts_dir, name);
797         FILE *fh = fopen(filename, "w");
798
799         if(!fh) {
800                 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
801                 fclose(f);
802                 return false;
803         }
804
805         snprintf(filename, sizeof(filename), "%s" SLASH "invitation-data", confbase);
806         FILE *finv = fopen(filename, "w");
807
808         if(!finv || fwrite(data, datalen, 1, finv) != 1) {
809                 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
810                 fclose(fh);
811                 fclose(f);
812                 fclose(finv);
813                 return false;
814         }
815
816         fclose(finv);
817
818         snprintf(filename, sizeof(filename), "%s" SLASH "tinc-up.invitation", confbase);
819         FILE *fup = fopen(filename, "w");
820
821         if(!fup) {
822                 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
823                 fclose(f);
824                 fclose(fh);
825                 return false;
826         }
827
828         ifconfig_header(fup);
829
830         // Filter first chunk on approved keywords, split between tinc.conf and hosts/Name
831         // Generate a tinc-up script from Ifconfig and Route keywords.
832         // Other chunks go unfiltered to their respective host config files
833         const char *p = data;
834         char *l, *value;
835
836         static char line[1024];
837
838         while((l = get_line(line, sizeof(line), &p))) {
839                 // Ignore comments
840                 if(*l == '#') {
841                         continue;
842                 }
843
844                 // Split line into variable and value
845                 size_t len = strcspn(l, "\t =");
846                 value = l + len;
847                 value += strspn(value, "\t ");
848
849                 if(*value == '=') {
850                         value++;
851                         value += strspn(value, "\t ");
852                 }
853
854                 l[len] = 0;
855
856                 // Ignore lines with empty variable names
857                 if(!*l) {
858                         continue;
859                 }
860
861                 // Is it a Name?
862                 if(!strcasecmp(l, "Name")) {
863                         if(strcmp(value, name)) {
864                                 break;
865                         } else {
866                                 continue;
867                         }
868                 } else if(!strcasecmp(l, "NetName")) {
869                         continue;
870                 }
871
872                 // Check the list of known variables
873                 bool found = false;
874                 int i;
875
876                 for(i = 0; variables[i].name; i++) {
877                         if(strcasecmp(l, variables[i].name)) {
878                                 continue;
879                         }
880
881                         found = true;
882                         break;
883                 }
884
885                 // Handle Ifconfig and Route statements
886                 if(!found) {
887                         if(!strcasecmp(l, "Ifconfig")) {
888                                 if(!strcasecmp(value, "dhcp")) {
889                                         ifconfig_dhcp(fup);
890                                 } else if(!strcasecmp(value, "dhcp6")) {
891                                         ifconfig_dhcp6(fup);
892                                 } else if(!strcasecmp(value, "slaac")) {
893                                         ifconfig_slaac(fup);
894                                 } else {
895                                         ifconfig_address(fup, value);
896                                 }
897
898                                 continue;
899                         } else if(!strcasecmp(l, "Route")) {
900                                 ifconfig_route(fup, value);
901                                 continue;
902                         }
903                 }
904
905                 // Ignore unknown and unsafe variables
906                 if(!found) {
907                         fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
908                         continue;
909                 } else if(!(variables[i].type & VAR_SAFE)) {
910                         if(force) {
911                                 fprintf(stderr, "Warning: unsafe variable '%s' in invitation.\n", l);
912                         } else {
913                                 fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
914                                 continue;
915                         }
916                 }
917
918                 // Copy the safe variable to the right config file
919                 fprintf((variables[i].type & VAR_HOST) ? fh : f, "%s = %s\n", l, value);
920         }
921
922         fclose(f);
923         bool valid_tinc_up = ifconfig_footer(fup);
924         fclose(fup);
925
926         while(l && !strcasecmp(l, "Name")) {
927                 if(!check_id(value)) {
928                         fprintf(stderr, "Invalid Name found in invitation.\n");
929                         return false;
930                 }
931
932                 if(!strcmp(value, name)) {
933                         fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
934                         return false;
935                 }
936
937                 snprintf(filename, sizeof(filename), "%s" SLASH "%s", hosts_dir, value);
938                 f = fopen(filename, "w");
939
940                 if(!f) {
941                         fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
942                         return false;
943                 }
944
945                 while((l = get_line(line, sizeof(line), &p))) {
946                         if(!strcmp(l, "#---------------------------------------------------------------#")) {
947                                 continue;
948                         }
949
950                         size_t len = strcspn(l, "\t =");
951
952                         if(len == 4 && !strncasecmp(l, "Name", 4)) {
953                                 value = l + len;
954                                 value += strspn(value, "\t ");
955
956                                 if(*value == '=') {
957                                         value++;
958                                         value += strspn(value, "\t ");
959                                 }
960
961                                 l[len] = 0;
962                                 break;
963                         }
964
965                         fputs(l, f);
966                         fputc('\n', f);
967                 }
968
969                 fclose(f);
970         }
971
972         // Generate our key and send a copy to the server
973         ecdsa_t *key = ecdsa_generate();
974
975         if(!key) {
976                 return false;
977         }
978
979         char *b64_pubkey = ecdsa_get_base64_public_key(key);
980
981         if(!b64_pubkey) {
982                 return false;
983         }
984
985         snprintf(filename, sizeof(filename), "%s" SLASH "ed25519_key.priv", confbase);
986         f = fopenmask(filename, "w", 0600);
987
988         if(!f) {
989                 return false;
990         }
991
992         if(!ecdsa_write_pem_private_key(key, f)) {
993                 fprintf(stderr, "Error writing private key!\n");
994                 ecdsa_free(key);
995                 fclose(f);
996                 return false;
997         }
998
999         fclose(f);
1000
1001         fprintf(fh, "Ed25519PublicKey = %s\n", b64_pubkey);
1002
1003         sptps_send_record(&sptps, 1, b64_pubkey, strlen(b64_pubkey));
1004         free(b64_pubkey);
1005         ecdsa_free(key);
1006
1007 #ifndef DISABLE_LEGACY
1008         rsa_t *rsa = rsa_generate(2048, 0x1001);
1009         snprintf(filename, sizeof(filename), "%s" SLASH "rsa_key.priv", confbase);
1010         f = fopenmask(filename, "w", 0600);
1011
1012         if(!f || !rsa_write_pem_private_key(rsa, f)) {
1013                 fprintf(stderr, "Could not write private RSA key\n");
1014         } else if(!rsa_write_pem_public_key(rsa, fh)) {
1015                 fprintf(stderr, "Could not write public RSA key\n");
1016         }
1017
1018         fclose(f);
1019
1020         fclose(fh);
1021
1022         rsa_free(rsa);
1023 #endif
1024
1025         check_port(name);
1026
1027 ask_netname:
1028
1029         if(ask_netname && tty) {
1030                 fprintf(stderr, "Enter a new netname: ");
1031
1032                 if(!fgets(line, sizeof(line), stdin)) {
1033                         fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1034                         return false;
1035                 }
1036
1037                 if(!*line || *line == '\n') {
1038                         goto ask_netname;
1039                 }
1040
1041                 line[strlen(line) - 1] = 0;
1042
1043                 char newbase[PATH_MAX];
1044
1045                 if((size_t)snprintf(newbase, sizeof(newbase), CONFDIR SLASH "tinc" SLASH "%s", line) >= sizeof(newbase)) {
1046                         fprintf(stderr, "Filename too long: " CONFDIR SLASH "tinc" SLASH "%s\n", line);
1047                         goto ask_netname;
1048                 }
1049
1050                 if(rename(confbase, newbase)) {
1051                         fprintf(stderr, "Error trying to rename %s to %s: %s\n", confbase, newbase, strerror(errno));
1052                         goto ask_netname;
1053                 }
1054
1055                 netname = line;
1056                 make_names(false);
1057         }
1058
1059         char filename2[PATH_MAX];
1060         snprintf(filename, sizeof(filename), "%s" SLASH "tinc-up.invitation", confbase);
1061
1062 #ifdef HAVE_WINDOWS
1063         snprintf(filename2, sizeof(filename2), "%s" SLASH "tinc-up.bat", confbase);
1064 #else
1065         snprintf(filename2, sizeof(filename2), "%s" SLASH "tinc-up", confbase);
1066 #endif
1067
1068         if(valid_tinc_up) {
1069                 if(tty) {
1070                         FILE *fup = fopen(filename, "r");
1071
1072                         if(fup) {
1073                                 fprintf(stderr, "\nPlease review the following tinc-up script:\n\n");
1074
1075                                 char buf[MAXSIZE];
1076
1077                                 while(fgets(buf, sizeof(buf), fup)) {
1078                                         fputs(buf, stderr);
1079                                 }
1080
1081                                 fclose(fup);
1082
1083                                 int response = 0;
1084
1085                                 do {
1086                                         fprintf(stderr, "\nDo you want to use this script [y]es/[n]o/[e]dit? ");
1087                                         response = tolower(getchar());
1088                                 } while(!strchr("yne", response));
1089
1090                                 fprintf(stderr, "\n");
1091
1092                                 if(response == 'e') {
1093                                         char *command;
1094 #ifndef HAVE_WINDOWS
1095                                         const char *editor = getenv("VISUAL");
1096
1097                                         if(!editor) {
1098                                                 editor = getenv("EDITOR");
1099                                         }
1100
1101                                         if(!editor) {
1102                                                 editor = "vi";
1103                                         }
1104
1105                                         xasprintf(&command, "\"%s\" \"%s\"", editor, filename);
1106 #else
1107                                         xasprintf(&command, "edit \"%s\"", filename);
1108 #endif
1109
1110                                         if(system(command)) {
1111                                                 response = 'n';
1112                                         } else {
1113                                                 response = 'y';
1114                                         }
1115
1116                                         free(command);
1117                                 }
1118
1119                                 if(response == 'y') {
1120                                         rename(filename, filename2);
1121                                         chmod(filename2, 0755);
1122                                         fprintf(stderr, "tinc-up enabled.\n");
1123                                 } else {
1124                                         fprintf(stderr, "tinc-up has been left disabled.\n");
1125                                 }
1126                         }
1127                 } else {
1128                         if(force) {
1129                                 rename(filename, filename2);
1130                                 chmod(filename2, 0755);
1131                                 fprintf(stderr, "tinc-up enabled.\n");
1132                         } else {
1133                                 fprintf(stderr, "A tinc-up script was generated, but has been left disabled.\n");
1134                         }
1135                 }
1136         } else {
1137                 // A placeholder was generated.
1138                 rename(filename, filename2);
1139                 chmod(filename2, 0755);
1140         }
1141
1142         fprintf(stderr, "Configuration stored in: %s\n", confbase);
1143
1144         return true;
1145 }
1146
1147
1148 static bool invitation_send(void *handle, uint8_t type, const void *vdata, size_t len) {
1149         (void)handle;
1150         (void)type;
1151         const char *data = vdata;
1152
1153         while(len) {
1154                 ssize_t result = send(sock, data, len, 0);
1155
1156                 if(result == -1 && sockwouldblock(sockerrno)) {
1157                         continue;
1158                 } else if(result <= 0) {
1159                         return false;
1160                 }
1161
1162                 data += result;
1163                 len -= result;
1164         }
1165
1166         return true;
1167 }
1168
1169 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
1170         (void)handle;
1171
1172         switch(type) {
1173         case SPTPS_HANDSHAKE:
1174                 return sptps_send_record(&sptps, 0, cookie, sizeof(cookie));
1175
1176         case 0:
1177                 data = xrealloc(data, datalen + len + 1);
1178                 memcpy(data + datalen, msg, len);
1179                 datalen += len;
1180                 data[datalen] = 0;
1181                 break;
1182
1183         case 1:
1184                 return finalize_join();
1185
1186         case 2:
1187                 fprintf(stderr, "Invitation successfully accepted.\n");
1188                 shutdown(sock, SHUT_RDWR);
1189                 success = true;
1190                 break;
1191
1192         default:
1193                 return false;
1194         }
1195
1196         return true;
1197 }
1198
1199 bool wait_socket_recv(int fd) {
1200         fd_set fds;
1201         FD_ZERO(&fds);
1202         FD_SET(fd, &fds);
1203
1204         struct timeval tv = {.tv_sec = 5};
1205
1206         if(select(fd + 1, &fds, NULL, NULL, &tv) != 1) {
1207                 fprintf(stderr, "Timed out waiting for the server to reply.\n");
1208                 return false;
1209         }
1210
1211         return true;
1212 }
1213
1214 int cmd_join(int argc, char *argv[]) {
1215         free(data);
1216         data = NULL;
1217         datalen = 0;
1218
1219         if(argc > 2) {
1220                 fprintf(stderr, "Too many arguments!\n");
1221                 return 1;
1222         }
1223
1224         // Make sure confbase exists and is accessible.
1225         if(!makedirs(DIR_CONFDIR | DIR_CONFBASE)) {
1226                 return false;
1227         }
1228
1229         if(access(confbase, R_OK | W_OK | X_OK)) {
1230                 fprintf(stderr, "No permission to write in directory %s: %s\n", confbase, strerror(errno));
1231                 return 1;
1232         }
1233
1234         // If a netname or explicit configuration directory is specified, check for an existing tinc.conf.
1235         if((netname || confbasegiven) && !access(tinc_conf, F_OK)) {
1236                 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1237                 return 1;
1238         }
1239
1240         // Either read the invitation from the command line or from stdin.
1241         char *invitation;
1242
1243         if(argc > 1) {
1244                 invitation = argv[1];
1245         } else {
1246                 if(tty) {
1247                         fprintf(stderr, "Enter invitation URL: ");
1248                 }
1249
1250                 errno = EPIPE;
1251
1252                 if(!fgets(line, sizeof(line), stdin)) {
1253                         fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1254                         return 1;
1255                 }
1256
1257                 invitation = line;
1258         }
1259
1260         // Parse the invitation URL.
1261         rstrip(line);
1262
1263         char *slash = strchr(invitation, '/');
1264
1265         if(!slash) {
1266                 goto invalid;
1267         }
1268
1269         *slash++ = 0;
1270
1271         if(strlen(slash) != 48) {
1272                 goto invalid;
1273         }
1274
1275         char *address = invitation;
1276         char *port = NULL;
1277
1278         if(*address == '[') {
1279                 address++;
1280                 char *bracket = strchr(address, ']');
1281
1282                 if(!bracket) {
1283                         goto invalid;
1284                 }
1285
1286                 *bracket = 0;
1287
1288                 if(bracket[1] == ':') {
1289                         port = bracket + 2;
1290                 }
1291         } else {
1292                 port = strchr(address, ':');
1293
1294                 if(port) {
1295                         *port++ = 0;
1296                 }
1297         }
1298
1299         if(!port || !*port) {
1300                 static char default_port[] = "655";
1301                 port = default_port;
1302         }
1303
1304         if(!b64decode_tinc(slash, hash, 24) || !b64decode_tinc(slash + 24, cookie, 24)) {
1305                 goto invalid;
1306         }
1307
1308         // Generate a throw-away key for the invitation.
1309         ecdsa_t *key = ecdsa_generate();
1310
1311         if(!key) {
1312                 return 1;
1313         }
1314
1315         char *b64_pubkey = ecdsa_get_base64_public_key(key);
1316
1317         // Connect to the tinc daemon mentioned in the URL.
1318         struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1319
1320         if(!ai) {
1321                 free(b64_pubkey);
1322                 ecdsa_free(key);
1323                 return 1;
1324         }
1325
1326         struct addrinfo *aip = NULL;
1327
1328 next:
1329         if(!aip) {
1330                 aip = ai;
1331         } else {
1332                 aip = aip->ai_next;
1333
1334                 if(!aip) {
1335                         freeaddrinfo(ai);
1336                         free(b64_pubkey);
1337                         ecdsa_free(key);
1338                         fprintf(stderr, "Could not connect to inviter. Please make sure the URL you entered is valid.\n");
1339                         return 1;
1340                 }
1341         }
1342
1343         sock = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
1344
1345         if(sock <= 0) {
1346                 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
1347                 goto next;
1348         }
1349
1350         if(connect(sock, aip->ai_addr, aip->ai_addrlen)) {
1351                 char *addrstr, *portstr;
1352                 sockaddr2str((sockaddr_t *)aip->ai_addr, &addrstr, &portstr);
1353                 fprintf(stderr, "Could not connect to %s port %s: %s\n", addrstr, portstr, strerror(errno));
1354                 free(addrstr);
1355                 free(portstr);
1356                 closesocket(sock);
1357                 goto next;
1358         }
1359
1360         fprintf(stderr, "Connected to %s port %s...\n", address, port);
1361
1362         // Tell him we have an invitation, and give him our throw-away key.
1363         ssize_t len = snprintf(line, sizeof(line), "0 ?%s %d.%d\n", b64_pubkey, PROT_MAJOR, PROT_MINOR);
1364
1365         if(len <= 0 || (size_t)len >= sizeof(line)) {
1366                 abort();
1367         }
1368
1369         if(!sendline(sock, "0 ?%s %d.%d", b64_pubkey, PROT_MAJOR, 1)) {
1370                 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1371                 closesocket(sock);
1372                 goto next;
1373         }
1374
1375         char hisname[4096] = "";
1376         int code, hismajor, hisminor = 0;
1377
1378         if(!recvline(sock, line, sizeof(line)) || sscanf(line, "%d %4095s %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) {
1379                 fprintf(stderr, "Cannot read greeting from peer\n");
1380                 closesocket(sock);
1381                 goto next;
1382         }
1383
1384         freeaddrinfo(ai);
1385         ai = NULL;
1386         aip = NULL;
1387
1388         free(b64_pubkey);
1389         b64_pubkey = NULL;
1390
1391         // Check if the hash of the key he gave us matches the hash in the URL.
1392         char *fingerprint = line + 2;
1393         char hishash[64];
1394
1395         if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1396                 fprintf(stderr, "Could not create digest\n%s\n", line + 2);
1397                 ecdsa_free(key);
1398                 return 1;
1399         }
1400
1401         if(memcmp(hishash, hash, 18)) {
1402                 fprintf(stderr, "Peer has an invalid key. Please make sure you're using the correct URL.\n%s\n", line + 2);
1403                 ecdsa_free(key);
1404                 return 1;
1405
1406         }
1407
1408         ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1409
1410         if(!hiskey) {
1411                 ecdsa_free(key);
1412                 return 1;
1413         }
1414
1415         // Start an SPTPS session
1416         if(!sptps_start(&sptps, NULL, true, false, key, hiskey, "tinc invitation", 15, invitation_send, invitation_receive)) {
1417                 ecdsa_free(hiskey);
1418                 ecdsa_free(key);
1419                 return 1;
1420         }
1421
1422         // Feed rest of input buffer to SPTPS
1423         if(!sptps_receive_data(&sptps, buffer, blen)) {
1424                 success = false;
1425                 goto exit;
1426         }
1427
1428         while(wait_socket_recv(sock) && (len = recv(sock, line, sizeof(line), 0))) {
1429                 if(len < 0) {
1430                         if(sockwouldblock(sockerrno)) {
1431                                 continue;
1432                         }
1433
1434 #if HAVE_WINDOWS
1435
1436                         // If socket has been shut down, recv() on Windows returns -1 and sets sockerrno
1437                         // to WSAESHUTDOWN, while on UNIX-like operating systems recv() returns 0, so we
1438                         // have to do an explicit check here.
1439                         if(sockshutdown(sockerrno)) {
1440                                 break;
1441                         }
1442
1443 #endif
1444                         fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, sockstrerror(sockerrno));
1445                         success = false;
1446                         goto exit;
1447                 }
1448
1449                 char *p = line;
1450
1451                 while(len) {
1452                         size_t done = sptps_receive_data(&sptps, p, len);
1453
1454                         if(!done) {
1455                                 success = false;
1456                                 goto exit;
1457                         }
1458
1459                         len -= (ssize_t) done;
1460                         p += done;
1461                 }
1462         }
1463
1464 exit:
1465         sptps_stop(&sptps);
1466         ecdsa_free(hiskey);
1467         ecdsa_free(key);
1468         closesocket(sock);
1469
1470         if(!success) {
1471                 fprintf(stderr, "Invitation cancelled. Please try again and contact the inviter for assistance if this error persists.\n");
1472                 return 1;
1473         }
1474
1475         return 0;
1476
1477 invalid:
1478         fprintf(stderr, "Invalid invitation URL.\n");
1479         return 1;
1480 }