339846a856061ef7b72c9c93467c13de86a46dd8
[strongswan.git] / src / charon / daemon.c
1 /*
2 * Copyright (C) 2006-2009 Tobias Brunner
3 * Copyright (C) 2006 Daniel Roethlisberger
4 * Copyright (C) 2005-2008 Martin Willi
5 * Copyright (C) 2005 Jan Hutter
6 * Hochschule fuer Technik Rapperswil
7 *
8 * This program is free software; you can redistribute it and/or modify it
9 * under the terms of the GNU General Public License as published by the
10 * Free Software Foundation; either version 2 of the License, or (at your
11 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
12 *
13 * This program is distributed in the hope that it will be useful, but
14 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
15 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 * for more details.
17 */
18
19 #include <stdio.h>
20 #ifdef HAVE_PRCTL
21 #include <sys/prctl.h>
22 #endif
23 #include <signal.h>
24 #include <pthread.h>
25 #include <sys/stat.h>
26 #include <sys/types.h>
27 #include <unistd.h>
28 #include <time.h>
29 #include <string.h>
30 #include <getopt.h>
31 #include <errno.h>
32 #include <pwd.h>
33 #include <grp.h>
34 #ifdef CAPABILITIES
35 #include <sys/capability.h>
36 #endif /* CAPABILITIES */
37
38 #include "daemon.h"
39
40 #include <library.h>
41 #include <utils/backtrace.h>
42 #include <config/traffic_selector.h>
43 #include <config/proposal.h>
44
45 #ifdef INTEGRITY_TEST
46 #include <fips/fips.h>
47 #include <fips/fips_signature.h>
48 #endif /* INTEGRITY_TEST */
49
50 typedef struct private_daemon_t private_daemon_t;
51
52 /**
53 * Private additions to daemon_t, contains threads and internal functions.
54 */
55 struct private_daemon_t {
56 /**
57 * Public members of daemon_t.
58 */
59 daemon_t public;
60
61 /**
62 * Signal set used for signal handling.
63 */
64 sigset_t signal_set;
65
66 #ifdef CAPABILITIES
67 /**
68 * capabilities to keep
69 */
70 cap_t caps;
71 #endif /* CAPABILITIES */
72 };
73
74 /**
75 * One and only instance of the daemon.
76 */
77 daemon_t *charon;
78
79 /**
80 * hook in library for debugging messages
81 */
82 extern void (*dbg) (int level, char *fmt, ...);
83
84 /**
85 * Logging hook for library logs, spreads debug message over bus
86 */
87 static void dbg_bus(int level, char *fmt, ...)
88 {
89 va_list args;
90
91 va_start(args, fmt);
92 charon->bus->vlog(charon->bus, DBG_LIB, level, fmt, args);
93 va_end(args);
94 }
95
96 /**
97 * Logging hook for library logs, using stderr output
98 */
99 static void dbg_stderr(int level, char *fmt, ...)
100 {
101 va_list args;
102
103 if (level <= 1)
104 {
105 va_start(args, fmt);
106 fprintf(stderr, "00[LIB] ");
107 vfprintf(stderr, fmt, args);
108 fprintf(stderr, "\n");
109 va_end(args);
110 }
111 }
112
113 /**
114 * Run the daemon and handle unix signals
115 */
116 static void run(private_daemon_t *this)
117 {
118 sigset_t set;
119
120 /* handle SIGINT, SIGHUP ans SIGTERM in this handler */
121 sigemptyset(&set);
122 sigaddset(&set, SIGINT);
123 sigaddset(&set, SIGHUP);
124 sigaddset(&set, SIGTERM);
125
126 while (TRUE)
127 {
128 int sig;
129 int error;
130
131 error = sigwait(&set, &sig);
132 if (error)
133 {
134 DBG1(DBG_DMN, "error %d while waiting for a signal", error);
135 return;
136 }
137 switch (sig)
138 {
139 case SIGHUP:
140 {
141 DBG1(DBG_DMN, "signal of type SIGHUP received. Ignored");
142 break;
143 }
144 case SIGINT:
145 {
146 DBG1(DBG_DMN, "signal of type SIGINT received. Shutting down");
147 return;
148 }
149 case SIGTERM:
150 {
151 DBG1(DBG_DMN, "signal of type SIGTERM received. Shutting down");
152 return;
153 }
154 default:
155 {
156 DBG1(DBG_DMN, "unknown signal %d received. Ignored", sig);
157 break;
158 }
159 }
160 }
161 }
162
163 /**
164 * Clean up all daemon resources
165 */
166 static void destroy(private_daemon_t *this)
167 {
168 /* terminate all idle threads */
169 if (this->public.processor)
170 {
171 this->public.processor->set_threads(this->public.processor, 0);
172 }
173 /* close all IKE_SAs */
174 if (this->public.ike_sa_manager)
175 {
176 this->public.ike_sa_manager->flush(this->public.ike_sa_manager);
177 }
178 /* unload plugins to release threads */
179 lib->plugins->unload(lib->plugins);
180 #ifdef CAPABILITIES
181 cap_free(this->caps);
182 #endif /* CAPABILITIES */
183 DESTROY_IF(this->public.ike_sa_manager);
184 DESTROY_IF(this->public.kernel_interface);
185 DESTROY_IF(this->public.scheduler);
186 DESTROY_IF(this->public.controller);
187 DESTROY_IF(this->public.eap);
188 DESTROY_IF(this->public.sim);
189 #ifdef ME
190 DESTROY_IF(this->public.connect_manager);
191 DESTROY_IF(this->public.mediation_manager);
192 #endif /* ME */
193 DESTROY_IF(this->public.backends);
194 DESTROY_IF(this->public.attributes);
195 DESTROY_IF(this->public.credentials);
196 DESTROY_IF(this->public.sender);
197 DESTROY_IF(this->public.receiver);
198 DESTROY_IF(this->public.socket);
199 /* wait until all threads are gone */
200 DESTROY_IF(this->public.processor);
201
202 /* rehook library logging, shutdown logging */
203 dbg = dbg_stderr;
204 DESTROY_IF(this->public.bus);
205 this->public.file_loggers->destroy_offset(this->public.file_loggers,
206 offsetof(file_logger_t, destroy));
207 this->public.sys_loggers->destroy_offset(this->public.sys_loggers,
208 offsetof(sys_logger_t, destroy));
209 free(this);
210 }
211
212 /**
213 * Enforce daemon shutdown, with a given reason to do so.
214 */
215 static void kill_daemon(private_daemon_t *this, char *reason)
216 {
217 /* we send SIGTERM, so the daemon can cleanly shut down */
218 if (this->public.bus)
219 {
220 DBG1(DBG_DMN, "killing daemon: %s", reason);
221 }
222 else
223 {
224 fprintf(stderr, "killing daemon: %s\n", reason);
225 }
226 if (this->public.main_thread_id == pthread_self())
227 {
228 /* initialization failed, terminate daemon */
229 unlink(PID_FILE);
230 exit(-1);
231 }
232 else
233 {
234 DBG1(DBG_DMN, "sending SIGTERM to ourself");
235 pthread_kill(this->public.main_thread_id, SIGTERM);
236 /* thread must die, since he produced a ciritcal failure and can't continue */
237 pthread_exit(NULL);
238 }
239 }
240
241 /**
242 * drop daemon capabilities
243 */
244 static void drop_capabilities(private_daemon_t *this)
245 {
246 #ifdef HAVE_PRCTL
247 prctl(PR_SET_KEEPCAPS, 1);
248 #endif
249
250 if (setgid(charon->gid) != 0)
251 {
252 kill_daemon(this, "change to unprivileged group failed");
253 }
254 if (setuid(charon->uid) != 0)
255 {
256 kill_daemon(this, "change to unprivileged user failed");
257 }
258
259 #ifdef CAPABILITIES
260 if (cap_set_proc(this->caps) != 0)
261 {
262 kill_daemon(this, "unable to drop daemon capabilities");
263 }
264 #endif /* CAPABILITIES */
265 }
266
267 /**
268 * Implementation of daemon_t.keep_cap
269 */
270 static void keep_cap(private_daemon_t *this, u_int cap)
271 {
272 #ifdef CAPABILITIES
273 cap_set_flag(this->caps, CAP_EFFECTIVE, 1, &cap, CAP_SET);
274 cap_set_flag(this->caps, CAP_INHERITABLE, 1, &cap, CAP_SET);
275 cap_set_flag(this->caps, CAP_PERMITTED, 1, &cap, CAP_SET);
276 #endif /* CAPABILITIES */
277 }
278
279 /**
280 * lookup UID and GID
281 */
282 static void lookup_uid_gid(private_daemon_t *this)
283 {
284 #ifdef IPSEC_USER
285 {
286 char buf[1024];
287 struct passwd passwd, *pwp;
288
289 if (getpwnam_r(IPSEC_USER, &passwd, buf, sizeof(buf), &pwp) != 0 ||
290 pwp == NULL)
291 {
292 kill_daemon(this, "resolving user '"IPSEC_USER"' failed");
293 }
294 charon->uid = pwp->pw_uid;
295 }
296 #endif
297 #ifdef IPSEC_GROUP
298 {
299 char buf[1024];
300 struct group group, *grp;
301
302 if (getgrnam_r(IPSEC_GROUP, &group, buf, sizeof(buf), &grp) != 0 ||
303 grp == NULL)
304 {
305 kill_daemon(this, "resolving group '"IPSEC_GROUP"' failed");
306 }
307 charon->gid = grp->gr_gid;
308 }
309 #endif
310 }
311
312 /**
313 * Log loaded plugins
314 */
315 static void print_plugins()
316 {
317 char buf[512], *plugin;
318 int len = 0;
319 enumerator_t *enumerator;
320
321 enumerator = lib->plugins->create_plugin_enumerator(lib->plugins);
322 while (len < sizeof(buf) && enumerator->enumerate(enumerator, &plugin))
323 {
324 len += snprintf(&buf[len], sizeof(buf)-len, "%s ", plugin);
325 }
326 enumerator->destroy(enumerator);
327 DBG1(DBG_DMN, "loaded plugins: %s", buf);
328 }
329
330 /**
331 * Initialize logging
332 */
333 static void initialize_loggers(private_daemon_t *this, bool use_stderr,
334 level_t levels[])
335 {
336 sys_logger_t *sys_logger;
337 file_logger_t *file_logger;
338 enumerator_t *enumerator;
339 char *facility, *filename;
340 int loggers_defined = 0;
341 debug_t group;
342 level_t def;
343 bool append;
344 FILE *file;
345
346 /* setup sysloggers */
347 enumerator = lib->settings->create_section_enumerator(lib->settings,
348 "charon.syslog");
349 while (enumerator->enumerate(enumerator, &facility))
350 {
351 loggers_defined++;
352 if (streq(facility, "daemon"))
353 {
354 sys_logger = sys_logger_create(LOG_DAEMON);
355 }
356 else if (streq(facility, "auth"))
357 {
358 sys_logger = sys_logger_create(LOG_AUTHPRIV);
359 }
360 else
361 {
362 continue;
363 }
364 def = lib->settings->get_int(lib->settings,
365 "charon.syslog.%s.default", 1, facility);
366 for (group = 0; group < DBG_MAX; group++)
367 {
368 sys_logger->set_level(sys_logger, group,
369 lib->settings->get_int(lib->settings,
370 "charon.syslog.%s.%N", def,
371 facility, debug_lower_names, group));
372 }
373 this->public.sys_loggers->insert_last(this->public.sys_loggers,
374 sys_logger);
375 this->public.bus->add_listener(this->public.bus, &sys_logger->listener);
376 }
377 enumerator->destroy(enumerator);
378
379 /* and file loggers */
380 enumerator = lib->settings->create_section_enumerator(lib->settings,
381 "charon.filelog");
382 while (enumerator->enumerate(enumerator, &filename))
383 {
384 loggers_defined++;
385 if (streq(filename, "stderr"))
386 {
387 file = stderr;
388 }
389 else if (streq(filename, "stdout"))
390 {
391 file = stdout;
392 }
393 else
394 {
395 append = lib->settings->get_bool(lib->settings,
396 "charon.filelog.%s.append", TRUE, filename);
397 file = fopen(filename, append ? "a" : "w");
398 if (file == NULL)
399 {
400 DBG1(DBG_DMN, "opening file %s for logging failed: %s",
401 filename, strerror(errno));
402 continue;
403 }
404 }
405 file_logger = file_logger_create(file);
406 def = lib->settings->get_int(lib->settings,
407 "charon.filelog.%s.default", 1, filename);
408 for (group = 0; group < DBG_MAX; group++)
409 {
410 file_logger->set_level(file_logger, group,
411 lib->settings->get_int(lib->settings,
412 "charon.filelog.%s.%N", def,
413 filename, debug_lower_names, group));
414 }
415 this->public.file_loggers->insert_last(this->public.file_loggers,
416 file_logger);
417 this->public.bus->add_listener(this->public.bus, &file_logger->listener);
418
419 }
420 enumerator->destroy(enumerator);
421
422 /* set up legacy style default loggers provided via command-line */
423 if (!loggers_defined)
424 {
425 /* set up default stdout file_logger */
426 file_logger = file_logger_create(stdout);
427 this->public.bus->add_listener(this->public.bus, &file_logger->listener);
428 this->public.file_loggers->insert_last(this->public.file_loggers,
429 file_logger);
430 /* set up default daemon sys_logger */
431 sys_logger = sys_logger_create(LOG_DAEMON);
432 this->public.bus->add_listener(this->public.bus, &sys_logger->listener);
433 this->public.sys_loggers->insert_last(this->public.sys_loggers,
434 sys_logger);
435 for (group = 0; group < DBG_MAX; group++)
436 {
437 sys_logger->set_level(sys_logger, group, levels[group]);
438 if (use_stderr)
439 {
440 file_logger->set_level(file_logger, group, levels[group]);
441 }
442 }
443
444 /* set up default auth sys_logger */
445 sys_logger = sys_logger_create(LOG_AUTHPRIV);
446 this->public.bus->add_listener(this->public.bus, &sys_logger->listener);
447 this->public.sys_loggers->insert_last(this->public.sys_loggers,
448 sys_logger);
449 sys_logger->set_level(sys_logger, DBG_ANY, LEVEL_AUDIT);
450 }
451 }
452
453 /**
454 * Initialize the daemon
455 */
456 static bool initialize(private_daemon_t *this, bool syslog, level_t levels[])
457 {
458 /* for uncritical pseudo random numbers */
459 srandom(time(NULL) + getpid());
460
461 /* setup bus and it's listeners first to enable log output */
462 this->public.bus = bus_create();
463 /* set up hook to log dbg message in library via charons message bus */
464 dbg = dbg_bus;
465
466 initialize_loggers(this, !syslog, levels);
467
468 DBG1(DBG_DMN, "starting charon (strongSwan Version %s)", VERSION);
469
470 /* load secrets, ca certificates and crls */
471 this->public.processor = processor_create();
472 this->public.scheduler = scheduler_create();
473 this->public.credentials = credential_manager_create();
474 this->public.controller = controller_create();
475 this->public.eap = eap_manager_create();
476 this->public.sim = sim_manager_create();
477 this->public.backends = backend_manager_create();
478 this->public.attributes = attribute_manager_create();
479 this->public.kernel_interface = kernel_interface_create();
480 this->public.socket = socket_create();
481
482 /* load plugins, further infrastructure may need it */
483 lib->plugins->load(lib->plugins, IPSEC_PLUGINDIR,
484 lib->settings->get_str(lib->settings, "charon.load", PLUGINS));
485
486 print_plugins();
487
488 /* create the kernel interfaces */
489 this->public.kernel_interface->create_interfaces(this->public.kernel_interface);
490
491 #ifdef INTEGRITY_TEST
492 DBG1(DBG_DMN, "integrity test of libstrongswan code");
493 if (fips_verify_hmac_signature(hmac_key, hmac_signature))
494 {
495 DBG1(DBG_DMN, " integrity test passed");
496 }
497 else
498 {
499 DBG1(DBG_DMN, " integrity test failed");
500 return FALSE;
501 }
502 #endif /* INTEGRITY_TEST */
503
504 this->public.ike_sa_manager = ike_sa_manager_create();
505 if (this->public.ike_sa_manager == NULL)
506 {
507 return FALSE;
508 }
509 this->public.sender = sender_create();
510 this->public.receiver = receiver_create();
511 if (this->public.receiver == NULL)
512 {
513 return FALSE;
514 }
515
516 #ifdef ME
517 this->public.connect_manager = connect_manager_create();
518 if (this->public.connect_manager == NULL)
519 {
520 return FALSE;
521 }
522 this->public.mediation_manager = mediation_manager_create();
523 #endif /* ME */
524
525 return TRUE;
526 }
527
528 /**
529 * Handle SIGSEGV/SIGILL signals raised by threads
530 */
531 static void segv_handler(int signal)
532 {
533 backtrace_t *backtrace;
534
535 DBG1(DBG_DMN, "thread %u received %d", pthread_self(), signal);
536 backtrace = backtrace_create(2);
537 backtrace->log(backtrace, stderr);
538 backtrace->destroy(backtrace);
539
540 DBG1(DBG_DMN, "killing ourself, received critical signal");
541 raise(SIGKILL);
542 }
543
544 /**
545 * Create the daemon.
546 */
547 private_daemon_t *daemon_create(void)
548 {
549 struct sigaction action;
550 private_daemon_t *this = malloc_thing(private_daemon_t);
551
552 /* assign methods */
553 this->public.kill = (void (*) (daemon_t*,char*))kill_daemon;
554 this->public.keep_cap = (void(*)(daemon_t*, u_int cap))keep_cap;
555
556 /* NULL members for clean destruction */
557 this->public.socket = NULL;
558 this->public.ike_sa_manager = NULL;
559 this->public.credentials = NULL;
560 this->public.backends = NULL;
561 this->public.attributes = NULL;
562 this->public.sender= NULL;
563 this->public.receiver = NULL;
564 this->public.scheduler = NULL;
565 this->public.kernel_interface = NULL;
566 this->public.processor = NULL;
567 this->public.controller = NULL;
568 this->public.eap = NULL;
569 this->public.sim = NULL;
570 this->public.bus = NULL;
571 this->public.file_loggers = linked_list_create();
572 this->public.sys_loggers = linked_list_create();
573 #ifdef ME
574 this->public.connect_manager = NULL;
575 this->public.mediation_manager = NULL;
576 #endif /* ME */
577 this->public.uid = 0;
578 this->public.gid = 0;
579
580 this->public.main_thread_id = pthread_self();
581 #ifdef CAPABILITIES
582 this->caps = cap_init();
583 keep_cap(this, CAP_NET_ADMIN);
584 if (lib->leak_detective)
585 {
586 keep_cap(this, CAP_SYS_NICE);
587 }
588 #endif /* CAPABILITIES */
589
590 /* add handler for SEGV and ILL,
591 * add handler for USR1 (cancellation).
592 * INT, TERM and HUP are handled by sigwait() in run() */
593 action.sa_handler = segv_handler;
594 action.sa_flags = 0;
595 sigemptyset(&action.sa_mask);
596 sigaddset(&action.sa_mask, SIGINT);
597 sigaddset(&action.sa_mask, SIGTERM);
598 sigaddset(&action.sa_mask, SIGHUP);
599 sigaction(SIGSEGV, &action, NULL);
600 sigaction(SIGILL, &action, NULL);
601 sigaction(SIGBUS, &action, NULL);
602 action.sa_handler = SIG_IGN;
603 sigaction(SIGPIPE, &action, NULL);
604
605 pthread_sigmask(SIG_SETMASK, &action.sa_mask, 0);
606
607 return this;
608 }
609
610 /**
611 * print command line usage and exit
612 */
613 static void usage(const char *msg)
614 {
615 if (msg != NULL && *msg != '\0')
616 {
617 fprintf(stderr, "%s\n", msg);
618 }
619 fprintf(stderr, "Usage: charon\n"
620 " [--help]\n"
621 " [--version]\n"
622 " [--use-syslog]\n"
623 " [--debug-<type> <level>]\n"
624 " <type>: log context type (dmn|mgr|ike|chd|job|cfg|knl|net|enc|lib)\n"
625 " <level>: log verbosity (-1 = silent, 0 = audit, 1 = control,\n"
626 " 2 = controlmore, 3 = raw, 4 = private)\n"
627 "\n"
628 );
629 exit(msg == NULL? 0 : 1);
630 }
631
632 /**
633 * Main function, manages the daemon.
634 */
635 int main(int argc, char *argv[])
636 {
637 bool use_syslog = FALSE;
638
639 private_daemon_t *private_charon;
640 FILE *pid_file;
641 struct stat stb;
642 level_t levels[DBG_MAX];
643 int group;
644
645 /* logging for library during initialization, as we have no bus yet */
646 dbg = dbg_stderr;
647
648 /* initialize library */
649 library_init(STRONGSWAN_CONF);
650 lib->printf_hook->add_handler(lib->printf_hook, 'R',
651 traffic_selector_printf_hook,
652 PRINTF_HOOK_ARGTYPE_POINTER,
653 PRINTF_HOOK_ARGTYPE_END);
654 lib->printf_hook->add_handler(lib->printf_hook, 'P',
655 proposal_printf_hook,
656 PRINTF_HOOK_ARGTYPE_POINTER,
657 PRINTF_HOOK_ARGTYPE_END);
658 private_charon = daemon_create();
659 charon = (daemon_t*)private_charon;
660
661 lookup_uid_gid(private_charon);
662
663 /* use CTRL loglevel for default */
664 for (group = 0; group < DBG_MAX; group++)
665 {
666 levels[group] = LEVEL_CTRL;
667 }
668
669 /* handle arguments */
670 for (;;)
671 {
672 struct option long_opts[] = {
673 { "help", no_argument, NULL, 'h' },
674 { "version", no_argument, NULL, 'v' },
675 { "use-syslog", no_argument, NULL, 'l' },
676 /* TODO: handle "debug-all" */
677 { "debug-dmn", required_argument, &group, DBG_DMN },
678 { "debug-mgr", required_argument, &group, DBG_MGR },
679 { "debug-ike", required_argument, &group, DBG_IKE },
680 { "debug-chd", required_argument, &group, DBG_CHD },
681 { "debug-job", required_argument, &group, DBG_JOB },
682 { "debug-cfg", required_argument, &group, DBG_CFG },
683 { "debug-knl", required_argument, &group, DBG_KNL },
684 { "debug-net", required_argument, &group, DBG_NET },
685 { "debug-enc", required_argument, &group, DBG_ENC },
686 { "debug-lib", required_argument, &group, DBG_LIB },
687 { 0,0,0,0 }
688 };
689
690 int c = getopt_long(argc, argv, "", long_opts, NULL);
691 switch (c)
692 {
693 case EOF:
694 break;
695 case 'h':
696 usage(NULL);
697 break;
698 case 'v':
699 printf("Linux strongSwan %s\n", VERSION);
700 exit(0);
701 case 'l':
702 use_syslog = TRUE;
703 continue;
704 case 0:
705 /* option is in group */
706 levels[group] = atoi(optarg);
707 continue;
708 default:
709 usage("");
710 break;
711 }
712 break;
713 }
714
715 /* initialize daemon */
716 if (!initialize(private_charon, use_syslog, levels))
717 {
718 DBG1(DBG_DMN, "initialization failed - aborting charon");
719 destroy(private_charon);
720 exit(-1);
721 }
722
723 /* check/setup PID file */
724 if (stat(PID_FILE, &stb) == 0)
725 {
726 DBG1(DBG_DMN, "charon already running (\""PID_FILE"\" exists)");
727 destroy(private_charon);
728 exit(-1);
729 }
730 pid_file = fopen(PID_FILE, "w");
731 if (pid_file)
732 {
733 fprintf(pid_file, "%d\n", getpid());
734 ignore_result(fchown(fileno(pid_file), charon->uid, charon->gid));
735 fclose(pid_file);
736 }
737
738 /* drop the capabilities we won't need */
739 drop_capabilities(private_charon);
740
741 /* start the engine, go multithreaded */
742 charon->processor->set_threads(charon->processor,
743 lib->settings->get_int(lib->settings, "charon.threads",
744 DEFAULT_THREADS));
745
746 /* run daemon */
747 run(private_charon);
748
749 /* normal termination, cleanup and exit */
750 destroy(private_charon);
751 unlink(PID_FILE);
752
753 library_deinit();
754
755 return 0;
756 }
757