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