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