plugin load configuration in strongswan.conf
[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 #include <pwd.h>
32 #include <grp.h>
33 #ifdef HAVE_BACKTRACE
34 # include <execinfo.h>
35 #endif /* HAVE_BACKTRACE */
36
37 #include "daemon.h"
38
39 #include <library.h>
40 #include <config/traffic_selector.h>
41
42 /* on some distros, a capset definition is missing */
43 #ifdef NO_CAPSET_DEFINED
44 extern int capset(cap_user_header_t hdrp, const cap_user_data_t datap);
45 #endif /* NO_CAPSET_DEFINED */
46
47 #ifdef INTEGRITY_TEST
48 #include <fips/fips.h>
49 #include <fips_signature.h>
50 #endif /* INTEGRITY_TEST */
51
52 typedef struct private_daemon_t private_daemon_t;
53
54 /**
55 * Private additions to daemon_t, contains threads and internal functions.
56 */
57 struct private_daemon_t {
58 /**
59 * Public members of daemon_t.
60 */
61 daemon_t public;
62
63 /**
64 * Signal set used for signal handling.
65 */
66 sigset_t signal_set;
67
68 /**
69 * The thread_id of main-thread.
70 */
71 pthread_t main_thread_id;
72 };
73
74 /**
75 * One and only instance of the daemon.
76 */
77 daemon_t *charon;
78
79 /**
80 * hook in library for debugging messages
81 */
82 extern void (*dbg) (int level, char *fmt, ...);
83
84 /**
85 * Logging hook for library logs, spreads debug message over bus
86 */
87 static void dbg_bus(int level, char *fmt, ...)
88 {
89 va_list args;
90
91 va_start(args, fmt);
92 charon->bus->vsignal(charon->bus, DBG_LIB, level, fmt, args);
93 va_end(args);
94 }
95
96 /**
97 * Logging hook for library logs, using stderr output
98 */
99 static void dbg_stderr(int level, char *fmt, ...)
100 {
101 va_list args;
102
103 if (level <= 1)
104 {
105 va_start(args, fmt);
106 fprintf(stderr, "00[LIB] ");
107 vfprintf(stderr, fmt, args);
108 fprintf(stderr, "\n");
109 va_end(args);
110 }
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 if (this->public.processor)
170 {
171 this->public.processor->set_threads(this->public.processor, 0);
172 }
173 /* close all IKE_SAs */
174 if (this->public.ike_sa_manager)
175 {
176 this->public.ike_sa_manager->flush(this->public.ike_sa_manager);
177 }
178 /* unload plugins to release threads */
179 lib->plugins->unload(lib->plugins);
180 DESTROY_IF(this->public.ike_sa_manager);
181 DESTROY_IF(this->public.kernel_interface);
182 DESTROY_IF(this->public.scheduler);
183 DESTROY_IF(this->public.controller);
184 DESTROY_IF(this->public.eap);
185 #ifdef ME
186 DESTROY_IF(this->public.connect_manager);
187 DESTROY_IF(this->public.mediation_manager);
188 #endif /* ME */
189 DESTROY_IF(this->public.backends);
190 DESTROY_IF(this->public.attributes);
191 DESTROY_IF(this->public.credentials);
192 DESTROY_IF(this->public.sender);
193 DESTROY_IF(this->public.receiver);
194 DESTROY_IF(this->public.socket);
195 /* wait until all threads are gone */
196 DESTROY_IF(this->public.processor);
197
198 /* rehook library logging, shutdown logging */
199 dbg = dbg_stderr;
200 DESTROY_IF(this->public.bus);
201 DESTROY_IF(this->public.outlog);
202 DESTROY_IF(this->public.syslog);
203 DESTROY_IF(this->public.authlog);
204 free(this);
205 }
206
207 /**
208 * Enforce daemon shutdown, with a given reason to do so.
209 */
210 static void kill_daemon(private_daemon_t *this, char *reason)
211 {
212 /* we send SIGTERM, so the daemon can cleanly shut down */
213 if (this->public.bus)
214 {
215 DBG1(DBG_DMN, "killing daemon: %s", reason);
216 }
217 else
218 {
219 fprintf(stderr, "killing daemon: %s\n", reason);
220 }
221 if (this->main_thread_id == pthread_self())
222 {
223 /* initialization failed, terminate daemon */
224 unlink(PID_FILE);
225 exit(-1);
226 }
227 else
228 {
229 DBG1(DBG_DMN, "sending SIGTERM to ourself");
230 raise(SIGTERM);
231 /* thread must die, since he produced a ciritcal failure and can't continue */
232 pthread_exit(NULL);
233 }
234 }
235
236 /**
237 * drop daemon capabilities
238 */
239 static void drop_capabilities(private_daemon_t *this, bool full)
240 {
241 struct __user_cap_header_struct hdr;
242 struct __user_cap_data_struct data;
243
244 /* CAP_NET_ADMIN is needed to use netlink */
245 u_int32_t keep = (1<<CAP_NET_ADMIN) | (1<<CAP_SYS_NICE);
246
247 if (full)
248 {
249 if (setgid(charon->gid) != 0)
250 {
251 kill_daemon(this, "change to unprivileged group failed");
252 }
253 if (setuid(charon->uid) != 0)
254 {
255 kill_daemon(this, "change to unprivileged user failed");
256 }
257 }
258 else
259 {
260 /* CAP_NET_BIND_SERVICE to bind services below port 1024 */
261 keep |= (1<<CAP_NET_BIND_SERVICE);
262 /* CAP_NET_RAW to create RAW sockets */
263 keep |= (1<<CAP_NET_RAW);
264 /* CAP_DAC_READ_SEARCH to read ipsec.secrets */
265 keep |= (1<<CAP_DAC_READ_SEARCH);
266 /* CAP_CHOWN to change file permissions (socket permissions) */
267 keep |= (1<<CAP_CHOWN);
268 /* CAP_SETUID to call setuid() */
269 keep |= (1<<CAP_SETUID);
270 /* CAP_SETGID to call setgid() */
271 keep |= (1<<CAP_SETGID);
272 }
273
274 /* we use the old capset version for now. For systems with version 2
275 * available, we specifiy version 1 excplicitly. */
276 #ifdef _LINUX_CAPABILITY_VERSION_1
277 hdr.version = _LINUX_CAPABILITY_VERSION_1;
278 #else
279 hdr.version = _LINUX_CAPABILITY_VERSION;
280 #endif
281 hdr.pid = 0;
282 data.inheritable = data.effective = data.permitted = keep;
283
284 if (capset(&hdr, &data))
285 {
286 kill_daemon(this, "unable to drop daemon capabilities");
287 }
288 }
289
290 /**
291 * lookup UID and GID
292 */
293 static void lookup_uid_gid(private_daemon_t *this)
294 {
295 #ifdef IPSEC_USER
296 {
297 char buf[1024];
298 struct passwd passwd, *pwp;
299
300 if (getpwnam_r(IPSEC_USER, &passwd, buf, sizeof(buf), &pwp) != 0 ||
301 pwp == NULL)
302 {
303 kill_daemon(this, "resolving user '"IPSEC_USER"' failed");
304 }
305 charon->uid = pwp->pw_uid;
306 }
307 #endif
308 #ifdef IPSEC_GROUP
309 {
310 char buf[1024];
311 struct group group, *grp;
312
313 if (getgrnam_r(IPSEC_GROUP, &group, buf, sizeof(buf), &grp) != 0 ||
314 grp == NULL)
315 {
316 kill_daemon(this, "reslvoing group '"IPSEC_GROUP"' failed");
317 }
318 charon->gid = grp->gr_gid;
319 }
320 #endif
321 }
322
323 /**
324 * Initialize the daemon
325 */
326 static bool initialize(private_daemon_t *this, bool syslog, level_t levels[])
327 {
328 signal_t signal;
329
330 /* for uncritical pseudo random numbers */
331 srandom(time(NULL) + getpid());
332
333 /* setup bus and it's listeners first to enable log output */
334 this->public.bus = bus_create();
335 this->public.outlog = file_logger_create(stdout);
336 this->public.syslog = sys_logger_create(LOG_DAEMON);
337 this->public.authlog = sys_logger_create(LOG_AUTHPRIV);
338 this->public.bus->add_listener(this->public.bus, &this->public.syslog->listener);
339 this->public.bus->add_listener(this->public.bus, &this->public.outlog->listener);
340 this->public.bus->add_listener(this->public.bus, &this->public.authlog->listener);
341 this->public.authlog->set_level(this->public.authlog, SIG_ANY, LEVEL_AUDIT);
342 /* set up hook to log dbg message in library via charons message bus */
343 dbg = dbg_bus;
344
345 /* apply loglevels */
346 for (signal = 0; signal < DBG_MAX; signal++)
347 {
348 this->public.syslog->set_level(this->public.syslog,
349 signal, levels[signal]);
350 if (!syslog)
351 {
352 this->public.outlog->set_level(this->public.outlog,
353 signal, levels[signal]);
354 }
355 }
356
357 DBG1(DBG_DMN, "starting charon (strongSwan Version %s)", VERSION);
358
359 #ifdef INTEGRITY_TEST
360 DBG1(DBG_DMN, "integrity test of libstrongswan code");
361 if (fips_verify_hmac_signature(hmac_key, hmac_signature))
362 {
363 DBG1(DBG_DMN, " integrity test passed");
364 }
365 else
366 {
367 DBG1(DBG_DMN, " integrity test failed");
368 return FALSE;
369 }
370 #endif /* INTEGRITY_TEST */
371
372 /* load secrets, ca certificates and crls */
373 this->public.processor = processor_create();
374 this->public.scheduler = scheduler_create();
375 this->public.credentials = credential_manager_create();
376 this->public.controller = controller_create();
377 this->public.eap = eap_manager_create();
378 this->public.backends = backend_manager_create();
379 this->public.attributes = attribute_manager_create();
380 this->public.kernel_interface = kernel_interface_create();
381 this->public.socket = socket_create();
382
383 /* load plugins, further infrastructure may need it */
384 lib->plugins->load(lib->plugins, IPSEC_PLUGINDIR,
385 lib->settings->get_str(lib->settings, "charon.load",
386 "aes des gmp hmac md5 random sha1 sha2 pubkey x509 xcbc stroke"));
387
388 this->public.ike_sa_manager = ike_sa_manager_create();
389 if (this->public.ike_sa_manager == NULL)
390 {
391 return FALSE;
392 }
393 this->public.sender = sender_create();
394 this->public.receiver = receiver_create();
395 if (this->public.receiver == NULL)
396 {
397 return FALSE;
398 }
399
400 #ifdef ME
401 this->public.connect_manager = connect_manager_create();
402 if (this->public.connect_manager == NULL)
403 {
404 return FALSE;
405 }
406 this->public.mediation_manager = mediation_manager_create();
407 #endif /* ME */
408
409 return TRUE;
410 }
411
412 /**
413 * Handle SIGSEGV/SIGILL signals raised by threads
414 */
415 static void segv_handler(int signal)
416 {
417 #ifdef HAVE_BACKTRACE
418 void *array[20];
419 size_t size;
420 char **strings;
421 size_t i;
422
423 size = backtrace(array, 20);
424 strings = backtrace_symbols(array, size);
425
426 DBG1(DBG_JOB, "thread %u received %s. Dumping %d frames from stack:",
427 pthread_self(), signal == SIGSEGV ? "SIGSEGV" : "SIGILL", size);
428
429 for (i = 0; i < size; i++)
430 {
431 DBG1(DBG_DMN, " %s", strings[i]);
432 }
433 free (strings);
434 #else /* !HAVE_BACKTRACE */
435 DBG1(DBG_DMN, "thread %u received %s",
436 pthread_self(), signal == SIGSEGV ? "SIGSEGV" : "SIGILL");
437 #endif /* HAVE_BACKTRACE */
438 DBG1(DBG_DMN, "killing ourself, received critical signal");
439 raise(SIGKILL);
440 }
441
442 /**
443 * Create the daemon.
444 */
445 private_daemon_t *daemon_create(void)
446 {
447 struct sigaction action;
448 private_daemon_t *this = malloc_thing(private_daemon_t);
449
450 /* assign methods */
451 this->public.kill = (void (*) (daemon_t*,char*))kill_daemon;
452
453 /* NULL members for clean destruction */
454 this->public.socket = NULL;
455 this->public.ike_sa_manager = NULL;
456 this->public.credentials = NULL;
457 this->public.backends = NULL;
458 this->public.attributes = NULL;
459 this->public.sender= NULL;
460 this->public.receiver = NULL;
461 this->public.scheduler = NULL;
462 this->public.kernel_interface = NULL;
463 this->public.processor = NULL;
464 this->public.controller = NULL;
465 this->public.eap = NULL;
466 this->public.bus = NULL;
467 this->public.outlog = NULL;
468 this->public.syslog = NULL;
469 this->public.authlog = NULL;
470 this->public.uid = 0;
471 this->public.gid = 0;
472
473 this->main_thread_id = pthread_self();
474
475 /* add handler for SEGV and ILL,
476 * add handler for USR1 (cancellation).
477 * INT, TERM and HUP are handled by sigwait() in run() */
478 action.sa_handler = segv_handler;
479 action.sa_flags = 0;
480 sigemptyset(&action.sa_mask);
481 sigaddset(&action.sa_mask, SIGINT);
482 sigaddset(&action.sa_mask, SIGTERM);
483 sigaddset(&action.sa_mask, SIGHUP);
484 sigaction(SIGSEGV, &action, NULL);
485 sigaction(SIGILL, &action, NULL);
486 action.sa_handler = SIG_IGN;
487 sigaction(SIGPIPE, &action, NULL);
488
489 pthread_sigmask(SIG_SETMASK, &action.sa_mask, 0);
490
491 return this;
492 }
493
494 /**
495 * print command line usage and exit
496 */
497 static void usage(const char *msg)
498 {
499 if (msg != NULL && *msg != '\0')
500 {
501 fprintf(stderr, "%s\n", msg);
502 }
503 fprintf(stderr, "Usage: charon\n"
504 " [--help]\n"
505 " [--version]\n"
506 " [--use-syslog]\n"
507 " [--debug-<type> <level>]\n"
508 " <type>: log context type (dmn|mgr|ike|chd|job|cfg|knl|net|enc|lib)\n"
509 " <level>: log verbosity (-1 = silent, 0 = audit, 1 = control,\n"
510 " 2 = controlmore, 3 = raw, 4 = private)\n"
511 "\n"
512 );
513 exit(msg == NULL? 0 : 1);
514 }
515
516 /**
517 * Main function, manages the daemon.
518 */
519 int main(int argc, char *argv[])
520 {
521 bool use_syslog = FALSE;
522
523 private_daemon_t *private_charon;
524 FILE *pid_file;
525 struct stat stb;
526 level_t levels[DBG_MAX];
527 int signal;
528
529 /* logging for library during initialization, as we have no bus yet */
530 dbg = dbg_stderr;
531
532 /* initialize library */
533 library_init(STRONGSWAN_CONF);
534 lib->printf_hook->add_handler(lib->printf_hook, 'R',
535 traffic_selector_get_printf_hooks());
536 private_charon = daemon_create();
537 charon = (daemon_t*)private_charon;
538
539 lookup_uid_gid(private_charon);
540
541 /* drop the capabilities we won't need for initialization */
542 prctl(PR_SET_KEEPCAPS, 1);
543 drop_capabilities(private_charon, FALSE);
544
545 /* use CTRL loglevel for default */
546 for (signal = 0; signal < DBG_MAX; signal++)
547 {
548 levels[signal] = LEVEL_CTRL;
549 }
550
551 /* handle arguments */
552 for (;;)
553 {
554 struct option long_opts[] = {
555 { "help", no_argument, NULL, 'h' },
556 { "version", no_argument, NULL, 'v' },
557 { "use-syslog", no_argument, NULL, 'l' },
558 /* TODO: handle "debug-all" */
559 { "debug-dmn", required_argument, &signal, DBG_DMN },
560 { "debug-mgr", required_argument, &signal, DBG_MGR },
561 { "debug-ike", required_argument, &signal, DBG_IKE },
562 { "debug-chd", required_argument, &signal, DBG_CHD },
563 { "debug-job", required_argument, &signal, DBG_JOB },
564 { "debug-cfg", required_argument, &signal, DBG_CFG },
565 { "debug-knl", required_argument, &signal, DBG_KNL },
566 { "debug-net", required_argument, &signal, DBG_NET },
567 { "debug-enc", required_argument, &signal, DBG_ENC },
568 { "debug-lib", required_argument, &signal, DBG_LIB },
569 { 0,0,0,0 }
570 };
571
572 int c = getopt_long(argc, argv, "", long_opts, NULL);
573 switch (c)
574 {
575 case EOF:
576 break;
577 case 'h':
578 usage(NULL);
579 break;
580 case 'v':
581 printf("Linux strongSwan %s\n", VERSION);
582 exit(0);
583 case 'l':
584 use_syslog = TRUE;
585 continue;
586 case 0:
587 /* option is in signal */
588 levels[signal] = atoi(optarg);
589 continue;
590 default:
591 usage("");
592 break;
593 }
594 break;
595 }
596
597 /* initialize daemon */
598 if (!initialize(private_charon, use_syslog, levels))
599 {
600 DBG1(DBG_DMN, "initialization failed - aborting charon");
601 destroy(private_charon);
602 exit(-1);
603 }
604
605 /* check/setup PID file */
606 if (stat(PID_FILE, &stb) == 0)
607 {
608 DBG1(DBG_DMN, "charon already running (\""PID_FILE"\" exists)");
609 destroy(private_charon);
610 exit(-1);
611 }
612 pid_file = fopen(PID_FILE, "w");
613 if (pid_file)
614 {
615 fprintf(pid_file, "%d\n", getpid());
616 fchown(fileno(pid_file), charon->uid, charon->gid);
617 fclose(pid_file);
618 }
619
620 /* drop additional capabilites (bind & root) */
621 drop_capabilities(private_charon, TRUE);
622
623 /* start the engine, go multithreaded */
624 charon->processor->set_threads(charon->processor,
625 lib->settings->get_int(lib->settings, "charon.threads",
626 DEFAULT_THREADS));
627
628 /* run daemon */
629 run(private_charon);
630
631 /* normal termination, cleanup and exit */
632 destroy(private_charon);
633 unlink(PID_FILE);
634
635 library_deinit();
636
637 return 0;
638 }
639