d628248d2f0668e1260d23615f1c3875588256f1
[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 <sys/prctl.h>
21 #include <signal.h>
22 #include <pthread.h>
23 #include <sys/stat.h>
24 #include <sys/types.h>
25 #include <unistd.h>
26 #include <time.h>
27 #include <string.h>
28 #include <getopt.h>
29 #include <errno.h>
30 #include <pwd.h>
31 #include <grp.h>
32 #ifdef CAPABILITIES
33 #include <sys/capability.h>
34 #endif /* CAPABILITIES */
35
36 #include "daemon.h"
37
38 #include <library.h>
39 #include <utils/backtrace.h>
40 #include <config/traffic_selector.h>
41 #include <config/proposal.h>
42
43 #ifdef INTEGRITY_TEST
44 #include <fips/fips.h>
45 #include <fips/fips_signature.h>
46 #endif /* INTEGRITY_TEST */
47
48 typedef struct private_daemon_t private_daemon_t;
49
50 /**
51 * Private additions to daemon_t, contains threads and internal functions.
52 */
53 struct private_daemon_t {
54 /**
55 * Public members of daemon_t.
56 */
57 daemon_t public;
58
59 /**
60 * Signal set used for signal handling.
61 */
62 sigset_t signal_set;
63
64 /**
65 * The thread_id of main-thread.
66 */
67 pthread_t main_thread_id;
68
69 #ifdef CAPABILITIES
70 /**
71 * capabilities to keep
72 */
73 cap_t caps;
74 #endif /* CAPABILITIES */
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->vlog(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 if (level <= 1)
107 {
108 va_start(args, fmt);
109 fprintf(stderr, "00[LIB] ");
110 vfprintf(stderr, fmt, args);
111 fprintf(stderr, "\n");
112 va_end(args);
113 }
114 }
115
116 /**
117 * Run the daemon and handle unix signals
118 */
119 static void run(private_daemon_t *this)
120 {
121 sigset_t set;
122
123 /* handle SIGINT, SIGHUP ans SIGTERM in this handler */
124 sigemptyset(&set);
125 sigaddset(&set, SIGINT);
126 sigaddset(&set, SIGHUP);
127 sigaddset(&set, SIGTERM);
128
129 while (TRUE)
130 {
131 int sig;
132 int error;
133
134 error = sigwait(&set, &sig);
135 if (error)
136 {
137 DBG1(DBG_DMN, "error %d while waiting for a signal", error);
138 return;
139 }
140 switch (sig)
141 {
142 case SIGHUP:
143 {
144 DBG1(DBG_DMN, "signal of type SIGHUP received. Ignored");
145 break;
146 }
147 case SIGINT:
148 {
149 DBG1(DBG_DMN, "signal of type SIGINT received. Shutting down");
150 return;
151 }
152 case SIGTERM:
153 {
154 DBG1(DBG_DMN, "signal of type SIGTERM received. Shutting down");
155 return;
156 }
157 default:
158 {
159 DBG1(DBG_DMN, "unknown signal %d received. Ignored", sig);
160 break;
161 }
162 }
163 }
164 }
165
166 /**
167 * Clean up all daemon resources
168 */
169 static void destroy(private_daemon_t *this)
170 {
171 /* terminate all idle threads */
172 if (this->public.processor)
173 {
174 this->public.processor->set_threads(this->public.processor, 0);
175 }
176 /* close all IKE_SAs */
177 if (this->public.ike_sa_manager)
178 {
179 this->public.ike_sa_manager->flush(this->public.ike_sa_manager);
180 }
181 /* unload plugins to release threads */
182 lib->plugins->unload(lib->plugins);
183 #ifdef CAPABILITIES
184 cap_free(this->caps);
185 #endif /* CAPABILITIES */
186 DESTROY_IF(this->public.ike_sa_manager);
187 DESTROY_IF(this->public.kernel_interface);
188 DESTROY_IF(this->public.scheduler);
189 DESTROY_IF(this->public.controller);
190 DESTROY_IF(this->public.eap);
191 DESTROY_IF(this->public.sim);
192 #ifdef ME
193 DESTROY_IF(this->public.connect_manager);
194 DESTROY_IF(this->public.mediation_manager);
195 #endif /* ME */
196 DESTROY_IF(this->public.backends);
197 DESTROY_IF(this->public.attributes);
198 DESTROY_IF(this->public.credentials);
199 DESTROY_IF(this->public.sender);
200 DESTROY_IF(this->public.receiver);
201 DESTROY_IF(this->public.socket);
202 /* wait until all threads are gone */
203 DESTROY_IF(this->public.processor);
204
205 /* rehook library logging, shutdown logging */
206 dbg = dbg_stderr;
207 DESTROY_IF(this->public.bus);
208 DESTROY_IF(this->public.outlog);
209 DESTROY_IF(this->public.syslog);
210 DESTROY_IF(this->public.authlog);
211 free(this);
212 }
213
214 /**
215 * Enforce daemon shutdown, with a given reason to do so.
216 */
217 static void kill_daemon(private_daemon_t *this, char *reason)
218 {
219 /* we send SIGTERM, so the daemon can cleanly shut down */
220 if (this->public.bus)
221 {
222 DBG1(DBG_DMN, "killing daemon: %s", reason);
223 }
224 else
225 {
226 fprintf(stderr, "killing daemon: %s\n", reason);
227 }
228 if (this->main_thread_id == pthread_self())
229 {
230 /* initialization failed, terminate daemon */
231 unlink(PID_FILE);
232 exit(-1);
233 }
234 else
235 {
236 DBG1(DBG_DMN, "sending SIGTERM to ourself");
237 raise(SIGTERM);
238 /* thread must die, since he produced a ciritcal failure and can't continue */
239 pthread_exit(NULL);
240 }
241 }
242
243 /**
244 * drop daemon capabilities
245 */
246 static void drop_capabilities(private_daemon_t *this)
247 {
248 prctl(PR_SET_KEEPCAPS, 1);
249
250 if (setgid(charon->gid) != 0)
251 {
252 kill_daemon(this, "change to unprivileged group failed");
253 }
254 if (setuid(charon->uid) != 0)
255 {
256 kill_daemon(this, "change to unprivileged user failed");
257 }
258
259 #ifdef CAPABILITIES
260 if (cap_set_proc(this->caps) != 0)
261 {
262 kill_daemon(this, "unable to drop daemon capabilities");
263 }
264 #endif /* CAPABILITIES */
265 }
266
267 /**
268 * Implementation of daemon_t.keep_cap
269 */
270 static void keep_cap(private_daemon_t *this, u_int cap)
271 {
272 #ifdef CAPABILITIES
273 cap_set_flag(this->caps, CAP_EFFECTIVE, 1, &cap, CAP_SET);
274 cap_set_flag(this->caps, CAP_INHERITABLE, 1, &cap, CAP_SET);
275 cap_set_flag(this->caps, CAP_PERMITTED, 1, &cap, CAP_SET);
276 #endif /* CAPABILITIES */
277 }
278
279 /**
280 * lookup UID and GID
281 */
282 static void lookup_uid_gid(private_daemon_t *this)
283 {
284 #ifdef IPSEC_USER
285 {
286 char buf[1024];
287 struct passwd passwd, *pwp;
288
289 if (getpwnam_r(IPSEC_USER, &passwd, buf, sizeof(buf), &pwp) != 0 ||
290 pwp == NULL)
291 {
292 kill_daemon(this, "resolving user '"IPSEC_USER"' failed");
293 }
294 charon->uid = pwp->pw_uid;
295 }
296 #endif
297 #ifdef IPSEC_GROUP
298 {
299 char buf[1024];
300 struct group group, *grp;
301
302 if (getgrnam_r(IPSEC_GROUP, &group, buf, sizeof(buf), &grp) != 0 ||
303 grp == NULL)
304 {
305 kill_daemon(this, "reslvoing group '"IPSEC_GROUP"' failed");
306 }
307 charon->gid = grp->gr_gid;
308 }
309 #endif
310 }
311
312 /**
313 * Log loaded plugins
314 */
315 static void print_plugins()
316 {
317 char buf[512], *plugin;
318 int len = 0;
319 enumerator_t *enumerator;
320
321 enumerator = lib->plugins->create_plugin_enumerator(lib->plugins);
322 while (len < sizeof(buf) && enumerator->enumerate(enumerator, &plugin))
323 {
324 len += snprintf(&buf[len], sizeof(buf)-len, "%s ", plugin);
325 }
326 enumerator->destroy(enumerator);
327 DBG1(DBG_DMN, "loaded plugins: %s", buf);
328 }
329
330 /**
331 * Initialize the daemon
332 */
333 static bool initialize(private_daemon_t *this, bool syslog, level_t levels[])
334 {
335 debug_t group;
336
337 /* for uncritical pseudo random numbers */
338 srandom(time(NULL) + getpid());
339
340 /* setup bus and it's listeners first to enable log output */
341 this->public.bus = bus_create();
342 this->public.outlog = file_logger_create(stdout);
343 this->public.syslog = sys_logger_create(LOG_DAEMON);
344 this->public.authlog = sys_logger_create(LOG_AUTHPRIV);
345 this->public.bus->add_listener(this->public.bus, &this->public.syslog->listener);
346 this->public.bus->add_listener(this->public.bus, &this->public.outlog->listener);
347 this->public.bus->add_listener(this->public.bus, &this->public.authlog->listener);
348 this->public.authlog->set_level(this->public.authlog, DBG_ANY, LEVEL_AUDIT);
349 /* set up hook to log dbg message in library via charons message bus */
350 dbg = dbg_bus;
351
352 /* apply loglevels */
353 for (group = 0; group < DBG_MAX; group++)
354 {
355 this->public.syslog->set_level(this->public.syslog,
356 group, levels[group]);
357 if (!syslog)
358 {
359 this->public.outlog->set_level(this->public.outlog,
360 group, levels[group]);
361 }
362 }
363
364 DBG1(DBG_DMN, "starting charon (strongSwan Version %s)", VERSION);
365
366 /* load secrets, ca certificates and crls */
367 this->public.processor = processor_create();
368 this->public.scheduler = scheduler_create();
369 this->public.credentials = credential_manager_create();
370 this->public.controller = controller_create();
371 this->public.eap = eap_manager_create();
372 this->public.sim = sim_manager_create();
373 this->public.backends = backend_manager_create();
374 this->public.attributes = attribute_manager_create();
375 this->public.kernel_interface = kernel_interface_create();
376 this->public.socket = socket_create();
377
378 /* load plugins, further infrastructure may need it */
379 lib->plugins->load(lib->plugins, IPSEC_PLUGINDIR,
380 lib->settings->get_str(lib->settings, "charon.load", PLUGINS));
381
382 print_plugins();
383
384 /* create the kernel interfaces */
385 this->public.kernel_interface->create_interfaces(this->public.kernel_interface);
386
387 #ifdef INTEGRITY_TEST
388 DBG1(DBG_DMN, "integrity test of libstrongswan code");
389 if (fips_verify_hmac_signature(hmac_key, hmac_signature))
390 {
391 DBG1(DBG_DMN, " integrity test passed");
392 }
393 else
394 {
395 DBG1(DBG_DMN, " integrity test failed");
396 return FALSE;
397 }
398 #endif /* INTEGRITY_TEST */
399
400 this->public.ike_sa_manager = ike_sa_manager_create();
401 if (this->public.ike_sa_manager == NULL)
402 {
403 return FALSE;
404 }
405 this->public.sender = sender_create();
406 this->public.receiver = receiver_create();
407 if (this->public.receiver == NULL)
408 {
409 return FALSE;
410 }
411
412 #ifdef ME
413 this->public.connect_manager = connect_manager_create();
414 if (this->public.connect_manager == NULL)
415 {
416 return FALSE;
417 }
418 this->public.mediation_manager = mediation_manager_create();
419 #endif /* ME */
420
421 return TRUE;
422 }
423
424 /**
425 * Handle SIGSEGV/SIGILL signals raised by threads
426 */
427 static void segv_handler(int signal)
428 {
429 backtrace_t *backtrace;
430
431 DBG1(DBG_DMN, "thread %u received %d", pthread_self(), signal);
432 backtrace = backtrace_create(2);
433 backtrace->log(backtrace, stderr);
434 backtrace->destroy(backtrace);
435
436 DBG1(DBG_DMN, "killing ourself, received critical signal");
437 raise(SIGKILL);
438 }
439
440 /**
441 * Create the daemon.
442 */
443 private_daemon_t *daemon_create(void)
444 {
445 struct sigaction action;
446 private_daemon_t *this = malloc_thing(private_daemon_t);
447
448 /* assign methods */
449 this->public.kill = (void (*) (daemon_t*,char*))kill_daemon;
450 this->public.keep_cap = (void(*)(daemon_t*, u_int cap))keep_cap;
451
452 /* NULL members for clean destruction */
453 this->public.socket = NULL;
454 this->public.ike_sa_manager = NULL;
455 this->public.credentials = NULL;
456 this->public.backends = NULL;
457 this->public.attributes = NULL;
458 this->public.sender= NULL;
459 this->public.receiver = NULL;
460 this->public.scheduler = NULL;
461 this->public.kernel_interface = NULL;
462 this->public.processor = NULL;
463 this->public.controller = NULL;
464 this->public.eap = NULL;
465 this->public.sim = NULL;
466 this->public.bus = NULL;
467 this->public.outlog = NULL;
468 this->public.syslog = NULL;
469 this->public.authlog = NULL;
470 #ifdef ME
471 this->public.connect_manager = NULL;
472 this->public.mediation_manager = NULL;
473 #endif /* ME */
474 this->public.uid = 0;
475 this->public.gid = 0;
476
477 this->main_thread_id = pthread_self();
478 #ifdef CAPABILITIES
479 this->caps = cap_init();
480 keep_cap(this, CAP_NET_ADMIN);
481 if (lib->leak_detective)
482 {
483 keep_cap(this, CAP_SYS_NICE);
484 }
485 #endif /* CAPABILITIES */
486
487 /* add handler for SEGV and ILL,
488 * add handler for USR1 (cancellation).
489 * INT, TERM and HUP are handled by sigwait() in run() */
490 action.sa_handler = segv_handler;
491 action.sa_flags = 0;
492 sigemptyset(&action.sa_mask);
493 sigaddset(&action.sa_mask, SIGINT);
494 sigaddset(&action.sa_mask, SIGTERM);
495 sigaddset(&action.sa_mask, SIGHUP);
496 sigaction(SIGSEGV, &action, NULL);
497 sigaction(SIGILL, &action, NULL);
498 sigaction(SIGBUS, &action, NULL);
499 action.sa_handler = SIG_IGN;
500 sigaction(SIGPIPE, &action, NULL);
501
502 pthread_sigmask(SIG_SETMASK, &action.sa_mask, 0);
503
504 return this;
505 }
506
507 /**
508 * print command line usage and exit
509 */
510 static void usage(const char *msg)
511 {
512 if (msg != NULL && *msg != '\0')
513 {
514 fprintf(stderr, "%s\n", msg);
515 }
516 fprintf(stderr, "Usage: charon\n"
517 " [--help]\n"
518 " [--version]\n"
519 " [--use-syslog]\n"
520 " [--debug-<type> <level>]\n"
521 " <type>: log context type (dmn|mgr|ike|chd|job|cfg|knl|net|enc|lib)\n"
522 " <level>: log verbosity (-1 = silent, 0 = audit, 1 = control,\n"
523 " 2 = controlmore, 3 = raw, 4 = private)\n"
524 "\n"
525 );
526 exit(msg == NULL? 0 : 1);
527 }
528
529 /**
530 * Main function, manages the daemon.
531 */
532 int main(int argc, char *argv[])
533 {
534 bool use_syslog = FALSE;
535
536 private_daemon_t *private_charon;
537 FILE *pid_file;
538 struct stat stb;
539 level_t levels[DBG_MAX];
540 int group;
541
542 /* logging for library during initialization, as we have no bus yet */
543 dbg = dbg_stderr;
544
545 /* initialize library */
546 library_init(STRONGSWAN_CONF);
547 lib->printf_hook->add_handler(lib->printf_hook, 'R',
548 traffic_selector_get_printf_hooks());
549 lib->printf_hook->add_handler(lib->printf_hook, 'P',
550 proposal_get_printf_hooks());
551 private_charon = daemon_create();
552 charon = (daemon_t*)private_charon;
553
554 lookup_uid_gid(private_charon);
555
556 /* use CTRL loglevel for default */
557 for (group = 0; group < DBG_MAX; group++)
558 {
559 levels[group] = LEVEL_CTRL;
560 }
561
562 /* handle arguments */
563 for (;;)
564 {
565 struct option long_opts[] = {
566 { "help", no_argument, NULL, 'h' },
567 { "version", no_argument, NULL, 'v' },
568 { "use-syslog", no_argument, NULL, 'l' },
569 /* TODO: handle "debug-all" */
570 { "debug-dmn", required_argument, &group, DBG_DMN },
571 { "debug-mgr", required_argument, &group, DBG_MGR },
572 { "debug-ike", required_argument, &group, DBG_IKE },
573 { "debug-chd", required_argument, &group, DBG_CHD },
574 { "debug-job", required_argument, &group, DBG_JOB },
575 { "debug-cfg", required_argument, &group, DBG_CFG },
576 { "debug-knl", required_argument, &group, DBG_KNL },
577 { "debug-net", required_argument, &group, DBG_NET },
578 { "debug-enc", required_argument, &group, DBG_ENC },
579 { "debug-lib", required_argument, &group, DBG_LIB },
580 { 0,0,0,0 }
581 };
582
583 int c = getopt_long(argc, argv, "", long_opts, NULL);
584 switch (c)
585 {
586 case EOF:
587 break;
588 case 'h':
589 usage(NULL);
590 break;
591 case 'v':
592 printf("Linux strongSwan %s\n", VERSION);
593 exit(0);
594 case 'l':
595 use_syslog = TRUE;
596 continue;
597 case 0:
598 /* option is in group */
599 levels[group] = atoi(optarg);
600 continue;
601 default:
602 usage("");
603 break;
604 }
605 break;
606 }
607
608 /* initialize daemon */
609 if (!initialize(private_charon, use_syslog, levels))
610 {
611 DBG1(DBG_DMN, "initialization failed - aborting charon");
612 destroy(private_charon);
613 exit(-1);
614 }
615
616 /* check/setup PID file */
617 if (stat(PID_FILE, &stb) == 0)
618 {
619 DBG1(DBG_DMN, "charon already running (\""PID_FILE"\" exists)");
620 destroy(private_charon);
621 exit(-1);
622 }
623 pid_file = fopen(PID_FILE, "w");
624 if (pid_file)
625 {
626 fprintf(pid_file, "%d\n", getpid());
627 fchown(fileno(pid_file), charon->uid, charon->gid);
628 fclose(pid_file);
629 }
630
631 /* drop the capabilities we won't need */
632 drop_capabilities(private_charon);
633
634 /* start the engine, go multithreaded */
635 charon->processor->set_threads(charon->processor,
636 lib->settings->get_int(lib->settings, "charon.threads",
637 DEFAULT_THREADS));
638
639 /* run daemon */
640 run(private_charon);
641
642 /* normal termination, cleanup and exit */
643 destroy(private_charon);
644 unlink(PID_FILE);
645
646 library_deinit();
647
648 return 0;
649 }
650