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