try outgoing connections before chroot/drop_privs
[tinc] / 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 #ifndef HAVE_MLOCKALL
164                                 logger(LOG_ERR, _("%s not supported on this platform"), "mlockall()");
165                                 return false;
166 #else
167                                 do_mlock = true;
168                                 break;
169 #endif
170
171                         case 'd':                               /* inc debug level */
172                                 if(optarg)
173                                         debug_level = atoi(optarg);
174                                 else
175                                         debug_level++;
176                                 break;
177
178                         case 'k':                               /* kill old tincds */
179 #ifndef HAVE_MINGW
180                                 if(optarg) {
181                                         if(!strcasecmp(optarg, "HUP"))
182                                                 kill_tincd = SIGHUP;
183                                         else if(!strcasecmp(optarg, "TERM"))
184                                                 kill_tincd = SIGTERM;
185                                         else if(!strcasecmp(optarg, "KILL"))
186                                                 kill_tincd = SIGKILL;
187                                         else if(!strcasecmp(optarg, "USR1"))
188                                                 kill_tincd = SIGUSR1;
189                                         else if(!strcasecmp(optarg, "USR2"))
190                                                 kill_tincd = SIGUSR2;
191                                         else if(!strcasecmp(optarg, "WINCH"))
192                                                 kill_tincd = SIGWINCH;
193                                         else if(!strcasecmp(optarg, "INT"))
194                                                 kill_tincd = SIGINT;
195                                         else if(!strcasecmp(optarg, "ALRM"))
196                                                 kill_tincd = SIGALRM;
197                                         else {
198                                                 kill_tincd = atoi(optarg);
199
200                                                 if(!kill_tincd) {
201                                                         fprintf(stderr, _("Invalid argument `%s'; SIGNAL must be a number or one of HUP, TERM, KILL, USR1, USR2, WINCH, INT or ALRM.\n"),
202                                                                         optarg);
203                                                         usage(true);
204                                                         return false;
205                                                 }
206                                         }
207                                 } else
208                                         kill_tincd = SIGTERM;
209 #else
210                                         kill_tincd = 1;
211 #endif
212                                 break;
213
214                         case 'n':                               /* net name given */
215                                 netname = xstrdup(optarg);
216                                 break;
217
218                         case 'K':                               /* generate public/private keypair */
219                                 if(optarg) {
220                                         generate_keys = atoi(optarg);
221
222                                         if(generate_keys < 512) {
223                                                 fprintf(stderr, _("Invalid argument `%s'; BITS must be a number equal to or greater than 512.\n"),
224                                                                 optarg);
225                                                 usage(true);
226                                                 return false;
227                                         }
228
229                                         generate_keys &= ~7;    /* Round it to bytes */
230                                 } else
231                                         generate_keys = 1024;
232                                 break;
233
234                         case 'R':                               /* chroot to NETNAME dir */
235                                 do_chroot = true;
236                                 break;
237
238                         case 'U':                               /* setuid to USER */
239                                 switchuser = optarg;
240                                 break;
241
242                         case 1:                                 /* show help */
243                                 show_help = true;
244                                 break;
245
246                         case 2:                                 /* show version */
247                                 show_version = true;
248                                 break;
249
250                         case 3:                                 /* bypass security */
251                                 bypass_security = true;
252                                 break;
253
254                         case 4:                                 /* write log entries to a file */
255                                 use_logfile = true;
256                                 if(optarg)
257                                         logfilename = xstrdup(optarg);
258                                 break;
259
260                         case 5:                                 /* write PID to a file */
261                                 pidfilename = xstrdup(optarg);
262                                 break;
263
264                         case '?':
265                                 usage(true);
266                                 return false;
267
268                         default:
269                                 break;
270                 }
271         }
272
273         return true;
274 }
275
276 /* This function prettyprints the key generation process */
277
278 static void indicator(int a, int b, void *p)
279 {
280         switch (a) {
281                 case 0:
282                         fprintf(stderr, ".");
283                         break;
284
285                 case 1:
286                         fprintf(stderr, "+");
287                         break;
288
289                 case 2:
290                         fprintf(stderr, "-");
291                         break;
292
293                 case 3:
294                         switch (b) {
295                                 case 0:
296                                         fprintf(stderr, " p\n");
297                                         break;
298
299                                 case 1:
300                                         fprintf(stderr, " q\n");
301                                         break;
302
303                                 default:
304                                         fprintf(stderr, "?");
305                         }
306                         break;
307
308                 default:
309                         fprintf(stderr, "?");
310         }
311 }
312
313 /*
314   Generate a public/private RSA keypair, and ask for a file to store
315   them in.
316 */
317 static bool keygen(int bits)
318 {
319         RSA *rsa_key;
320         FILE *f;
321         char *name = NULL;
322         char *filename;
323
324         get_config_string(lookup_config(config_tree, "Name"), &name);
325
326         if(name && !check_id(name)) {
327                 fprintf(stderr, _("Invalid name for myself!\n"));
328                 return false;
329         }
330
331         fprintf(stderr, _("Generating %d bits keys:\n"), bits);
332         rsa_key = RSA_generate_key(bits, 0x10001, indicator, NULL);
333
334         if(!rsa_key) {
335                 fprintf(stderr, _("Error during key generation!\n"));
336                 return false;
337         } else
338                 fprintf(stderr, _("Done.\n"));
339
340         asprintf(&filename, "%s/rsa_key.priv", confbase);
341         f = ask_and_open(filename, _("private RSA key"));
342
343         if(!f)
344                 return false;
345
346         if(disable_old_keys(f))
347                 fprintf(stderr, _("Warning: old key(s) found and disabled.\n"));
348   
349 #ifdef HAVE_FCHMOD
350         /* Make it unreadable for others. */
351         fchmod(fileno(f), 0600);
352 #endif
353                 
354         PEM_write_RSAPrivateKey(f, rsa_key, NULL, NULL, 0, NULL, NULL);
355         fclose(f);
356         free(filename);
357
358         if(name)
359                 asprintf(&filename, "%s/hosts/%s", confbase, name);
360         else
361                 asprintf(&filename, "%s/rsa_key.pub", confbase);
362
363         f = ask_and_open(filename, _("public RSA key"));
364
365         if(!f)
366                 return false;
367
368         if(disable_old_keys(f))
369                 fprintf(stderr, _("Warning: old key(s) found and disabled.\n"));
370
371         PEM_write_RSAPublicKey(f, rsa_key);
372         fclose(f);
373         free(filename);
374         if(name)
375                 free(name);
376
377         return true;
378 }
379
380 /*
381   Set all files and paths according to netname
382 */
383 static void make_names(void)
384 {
385 #ifdef HAVE_MINGW
386         HKEY key;
387         char installdir[1024] = "";
388         long len = sizeof(installdir);
389 #endif
390
391         if(netname)
392                 asprintf(&identname, "tinc.%s", netname);
393         else
394                 identname = xstrdup("tinc");
395
396 #ifdef HAVE_MINGW
397         if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
398                 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
399                         if(!logfilename)
400                                 asprintf(&logfilename, "%s/log/%s.log", identname);
401                         if(!confbase) {
402                                 if(netname)
403                                         asprintf(&confbase, "%s/%s", installdir, netname);
404                                 else
405                                         asprintf(&confbase, "%s", installdir);
406                         }
407                 }
408                 RegCloseKey(key);
409                 if(*installdir)
410                         return;
411         }
412 #endif
413
414         if(!pidfilename)
415                 asprintf(&pidfilename, LOCALSTATEDIR "/run/%s.pid", identname);
416
417         if(!logfilename)
418                 asprintf(&logfilename, LOCALSTATEDIR "/log/%s.log", identname);
419
420         if(netname) {
421                 if(!confbase)
422                         asprintf(&confbase, CONFDIR "/tinc/%s", netname);
423                 else
424                         logger(LOG_INFO, _("Both netname and configuration directory given, using the latter..."));
425         } else {
426                 if(!confbase)
427                         asprintf(&confbase, CONFDIR "/tinc");
428         }
429 }
430
431 static void free_names() {
432         if (identname) free(identname);
433         if (netname) free(netname);
434         if (pidfilename) free(pidfilename);
435         if (logfilename) free(logfilename);
436         if (confbase) free(confbase);
437 }
438
439 static bool drop_privs() {
440 #ifdef HAVE_MINGW
441         if (switchuser) {
442                 logger(LOG_ERR, _("%s not supported on this platform"), "-U");
443                 return false;
444         }
445         if (do_chroot) {
446                 logger(LOG_ERR, _("%s not supported on this platform"), "-R");
447                 return false;
448         }
449 #else
450         uid_t uid = 0;
451         if (switchuser) {
452                 struct passwd *pw = getpwnam(switchuser);
453                 if (!pw) {
454                         logger(LOG_ERR, _("unknown user `%s'"), switchuser);
455                         return false;
456                 }
457                 uid = pw->pw_uid;
458                 if (initgroups(switchuser, pw->pw_gid) != 0 ||
459                     setgid(pw->pw_gid) != 0) {
460                         logger(LOG_ERR, _("System call `%s' failed: %s"),
461                                "initgroups", strerror(errno));
462                         return false;
463                 }
464                 endgrent();
465                 endpwent();
466         }
467         if (do_chroot) {
468                 tzset();        /* for proper timestamps in logs */
469                 if (chroot(confbase) != 0 || chdir("/") != 0) {
470                         logger(LOG_ERR, _("System call `%s' failed: %s"),
471                                "chroot", strerror(errno));
472                         return false;
473                 }
474                 free(confbase);
475                 confbase = xstrdup("");
476         }
477         if (switchuser)
478                 if (setuid(uid) != 0) {
479                         logger(LOG_ERR, _("System call `%s' failed: %s"),
480                                "setuid", strerror(errno));
481                         return false;
482                 }
483 #endif
484         return true;
485 }
486
487 #ifdef HAVE_MINGW
488 # define setpriority(level) SetPriorityClass(GetCurrentProcess(), level);
489 #else
490 # define NORMAL_PRIORITY_CLASS 0
491 # define BELOW_NORMAL_PRIORITY_CLASS 10
492 # define HIGH_PRIORITY_CLASS -10
493 # define setpriority(level) nice(level)
494 #endif
495
496 int main(int argc, char **argv)
497 {
498         program_name = argv[0];
499
500         setlocale(LC_ALL, "");
501         bindtextdomain(PACKAGE, LOCALEDIR);
502         textdomain(PACKAGE);
503
504         if(!parse_options(argc, argv))
505                 return 1;
506         
507         make_names();
508
509         if(show_version) {
510                 printf(_("%s version %s (built %s %s, protocol %d)\n"), PACKAGE,
511                            VERSION, __DATE__, __TIME__, PROT_CURRENT);
512                 printf(_("Copyright (C) 1998-2009 Ivo Timmermans, Guus Sliepen and others.\n"
513                                 "See the AUTHORS file for a complete list.\n\n"
514                                 "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
515                                 "and you are welcome to redistribute it under certain conditions;\n"
516                                 "see the file COPYING for details.\n"));
517
518                 return 0;
519         }
520
521         if(show_help) {
522                 usage(false);
523                 return 0;
524         }
525
526         if(kill_tincd)
527                 return !kill_other(kill_tincd);
528
529         openlogger("tinc", use_logfile?LOGMODE_FILE:LOGMODE_STDERR);
530
531         g_argv = argv;
532
533         init_configuration(&config_tree);
534
535         /* Slllluuuuuuurrrrp! */
536
537         RAND_load_file("/dev/urandom", 1024);
538
539         ENGINE_load_builtin_engines();
540         ENGINE_register_all_complete();
541
542         OpenSSL_add_all_algorithms();
543
544         if(generate_keys) {
545                 read_server_config();
546                 return !keygen(generate_keys);
547         }
548
549         if(!read_server_config())
550                 return 1;
551
552         if(lzo_init() != LZO_E_OK) {
553                 logger(LOG_ERR, _("Error initializing LZO compressor!"));
554                 return 1;
555         }
556
557 #ifdef HAVE_MINGW
558         if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
559                 logger(LOG_ERR, _("System call `%s' failed: %s"), "WSAStartup", winerror(GetLastError()));
560                 return 1;
561         }
562
563         if(!do_detach || !init_service())
564                 return main2(argc, argv);
565         else
566                 return 1;
567 }
568
569 int main2(int argc, char **argv)
570 {
571 #endif
572
573         if(!detach())
574                 return 1;
575
576 #ifdef HAVE_MLOCKALL
577         /* Lock all pages into memory if requested.
578          * This has to be done after daemon()/fork() so it works for child.
579          * No need to do that in parent as it's very short-lived. */
580         if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
581                 logger(LOG_ERR, _("System call `%s' failed: %s"), "mlockall",
582                    strerror(errno));
583                 return 1;
584         }
585 #endif
586
587         /* Setup sockets and open device. */
588
589         if(!setup_network())
590                 goto end;
591
592         /* Initiate all outgoing connections. */
593
594         try_outgoing_connections();
595
596         /* Change process priority */
597
598         char *priority = 0;
599
600         if(get_config_string(lookup_config(config_tree, "ProcessPriority"), &priority)) {
601                 if(!strcasecmp(priority, "Normal"))
602                         setpriority(NORMAL_PRIORITY_CLASS);
603                 else if(!strcasecmp(priority, "Low"))
604                         setpriority(BELOW_NORMAL_PRIORITY_CLASS);
605                 else if(!strcasecmp(priority, "High"))
606                         setpriority(HIGH_PRIORITY_CLASS);
607                 else {
608                         logger(LOG_ERR, _("Invalid priority `%s`!"), priority);
609                         goto end;
610                 }
611         }
612
613         /* drop privileges */
614         if (!drop_privs())
615                 goto end;
616
617         /* Start main loop. It only exits when tinc is killed. */
618
619         status = main_loop();
620
621         /* Shutdown properly. */
622
623         ifdebug(CONNECTIONS)
624                 dump_device_stats();
625
626         close_network_connections();
627
628 end:
629         logger(LOG_NOTICE, _("Terminating"));
630
631 #ifndef HAVE_MINGW
632         remove_pid(pidfilename);
633 #endif
634
635         EVP_cleanup();
636         ENGINE_cleanup();
637         CRYPTO_cleanup_all_ex_data();
638         ERR_remove_state(0);
639         ERR_free_strings();
640
641         exit_configuration(&config_tree);
642         free_names();
643
644         return status;
645 }