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