fixed daemon kill before threads are spawned
[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 /* Copyright (C) 2006-2007 Tobias Brunner
9 * Copyright (C) 2006 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 #ifdef P2P
181 DESTROY_IF(this->public.connect_manager);
182 DESTROY_IF(this->public.mediation_manager);
183 #endif /* P2P */
184 DESTROY_IF(this->public.backends);
185 DESTROY_IF(this->public.credentials);
186 DESTROY_IF(this->public.sender);
187 DESTROY_IF(this->public.receiver);
188 DESTROY_IF(this->public.socket);
189 /* wait until all threads are gone */
190 DESTROY_IF(this->public.processor);
191
192 /* rehook library logging, shutdown logging */
193 dbg = dbg_stderr;
194 DESTROY_IF(this->public.bus);
195 DESTROY_IF(this->public.outlog);
196 DESTROY_IF(this->public.syslog);
197 DESTROY_IF(this->public.authlog);
198 free(this);
199 }
200
201 /**
202 * Enforce daemon shutdown, with a given reason to do so.
203 */
204 static void kill_daemon(private_daemon_t *this, char *reason)
205 {
206 /* we send SIGTERM, so the daemon can cleanly shut down */
207 DBG1(DBG_DMN, "killing daemon: %s", reason);
208 if (this->main_thread_id == pthread_self())
209 {
210 /* initialization failed, terminate daemon */
211 destroy(this);
212 unlink(PID_FILE);
213 exit(-1);
214 }
215 else
216 {
217 DBG1(DBG_DMN, "sending SIGTERM to ourself");
218 raise(SIGTERM);
219 /* thread must die, since he produced a ciritcal failure and can't continue */
220 pthread_exit(NULL);
221 }
222 }
223
224 /**
225 * drop daemon capabilities
226 */
227 static void drop_capabilities(private_daemon_t *this, bool full)
228 {
229 struct __user_cap_header_struct hdr;
230 struct __user_cap_data_struct data;
231
232 /* CAP_NET_ADMIN is needed to use netlink */
233 u_int32_t keep = (1<<CAP_NET_ADMIN);
234
235 if (full)
236 {
237 # if IPSEC_GID
238 if (setgid(IPSEC_GID) != 0)
239 {
240 kill_daemon(this, "changing GID to unprivileged group failed");
241 }
242 # endif
243 # if IPSEC_UID
244 if (setuid(IPSEC_UID) != 0)
245 {
246 kill_daemon(this, "changing UID to unprivileged user failed");
247 }
248 # endif
249 }
250 else
251 {
252 /* CAP_NET_BIND_SERVICE to bind services below port 1024 */
253 keep |= (1<<CAP_NET_BIND_SERVICE);
254 /* CAP_NET_RAW to create RAW sockets */
255 keep |= (1<<CAP_NET_RAW);
256 /* CAP_DAC_READ_SEARCH to read ipsec.secrets */
257 keep |= (1<<CAP_DAC_READ_SEARCH);
258 /* CAP_CHOWN to change file permissions (socket permissions) */
259 keep |= (1<<CAP_CHOWN);
260 /* CAP_SETUID to call setuid() */
261 keep |= (1<<CAP_SETUID);
262 /* CAP_SETGID to call setgid() */
263 keep |= (1<<CAP_SETGID);
264 }
265
266 hdr.version = _LINUX_CAPABILITY_VERSION;
267 hdr.pid = 0;
268 data.inheritable = data.effective = data.permitted = keep;
269
270 if (capset(&hdr, &data))
271 {
272 kill_daemon(this, "unable to drop daemon capabilities");
273 }
274 }
275
276 /**
277 * Initialize the daemon
278 */
279 static bool initialize(private_daemon_t *this, bool syslog, level_t levels[])
280 {
281 signal_t signal;
282
283 /* for uncritical pseudo random numbers */
284 srandom(time(NULL) + getpid());
285
286 /* setup bus and it's listeners first to enable log output */
287 this->public.bus = bus_create();
288 this->public.outlog = file_logger_create(stdout);
289 this->public.syslog = sys_logger_create(LOG_DAEMON);
290 this->public.authlog = sys_logger_create(LOG_AUTHPRIV);
291 this->public.bus->add_listener(this->public.bus, &this->public.syslog->listener);
292 this->public.bus->add_listener(this->public.bus, &this->public.outlog->listener);
293 this->public.bus->add_listener(this->public.bus, &this->public.authlog->listener);
294 this->public.authlog->set_level(this->public.authlog, SIG_ANY, LEVEL_AUDIT);
295 /* set up hook to log dbg message in library via charons message bus */
296 dbg = dbg_bus;
297
298 /* apply loglevels */
299 for (signal = 0; signal < DBG_MAX; signal++)
300 {
301 this->public.syslog->set_level(this->public.syslog,
302 signal, levels[signal]);
303 if (!syslog)
304 {
305 this->public.outlog->set_level(this->public.outlog,
306 signal, levels[signal]);
307 }
308 }
309
310 DBG1(DBG_DMN, "starting charon (strongSwan Version %s)", VERSION);
311
312 #ifdef INTEGRITY_TEST
313 DBG1(DBG_DMN, "integrity test of libstrongswan code");
314 if (fips_verify_hmac_signature(hmac_key, hmac_signature))
315 {
316 DBG1(DBG_DMN, " integrity test passed");
317 }
318 else
319 {
320 DBG1(DBG_DMN, " integrity test failed");
321 return FALSE;
322 }
323 #endif /* INTEGRITY_TEST */
324
325 this->public.ike_sa_manager = ike_sa_manager_create();
326 this->public.processor = processor_create();
327 this->public.scheduler = scheduler_create();
328
329 /* load secrets, ca certificates and crls */
330 this->public.credentials = (credential_store_t*)local_credential_store_create();
331 this->public.credentials->load_ca_certificates(this->public.credentials);
332 this->public.credentials->load_aa_certificates(this->public.credentials);
333 this->public.credentials->load_attr_certificates(this->public.credentials);
334 this->public.credentials->load_ocsp_certificates(this->public.credentials);
335 this->public.credentials->load_crls(this->public.credentials);
336 this->public.credentials->load_secrets(this->public.credentials, FALSE);
337
338 this->public.interfaces = interface_manager_create();
339 this->public.backends = backend_manager_create();
340 this->public.kernel_interface = kernel_interface_create();
341 this->public.socket = socket_create(IKEV2_UDP_PORT, IKEV2_NATT_PORT);
342 this->public.sender = sender_create();
343 this->public.receiver = receiver_create();
344
345 #ifdef P2P
346 this->public.connect_manager = connect_manager_create();
347 this->public.mediation_manager = mediation_manager_create();
348 #endif /* P2P */
349
350 return TRUE;
351 }
352
353 /**
354 * Handle SIGSEGV/SIGILL signals raised by threads
355 */
356 static void segv_handler(int signal)
357 {
358 #ifdef HAVE_BACKTRACE
359 void *array[20];
360 size_t size;
361 char **strings;
362 size_t i;
363
364 size = backtrace(array, 20);
365 strings = backtrace_symbols(array, size);
366
367 DBG1(DBG_JOB, "thread %u received %s. Dumping %d frames from stack:",
368 pthread_self(), signal == SIGSEGV ? "SIGSEGV" : "SIGILL", size);
369
370 for (i = 0; i < size; i++)
371 {
372 DBG1(DBG_DMN, " %s", strings[i]);
373 }
374 free (strings);
375 #else /* !HAVE_BACKTRACE */
376 DBG1(DBG_DMN, "thread %u received %s",
377 pthread_self(), signal == SIGSEGV ? "SIGSEGV" : "SIGILL");
378 #endif /* HAVE_BACKTRACE */
379 DBG1(DBG_DMN, "killing ourself, received critical signal");
380 raise(SIGKILL);
381 }
382
383 /**
384 * Create the daemon.
385 */
386 private_daemon_t *daemon_create(void)
387 {
388 struct sigaction action;
389 private_daemon_t *this = malloc_thing(private_daemon_t);
390
391 /* assign methods */
392 this->public.kill = (void (*) (daemon_t*,char*))kill_daemon;
393
394 /* NULL members for clean destruction */
395 this->public.socket = NULL;
396 this->public.ike_sa_manager = NULL;
397 this->public.credentials = NULL;
398 this->public.backends = NULL;
399 this->public.sender= NULL;
400 this->public.receiver = NULL;
401 this->public.scheduler = NULL;
402 this->public.kernel_interface = NULL;
403 this->public.processor = NULL;
404 this->public.interfaces = NULL;
405 this->public.bus = NULL;
406 this->public.outlog = NULL;
407 this->public.syslog = NULL;
408 this->public.authlog = NULL;
409
410 this->main_thread_id = pthread_self();
411
412 /* add handler for SEGV and ILL,
413 * add handler for USR1 (cancellation).
414 * INT, TERM and HUP are handled by sigwait() in run() */
415 action.sa_handler = segv_handler;
416 action.sa_flags = 0;
417 sigemptyset(&action.sa_mask);
418 sigaddset(&action.sa_mask, SIGINT);
419 sigaddset(&action.sa_mask, SIGTERM);
420 sigaddset(&action.sa_mask, SIGHUP);
421 sigaction(SIGSEGV, &action, NULL);
422 sigaction(SIGILL, &action, NULL);
423 action.sa_handler = SIG_IGN;
424 sigaction(SIGPIPE, &action, NULL);
425
426 pthread_sigmask(SIG_SETMASK, &action.sa_mask, 0);
427
428 return this;
429 }
430
431 /**
432 * print command line usage and exit
433 */
434 static void usage(const char *msg)
435 {
436 if (msg != NULL && *msg != '\0')
437 {
438 fprintf(stderr, "%s\n", msg);
439 }
440 fprintf(stderr, "Usage: charon\n"
441 " [--help]\n"
442 " [--version]\n"
443 " [--strictcrlpolicy]\n"
444 " [--cachecrls]\n"
445 " [--crlcheckinterval <interval>]\n"
446 " [--eapdir <dir>]\n"
447 " [--use-syslog]\n"
448 " [--debug-<type> <level>]\n"
449 " <type>: log context type (dmn|mgr|ike|chd|job|cfg|knl|net|enc|lib)\n"
450 " <level>: log verbosity (-1 = silent, 0 = audit, 1 = control,\n"
451 " 2 = controlmore, 3 = raw, 4 = private)\n"
452 "\n"
453 );
454 exit(msg == NULL? 0 : 1);
455 }
456
457 /**
458 * Main function, manages the daemon.
459 */
460 int main(int argc, char *argv[])
461 {
462 u_int crl_check_interval = 0;
463 strict_t strict_crl_policy = STRICT_NO;
464 bool cache_crls = FALSE;
465 bool use_syslog = FALSE;
466 char *eapdir = IPSEC_EAPDIR;
467
468 private_daemon_t *private_charon;
469 FILE *pid_file;
470 struct stat stb;
471 level_t levels[DBG_MAX];
472 int signal;
473
474 private_charon = daemon_create();
475 charon = (daemon_t*)private_charon;
476
477 /* drop the capabilities we won't need for initialization */
478 prctl(PR_SET_KEEPCAPS, 1);
479 drop_capabilities(private_charon, FALSE);
480
481 /* use CTRL loglevel for default */
482 for (signal = 0; signal < DBG_MAX; signal++)
483 {
484 levels[signal] = LEVEL_CTRL;
485 }
486
487 /* handle arguments */
488 for (;;)
489 {
490 struct option long_opts[] = {
491 { "help", no_argument, NULL, 'h' },
492 { "version", no_argument, NULL, 'v' },
493 { "use-syslog", no_argument, NULL, 'l' },
494 { "strictcrlpolicy", required_argument, NULL, 'r' },
495 { "cachecrls", no_argument, NULL, 'C' },
496 { "crlcheckinterval", required_argument, NULL, 'x' },
497 { "eapdir", required_argument, NULL, 'e' },
498 /* TODO: handle "debug-all" */
499 { "debug-dmn", required_argument, &signal, DBG_DMN },
500 { "debug-mgr", required_argument, &signal, DBG_MGR },
501 { "debug-ike", required_argument, &signal, DBG_IKE },
502 { "debug-chd", required_argument, &signal, DBG_CHD },
503 { "debug-job", required_argument, &signal, DBG_JOB },
504 { "debug-cfg", required_argument, &signal, DBG_CFG },
505 { "debug-knl", required_argument, &signal, DBG_KNL },
506 { "debug-net", required_argument, &signal, DBG_NET },
507 { "debug-enc", required_argument, &signal, DBG_ENC },
508 { "debug-lib", required_argument, &signal, DBG_LIB },
509 { 0,0,0,0 }
510 };
511
512 int c = getopt_long(argc, argv, "", long_opts, NULL);
513 switch (c)
514 {
515 case EOF:
516 break;
517 case 'h':
518 usage(NULL);
519 break;
520 case 'v':
521 printf("Linux strongSwan %s\n", VERSION);
522 exit(0);
523 case 'l':
524 use_syslog = TRUE;
525 continue;
526 case 'r':
527 strict_crl_policy = atoi(optarg);
528 continue;
529 case 'C':
530 cache_crls = TRUE;
531 continue;
532 case 'x':
533 crl_check_interval = atoi(optarg);
534 continue;
535 case 'e':
536 eapdir = optarg;
537 continue;
538 case 0:
539 /* option is in signal */
540 levels[signal] = atoi(optarg);
541 continue;
542 default:
543 usage("");
544 break;
545 }
546 break;
547 }
548
549 /* initialize daemon */
550 if (!initialize(private_charon, use_syslog, levels))
551 {
552 DBG1(DBG_DMN, "initialization failed - aborting charon");
553 destroy(private_charon);
554 exit(-1);
555 }
556
557 /* initialize fetcher_t class */
558 fetcher_initialize();
559 /* load pluggable EAP modules */
560 eap_method_load(eapdir);
561
562 /* set strict_crl_policy, cache_crls and crl_check_interval options */
563 ca_info_set_options(strict_crl_policy, cache_crls, crl_check_interval);
564
565 /* check/setup PID file */
566 if (stat(PID_FILE, &stb) == 0)
567 {
568 DBG1(DBG_DMN, "charon already running (\""PID_FILE"\" exists)");
569 destroy(private_charon);
570 exit(-1);
571 }
572 pid_file = fopen(PID_FILE, "w");
573 if (pid_file)
574 {
575 fprintf(pid_file, "%d\n", getpid());
576 fchown(fileno(pid_file), IPSEC_UID, IPSEC_GID);
577 fclose(pid_file);
578 }
579
580 /* drop additional capabilites (bind & root) */
581 drop_capabilities(private_charon, TRUE);
582
583 /* start the engine, go multithreaded */
584 charon->processor->set_threads(charon->processor, WORKER_THREADS);
585
586 /* run daemon */
587 run(private_charon);
588
589 eap_method_unload();
590 fetcher_finalize();
591 /* normal termination, cleanup and exit */
592 destroy(private_charon);
593 unlink(PID_FILE);
594
595 return 0;
596 }
597