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