fixed shutdown order to prevent crash when kernel interface schedules events
[strongswan.git] / src / charon / daemon.c
1 /**
2 * @file daemon.c
3 *
4 * @brief Implementation of daemon_t and main of IKEv2-Daemon.
5 *
6 */
7
8 /*
9 * Copyright (C) 2006 Tobias Brunner, Daniel Roethlisberger
10 * Copyright (C) 2005-2006 Martin Willi
11 * Copyright (C) 2005 Jan Hutter
12 * Hochschule fuer Technik Rapperswil
13 *
14 * This program is free software; you can redistribute it and/or modify it
15 * under the terms of the GNU General Public License as published by the
16 * Free Software Foundation; either version 2 of the License, or (at your
17 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
18 *
19 * This program is distributed in the hope that it will be useful, but
20 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
21 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
22 * for more details.
23 */
24
25 #include <stdio.h>
26 #include <linux/capability.h>
27 #include <sys/prctl.h>
28 #include <signal.h>
29 #include <pthread.h>
30 #include <sys/stat.h>
31 #include <sys/types.h>
32 #include <unistd.h>
33 #include <time.h>
34 #include <string.h>
35 #include <getopt.h>
36 #include <errno.h>
37 #ifdef HAVE_BACKTRACE
38 # include <execinfo.h>
39 #endif /* HAVE_BACKTRACE */
40
41 #include "daemon.h"
42
43 #include <library.h>
44 #include <crypto/ca.h>
45 #include <utils/fetcher.h>
46 #include <config/credentials/local_credential_store.h>
47 #include <config/backends/local_backend.h>
48 #include <sa/authenticators/eap/eap_method.h>
49
50 /* on some distros, a capset definition is missing */
51 #ifdef NO_CAPSET_DEFINED
52 extern int capset(cap_user_header_t hdrp, const cap_user_data_t datap);
53 #endif /* NO_CAPSET_DEFINED */
54
55 #ifdef INTEGRITY_TEST
56 #include <fips/fips.h>
57 #include <fips_signature.h>
58 #endif /* INTEGRITY_TEST */
59
60 typedef struct private_daemon_t private_daemon_t;
61
62 /**
63 * Private additions to daemon_t, contains threads and internal functions.
64 */
65 struct private_daemon_t {
66 /**
67 * Public members of daemon_t.
68 */
69 daemon_t public;
70
71 /**
72 * Signal set used for signal handling.
73 */
74 sigset_t signal_set;
75
76 /**
77 * The thread_id of main-thread.
78 */
79 pthread_t main_thread_id;
80 };
81
82 /**
83 * One and only instance of the daemon.
84 */
85 daemon_t *charon;
86
87 /**
88 * hook in library for debugging messages
89 */
90 extern void (*dbg) (int level, char *fmt, ...);
91
92 /**
93 * Logging hook for library logs, spreads debug message over bus
94 */
95 static void dbg_bus(int level, char *fmt, ...)
96 {
97 va_list args;
98
99 va_start(args, fmt);
100 charon->bus->vsignal(charon->bus, DBG_LIB, level, fmt, args);
101 va_end(args);
102 }
103
104 /**
105 * Logging hook for library logs, using stderr output
106 */
107 static void dbg_stderr(int level, char *fmt, ...)
108 {
109 va_list args;
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 * Run the daemon and handle unix signals
120 */
121 static void run(private_daemon_t *this)
122 {
123 sigset_t set;
124
125 /* handle SIGINT, SIGHUP ans SIGTERM in this handler */
126 sigemptyset(&set);
127 sigaddset(&set, SIGINT);
128 sigaddset(&set, SIGHUP);
129 sigaddset(&set, SIGTERM);
130
131 while (TRUE)
132 {
133 int sig;
134 int error;
135
136 error = sigwait(&set, &sig);
137 if (error)
138 {
139 DBG1(DBG_DMN, "error %d while waiting for a signal", error);
140 return;
141 }
142 switch (sig)
143 {
144 case SIGHUP:
145 {
146 DBG1(DBG_DMN, "signal of type SIGHUP received. Ignored");
147 break;
148 }
149 case SIGINT:
150 {
151 DBG1(DBG_DMN, "signal of type SIGINT received. Shutting down");
152 return;
153 }
154 case SIGTERM:
155 {
156 DBG1(DBG_DMN, "signal of type SIGTERM received. Shutting down");
157 return;
158 }
159 default:
160 {
161 DBG1(DBG_DMN, "unknown signal %d received. Ignored", sig);
162 break;
163 }
164 }
165 }
166 }
167
168 /**
169 * Clean up all daemon resources
170 */
171 static void destroy(private_daemon_t *this)
172 {
173 /* terminate all idle threads */
174 this->public.processor->set_threads(this->public.processor, 0);
175 /* close all IKE_SAs */
176 DESTROY_IF(this->public.ike_sa_manager);
177 DESTROY_IF(this->public.kernel_interface);
178 DESTROY_IF(this->public.scheduler);
179 DESTROY_IF(this->public.interfaces);
180 DESTROY_IF(this->public.backends);
181 DESTROY_IF(this->public.credentials);
182 DESTROY_IF(this->public.sender);
183 DESTROY_IF(this->public.receiver);
184 DESTROY_IF(this->public.socket);
185 /* wait until all threads are gone */
186 DESTROY_IF(this->public.processor);
187
188 /* rehook library logging, shutdown logging */
189 dbg = dbg_stderr;
190 DESTROY_IF(this->public.bus);
191 DESTROY_IF(this->public.outlog);
192 DESTROY_IF(this->public.syslog);
193 DESTROY_IF(this->public.authlog);
194 free(this);
195 }
196
197 /**
198 * Enforce daemon shutdown, with a given reason to do so.
199 */
200 static void kill_daemon(private_daemon_t *this, char *reason)
201 {
202 /* we send SIGTERM, so the daemon can cleanly shut down */
203 DBG1(DBG_DMN, "killing daemon: %s", reason);
204 if (this->main_thread_id == pthread_self())
205 {
206 /* initialization failed, terminate daemon */
207 destroy(this);
208 unlink(PID_FILE);
209 exit(-1);
210 }
211 else
212 {
213 DBG1(DBG_DMN, "sending SIGTERM to ourself");
214 raise(SIGTERM);
215 /* thread must die, since he produced a ciritcal failure and can't continue */
216 pthread_exit(NULL);
217 }
218 }
219
220 /**
221 * drop daemon capabilities
222 */
223 static void drop_capabilities(private_daemon_t *this, bool full)
224 {
225 struct __user_cap_header_struct hdr;
226 struct __user_cap_data_struct data;
227
228 /* CAP_NET_ADMIN is needed to use netlink */
229 u_int32_t keep = (1<<CAP_NET_ADMIN);
230
231 if (full)
232 {
233 # if IPSEC_GID
234 setgid(IPSEC_GID);
235 # endif
236 # if IPSEC_UID
237 setuid(IPSEC_UID);
238 # endif
239 }
240 else
241 {
242 /* CAP_NET_BIND_SERVICE to bind services below port 1024 */
243 keep |= (1<<CAP_NET_BIND_SERVICE);
244 /* CAP_NET_RAW to create RAW sockets */
245 keep |= (1<<CAP_NET_RAW);
246 /* CAP_DAC_READ_SEARCH to read ipsec.secrets */
247 keep |= (1<<CAP_DAC_READ_SEARCH);
248 }
249
250 hdr.version = _LINUX_CAPABILITY_VERSION;
251 hdr.pid = 0;
252 data.effective = data.permitted = keep;
253 data.inheritable = 0;
254
255 if (capset(&hdr, &data))
256 {
257 kill_daemon(this, "unable to drop daemon capabilities");
258 }
259 }
260
261 /**
262 * Initialize the daemon
263 */
264 static bool initialize(private_daemon_t *this, bool syslog, level_t levels[])
265 {
266 signal_t signal;
267
268 /* for uncritical pseudo random numbers */
269 srandom(time(NULL) + getpid());
270
271 /* setup bus and it's listeners first to enable log output */
272 this->public.bus = bus_create();
273 this->public.outlog = file_logger_create(stdout);
274 this->public.syslog = sys_logger_create(LOG_DAEMON);
275 this->public.authlog = sys_logger_create(LOG_AUTHPRIV);
276 this->public.bus->add_listener(this->public.bus, &this->public.syslog->listener);
277 this->public.bus->add_listener(this->public.bus, &this->public.outlog->listener);
278 this->public.bus->add_listener(this->public.bus, &this->public.authlog->listener);
279 this->public.authlog->set_level(this->public.authlog, SIG_ANY, LEVEL_AUDIT);
280 /* set up hook to log dbg message in library via charons message bus */
281 dbg = dbg_bus;
282
283 /* apply loglevels */
284 for (signal = 0; signal < DBG_MAX; signal++)
285 {
286 this->public.syslog->set_level(this->public.syslog,
287 signal, levels[signal]);
288 if (!syslog)
289 {
290 this->public.outlog->set_level(this->public.outlog,
291 signal, levels[signal]);
292 }
293 }
294
295 DBG1(DBG_DMN, "starting charon (strongSwan Version %s)", VERSION);
296
297 #ifdef INTEGRITY_TEST
298 DBG1(DBG_DMN, "integrity test of libstrongswan code");
299 if (fips_verify_hmac_signature(hmac_key, hmac_signature))
300 {
301 DBG1(DBG_DMN, " integrity test passed");
302 }
303 else
304 {
305 DBG1(DBG_DMN, " integrity test failed");
306 return FALSE;
307 }
308 #endif /* INTEGRITY_TEST */
309
310 this->public.ike_sa_manager = ike_sa_manager_create();
311 this->public.processor = processor_create();
312 this->public.scheduler = scheduler_create();
313
314 /* load secrets, ca certificates and crls */
315 this->public.credentials = (credential_store_t*)local_credential_store_create();
316 this->public.credentials->load_ca_certificates(this->public.credentials);
317 this->public.credentials->load_aa_certificates(this->public.credentials);
318 this->public.credentials->load_attr_certificates(this->public.credentials);
319 this->public.credentials->load_ocsp_certificates(this->public.credentials);
320 this->public.credentials->load_crls(this->public.credentials);
321 this->public.credentials->load_secrets(this->public.credentials, FALSE);
322
323 this->public.interfaces = interface_manager_create();
324 this->public.backends = backend_manager_create();
325 this->public.kernel_interface = kernel_interface_create();
326 this->public.socket = socket_create(IKEV2_UDP_PORT, IKEV2_NATT_PORT);
327 this->public.sender = sender_create();
328 this->public.receiver = receiver_create();
329 return TRUE;
330 }
331
332 /**
333 * Handle SIGSEGV/SIGILL signals raised by threads
334 */
335 static void segv_handler(int signal)
336 {
337 #ifdef HAVE_BACKTRACE
338 void *array[20];
339 size_t size;
340 char **strings;
341 size_t i;
342
343 size = backtrace(array, 20);
344 strings = backtrace_symbols(array, size);
345
346 DBG1(DBG_JOB, "thread %u received %s. Dumping %d frames from stack:",
347 pthread_self(), signal == SIGSEGV ? "SIGSEGV" : "SIGILL", size);
348
349 for (i = 0; i < size; i++)
350 {
351 DBG1(DBG_DMN, " %s", strings[i]);
352 }
353 free (strings);
354 #else /* !HAVE_BACKTRACE */
355 DBG1(DBG_DMN, "thread %u received %s",
356 pthread_self(), signal == SIGSEGV ? "SIGSEGV" : "SIGILL");
357 #endif /* HAVE_BACKTRACE */
358 DBG1(DBG_DMN, "killing ourself, received critical signal");
359 raise(SIGKILL);
360 }
361
362 /**
363 * Create the daemon.
364 */
365 private_daemon_t *daemon_create(void)
366 {
367 struct sigaction action;
368 private_daemon_t *this = malloc_thing(private_daemon_t);
369
370 /* assign methods */
371 this->public.kill = (void (*) (daemon_t*,char*))kill_daemon;
372
373 /* NULL members for clean destruction */
374 this->public.socket = NULL;
375 this->public.ike_sa_manager = NULL;
376 this->public.credentials = NULL;
377 this->public.backends = NULL;
378 this->public.sender= NULL;
379 this->public.receiver = NULL;
380 this->public.scheduler = NULL;
381 this->public.kernel_interface = NULL;
382 this->public.processor = NULL;
383 this->public.interfaces = NULL;
384 this->public.bus = NULL;
385 this->public.outlog = NULL;
386 this->public.syslog = NULL;
387 this->public.authlog = NULL;
388
389 this->main_thread_id = pthread_self();
390
391 /* add handler for SEGV and ILL,
392 * add handler for USR1 (cancellation).
393 * INT, TERM and HUP are handled by sigwait() in run() */
394 action.sa_handler = segv_handler;
395 action.sa_flags = 0;
396 sigemptyset(&action.sa_mask);
397 sigaddset(&action.sa_mask, SIGINT);
398 sigaddset(&action.sa_mask, SIGTERM);
399 sigaddset(&action.sa_mask, SIGHUP);
400 sigaction(SIGSEGV, &action, NULL);
401 sigaction(SIGILL, &action, NULL);
402 action.sa_handler = SIG_IGN;
403 sigaction(SIGPIPE, &action, NULL);
404
405 pthread_sigmask(SIG_SETMASK, &action.sa_mask, 0);
406
407 return this;
408 }
409
410 /**
411 * print command line usage and exit
412 */
413 static void usage(const char *msg)
414 {
415 if (msg != NULL && *msg != '\0')
416 {
417 fprintf(stderr, "%s\n", msg);
418 }
419 fprintf(stderr, "Usage: charon\n"
420 " [--help]\n"
421 " [--version]\n"
422 " [--strictcrlpolicy]\n"
423 " [--cachecrls]\n"
424 " [--crlcheckinterval <interval>]\n"
425 " [--eapdir <dir>]\n"
426 " [--use-syslog]\n"
427 " [--debug-<type> <level>]\n"
428 " <type>: log context type (dmn|mgr|ike|chd|job|cfg|knl|net|enc|lib)\n"
429 " <level>: log verbosity (-1 = silent, 0 = audit, 1 = control,\n"
430 " 2 = controlmore, 3 = raw, 4 = private)\n"
431 "\n"
432 );
433 exit(msg == NULL? 0 : 1);
434 }
435
436 /**
437 * Main function, manages the daemon.
438 */
439 int main(int argc, char *argv[])
440 {
441 u_int crl_check_interval = 0;
442 strict_t strict_crl_policy = STRICT_NO;
443 bool cache_crls = FALSE;
444 bool use_syslog = FALSE;
445 char *eapdir = IPSEC_EAPDIR;
446
447 private_daemon_t *private_charon;
448 FILE *pid_file;
449 struct stat stb;
450 level_t levels[DBG_MAX];
451 int signal;
452
453 private_charon = daemon_create();
454 charon = (daemon_t*)private_charon;
455
456 /* drop the capabilities we won't need for initialization */
457 prctl(PR_SET_KEEPCAPS, 1);
458 drop_capabilities(private_charon, FALSE);
459
460 /* use CTRL loglevel for default */
461 for (signal = 0; signal < DBG_MAX; signal++)
462 {
463 levels[signal] = LEVEL_CTRL;
464 }
465
466 /* handle arguments */
467 for (;;)
468 {
469 struct option long_opts[] = {
470 { "help", no_argument, NULL, 'h' },
471 { "version", no_argument, NULL, 'v' },
472 { "use-syslog", no_argument, NULL, 'l' },
473 { "strictcrlpolicy", required_argument, NULL, 'r' },
474 { "cachecrls", no_argument, NULL, 'C' },
475 { "crlcheckinterval", required_argument, NULL, 'x' },
476 { "eapdir", required_argument, NULL, 'e' },
477 /* TODO: handle "debug-all" */
478 { "debug-dmn", required_argument, &signal, DBG_DMN },
479 { "debug-mgr", required_argument, &signal, DBG_MGR },
480 { "debug-ike", required_argument, &signal, DBG_IKE },
481 { "debug-chd", required_argument, &signal, DBG_CHD },
482 { "debug-job", required_argument, &signal, DBG_JOB },
483 { "debug-cfg", required_argument, &signal, DBG_CFG },
484 { "debug-knl", required_argument, &signal, DBG_KNL },
485 { "debug-net", required_argument, &signal, DBG_NET },
486 { "debug-enc", required_argument, &signal, DBG_ENC },
487 { "debug-lib", required_argument, &signal, DBG_LIB },
488 { 0,0,0,0 }
489 };
490
491 int c = getopt_long(argc, argv, "", long_opts, NULL);
492 switch (c)
493 {
494 case EOF:
495 break;
496 case 'h':
497 usage(NULL);
498 break;
499 case 'v':
500 printf("Linux strongSwan %s\n", VERSION);
501 exit(0);
502 case 'l':
503 use_syslog = TRUE;
504 continue;
505 case 'r':
506 strict_crl_policy = atoi(optarg);
507 continue;
508 case 'C':
509 cache_crls = TRUE;
510 continue;
511 case 'x':
512 crl_check_interval = atoi(optarg);
513 continue;
514 case 'e':
515 eapdir = optarg;
516 continue;
517 case 0:
518 /* option is in signal */
519 levels[signal] = atoi(optarg);
520 continue;
521 default:
522 usage("");
523 break;
524 }
525 break;
526 }
527
528 /* initialize daemon */
529 if (!initialize(private_charon, use_syslog, levels))
530 {
531 DBG1(DBG_DMN, "initialization failed - aborting charon");
532 destroy(private_charon);
533 exit(-1);
534 }
535
536 /* initialize fetcher_t class */
537 fetcher_initialize();
538 /* load pluggable EAP modules */
539 eap_method_load(eapdir);
540
541 /* set strict_crl_policy, cache_crls and crl_check_interval options */
542 ca_info_set_options(strict_crl_policy, cache_crls, crl_check_interval);
543
544 /* check/setup PID file */
545 if (stat(PID_FILE, &stb) == 0)
546 {
547 DBG1(DBG_DMN, "charon already running (\""PID_FILE"\" exists)");
548 destroy(private_charon);
549 exit(-1);
550 }
551 pid_file = fopen(PID_FILE, "w");
552 if (pid_file)
553 {
554 fprintf(pid_file, "%d\n", getpid());
555 fclose(pid_file);
556 }
557
558 /* drop additional capabilites (bind & root) */
559 drop_capabilities(private_charon, TRUE);
560
561 /* start the engine, go multithreaded */
562 charon->processor->set_threads(charon->processor, WORKER_THREADS);
563
564 /* run daemon */
565 run(private_charon);
566
567 eap_method_unload();
568 fetcher_finalize();
569 /* normal termination, cleanup and exit */
570 destroy(private_charon);
571 unlink(PID_FILE);
572
573 return 0;
574 }
575