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