Implement privilege dropping
[oweals/tinc.git] / src / tincd.c
1 /*
2     tincd.c -- the main file for tincd
3     Copyright (C) 1998-2005 Ivo Timmermans
4                   2000-2009 Guus Sliepen <guus@tinc-vpn.org>
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20     $Id$
21 */
22
23 #include "system.h"
24
25 /* Darwin (MacOS/X) needs the following definition... */
26 #ifndef _P1003_1B_VISIBLE
27 #define _P1003_1B_VISIBLE
28 #endif
29
30 #ifdef HAVE_SYS_MMAN_H
31 #include <sys/mman.h>
32 #endif
33
34 #include <openssl/rand.h>
35 #include <openssl/rsa.h>
36 #include <openssl/pem.h>
37 #include <openssl/evp.h>
38 #include <openssl/engine.h>
39
40 #include LZO1X_H
41
42 #ifndef HAVE_MINGW
43 #include <pwd.h>
44 #include <grp.h>
45 #include <time.h>
46 #endif
47
48 #include <getopt.h>
49 #include "pidfile.h"
50
51 #include "conf.h"
52 #include "device.h"
53 #include "logger.h"
54 #include "net.h"
55 #include "netutl.h"
56 #include "process.h"
57 #include "protocol.h"
58 #include "utils.h"
59 #include "xalloc.h"
60
61 /* The name this program was run with. */
62 char *program_name = NULL;
63
64 /* If nonzero, display usage information and exit. */
65 bool show_help = false;
66
67 /* If nonzero, print the version on standard output and exit.  */
68 bool show_version = false;
69
70 /* If nonzero, it will attempt to kill a running tincd and exit. */
71 int kill_tincd = 0;
72
73 /* If nonzero, generate public/private keypair for this host/net. */
74 int generate_keys = 0;
75
76 /* If nonzero, use null ciphers and skip all key exchanges. */
77 bool bypass_security = false;
78
79 /* If nonzero, disable swapping for this process. */
80 bool do_mlock = false;
81
82 /* If nonzero, chroot to netdir after startup. */
83 static bool do_chroot = false;
84
85 /* If !NULL, do setuid to given user after startup */
86 static const char *switchuser = NULL;
87
88 /* If nonzero, write log entries to a separate file. */
89 bool use_logfile = false;
90
91 char *identname = NULL;                         /* program name for syslog */
92 char *pidfilename = NULL;                       /* pid file location */
93 char *logfilename = NULL;                       /* log file location */
94 char **g_argv;                                  /* a copy of the cmdline arguments */
95
96 static int status;
97
98 static struct option const long_options[] = {
99         {"config", required_argument, NULL, 'c'},
100         {"kill", optional_argument, NULL, 'k'},
101         {"net", required_argument, NULL, 'n'},
102         {"help", no_argument, NULL, 1},
103         {"version", no_argument, NULL, 2},
104         {"no-detach", no_argument, NULL, 'D'},
105         {"generate-keys", optional_argument, NULL, 'K'},
106         {"debug", optional_argument, NULL, 'd'},
107         {"bypass-security", no_argument, NULL, 3},
108         {"mlock", no_argument, NULL, 'L'},
109         {"chroot", no_argument, NULL, 'R'},
110         {"user", required_argument, NULL, 'U'},
111         {"logfile", optional_argument, NULL, 4},
112         {"pidfile", required_argument, NULL, 5},
113         {NULL, 0, NULL, 0}
114 };
115
116 #ifdef HAVE_MINGW
117 static struct WSAData wsa_state;
118 #endif
119
120 static void usage(bool status)
121 {
122         if(status)
123                 fprintf(stderr, _("Try `%s --help\' for more information.\n"),
124                                 program_name);
125         else {
126                 printf(_("Usage: %s [option]...\n\n"), program_name);
127                 printf(_("  -c, --config=DIR           Read configuration options from DIR.\n"
128                                 "  -D, --no-detach            Don't fork and detach.\n"
129                                 "  -d, --debug[=LEVEL]        Increase debug level or set it to LEVEL.\n"
130                                 "  -k, --kill[=SIGNAL]        Attempt to kill a running tincd and exit.\n"
131                                 "  -n, --net=NETNAME          Connect to net NETNAME.\n"
132                                 "  -K, --generate-keys[=BITS] Generate public/private RSA keypair.\n"
133                                 "  -L, --mlock                Lock tinc into main memory.\n"
134                                 "      --logfile[=FILENAME]   Write log entries to a logfile.\n"
135                                 "      --pidfile=FILENAME     Write PID to FILENAME.\n"
136                                 "  -R, --chroot               chroot to NET dir at startup.\n"
137                                 "  -U, --user=USER            setuid to given USER at startup.\n"
138                                 "      --help                 Display this help and exit.\n"
139                                 "      --version              Output version information and exit.\n\n"));
140                 printf(_("Report bugs to tinc@tinc-vpn.org.\n"));
141         }
142 }
143
144 static bool parse_options(int argc, char **argv)
145 {
146         int r;
147         int option_index = 0;
148
149         while((r = getopt_long(argc, argv, "c:DLd::k::n:K::RU:", long_options, &option_index)) != EOF) {
150                 switch (r) {
151                         case 0:                         /* long option */
152                                 break;
153
154                         case 'c':                               /* config file */
155                                 confbase = xstrdup(optarg);
156                                 break;
157
158                         case 'D':                               /* no detach */
159                                 do_detach = false;
160                                 break;
161
162                         case 'L':                               /* no detach */
163                                 do_mlock = true;
164                                 break;
165
166                         case 'd':                               /* inc debug level */
167                                 if(optarg)
168                                         debug_level = atoi(optarg);
169                                 else
170                                         debug_level++;
171                                 break;
172
173                         case 'k':                               /* kill old tincds */
174 #ifndef HAVE_MINGW
175                                 if(optarg) {
176                                         if(!strcasecmp(optarg, "HUP"))
177                                                 kill_tincd = SIGHUP;
178                                         else if(!strcasecmp(optarg, "TERM"))
179                                                 kill_tincd = SIGTERM;
180                                         else if(!strcasecmp(optarg, "KILL"))
181                                                 kill_tincd = SIGKILL;
182                                         else if(!strcasecmp(optarg, "USR1"))
183                                                 kill_tincd = SIGUSR1;
184                                         else if(!strcasecmp(optarg, "USR2"))
185                                                 kill_tincd = SIGUSR2;
186                                         else if(!strcasecmp(optarg, "WINCH"))
187                                                 kill_tincd = SIGWINCH;
188                                         else if(!strcasecmp(optarg, "INT"))
189                                                 kill_tincd = SIGINT;
190                                         else if(!strcasecmp(optarg, "ALRM"))
191                                                 kill_tincd = SIGALRM;
192                                         else {
193                                                 kill_tincd = atoi(optarg);
194
195                                                 if(!kill_tincd) {
196                                                         fprintf(stderr, _("Invalid argument `%s'; SIGNAL must be a number or one of HUP, TERM, KILL, USR1, USR2, WINCH, INT or ALRM.\n"),
197                                                                         optarg);
198                                                         usage(true);
199                                                         return false;
200                                                 }
201                                         }
202                                 } else
203                                         kill_tincd = SIGTERM;
204 #else
205                                         kill_tincd = 1;
206 #endif
207                                 break;
208
209                         case 'n':                               /* net name given */
210                                 netname = xstrdup(optarg);
211                                 break;
212
213                         case 'K':                               /* generate public/private keypair */
214                                 if(optarg) {
215                                         generate_keys = atoi(optarg);
216
217                                         if(generate_keys < 512) {
218                                                 fprintf(stderr, _("Invalid argument `%s'; BITS must be a number equal to or greater than 512.\n"),
219                                                                 optarg);
220                                                 usage(true);
221                                                 return false;
222                                         }
223
224                                         generate_keys &= ~7;    /* Round it to bytes */
225                                 } else
226                                         generate_keys = 1024;
227                                 break;
228
229                         case 'R':                               /* chroot to NETNAME dir */
230                                 do_chroot = true;
231                                 break;
232
233                         case 'U':                               /* setuid to USER */
234                                 switchuser = optarg;
235                                 break;
236
237                         case 1:                                 /* show help */
238                                 show_help = true;
239                                 break;
240
241                         case 2:                                 /* show version */
242                                 show_version = true;
243                                 break;
244
245                         case 3:                                 /* bypass security */
246                                 bypass_security = true;
247                                 break;
248
249                         case 4:                                 /* write log entries to a file */
250                                 use_logfile = true;
251                                 if(optarg)
252                                         logfilename = xstrdup(optarg);
253                                 break;
254
255                         case 5:                                 /* write PID to a file */
256                                 pidfilename = xstrdup(optarg);
257                                 break;
258
259                         case '?':
260                                 usage(true);
261                                 return false;
262
263                         default:
264                                 break;
265                 }
266         }
267
268         return true;
269 }
270
271 /* This function prettyprints the key generation process */
272
273 static void indicator(int a, int b, void *p)
274 {
275         switch (a) {
276                 case 0:
277                         fprintf(stderr, ".");
278                         break;
279
280                 case 1:
281                         fprintf(stderr, "+");
282                         break;
283
284                 case 2:
285                         fprintf(stderr, "-");
286                         break;
287
288                 case 3:
289                         switch (b) {
290                                 case 0:
291                                         fprintf(stderr, " p\n");
292                                         break;
293
294                                 case 1:
295                                         fprintf(stderr, " q\n");
296                                         break;
297
298                                 default:
299                                         fprintf(stderr, "?");
300                         }
301                         break;
302
303                 default:
304                         fprintf(stderr, "?");
305         }
306 }
307
308 /*
309   Generate a public/private RSA keypair, and ask for a file to store
310   them in.
311 */
312 static bool keygen(int bits)
313 {
314         RSA *rsa_key;
315         FILE *f;
316         char *name = NULL;
317         char *filename;
318
319         get_config_string(lookup_config(config_tree, "Name"), &name);
320
321         if(name && !check_id(name)) {
322                 fprintf(stderr, _("Invalid name for myself!\n"));
323                 return false;
324         }
325
326         fprintf(stderr, _("Generating %d bits keys:\n"), bits);
327         rsa_key = RSA_generate_key(bits, 0x10001, indicator, NULL);
328
329         if(!rsa_key) {
330                 fprintf(stderr, _("Error during key generation!\n"));
331                 return false;
332         } else
333                 fprintf(stderr, _("Done.\n"));
334
335         asprintf(&filename, "%s/rsa_key.priv", confbase);
336         f = ask_and_open(filename, _("private RSA key"));
337
338         if(!f)
339                 return false;
340
341         if(disable_old_keys(f))
342                 fprintf(stderr, _("Warning: old key(s) found and disabled.\n"));
343   
344 #ifdef HAVE_FCHMOD
345         /* Make it unreadable for others. */
346         fchmod(fileno(f), 0600);
347 #endif
348                 
349         PEM_write_RSAPrivateKey(f, rsa_key, NULL, NULL, 0, NULL, NULL);
350         fclose(f);
351         free(filename);
352
353         if(name)
354                 asprintf(&filename, "%s/hosts/%s", confbase, name);
355         else
356                 asprintf(&filename, "%s/rsa_key.pub", confbase);
357
358         f = ask_and_open(filename, _("public RSA key"));
359
360         if(!f)
361                 return false;
362
363         if(disable_old_keys(f))
364                 fprintf(stderr, _("Warning: old key(s) found and disabled.\n"));
365
366         PEM_write_RSAPublicKey(f, rsa_key);
367         fclose(f);
368         free(filename);
369         if(name)
370                 free(name);
371
372         return true;
373 }
374
375 /*
376   Set all files and paths according to netname
377 */
378 static void make_names(void)
379 {
380 #ifdef HAVE_MINGW
381         HKEY key;
382         char installdir[1024] = "";
383         long len = sizeof(installdir);
384 #endif
385
386         if(netname)
387                 asprintf(&identname, "tinc.%s", netname);
388         else
389                 identname = xstrdup("tinc");
390
391 #ifdef HAVE_MINGW
392         if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
393                 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
394                         if(!logfilename)
395                                 asprintf(&logfilename, "%s/log/%s.log", identname);
396                         if(!confbase) {
397                                 if(netname)
398                                         asprintf(&confbase, "%s/%s", installdir, netname);
399                                 else
400                                         asprintf(&confbase, "%s", installdir);
401                         }
402                 }
403                 RegCloseKey(key);
404                 if(*installdir)
405                         return;
406         }
407 #endif
408
409         if(!pidfilename)
410                 asprintf(&pidfilename, LOCALSTATEDIR "/run/%s.pid", identname);
411
412         if(!logfilename)
413                 asprintf(&logfilename, LOCALSTATEDIR "/log/%s.log", identname);
414
415         if(netname) {
416                 if(!confbase)
417                         asprintf(&confbase, CONFDIR "/tinc/%s", netname);
418                 else
419                         logger(LOG_INFO, _("Both netname and configuration directory given, using the latter..."));
420         } else {
421                 if(!confbase)
422                         asprintf(&confbase, CONFDIR "/tinc");
423         }
424 }
425
426 static void free_names() {
427         if (identname) free(identname);
428         if (netname) free(netname);
429         if (pidfilename) free(pidfilename);
430         if (logfilename) free(logfilename);
431         if (confbase) free(confbase);
432 }
433
434 static bool drop_privs() {
435 #ifdef HAVE_MINGW
436         if (switchuser) {
437                 logger(LOG_ERR, _("%s not supported on this platform"), "-U");
438                 return false;
439         }
440         if (do_chroot) {
441                 logger(LOG_ERR, _("%s not supported on this platform"), "-R");
442                 return false;
443         }
444 #else
445         uid_t uid = 0;
446         if (switchuser) {
447                 struct passwd *pw = getpwnam(switchuser);
448                 if (!pw) {
449                         logger(LOG_ERR, _("unknown user `%s'"), switchuser);
450                         return false;
451                 }
452                 uid = pw->pw_uid;
453                 if (initgroups(switchuser, pw->pw_gid) != 0 ||
454                     setgid(pw->pw_gid) != 0) {
455                         logger(LOG_ERR, _("%s failed"), "initgroups()");
456                         return false;
457                 }
458                 endgrent();
459                 endpwent();
460         }
461         if (do_chroot) {
462                 tzset();        /* for proper timestamps in logs */
463                 if (chroot(confbase) != 0 || chdir(".") != 0) {
464                         logger(LOG_ERR, _("%s failed"), "chroot()");
465                         return false;
466                 }
467                 free(confbase);
468                 confbase = xstrdup("");
469         }
470         if (switchuser)
471                 if (setuid(uid) != 0) {
472                         logger(LOG_ERR, _("%s failed"), "setuid()");
473                         return false;
474                 }
475 #endif
476         return true;
477 }
478
479 int main(int argc, char **argv)
480 {
481         program_name = argv[0];
482
483         setlocale(LC_ALL, "");
484         bindtextdomain(PACKAGE, LOCALEDIR);
485         textdomain(PACKAGE);
486
487         if(!parse_options(argc, argv))
488                 return 1;
489         
490         make_names();
491
492         if(show_version) {
493                 printf(_("%s version %s (built %s %s, protocol %d)\n"), PACKAGE,
494                            VERSION, __DATE__, __TIME__, PROT_CURRENT);
495                 printf(_("Copyright (C) 1998-2009 Ivo Timmermans, Guus Sliepen and others.\n"
496                                 "See the AUTHORS file for a complete list.\n\n"
497                                 "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
498                                 "and you are welcome to redistribute it under certain conditions;\n"
499                                 "see the file COPYING for details.\n"));
500
501                 return 0;
502         }
503
504         if(show_help) {
505                 usage(false);
506                 return 0;
507         }
508
509         if(kill_tincd)
510                 return !kill_other(kill_tincd);
511
512         openlogger("tinc", use_logfile?LOGMODE_FILE:LOGMODE_STDERR);
513
514         /* Lock all pages into memory if requested */
515
516         if(do_mlock)
517 #ifdef HAVE_MLOCKALL
518                 if(mlockall(MCL_CURRENT | MCL_FUTURE)) {
519                         logger(LOG_ERR, _("System call `%s' failed: %s"), "mlockall",
520                                    strerror(errno));
521 #else
522         {
523                 logger(LOG_ERR, _("mlockall() not supported on this platform!"));
524 #endif
525                 return -1;
526         }
527
528         g_argv = argv;
529
530         init_configuration(&config_tree);
531
532         /* Slllluuuuuuurrrrp! */
533
534         RAND_load_file("/dev/urandom", 1024);
535
536         ENGINE_load_builtin_engines();
537         ENGINE_register_all_complete();
538
539         OpenSSL_add_all_algorithms();
540
541         if(generate_keys) {
542                 read_server_config();
543                 return !keygen(generate_keys);
544         }
545
546         if(!read_server_config())
547                 return 1;
548
549         if(lzo_init() != LZO_E_OK) {
550                 logger(LOG_ERR, _("Error initializing LZO compressor!"));
551                 return 1;
552         }
553
554 #ifdef HAVE_MINGW
555         if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
556                 logger(LOG_ERR, _("System call `%s' failed: %s"), "WSAStartup", winerror(GetLastError()));
557                 return 1;
558         }
559
560         if(!do_detach || !init_service())
561                 return main2(argc, argv);
562         else
563                 return 1;
564 }
565
566 int main2(int argc, char **argv)
567 {
568 #endif
569
570         if(!detach())
571                 return 1;
572
573         /* Setup sockets and open device. */
574
575         if(!setup_network())
576                 goto end;
577
578         /* drop privileges */
579         if (!drop_privs())
580                 goto end;
581
582         /* Initiate all outgoing connections. */
583
584         try_outgoing_connections();
585
586         /* Start main loop. It only exits when tinc is killed. */
587
588         status = main_loop();
589
590         /* Shutdown properly. */
591
592         ifdebug(CONNECTIONS)
593                 dump_device_stats();
594
595         close_network_connections();
596
597 end:
598         logger(LOG_NOTICE, _("Terminating"));
599
600 #ifndef HAVE_MINGW
601         remove_pid(pidfilename);
602 #endif
603
604         EVP_cleanup();
605         ENGINE_cleanup();
606         CRYPTO_cleanup_all_ex_data();
607         ERR_remove_state(0);
608         ERR_free_strings();
609
610         exit_configuration(&config_tree);
611         free_names();
612
613         return status;
614 }