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