Refactor crypto RNG; add getrandom() support
[tinc] / src / tincd.c
1 /*
2     tincd.c -- the main file for tincd
3     Copyright (C) 1998-2005 Ivo Timmermans
4                   2000-2022 Guus Sliepen <guus@tinc-vpn.org>
5                   2008      Max Rijevski <maksuf@gmail.com>
6                   2009      Michael Tokarev <mjt@tls.msk.ru>
7                   2010      Julien Muchembled <jm@jmuchemb.eu>
8                   2010      Timothy Redaelli <timothy@redaelli.eu>
9
10     This program is free software; you can redistribute it and/or modify
11     it under the terms of the GNU General Public License as published by
12     the Free Software Foundation; either version 2 of the License, or
13     (at your option) any later version.
14
15     This program is distributed in the hope that it will be useful,
16     but WITHOUT ANY WARRANTY; without even the implied warranty of
17     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18     GNU General Public License for more details.
19
20     You should have received a copy of the GNU General Public License along
21     with this program; if not, write to the Free Software Foundation, Inc.,
22     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 */
24
25 #include "system.h"
26
27 /* Darwin (MacOS/X) needs the following definition... */
28 #ifndef _P1003_1B_VISIBLE
29 #define _P1003_1B_VISIBLE
30 #endif
31
32 #ifdef HAVE_LZO
33 #include LZO1X_H
34 #endif
35
36 #ifdef HAVE_LZ4
37 #include <lz4.h>
38 #endif
39
40 #ifndef HAVE_WINDOWS
41 #include <pwd.h>
42 #include <grp.h>
43 #include <time.h>
44 #endif
45
46 #include "conf.h"
47 #include "crypto.h"
48 #include "event.h"
49 #include "logger.h"
50 #include "names.h"
51 #include "net.h"
52 #include "process.h"
53 #include "protocol.h"
54 #include "utils.h"
55 #include "xalloc.h"
56 #include "version.h"
57 #include "random.h"
58
59 /* If nonzero, display usage information and exit. */
60 static bool show_help = false;
61
62 /* If nonzero, print the version on standard output and exit.  */
63 static bool show_version = false;
64
65 #ifdef HAVE_MLOCKALL
66 /* If nonzero, disable swapping for this process. */
67 static bool do_mlock = false;
68 #endif
69
70 #ifndef HAVE_WINDOWS
71 /* If nonzero, chroot to netdir after startup. */
72 static bool do_chroot = false;
73
74 /* If !NULL, do setuid to given user after startup */
75 static const char *switchuser = NULL;
76 #endif
77
78 char **g_argv;                  /* a copy of the cmdline arguments */
79
80 static int status = 1;
81
82 static struct option const long_options[] = {
83         {"config", required_argument, NULL, 'c'},
84         {"net", required_argument, NULL, 'n'},
85         {"help", no_argument, NULL, 1},
86         {"version", no_argument, NULL, 2},
87         {"no-detach", no_argument, NULL, 'D'},
88         {"debug", optional_argument, NULL, 'd'},
89         {"bypass-security", no_argument, NULL, 3},
90         {"mlock", no_argument, NULL, 'L'},
91         {"chroot", no_argument, NULL, 'R'},
92         {"user", required_argument, NULL, 'U'},
93         {"logfile", optional_argument, NULL, 4},
94         {"syslog", no_argument, NULL, 's'},
95         {"pidfile", required_argument, NULL, 5},
96         {"option", required_argument, NULL, 'o'},
97         {NULL, 0, NULL, 0}
98 };
99
100 #ifdef HAVE_WINDOWS
101 static struct WSAData wsa_state;
102 int main2(int argc, char **argv);
103 #endif
104
105 static void usage(bool status) {
106         if(status)
107                 fprintf(stderr, "Try `%s --help\' for more information.\n",
108                         program_name);
109         else {
110                 static const char *message =
111                         "Usage: %s [option]...\n"
112                         "\n"
113                         "  -c, --config=DIR              Read configuration options from DIR.\n"
114                         "  -D, --no-detach               Don't fork and detach.\n"
115                         "  -d, --debug[=LEVEL]           Increase debug level or set it to LEVEL.\n"
116                         "  -n, --net=NETNAME             Connect to net NETNAME.\n"
117 #ifdef HAVE_MLOCKALL
118                         "  -L, --mlock                   Lock tinc into main memory.\n"
119 #endif
120                         "      --logfile[=FILENAME]      Write log entries to a logfile.\n"
121                         "  -s  --syslog                  Use syslog instead of stderr with --no-detach.\n"
122                         "      --pidfile=FILENAME        Write PID and control socket cookie to FILENAME.\n"
123                         "      --bypass-security         Disables meta protocol security, for debugging.\n"
124                         "  -o, --option[HOST.]KEY=VALUE  Set global/host configuration value.\n"
125 #ifndef HAVE_WINDOWS
126                         "  -R, --chroot                  chroot to NET dir at startup.\n"
127                         "  -U, --user=USER               setuid to given USER at startup.\n"
128 #endif
129                         "      --help                    Display this help and exit.\n"
130                         "      --version                 Output version information and exit.\n"
131                         "\n"
132                         "Report bugs to tinc@tinc-vpn.org.\n";
133
134                 printf(message, program_name);
135         }
136 }
137
138 static bool parse_options(int argc, char **argv) {
139         config_t *cfg;
140         int r;
141         int option_index = 0;
142         int lineno = 0;
143
144         while((r = getopt_long(argc, argv, "c:DLd::n:so:RU:", long_options, &option_index)) != EOF) {
145                 switch(r) {
146                 case 0:   /* long option */
147                         break;
148
149                 case 'c': /* config file */
150                         free(confbase);
151                         confbase = xstrdup(optarg);
152                         break;
153
154                 case 'D': /* no detach */
155                         do_detach = false;
156                         break;
157
158                 case 'L': /* no detach */
159 #ifndef HAVE_MLOCKALL
160                         logger(DEBUG_ALWAYS, LOG_ERR, "The %s option is not supported on this platform.", argv[optind - 1]);
161                         goto exit_fail;
162 #else
163                         do_mlock = true;
164                         break;
165 #endif
166
167                 case 'd': /* increase debug level */
168                         if(!optarg && optind < argc && *argv[optind] != '-') {
169                                 optarg = argv[optind++];
170                         }
171
172                         if(optarg) {
173                                 debug_level = atoi(optarg);
174                         } else {
175                                 debug_level++;
176                         }
177
178                         break;
179
180                 case 'n': /* net name given */
181                         free(netname);
182                         netname = xstrdup(optarg);
183                         break;
184
185                 case 's': /* syslog */
186                         use_logfile = false;
187                         use_syslog = true;
188                         break;
189
190                 case 'o': /* option */
191                         cfg = parse_config_line(optarg, NULL, ++lineno);
192
193                         if(!cfg) {
194                                 goto exit_fail;
195                         }
196
197                         list_insert_tail(&cmdline_conf, cfg);
198                         break;
199
200 #ifdef HAVE_WINDOWS
201
202                 case 'R':
203                 case 'U':
204                         logger(DEBUG_ALWAYS, LOG_ERR, "The %s option is not supported on this platform.", argv[optind - 1]);
205                         goto exit_fail;
206 #else
207
208                 case 'R': /* chroot to NETNAME dir */
209                         do_chroot = true;
210                         break;
211
212                 case 'U': /* setuid to USER */
213                         switchuser = optarg;
214                         break;
215 #endif
216
217                 case 1:   /* show help */
218                         show_help = true;
219                         break;
220
221                 case 2:   /* show version */
222                         show_version = true;
223                         break;
224
225                 case 3:   /* bypass security */
226                         bypass_security = true;
227                         break;
228
229                 case 4:   /* write log entries to a file */
230                         use_syslog = false;
231                         use_logfile = true;
232
233                         if(!optarg && optind < argc && *argv[optind] != '-') {
234                                 optarg = argv[optind++];
235                         }
236
237                         if(optarg) {
238                                 free(logfilename);
239                                 logfilename = xstrdup(optarg);
240                         }
241
242                         break;
243
244                 case 5:   /* open control socket here */
245                         free(pidfilename);
246                         pidfilename = xstrdup(optarg);
247                         break;
248
249                 case '?': /* wrong options */
250                         usage(true);
251                         goto exit_fail;
252
253                 default:
254                         break;
255                 }
256         }
257
258         if(optind < argc) {
259                 fprintf(stderr, "%s: unrecognized argument '%s'\n", argv[0], argv[optind]);
260                 usage(true);
261                 goto exit_fail;
262         }
263
264         if(!netname && (netname = getenv("NETNAME"))) {
265                 netname = xstrdup(netname);
266         }
267
268         /* netname "." is special: a "top-level name" */
269
270         if(netname && (!*netname || !strcmp(netname, "."))) {
271                 free(netname);
272                 netname = NULL;
273         }
274
275         if(netname && !check_netname(netname, false)) {
276                 fprintf(stderr, "Invalid character in netname!\n");
277                 goto exit_fail;
278         }
279
280         if(netname && !check_netname(netname, true)) {
281                 fprintf(stderr, "Warning: unsafe character in netname!\n");
282         }
283
284         return true;
285
286 exit_fail:
287         free_names();
288         list_empty_list(&cmdline_conf);
289         return false;
290 }
291
292 static bool drop_privs(void) {
293 #ifndef HAVE_WINDOWS
294         uid_t uid = 0;
295
296         if(switchuser) {
297                 struct passwd *pw = getpwnam(switchuser);
298
299                 if(!pw) {
300                         logger(DEBUG_ALWAYS, LOG_ERR, "unknown user `%s'", switchuser);
301                         return false;
302                 }
303
304                 uid = pw->pw_uid;
305
306                 // The second parameter to initgroups on macOS requires int,
307                 // but __gid_t is unsigned int. There's not much we can do here.
308                 if(initgroups(switchuser, pw->pw_gid) != 0 || // NOLINT(bugprone-narrowing-conversions)
309                                 setgid(pw->pw_gid) != 0) {
310                         logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
311                                "initgroups", strerror(errno));
312                         return false;
313                 }
314
315 #ifndef __ANDROID__
316 // Not supported in android NDK
317                 endgrent();
318                 endpwent();
319 #endif
320         }
321
322         if(do_chroot) {
323                 tzset();        /* for proper timestamps in logs */
324
325                 if(chroot(confbase) != 0 || chdir("/") != 0) {
326                         logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
327                                "chroot", strerror(errno));
328                         return false;
329                 }
330
331                 free(confbase);
332                 confbase = xstrdup("");
333         }
334
335         if(switchuser)
336                 if(setuid(uid) != 0) {
337                         logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
338                                "setuid", strerror(errno));
339                         return false;
340                 }
341
342 #endif
343         return true;
344 }
345
346 #ifdef HAVE_WINDOWS
347 # define setpriority(level) !SetPriorityClass(GetCurrentProcess(), (level))
348
349 static void stop_handler(void *data, int flags) {
350         (void)data;
351         (void)flags;
352
353         event_exit();
354 }
355
356 static BOOL WINAPI console_ctrl_handler(DWORD type) {
357         (void)type;
358
359         logger(DEBUG_ALWAYS, LOG_NOTICE, "Got console shutdown request");
360
361         if(WSASetEvent(stop_io.event) == FALSE) {
362                 abort();
363         }
364
365         return TRUE;
366 }
367 #else
368 # define NORMAL_PRIORITY_CLASS 0
369 # define BELOW_NORMAL_PRIORITY_CLASS 10
370 # define HIGH_PRIORITY_CLASS -10
371 # define setpriority(level) (setpriority(PRIO_PROCESS, 0, (level)))
372 #endif
373
374 static void cleanup(void) {
375         splay_empty_tree(&config_tree);
376         list_empty_list(&cmdline_conf);
377         free_names();
378 }
379
380 int main(int argc, char **argv) {
381         program_name = argv[0];
382
383         if(!parse_options(argc, argv)) {
384                 return 1;
385         }
386
387         if(show_version) {
388                 static const char *message =
389                         "%s version %s (built %s %s, protocol %d.%d)\n"
390                         "Features:"
391 #ifdef HAVE_OPENSSL
392                         " openssl"
393 #endif
394 #ifdef HAVE_LIBGCRYPT
395                         " libgcrypt"
396 #endif
397 #ifdef HAVE_LZO
398                         " comp_lzo"
399 #endif
400 #ifdef HAVE_ZLIB
401                         " comp_zlib"
402 #endif
403 #ifdef HAVE_LZ4
404                         " comp_lz4"
405 #endif
406 #ifndef DISABLE_LEGACY
407                         " legacy_protocol"
408 #endif
409 #ifdef ENABLE_JUMBOGRAMS
410                         " jumbograms"
411 #endif
412 #ifdef ENABLE_TUNEMU
413                         " tunemu"
414 #endif
415 #ifdef HAVE_MINIUPNPC
416                         " miniupnpc"
417 #endif
418 #ifdef ENABLE_UML
419                         " uml"
420 #endif
421 #ifdef ENABLE_VDE
422                         " vde"
423 #endif
424                         "\n\n"
425                         "Copyright (C) 1998-2021 Ivo Timmermans, Guus Sliepen and others.\n"
426                         "See the AUTHORS file for a complete list.\n"
427                         "\n"
428                         "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
429                         "and you are welcome to redistribute it under certain conditions;\n"
430                         "see the file COPYING for details.\n";
431
432                 printf(message, PACKAGE, BUILD_VERSION, BUILD_DATE, BUILD_TIME, PROT_MAJOR, PROT_MINOR);
433                 return 0;
434         }
435
436         if(show_help) {
437                 usage(false);
438                 return 0;
439         }
440
441         make_names(true);
442         atexit(cleanup);
443
444         if(chdir(confbase) == -1) {
445                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not change to configuration directory: %s", strerror(errno));
446                 return 1;
447         }
448
449 #ifdef HAVE_WINDOWS
450
451         if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
452                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
453                 return 1;
454         }
455
456 #else
457         // Check if we got an umbilical fd from the process that started us
458         char *umbstr = getenv("TINC_UMBILICAL");
459
460         if(umbstr) {
461                 umbilical = atoi(umbstr);
462
463                 if(fcntl(umbilical, F_GETFL) < 0) {
464                         umbilical = 0;
465                 }
466
467 #ifdef FD_CLOEXEC
468
469                 if(umbilical) {
470                         fcntl(umbilical, F_SETFD, FD_CLOEXEC);
471                 }
472
473 #endif
474         }
475
476 #endif
477
478         openlogger("tinc", use_logfile ? LOGMODE_FILE : LOGMODE_STDERR);
479
480         g_argv = argv;
481
482         if(getenv("LISTEN_PID") && atoi(getenv("LISTEN_PID")) == getpid()) {
483                 do_detach = false;
484         }
485
486 #ifdef HAVE_UNSETENV
487         unsetenv("LISTEN_PID");
488 #endif
489
490         gettimeofday(&now, NULL);
491         random_init();
492         crypto_init();
493         prng_init();
494
495         if(!read_server_config(&config_tree)) {
496                 return 1;
497         }
498
499         if(debug_level == DEBUG_NOTHING) {
500                 int level = 0;
501
502                 if(get_config_int(lookup_config(&config_tree, "LogLevel"), &level)) {
503                         debug_level = level;
504                 }
505         }
506
507 #ifdef HAVE_LZO
508
509         if(lzo_init() != LZO_E_OK) {
510                 logger(DEBUG_ALWAYS, LOG_ERR, "Error initializing LZO compressor!");
511                 return 1;
512         }
513
514 #endif
515
516 #ifdef HAVE_WINDOWS
517         io_add_event(&stop_io, stop_handler, NULL, WSACreateEvent());
518
519         if(stop_io.event == FALSE) {
520                 abort();
521         }
522
523         int result;
524
525         if(!do_detach || !init_service()) {
526                 SetConsoleCtrlHandler(console_ctrl_handler, TRUE);
527                 result = main2(argc, argv);
528         } else {
529                 result = 1;
530         }
531
532         if(WSACloseEvent(stop_io.event) == FALSE) {
533                 abort();
534         }
535
536         io_del(&stop_io);
537         return result;
538 }
539
540 int main2(int argc, char **argv) {
541         (void)argc;
542         (void)argv;
543 #endif
544         char *priority = NULL;
545
546         if(!detach()) {
547                 return 1;
548         }
549
550 #ifdef HAVE_MLOCKALL
551
552         /* Lock all pages into memory if requested.
553          * This has to be done after daemon()/fork() so it works for child.
554          * No need to do that in parent as it's very short-lived. */
555         if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
556                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "mlockall",
557                        strerror(errno));
558                 return 1;
559         }
560
561 #endif
562
563         /* Setup sockets and open device. */
564
565         if(!setup_network()) {
566                 goto end;
567         }
568
569         /* Change process priority */
570
571         if(get_config_string(lookup_config(&config_tree, "ProcessPriority"), &priority)) {
572                 if(!strcasecmp(priority, "Normal")) {
573                         if(setpriority(NORMAL_PRIORITY_CLASS) != 0) {
574                                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
575                                 goto end;
576                         }
577                 } else if(!strcasecmp(priority, "Low")) {
578                         if(setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
579                                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
580                                 goto end;
581                         }
582                 } else if(!strcasecmp(priority, "High")) {
583                         if(setpriority(HIGH_PRIORITY_CLASS) != 0) {
584                                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
585                                 goto end;
586                         }
587                 } else {
588                         logger(DEBUG_ALWAYS, LOG_ERR, "Invalid priority `%s`!", priority);
589                         goto end;
590                 }
591         }
592
593         /* drop privileges */
594         if(!drop_privs()) {
595                 goto end;
596         }
597
598         /* Start main loop. It only exits when tinc is killed. */
599
600         logger(DEBUG_ALWAYS, LOG_NOTICE, "Ready");
601
602         if(umbilical) { // snip!
603                 if(write(umbilical, "", 1) != 1) {
604                         // Pipe full or broken, nothing we can do about it.
605                 }
606
607                 close(umbilical);
608                 umbilical = 0;
609         }
610
611         try_outgoing_connections();
612
613         status = main_loop();
614
615         /* Shutdown properly. */
616
617 end:
618         close_network_connections();
619
620         logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
621
622         free(priority);
623
624         random_exit();
625
626         return status;
627 }