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