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