Move key generation to tincctl.
[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 <openssl/rand.h>
26 #include <openssl/rsa.h>
27 #include <openssl/pem.h>
28 #include <openssl/evp.h>
29 #include <openssl/engine.h>
30
31 #include <getopt.h>
32
33 #include "protocol.h"
34 #include "xalloc.h"
35
36 /* The name this program was run with. */
37 char *program_name = NULL;
38
39 /* If nonzero, display usage information and exit. */
40 bool show_help = false;
41
42 /* If nonzero, print the version on standard output and exit.  */
43 bool show_version = false;
44
45 /* If nonzero, it will attempt to kill a running tincd and exit. */
46 int kill_tincd = 0;
47
48 /* If nonzero, generate public/private keypair for this host/net. */
49 int generate_keys = 0;
50
51 static char *identname = NULL;                          /* program name for syslog */
52 static char *controlsocketname = NULL;                  /* pid file location */
53 char *netname = NULL;
54 char *confbase = NULL;
55
56 static struct option const long_options[] = {
57         {"config", required_argument, NULL, 'c'},
58         {"net", required_argument, NULL, 'n'},
59         {"help", no_argument, NULL, 1},
60         {"version", no_argument, NULL, 2},
61         {"controlsocket", required_argument, NULL, 5},
62         {NULL, 0, NULL, 0}
63 };
64
65 static void usage(bool status) {
66         if(status)
67                 fprintf(stderr, _("Try `%s --help\' for more information.\n"),
68                                 program_name);
69         else {
70                 printf(_("Usage: %s [options] command\n\n"), program_name);
71                 printf(_("Valid options are:\n"
72                                 "  -c, --config=DIR              Read configuration options from DIR.\n"
73                                 "  -n, --net=NETNAME             Connect to net NETNAME.\n"
74                                 "      --controlsocket=FILENAME  Open control socket at FILENAME.\n"
75                                 "      --help                    Display this help and exit.\n"
76                                 "      --version                 Output version information and exit.\n"
77                                 "\n"
78                                 "Valid commands are:\n"
79                                 "  start                      Start tincd.\n"
80                                 "  stop                       Stop tincd.\n"
81                                 "  restart                    Restart tincd.\n"
82                                 "  reload                     Reload configuration of running tincd.\n"
83                                 "  generate-keys [bits]       Generate a new public/private keypair.\n"
84                                 "  dump                       Dump a list of one of the following things:\n"
85                                 "    nodes                    - all known nodes in the VPN\n"
86                                 "    edges                    - all known connections in the VPN\n"
87                                 "    subnets                  - all known subnets in the VPN\n"
88                                 "    connections              - all meta connections with ourself\n"
89                                 "    graph                    - graph of the VPN in dotty format\n"
90                                 "\n"));
91                 printf(_("Report bugs to tinc@tinc-vpn.org.\n"));
92         }
93 }
94
95 static bool parse_options(int argc, char **argv) {
96         int r;
97         int option_index = 0;
98
99         while((r = getopt_long(argc, argv, "c:n:", long_options, &option_index)) != EOF) {
100                 switch (r) {
101                         case 0:                         /* long option */
102                                 break;
103
104                         case 'c':                               /* config file */
105                                 confbase = xstrdup(optarg);
106                                 break;
107
108                         case 'n':                               /* net name given */
109                                 netname = xstrdup(optarg);
110                                 break;
111
112                         case 1:                                 /* show help */
113                                 show_help = true;
114                                 break;
115
116                         case 2:                                 /* show version */
117                                 show_version = true;
118                                 break;
119
120                         case 5:                                 /* open control socket here */
121                                 controlsocketname = xstrdup(optarg);
122                                 break;
123
124                         case '?':
125                                 usage(true);
126                                 return false;
127
128                         default:
129                                 break;
130                 }
131         }
132
133         return true;
134 }
135
136 FILE *ask_and_open(const char *filename, const char *what, const char *mode) {
137         FILE *r;
138         char *directory;
139         char buf[PATH_MAX];
140         char buf2[PATH_MAX];
141         size_t len;
142
143         /* Check stdin and stdout */
144         if(isatty(0) && isatty(1)) {
145                 /* Ask for a file and/or directory name. */
146                 fprintf(stdout, _("Please enter a file to save %s to [%s]: "),
147                                 what, filename);
148                 fflush(stdout);
149
150                 if(fgets(buf, sizeof buf, stdin) < 0) {
151                         fprintf(stderr, _("Error while reading stdin: %s\n"),
152                                         strerror(errno));
153                         return NULL;
154                 }
155
156                 len = strlen(buf);
157                 if(len)
158                         buf[--len] = 0;
159
160                 if(len)
161                         filename = buf;
162         }
163
164 #ifdef HAVE_MINGW
165         if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
166 #else
167         if(filename[0] != '/') {
168 #endif
169                 /* The directory is a relative path or a filename. */
170                 directory = get_current_dir_name();
171                 snprintf(buf2, sizeof buf2, "%s/%s", directory, filename);
172                 filename = buf2;
173         }
174
175         umask(0077);                            /* Disallow everything for group and other */
176
177         /* Open it first to keep the inode busy */
178
179         r = fopen(filename, mode);
180
181         if(!r) {
182                 fprintf(stderr, _("Error opening file `%s': %s\n"), filename, strerror(errno));
183                 return NULL;
184         }
185
186         return r;
187 }
188
189 /* This function prettyprints the key generation process */
190
191 static void indicator(int a, int b, void *p) {
192         switch (a) {
193                 case 0:
194                         fprintf(stderr, ".");
195                         break;
196
197                 case 1:
198                         fprintf(stderr, "+");
199                         break;
200
201                 case 2:
202                         fprintf(stderr, "-");
203                         break;
204
205                 case 3:
206                         switch (b) {
207                                 case 0:
208                                         fprintf(stderr, " p\n");
209                                         break;
210
211                                 case 1:
212                                         fprintf(stderr, " q\n");
213                                         break;
214
215                                 default:
216                                         fprintf(stderr, "?");
217                         }
218                         break;
219
220                 default:
221                         fprintf(stderr, "?");
222         }
223 }
224
225 /*
226   Generate a public/private RSA keypair, and ask for a file to store
227   them in.
228 */
229 static bool keygen(int bits) {
230         RSA *rsa_key;
231         FILE *f;
232         char *name = NULL;
233         char *filename;
234
235         fprintf(stderr, _("Generating %d bits keys:\n"), bits);
236         rsa_key = RSA_generate_key(bits, 0x10001, indicator, NULL);
237
238         if(!rsa_key) {
239                 fprintf(stderr, _("Error during key generation!\n"));
240                 return false;
241         } else
242                 fprintf(stderr, _("Done.\n"));
243
244         asprintf(&filename, "%s/rsa_key.priv", confbase);
245         f = ask_and_open(filename, _("private RSA key"), "a");
246
247         if(!f)
248                 return false;
249   
250 #ifdef HAVE_FCHMOD
251         /* Make it unreadable for others. */
252         fchmod(fileno(f), 0600);
253 #endif
254                 
255         if(ftell(f))
256                 fprintf(stderr, _("Appending key to existing contents.\nMake sure only one key is stored in the file.\n"));
257
258         PEM_write_RSAPrivateKey(f, rsa_key, NULL, NULL, 0, NULL, NULL);
259         fclose(f);
260         free(filename);
261
262         if(name)
263                 asprintf(&filename, "%s/hosts/%s", confbase, name);
264         else
265                 asprintf(&filename, "%s/rsa_key.pub", confbase);
266
267         f = ask_and_open(filename, _("public RSA key"), "a");
268
269         if(!f)
270                 return false;
271
272         if(ftell(f))
273                 fprintf(stderr, _("Appending key to existing contents.\nMake sure only one key is stored in the file.\n"));
274
275         PEM_write_RSAPublicKey(f, rsa_key);
276         fclose(f);
277         free(filename);
278
279         return true;
280 }
281
282 /*
283   Set all files and paths according to netname
284 */
285 static void make_names(void) {
286 #ifdef HAVE_MINGW
287         HKEY key;
288         char installdir[1024] = "";
289         long len = sizeof(installdir);
290 #endif
291
292         if(netname)
293                 asprintf(&identname, "tinc.%s", netname);
294         else
295                 identname = xstrdup("tinc");
296
297 #ifdef HAVE_MINGW
298         if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
299                 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
300                         if(!logfilename)
301                                 asprintf(&logfilename, "%s/log/%s.log", identname);
302                         if(!confbase) {
303                                 if(netname)
304                                         asprintf(&confbase, "%s/%s", installdir, netname);
305                                 else
306                                         asprintf(&confbase, "%s", installdir);
307                         }
308                 }
309                 RegCloseKey(key);
310                 if(*installdir)
311                         return;
312         }
313 #endif
314
315         if(!controlsocketname)
316                 asprintf(&controlsocketname, LOCALSTATEDIR "/run/%s.control", identname);
317
318         if(netname) {
319                 if(!confbase)
320                         asprintf(&confbase, CONFDIR "/tinc/%s", netname);
321                 else
322                         fprintf(stderr, _("Both netname and configuration directory given, using the latter...\n"));
323         } else {
324                 if(!confbase)
325                         asprintf(&confbase, CONFDIR "/tinc");
326         }
327 }
328
329 int main(int argc, char **argv) {
330         int fd;
331         struct sockaddr_un addr;
332         program_name = argv[0];
333
334         setlocale(LC_ALL, "");
335         bindtextdomain(PACKAGE, LOCALEDIR);
336         textdomain(PACKAGE);
337
338         if(!parse_options(argc, argv))
339                 return 1;
340         
341         make_names();
342
343         if(show_version) {
344                 printf(_("%s version %s (built %s %s, protocol %d)\n"), PACKAGE,
345                            VERSION, __DATE__, __TIME__, PROT_CURRENT);
346                 printf(_("Copyright (C) 1998-2007 Ivo Timmermans, Guus Sliepen and others.\n"
347                                 "See the AUTHORS file for a complete list.\n\n"
348                                 "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
349                                 "and you are welcome to redistribute it under certain conditions;\n"
350                                 "see the file COPYING for details.\n"));
351
352                 return 0;
353         }
354
355         if(show_help) {
356                 usage(false);
357                 return 0;
358         }
359
360         if(optind >= argc) {
361                 fprintf(stderr, _("Not enough arguments.\n"));
362                 usage(true);
363                 return 1;
364         }
365
366         if(!strcasecmp(argv[optind], "generate-keys")) {
367                 return !keygen(optind > argc ? atoi(argv[optind + 1]) : 1024);
368         }
369
370         if(strlen(controlsocketname) >= sizeof addr.sun_path) {
371                 fprintf(stderr, _("Control socket filename too long!\n"));
372                 return 1;
373         }
374
375         fd = socket(PF_UNIX, SOCK_STREAM, 0);
376         if(fd < 0) {
377                 fprintf(stderr, _("Cannot create UNIX socket: %s\n"), strerror(errno));
378                 return 1;
379         }
380
381         memset(&addr, 0, sizeof addr);
382         addr.sun_family = AF_UNIX;
383         strncpy(addr.sun_path, controlsocketname, sizeof addr.sun_path - 1);
384
385         if(connect(fd, (struct sockaddr *)&addr, sizeof addr) < 0) {
386                 fprintf(stderr, _("Cannot connect to %s: %s\n"), controlsocketname, strerror(errno));
387                 return 1;
388         }
389
390         printf("Connected to %s.\n", controlsocketname);
391
392         close(fd);
393
394         return 0;
395 }