Require OpenSSL 1.1.0 or later.
[tinc] / src / tincd.c
1 /*
2     tincd.c -- the main file for tincd
3     Copyright (C) 1998-2005 Ivo Timmermans
4                   2000-2019 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_SYS_MMAN_H
33 #include <sys/mman.h>
34 #endif
35
36 #include <openssl/rand.h>
37 #include <openssl/rsa.h>
38 #include <openssl/pem.h>
39 #include <openssl/evp.h>
40 #include <openssl/engine.h>
41 #include <openssl/bn.h>
42
43 #ifdef HAVE_LZO
44 #include LZO1X_H
45 #endif
46
47 #ifndef HAVE_MINGW
48 #include <pwd.h>
49 #include <grp.h>
50 #include <time.h>
51 #endif
52
53 #ifdef HAVE_GETOPT_LONG
54 #include <getopt.h>
55 #else
56 #include "getopt.h"
57 #endif
58
59 #include "pidfile.h"
60
61 #include "conf.h"
62 #include "device.h"
63 #include "logger.h"
64 #include "net.h"
65 #include "netutl.h"
66 #include "process.h"
67 #include "protocol.h"
68 #include "utils.h"
69 #include "xalloc.h"
70
71 /* The name this program was run with. */
72 char *program_name = NULL;
73
74 /* If nonzero, display usage information and exit. */
75 bool show_help = false;
76
77 /* If nonzero, print the version on standard output and exit.  */
78 bool show_version = false;
79
80 /* If nonzero, it will attempt to kill a running tincd and exit. */
81 int kill_tincd = 0;
82
83 /* If nonzero, generate public/private keypair for this host/net. */
84 int generate_keys = 0;
85
86 /* If nonzero, use null ciphers and skip all key exchanges. */
87 bool bypass_security = false;
88
89 /* If nonzero, disable swapping for this process. */
90 bool do_mlock = false;
91
92 /* If nonzero, chroot to netdir after startup. */
93 static bool do_chroot = false;
94
95 /* If !NULL, do setuid to given user after startup */
96 static const char *switchuser = NULL;
97
98 /* If nonzero, write log entries to a separate file. */
99 bool use_logfile = false;
100
101 char *identname = NULL;                         /* program name for syslog */
102 char *pidfilename = NULL;                       /* pid file location */
103 char *logfilename = NULL;                       /* log file location */
104 char **g_argv;                                  /* a copy of the cmdline arguments */
105
106 static int status = 1;
107
108 static struct option const long_options[] = {
109         {"config", required_argument, NULL, 'c'},
110         {"kill", optional_argument, NULL, 'k'},
111         {"net", required_argument, NULL, 'n'},
112         {"help", no_argument, NULL, 1},
113         {"version", no_argument, NULL, 2},
114         {"no-detach", no_argument, NULL, 'D'},
115         {"generate-keys", optional_argument, NULL, 'K'},
116         {"debug", optional_argument, NULL, 'd'},
117         {"bypass-security", no_argument, NULL, 3},
118         {"mlock", no_argument, NULL, 'L'},
119         {"chroot", no_argument, NULL, 'R'},
120         {"user", required_argument, NULL, 'U'},
121         {"logfile", optional_argument, NULL, 4},
122         {"pidfile", required_argument, NULL, 5},
123         {"option", required_argument, NULL, 'o'},
124         {NULL, 0, NULL, 0}
125 };
126
127 #ifdef HAVE_MINGW
128 static struct WSAData wsa_state;
129 CRITICAL_SECTION mutex;
130 int main2(int argc, char **argv);
131 #endif
132
133 static void usage(bool status) {
134         if(status)
135                 fprintf(stderr, "Try `%s --help\' for more information.\n",
136                         program_name);
137         else {
138                 printf("Usage: %s [option]...\n\n", program_name);
139                 printf("  -c, --config=DIR               Read configuration options from DIR.\n"
140                        "  -D, --no-detach                Don't fork and detach.\n"
141                        "  -d, --debug[=LEVEL]            Increase debug level or set it to LEVEL.\n"
142                        "  -k, --kill[=SIGNAL]            Attempt to kill a running tincd and exit.\n"
143                        "  -n, --net=NETNAME              Connect to net NETNAME.\n"
144                        "  -K, --generate-keys[=BITS]     Generate public/private RSA keypair.\n"
145                        "  -L, --mlock                    Lock tinc into main memory.\n"
146                        "      --logfile[=FILENAME]       Write log entries to a logfile.\n"
147                        "      --pidfile=FILENAME         Write PID to FILENAME.\n"
148                        "  -o, --option=[HOST.]KEY=VALUE  Set global/host configuration value.\n"
149                        "  -R, --chroot                   chroot to NET dir at startup.\n"
150                        "  -U, --user=USER                setuid to given USER at startup.\n"
151                        "      --help                     Display this help and exit.\n"
152                        "      --version                  Output version information and exit.\n\n");
153                 printf("Report bugs to tinc@tinc-vpn.org.\n");
154         }
155 }
156
157 static bool parse_options(int argc, char **argv) {
158         config_t *cfg;
159         int r;
160         int option_index = 0;
161         int lineno = 0;
162
163         cmdline_conf = list_alloc((list_action_t)free_config);
164
165         while((r = getopt_long(argc, argv, "c:DLd::k::n:o:K::RU:", long_options, &option_index)) != EOF) {
166                 switch(r) {
167                 case 0:                         /* long option */
168                         break;
169
170                 case 'c':                               /* config file */
171                         if(confbase) {
172                                 fprintf(stderr, "Only one configuration directory can be given.\n");
173                                 usage(true);
174                                 return false;
175                         }
176
177                         confbase = xstrdup(optarg);
178                         break;
179
180                 case 'D':                               /* no detach */
181                         do_detach = false;
182                         break;
183
184                 case 'L':                               /* no detach */
185 #ifndef HAVE_MLOCKALL
186                         logger(LOG_ERR, "%s not supported on this platform", "mlockall()");
187                         return false;
188 #else
189                         do_mlock = true;
190                         break;
191 #endif
192
193                 case 'd':                               /* increase debug level */
194                         if(!optarg && optind < argc && *argv[optind] != '-') {
195                                 optarg = argv[optind++];
196                         }
197
198                         if(optarg) {
199                                 debug_level = atoi(optarg);
200                         } else {
201                                 debug_level++;
202                         }
203
204                         break;
205
206                 case 'k':                               /* kill old tincds */
207 #ifndef HAVE_MINGW
208                         if(!optarg && optind < argc && *argv[optind] != '-') {
209                                 optarg = argv[optind++];
210                         }
211
212                         if(optarg) {
213                                 if(!strcasecmp(optarg, "HUP")) {
214                                         kill_tincd = SIGHUP;
215                                 } else if(!strcasecmp(optarg, "TERM")) {
216                                         kill_tincd = SIGTERM;
217                                 } else if(!strcasecmp(optarg, "KILL")) {
218                                         kill_tincd = SIGKILL;
219                                 } else if(!strcasecmp(optarg, "USR1")) {
220                                         kill_tincd = SIGUSR1;
221                                 } else if(!strcasecmp(optarg, "USR2")) {
222                                         kill_tincd = SIGUSR2;
223                                 } else if(!strcasecmp(optarg, "WINCH")) {
224                                         kill_tincd = SIGWINCH;
225                                 } else if(!strcasecmp(optarg, "INT")) {
226                                         kill_tincd = SIGINT;
227                                 } else if(!strcasecmp(optarg, "ALRM")) {
228                                         kill_tincd = SIGALRM;
229                                 } else if(!strcasecmp(optarg, "ABRT")) {
230                                         kill_tincd = SIGABRT;
231                                 } else {
232                                         kill_tincd = atoi(optarg);
233
234                                         if(!kill_tincd) {
235                                                 fprintf(stderr, "Invalid argument `%s'; SIGNAL must be a number or one of HUP, TERM, KILL, USR1, USR2, WINCH, INT or ALRM.\n",
236                                                         optarg);
237                                                 usage(true);
238                                                 return false;
239                                         }
240                                 }
241                         } else {
242                                 kill_tincd = SIGTERM;
243                         }
244
245 #else
246                         kill_tincd = 1;
247 #endif
248                         break;
249
250                 case 'n':                               /* net name given */
251
252                         /* netname "." is special: a "top-level name" */
253                         if(netname) {
254                                 fprintf(stderr, "Only one netname can be given.\n");
255                                 usage(true);
256                                 return false;
257                         }
258
259                         if(optarg && strcmp(optarg, ".")) {
260                                 netname = xstrdup(optarg);
261                         }
262
263                         break;
264
265                 case 'o':                               /* option */
266                         cfg = parse_config_line(optarg, NULL, ++lineno);
267
268                         if(!cfg) {
269                                 return false;
270                         }
271
272                         list_insert_tail(cmdline_conf, cfg);
273                         break;
274
275                 case 'K':                               /* generate public/private keypair */
276                         if(!optarg && optind < argc && *argv[optind] != '-') {
277                                 optarg = argv[optind++];
278                         }
279
280                         if(optarg) {
281                                 generate_keys = atoi(optarg);
282
283                                 if(generate_keys < 512) {
284                                         fprintf(stderr, "Invalid argument `%s'; BITS must be a number equal to or greater than 512.\n",
285                                                 optarg);
286                                         usage(true);
287                                         return false;
288                                 }
289
290                                 generate_keys &= ~7;    /* Round it to bytes */
291                         } else {
292                                 generate_keys = 2048;
293                         }
294
295                         break;
296
297                 case 'R':                               /* chroot to NETNAME dir */
298                         do_chroot = true;
299                         break;
300
301                 case 'U':                               /* setuid to USER */
302                         switchuser = optarg;
303                         break;
304
305                 case 1:                                 /* show help */
306                         show_help = true;
307                         break;
308
309                 case 2:                                 /* show version */
310                         show_version = true;
311                         break;
312
313                 case 3:                                 /* bypass security */
314                         bypass_security = true;
315                         break;
316
317                 case 4:                                 /* write log entries to a file */
318                         use_logfile = true;
319
320                         if(!optarg && optind < argc && *argv[optind] != '-') {
321                                 optarg = argv[optind++];
322                         }
323
324                         if(optarg) {
325                                 if(logfilename) {
326                                         fprintf(stderr, "Only one logfile can be given.\n");
327                                         usage(true);
328                                         return false;
329                                 }
330
331                                 logfilename = xstrdup(optarg);
332                         }
333
334                         break;
335
336                 case 5:                                 /* write PID to a file */
337                         if(pidfilename) {
338                                 fprintf(stderr, "Only one pidfile can be given.\n");
339                                 usage(true);
340                                 return false;
341                         }
342
343                         pidfilename = xstrdup(optarg);
344                         break;
345
346                 case '?':
347                         usage(true);
348                         return false;
349
350                 default:
351                         break;
352                 }
353         }
354
355         if(optind < argc) {
356                 fprintf(stderr, "%s: unrecognized argument '%s'\n", argv[0], argv[optind]);
357                 usage(true);
358                 return false;
359         }
360
361         return true;
362 }
363
364 /* This function prettyprints the key generation process */
365
366 static int indicator(int a, int b, BN_GENCB *cb) {
367         (void)cb;
368
369         switch(a) {
370         case 0:
371                 fprintf(stderr, ".");
372                 break;
373
374         case 1:
375                 fprintf(stderr, "+");
376                 break;
377
378         case 2:
379                 fprintf(stderr, "-");
380                 break;
381
382         case 3:
383                 switch(b) {
384                 case 0:
385                         fprintf(stderr, " p\n");
386                         break;
387
388                 case 1:
389                         fprintf(stderr, " q\n");
390                         break;
391
392                 default:
393                         fprintf(stderr, "?");
394                 }
395
396                 break;
397
398         default:
399                 fprintf(stderr, "?");
400         }
401
402         return 1;
403 }
404
405 /*
406   Generate a public/private RSA keypair, and ask for a file to store
407   them in.
408 */
409 static bool keygen(int bits) {
410         BIGNUM *e = NULL;
411         RSA *rsa_key;
412         FILE *f;
413         char filename[PATH_MAX];
414         BN_GENCB *cb;
415         int result;
416
417         fprintf(stderr, "Generating %d bits keys:\n", bits);
418
419         cb = BN_GENCB_new();
420
421         if(!cb) {
422                 abort();
423         }
424
425         BN_GENCB_set(cb, indicator, NULL);
426
427         rsa_key = RSA_new();
428
429         if(BN_hex2bn(&e, "10001") == 0) {
430                 abort();
431         }
432
433         if(!rsa_key || !e) {
434                 abort();
435         }
436
437         result = RSA_generate_key_ex(rsa_key, bits, e, cb);
438
439         BN_free(e);
440         BN_GENCB_free(cb);
441
442         if(!result) {
443                 fprintf(stderr, "Error during key generation!\n");
444                 RSA_free(rsa_key);
445                 return false;
446         } else {
447                 fprintf(stderr, "Done.\n");
448         }
449
450         snprintf(filename, sizeof(filename), "%s/rsa_key.priv", confbase);
451         f = ask_and_open(filename, "private RSA key");
452
453         if(!f) {
454                 RSA_free(rsa_key);
455                 return false;
456         }
457
458 #ifdef HAVE_FCHMOD
459         /* Make it unreadable for others. */
460         fchmod(fileno(f), 0600);
461 #endif
462
463         fputc('\n', f);
464         PEM_write_RSAPrivateKey(f, rsa_key, NULL, NULL, 0, NULL, NULL);
465         fclose(f);
466
467         char *name = get_name();
468
469         if(name) {
470                 snprintf(filename, sizeof(filename), "%s/hosts/%s", confbase, name);
471                 free(name);
472         } else {
473                 snprintf(filename, sizeof(filename), "%s/rsa_key.pub", confbase);
474         }
475
476         f = ask_and_open(filename, "public RSA key");
477
478         if(!f) {
479                 RSA_free(rsa_key);
480                 return false;
481         }
482
483         fputc('\n', f);
484         PEM_write_RSAPublicKey(f, rsa_key);
485         fclose(f);
486
487         RSA_free(rsa_key);
488
489         return true;
490 }
491
492 /*
493   Set all files and paths according to netname
494 */
495 static void make_names(void) {
496 #ifdef HAVE_MINGW
497         HKEY key;
498         char installdir[1024] = "";
499         DWORD len = sizeof(installdir);
500 #endif
501
502         if(netname) {
503                 xasprintf(&identname, "tinc.%s", netname);
504         } else {
505                 identname = xstrdup("tinc");
506         }
507
508 #ifdef HAVE_MINGW
509
510         if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
511                 if(!RegQueryValueEx(key, NULL, 0, 0, (LPBYTE)installdir, &len)) {
512                         if(!confbase) {
513                                 if(netname) {
514                                         xasprintf(&confbase, "%s/%s", installdir, netname);
515                                 } else {
516                                         xasprintf(&confbase, "%s", installdir);
517                                 }
518                         }
519
520                         if(!logfilename) {
521                                 xasprintf(&logfilename, "%s/tinc.log", confbase);
522                         }
523                 }
524
525                 RegCloseKey(key);
526
527                 if(*installdir) {
528                         return;
529                 }
530         }
531
532 #endif
533
534         if(!pidfilename) {
535                 xasprintf(&pidfilename, RUNSTATEDIR "/%s.pid", identname);
536         }
537
538         if(!logfilename) {
539                 xasprintf(&logfilename, LOCALSTATEDIR "/log/%s.log", identname);
540         }
541
542         if(netname) {
543                 if(!confbase) {
544                         xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
545                 } else {
546                         logger(LOG_INFO, "Both netname and configuration directory given, using the latter...");
547                 }
548         } else {
549                 if(!confbase) {
550                         xasprintf(&confbase, CONFDIR "/tinc");
551                 }
552         }
553 }
554
555 static void free_names() {
556         free(identname);
557         free(netname);
558         free(pidfilename);
559         free(logfilename);
560         free(confbase);
561 }
562
563 static bool drop_privs() {
564 #ifdef HAVE_MINGW
565
566         if(switchuser) {
567                 logger(LOG_ERR, "%s not supported on this platform", "-U");
568                 return false;
569         }
570
571         if(do_chroot) {
572                 logger(LOG_ERR, "%s not supported on this platform", "-R");
573                 return false;
574         }
575
576 #else
577         uid_t uid = 0;
578
579         if(switchuser) {
580                 struct passwd *pw = getpwnam(switchuser);
581
582                 if(!pw) {
583                         logger(LOG_ERR, "unknown user `%s'", switchuser);
584                         return false;
585                 }
586
587                 uid = pw->pw_uid;
588
589                 if(initgroups(switchuser, pw->pw_gid) != 0 ||
590                                 setgid(pw->pw_gid) != 0) {
591                         logger(LOG_ERR, "System call `%s' failed: %s",
592                                "initgroups", strerror(errno));
593                         return false;
594                 }
595
596 #ifndef ANDROID
597 // Not supported in android NDK
598                 endgrent();
599                 endpwent();
600 #endif
601         }
602
603         if(do_chroot) {
604                 tzset();        /* for proper timestamps in logs */
605
606                 if(chroot(confbase) != 0 || chdir("/") != 0) {
607                         logger(LOG_ERR, "System call `%s' failed: %s",
608                                "chroot", strerror(errno));
609                         return false;
610                 }
611
612                 free(confbase);
613                 confbase = xstrdup("");
614         }
615
616         if(switchuser)
617                 if(setuid(uid) != 0) {
618                         logger(LOG_ERR, "System call `%s' failed: %s",
619                                "setuid", strerror(errno));
620                         return false;
621                 }
622
623 #endif
624         return true;
625 }
626
627 #ifdef HAVE_MINGW
628 # define setpriority(level) !SetPriorityClass(GetCurrentProcess(), (level))
629 #else
630 # define NORMAL_PRIORITY_CLASS 0
631 # define BELOW_NORMAL_PRIORITY_CLASS 10
632 # define HIGH_PRIORITY_CLASS -10
633 # define setpriority(level) (setpriority(PRIO_PROCESS, 0, (level)))
634 #endif
635
636 int main(int argc, char **argv) {
637         program_name = argv[0];
638
639         if(!parse_options(argc, argv)) {
640                 return 1;
641         }
642
643         if(show_version) {
644                 printf("%s version %s\n", PACKAGE, VERSION);
645                 printf("Copyright (C) 1998-2019 Ivo Timmermans, Guus Sliepen and others.\n"
646                        "See the AUTHORS file for a complete list.\n\n"
647                        "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
648                        "and you are welcome to redistribute it under certain conditions;\n"
649                        "see the file COPYING for details.\n");
650
651                 return 0;
652         }
653
654         if(show_help) {
655                 usage(false);
656                 return 0;
657         }
658
659         make_names();
660
661         if(kill_tincd) {
662                 return !kill_other(kill_tincd);
663         }
664
665         openlogger("tinc", use_logfile ? LOGMODE_FILE : LOGMODE_STDERR);
666
667         g_argv = argv;
668
669         if(getenv("LISTEN_PID") && atoi(getenv("LISTEN_PID")) == getpid()) {
670                 do_detach = false;
671         }
672
673 #ifdef HAVE_UNSETENV
674         unsetenv("LISTEN_PID");
675 #endif
676
677         init_configuration(&config_tree);
678
679         ENGINE_load_builtin_engines();
680
681         if(generate_keys) {
682                 read_server_config();
683                 return !keygen(generate_keys);
684         }
685
686         if(!read_server_config()) {
687                 return 1;
688         }
689
690 #ifdef HAVE_LZO
691
692         if(lzo_init() != LZO_E_OK) {
693                 logger(LOG_ERR, "Error initializing LZO compressor!");
694                 return 1;
695         }
696
697 #endif
698
699 #ifdef HAVE_MINGW
700
701         if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
702                 logger(LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
703                 return 1;
704         }
705
706         if(!do_detach || !init_service()) {
707                 return main2(argc, argv);
708         } else {
709                 return 1;
710         }
711 }
712
713 int main2(int argc, char **argv) {
714         InitializeCriticalSection(&mutex);
715         EnterCriticalSection(&mutex);
716 #endif
717         char *priority = NULL;
718
719         if(!detach()) {
720                 return 1;
721         }
722
723 #ifdef HAVE_MLOCKALL
724
725         /* Lock all pages into memory if requested.
726          * This has to be done after daemon()/fork() so it works for child.
727          * No need to do that in parent as it's very short-lived. */
728         if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
729                 logger(LOG_ERR, "System call `%s' failed: %s", "mlockall",
730                        strerror(errno));
731                 return 1;
732         }
733
734 #endif
735
736         /* Setup sockets and open device. */
737
738         if(!setup_network()) {
739                 goto end;
740         }
741
742         /* Initiate all outgoing connections. */
743
744         try_outgoing_connections();
745
746         /* Change process priority */
747
748         if(get_config_string(lookup_config(config_tree, "ProcessPriority"), &priority)) {
749                 if(!strcasecmp(priority, "Normal")) {
750                         if(setpriority(NORMAL_PRIORITY_CLASS) != 0) {
751                                 logger(LOG_ERR, "System call `%s' failed: %s",
752                                        "setpriority", strerror(errno));
753                                 goto end;
754                         }
755                 } else if(!strcasecmp(priority, "Low")) {
756                         if(setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
757                                 logger(LOG_ERR, "System call `%s' failed: %s",
758                                        "setpriority", strerror(errno));
759                                 goto end;
760                         }
761                 } else if(!strcasecmp(priority, "High")) {
762                         if(setpriority(HIGH_PRIORITY_CLASS) != 0) {
763                                 logger(LOG_ERR, "System call `%s' failed: %s",
764                                        "setpriority", strerror(errno));
765                                 goto end;
766                         }
767                 } else {
768                         logger(LOG_ERR, "Invalid priority `%s`!", priority);
769                         goto end;
770                 }
771         }
772
773         /* drop privileges */
774         if(!drop_privs()) {
775                 goto end;
776         }
777
778         /* Start main loop. It only exits when tinc is killed. */
779
780         status = main_loop();
781
782         /* Shutdown properly. */
783
784         ifdebug(CONNECTIONS)
785         devops.dump_stats();
786
787         close_network_connections();
788
789 end:
790         logger(LOG_NOTICE, "Terminating");
791
792 #ifndef HAVE_MINGW
793         remove_pid(pidfilename);
794 #endif
795
796         free(priority);
797
798         exit_configuration(&config_tree);
799         list_delete_list(cmdline_conf);
800         free_names();
801
802         return status;
803 }