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