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