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