Move RSA key generation into the wrappers.
[tinc] / src / tincctl.c
1 /*
2     tincctl.c -- Controlling a running tincd
3     Copyright (C) 2007 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
16     along with this program; if not, write to the Free Software
17     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
19     $Id$
20 */
21
22 #include "system.h"
23
24 #include <sys/un.h>
25 #include <getopt.h>
26
27 #include "xalloc.h"
28 #include "protocol.h"
29 #include "control_common.h"
30 #include "rsagen.h"
31
32 /* The name this program was run with. */
33 char *program_name = NULL;
34
35 /* If nonzero, display usage information and exit. */
36 bool show_help = false;
37
38 /* If nonzero, print the version on standard output and exit.  */
39 bool show_version = false;
40
41 /* If nonzero, it will attempt to kill a running tincd and exit. */
42 int kill_tincd = 0;
43
44 /* If nonzero, generate public/private keypair for this host/net. */
45 int generate_keys = 0;
46
47 static char *identname = NULL;                          /* program name for syslog */
48 static char *controlsocketname = NULL;                  /* pid file location */
49 char *netname = NULL;
50 char *confbase = NULL;
51
52 static struct option const long_options[] = {
53         {"config", required_argument, NULL, 'c'},
54         {"net", required_argument, NULL, 'n'},
55         {"help", no_argument, NULL, 1},
56         {"version", no_argument, NULL, 2},
57         {"controlsocket", required_argument, NULL, 5},
58         {NULL, 0, NULL, 0}
59 };
60
61 static void usage(bool status) {
62         if(status)
63                 fprintf(stderr, _("Try `%s --help\' for more information.\n"),
64                                 program_name);
65         else {
66                 printf(_("Usage: %s [options] command\n\n"), program_name);
67                 printf(_("Valid options are:\n"
68                                 "  -c, --config=DIR              Read configuration options from DIR.\n"
69                                 "  -n, --net=NETNAME             Connect to net NETNAME.\n"
70                                 "      --controlsocket=FILENAME  Open control socket at FILENAME.\n"
71                                 "      --help                    Display this help and exit.\n"
72                                 "      --version                 Output version information and exit.\n"
73                                 "\n"
74                                 "Valid commands are:\n"
75                                 "  start                      Start tincd.\n"
76                                 "  stop                       Stop tincd.\n"
77                                 "  restart                    Restart tincd.\n"
78                                 "  reload                     Reload configuration of running tincd.\n"
79                                 "  pid                        Show PID of currently running tincd.\n"
80                                 "  generate-keys [bits]       Generate a new public/private keypair.\n"
81                                 "  dump                       Dump a list of one of the following things:\n"
82                                 "    nodes                    - all known nodes in the VPN\n"
83                                 "    edges                    - all known connections in the VPN\n"
84                                 "    subnets                  - all known subnets in the VPN\n"
85                                 "    connections              - all meta connections with ourself\n"
86                                 "    graph                    - graph of the VPN in dotty format\n"
87                                 "  purge                      Purge unreachable nodes\n"
88                                 "  debug N                    Set debug level\n"
89                                 "  retry                      Retry all outgoing connections\n"
90                                 "  reload                     Partial reload of configuration\n"
91                                 "\n"));
92                 printf(_("Report bugs to tinc@tinc-vpn.org.\n"));
93         }
94 }
95
96 static bool parse_options(int argc, char **argv) {
97         int r;
98         int option_index = 0;
99
100         while((r = getopt_long(argc, argv, "c:n:", long_options, &option_index)) != EOF) {
101                 switch (r) {
102                         case 0:                         /* long option */
103                                 break;
104
105                         case 'c':                               /* config file */
106                                 confbase = xstrdup(optarg);
107                                 break;
108
109                         case 'n':                               /* net name given */
110                                 netname = xstrdup(optarg);
111                                 break;
112
113                         case 1:                                 /* show help */
114                                 show_help = true;
115                                 break;
116
117                         case 2:                                 /* show version */
118                                 show_version = true;
119                                 break;
120
121                         case 5:                                 /* open control socket here */
122                                 controlsocketname = xstrdup(optarg);
123                                 break;
124
125                         case '?':
126                                 usage(true);
127                                 return false;
128
129                         default:
130                                 break;
131                 }
132         }
133
134         return true;
135 }
136
137 FILE *ask_and_open(const char *filename, const char *what, const char *mode) {
138         FILE *r;
139         char *directory;
140         char buf[PATH_MAX];
141         char buf2[PATH_MAX];
142         size_t len;
143
144         /* Check stdin and stdout */
145         if(isatty(0) && isatty(1)) {
146                 /* Ask for a file and/or directory name. */
147                 fprintf(stdout, _("Please enter a file to save %s to [%s]: "),
148                                 what, filename);
149                 fflush(stdout);
150
151                 if(fgets(buf, sizeof buf, stdin) < 0) {
152                         fprintf(stderr, _("Error while reading stdin: %s\n"),
153                                         strerror(errno));
154                         return NULL;
155                 }
156
157                 len = strlen(buf);
158                 if(len)
159                         buf[--len] = 0;
160
161                 if(len)
162                         filename = buf;
163         }
164
165 #ifdef HAVE_MINGW
166         if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
167 #else
168         if(filename[0] != '/') {
169 #endif
170                 /* The directory is a relative path or a filename. */
171                 directory = get_current_dir_name();
172                 snprintf(buf2, sizeof buf2, "%s/%s", directory, filename);
173                 filename = buf2;
174         }
175
176         umask(0077);                            /* Disallow everything for group and other */
177
178         /* Open it first to keep the inode busy */
179
180         r = fopen(filename, mode);
181
182         if(!r) {
183                 fprintf(stderr, _("Error opening file `%s': %s\n"), filename, strerror(errno));
184                 return NULL;
185         }
186
187         return r;
188 }
189
190 /*
191   Generate a public/private RSA keypair, and ask for a file to store
192   them in.
193 */
194 static bool keygen(int bits) {
195         rsa_t key;
196         FILE *f;
197         char *name = NULL;
198         char *filename;
199
200         fprintf(stderr, _("Generating %d bits keys:\n"), bits);
201
202         if(!rsa_generate(&key, bits, 0x10001)) {
203                 fprintf(stderr, _("Error during key generation!\n"));
204                 return false;
205         } else
206                 fprintf(stderr, _("Done.\n"));
207
208         asprintf(&filename, "%s/rsa_key.priv", confbase);
209         f = ask_and_open(filename, _("private RSA key"), "a");
210
211         if(!f)
212                 return false;
213   
214 #ifdef HAVE_FCHMOD
215         /* Make it unreadable for others. */
216         fchmod(fileno(f), 0600);
217 #endif
218                 
219         if(ftell(f))
220                 fprintf(stderr, _("Appending key to existing contents.\nMake sure only one key is stored in the file.\n"));
221
222         rsa_write_pem_private_key(&key, f);
223
224         fclose(f);
225         free(filename);
226
227         if(name)
228                 asprintf(&filename, "%s/hosts/%s", confbase, name);
229         else
230                 asprintf(&filename, "%s/rsa_key.pub", confbase);
231
232         f = ask_and_open(filename, _("public RSA key"), "a");
233
234         if(!f)
235                 return false;
236
237         if(ftell(f))
238                 fprintf(stderr, _("Appending key to existing contents.\nMake sure only one key is stored in the file.\n"));
239
240         rsa_write_pem_public_key(&key, f);
241
242         fclose(f);
243         free(filename);
244
245         return true;
246 }
247
248 /*
249   Set all files and paths according to netname
250 */
251 static void make_names(void) {
252 #ifdef HAVE_MINGW
253         HKEY key;
254         char installdir[1024] = "";
255         long len = sizeof installdir;
256 #endif
257
258         if(netname)
259                 asprintf(&identname, "tinc.%s", netname);
260         else
261                 identname = xstrdup("tinc");
262
263 #ifdef HAVE_MINGW
264         if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
265                 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
266                         if(!logfilename)
267                                 asprintf(&logfilename, "%s/log/%s.log", identname);
268                         if(!confbase) {
269                                 if(netname)
270                                         asprintf(&confbase, "%s/%s", installdir, netname);
271                                 else
272                                         asprintf(&confbase, "%s", installdir);
273                         }
274                 }
275                 RegCloseKey(key);
276                 if(*installdir)
277                         return;
278         }
279 #endif
280
281         if(!controlsocketname)
282                 asprintf(&controlsocketname, "%s/run/%s.control/socket", LOCALSTATEDIR, identname);
283
284         if(netname) {
285                 if(!confbase)
286                         asprintf(&confbase, CONFDIR "/tinc/%s", netname);
287                 else
288                         fprintf(stderr, _("Both netname and configuration directory given, using the latter...\n"));
289         } else {
290                 if(!confbase)
291                         asprintf(&confbase, CONFDIR "/tinc");
292         }
293 }
294
295 static int fullread(int fd, void *data, size_t datalen) {
296         int rv, len = 0;
297
298         while(len < datalen) {
299                 rv = read(fd, data + len, datalen - len);
300                 if(rv == -1 && errno == EINTR)
301                         continue;
302                 else if(rv == -1)
303                         return rv;
304                 else if(rv == 0) {
305                         errno = ENODATA;
306                         return -1;
307                 }
308                 len += rv;
309         }
310         return 0;
311 }
312
313 /*
314    Send a request (raw)
315 */
316 static int send_ctl_request(int fd, enum request_type type,
317                                                    void const *outdata, size_t outdatalen,
318                                                    int *res_errno_p, void **indata_p,
319                                                    size_t *indatalen_p) {
320         tinc_ctl_request_t req;
321         int rv;
322         struct iovec vector[2] = {
323                 {&req, sizeof req},
324                 {(void*) outdata, outdatalen}
325         };
326         void *indata;
327
328         if(res_errno_p == NULL)
329                 return -1;
330
331         memset(&req, 0, sizeof req);
332         req.length = sizeof req + outdatalen;
333         req.type = type;
334         req.res_errno = 0;
335
336         while((rv = writev(fd, vector, 2)) == -1 && errno == EINTR) ;
337         if(rv != req.length)
338                 return -1;
339
340         if(fullread(fd, &req, sizeof req) == -1)
341                 return -1;
342
343         if(req.length < sizeof req) {
344                 errno = EINVAL;
345                 return -1;
346         }
347
348         if(req.length > sizeof req) {
349                 if(indata_p == NULL) {
350                         errno = EINVAL;
351                         return -1;
352                 }
353
354                 indata = xmalloc(req.length - sizeof req);
355
356                 if(fullread(fd, indata, req.length - sizeof req) == -1) {
357                         free(indata);
358                         return -1;
359                 }
360
361                 *indata_p = indata;
362                 if(indatalen_p != NULL)
363                         *indatalen_p = req.length - sizeof req;
364         }
365
366         *res_errno_p = req.res_errno;
367
368         return 0;
369 }
370
371 /*
372    Send a request (with printfs)
373 */
374 static int send_ctl_request_cooked(int fd, enum request_type type,
375                                                                    void const *outdata, size_t outdatalen)
376 {
377         int res_errno = -1;
378         char *buf = NULL;
379         size_t buflen = 0;
380
381         if(send_ctl_request(fd, type, outdata, outdatalen, &res_errno,
382                                                 (void**) &buf, &buflen)) {
383                 fprintf(stderr, _("Error sending request: %s\n"), strerror(errno));
384                 return -1;
385         }
386
387         if(buf != NULL) {
388                 printf("%*s", (int)buflen, buf);
389                 free(buf);
390         }
391
392         if(res_errno != 0) {
393                 fprintf(stderr, _("Server reported error: %s\n"), strerror(res_errno));
394                 return -1;
395         }
396
397         return 0;
398 }
399
400 int main(int argc, char *argv[], char *envp[]) {
401         struct sockaddr_un addr;
402         tinc_ctl_greeting_t greeting;
403         int fd;
404         int result;
405
406         program_name = argv[0];
407
408         setlocale(LC_ALL, "");
409         bindtextdomain(PACKAGE, LOCALEDIR);
410         textdomain(PACKAGE);
411
412         if(!parse_options(argc, argv))
413                 return 1;
414         
415         make_names();
416
417         if(show_version) {
418                 printf(_("%s version %s (built %s %s, protocol %d)\n"), PACKAGE,
419                            VERSION, __DATE__, __TIME__, PROT_CURRENT);
420                 printf(_("Copyright (C) 1998-2007 Ivo Timmermans, Guus Sliepen and others.\n"
421                                 "See the AUTHORS file for a complete list.\n\n"
422                                 "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
423                                 "and you are welcome to redistribute it under certain conditions;\n"
424                                 "see the file COPYING for details.\n"));
425
426                 return 0;
427         }
428
429         if(show_help) {
430                 usage(false);
431                 return 0;
432         }
433
434         if(optind >= argc) {
435                 fprintf(stderr, _("Not enough arguments.\n"));
436                 usage(true);
437                 return 1;
438         }
439
440         // First handle commands that don't involve connecting to a running tinc daemon.
441
442         if(!strcasecmp(argv[optind], "generate-keys")) {
443                 return !keygen(optind > argc ? atoi(argv[optind + 1]) : 1024);
444         }
445
446         if(!strcasecmp(argv[optind], "start")) {
447                 argv[optind] = NULL;
448                 execve(SBINDIR "/tincd", argv, envp);
449                 fprintf(stderr, _("Could not start tincd: %s"), strerror(errno));
450                 return 1;
451         }
452
453         /*
454          * Now handle commands that do involve connecting to a running tinc daemon.
455          * Authenticate the server by ensuring the parent directory can be
456          * traversed only by root. Note this is not totally race-free unless all
457          * ancestors are writable only by trusted users, which we don't verify.
458          */
459
460         struct stat statbuf;
461         char *lastslash = strrchr(controlsocketname, '/');
462         if(lastslash != NULL) {
463                 /* control socket is not in cwd; stat its parent */
464                 *lastslash = 0;
465                 result = stat(controlsocketname, &statbuf);
466                 *lastslash = '/';
467         } else
468                 result = stat(".", &statbuf);
469
470         if(result < 0) {
471                 fprintf(stderr, _("Unable to check control socket directory permissions: %s\n"), strerror(errno));
472                 return 1;
473         }
474
475         if(statbuf.st_uid != 0 || (statbuf.st_mode & S_IXOTH) != 0 || (statbuf.st_gid != 0 && (statbuf.st_mode & S_IXGRP)) != 0) {
476                 fprintf(stderr, _("Insecure permissions on control socket directory\n"));
477                 return 1;
478         }
479
480         if(strlen(controlsocketname) >= sizeof addr.sun_path) {
481                 fprintf(stderr, _("Control socket filename too long!\n"));
482                 return 1;
483         }
484
485         fd = socket(PF_UNIX, SOCK_STREAM, 0);
486         if(fd < 0) {
487                 fprintf(stderr, _("Cannot create UNIX socket: %s\n"), strerror(errno));
488                 return 1;
489         }
490
491         memset(&addr, 0, sizeof addr);
492         addr.sun_family = AF_UNIX;
493         strncpy(addr.sun_path, controlsocketname, sizeof addr.sun_path - 1);
494
495         if(connect(fd, (struct sockaddr *)&addr, sizeof addr) < 0) {
496                 fprintf(stderr, _("Cannot connect to %s: %s\n"), controlsocketname, strerror(errno));
497                 return 1;
498         }
499
500         if(fullread(fd, &greeting, sizeof greeting) == -1) {
501                 fprintf(stderr, _("Cannot read greeting from control socket: %s\n"),
502                                 strerror(errno));
503                 return 1;
504         }
505
506         if(greeting.version != TINC_CTL_VERSION_CURRENT) {
507                 fprintf(stderr, _("Version mismatch: server %d, client %d\n"),
508                                 greeting.version, TINC_CTL_VERSION_CURRENT);
509                 return 1;
510         }
511
512         if(!strcasecmp(argv[optind], "pid")) {
513                 printf("%d\n", greeting.pid);
514                 return 0;
515         }
516
517         if(!strcasecmp(argv[optind], "stop")) {
518                 return send_ctl_request_cooked(fd, REQ_STOP, NULL, 0) != -1;
519         }
520
521         if(!strcasecmp(argv[optind], "reload")) {
522                 return send_ctl_request_cooked(fd, REQ_RELOAD, NULL, 0) != -1;
523         }
524         
525         if(!strcasecmp(argv[optind], "restart")) {
526                 return send_ctl_request_cooked(fd, REQ_RESTART, NULL, 0) != -1;
527         }
528
529         if(!strcasecmp(argv[optind], "dump")) {
530                 if(argc < optind + 2) {
531                         fprintf(stderr, _("Not enough arguments.\n"));
532                         usage(true);
533                         return 1;
534                 }
535
536                 if(!strcasecmp(argv[optind+1], "nodes")) {
537                         return send_ctl_request_cooked(fd, REQ_DUMP_NODES, NULL, 0) != -1;
538                 }
539
540                 if(!strcasecmp(argv[optind+1], "edges")) {
541                         return send_ctl_request_cooked(fd, REQ_DUMP_EDGES, NULL, 0) != -1;
542                 }
543
544                 if(!strcasecmp(argv[optind+1], "subnets")) {
545                         return send_ctl_request_cooked(fd, REQ_DUMP_SUBNETS, NULL, 0) != -1;
546                 }
547
548                 if(!strcasecmp(argv[optind+1], "connections")) {
549                         return send_ctl_request_cooked(fd, REQ_DUMP_CONNECTIONS, NULL, 0) != -1;
550                 }
551
552                 if(!strcasecmp(argv[optind+1], "graph")) {
553                         return send_ctl_request_cooked(fd, REQ_DUMP_GRAPH, NULL, 0) != -1;
554                 }
555
556                 fprintf(stderr, _("Unknown dump type '%s'.\n"), argv[optind+1]);
557                 usage(true);
558                 return 1;
559         }
560
561         if(!strcasecmp(argv[optind], "purge")) {
562                 return send_ctl_request_cooked(fd, REQ_PURGE, NULL, 0) != -1;
563         }
564
565         if(!strcasecmp(argv[optind], "debug")) {
566                 int debuglevel;
567
568                 if(argc != optind + 2) {
569                         fprintf(stderr, "Invalid arguments.\n");
570                         return 1;
571                 }
572                 debuglevel = atoi(argv[optind+1]);
573                 return send_ctl_request_cooked(fd, REQ_SET_DEBUG, &debuglevel,
574                                                                            sizeof debuglevel) != -1;
575         }
576
577         if(!strcasecmp(argv[optind], "retry")) {
578                 return send_ctl_request_cooked(fd, REQ_RETRY, NULL, 0) != -1;
579         }
580
581         if(!strcasecmp(argv[optind], "reload")) {
582                 return send_ctl_request_cooked(fd, REQ_RELOAD, NULL, 0) != -1;
583         }
584
585         fprintf(stderr, _("Unknown command `%s'.\n"), argv[optind]);
586         usage(true);
587         
588         close(fd);
589
590         return 0;
591 }