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