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