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