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