xref: /freebsd/contrib/openbsm/bin/auditd/auditd.c (revision 1f4bcc459a76b7aa664f3fd557684cd0ba6da352)
1 /*-
2  * Copyright (c) 2004-2009 Apple Inc.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1.  Redistributions of source code must retain the above copyright
10  *     notice, this list of conditions and the following disclaimer.
11  * 2.  Redistributions in binary form must reproduce the above copyright
12  *     notice, this list of conditions and the following disclaimer in the
13  *     documentation and/or other materials provided with the distribution.
14  * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
15  *     its contributors may be used to endorse or promote products derived
16  *     from this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
19  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
22  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 #include <sys/types.h>
31 
32 #include <config/config.h>
33 
34 #include <sys/dirent.h>
35 #ifdef HAVE_FULL_QUEUE_H
36 #include <sys/queue.h>
37 #else	/* !HAVE_FULL_QUEUE_H */
38 #include <compat/queue.h>
39 #endif	/* !HAVE_FULL_QUEUE_H */
40 #include <sys/mman.h>
41 #include <sys/param.h>
42 #include <sys/stat.h>
43 #include <sys/wait.h>
44 
45 #include <bsm/audit.h>
46 #include <bsm/audit_uevents.h>
47 #include <bsm/auditd_lib.h>
48 #include <bsm/libbsm.h>
49 
50 #include <err.h>
51 #include <errno.h>
52 #include <fcntl.h>
53 #include <grp.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <time.h>
57 #include <unistd.h>
58 #include <signal.h>
59 #include <string.h>
60 
61 #include "auditd.h"
62 
63 #ifndef HAVE_STRLCPY
64 #include <compat/strlcpy.h>
65 #endif
66 
67 /*
68  * XXX The following are temporary until these can be added to the kernel
69  * audit.h header.
70  */
71 #ifndef	AUDIT_TRIGGER_INITIALIZE
72 #define	AUDIT_TRIGGER_INITIALIZE	7
73 #endif
74 #ifndef	AUDIT_TRIGGER_EXPIRE_TRAILS
75 #define	AUDIT_TRIGGER_EXPIRE_TRAILS	8
76 #endif
77 
78 
79 /*
80  * LaunchD flag (Mac OS X and, maybe, FreeBSD only.)  See launchd(8) and
81  * http://wiki.freebsd.org/launchd for more information.
82  *
83  *	In order for auditd to work "on demand" with launchd(8) it can't:
84  *		call daemon(3)
85  *		call fork and having the parent process exit
86  *		change uids or gids.
87  *		set up the current working directory or chroot.
88  *		set the session id
89  *		change stdio to /dev/null.
90  *		call setrusage(2)
91  *		call setpriority(2)
92  *		Ignore SIGTERM.
93  *	auditd (in 'launchd mode') is launched on demand so it must catch
94  *	SIGTERM to exit cleanly.
95  */
96 static int	launchd_flag = 0;
97 
98 /*
99  * The GID of the audit review group (if used).  The audit trail files and
100  * system logs (Mac OS X only) can only be reviewed by members of this group
101  * or the audit administrator (aka. "root").
102  */
103 static gid_t	audit_review_gid = -1;
104 
105 /*
106  * The path and file name of the last audit trail file.
107  */
108 static char	*lastfile = NULL;
109 
110 /*
111  * Error starting auditd. Run warn script and exit.
112  */
113 static void
114 fail_exit(void)
115 {
116 
117 	audit_warn_nostart();
118 	exit(1);
119 }
120 
121 /*
122  * Follow the 'current' symlink to get the active trail file name.
123  */
124 static char *
125 get_curfile(void)
126 {
127 	char *cf;
128 	int len;
129 
130 	cf = malloc(MAXPATHLEN);
131 	if (cf == NULL) {
132 		auditd_log_err("malloc failed: %m");
133 		return (NULL);
134 	}
135 
136 	len = readlink(AUDIT_CURRENT_LINK, cf, MAXPATHLEN - 1);
137 	if (len < 0) {
138 		free(cf);
139 		return (NULL);
140 	}
141 
142 	/* readlink() doesn't terminate string. */
143 	cf[len] = '\0';
144 
145 	return (cf);
146 }
147 
148 /*
149  * Close the previous audit trail file.
150  */
151 static int
152 close_lastfile(char *TS)
153 {
154 	char *ptr;
155 	char *oldname;
156 
157 	/* If lastfile is NULL try to get it from the 'current' link.  */
158 	if (lastfile == NULL)
159 		lastfile = get_curfile();
160 
161 	if (lastfile != NULL) {
162 		oldname = strdup(lastfile);
163 		if (oldname == NULL)
164 			return (-1);
165 
166 		/* Rename the last file -- append timestamp. */
167 		if ((ptr = strstr(lastfile, NOT_TERMINATED)) != NULL) {
168 			memcpy(ptr, TS, POSTFIX_LEN);
169 			if (auditd_rename(oldname, lastfile) != 0)
170 				auditd_log_err(
171 				    "Could not rename %s to %s: %m", oldname,
172 				    lastfile);
173 			else {
174 				/*
175 				 * Remove the 'current' symlink since the link
176 				 * is now invalid.
177 				 */
178 				(void) unlink(AUDIT_CURRENT_LINK);
179 				auditd_log_notice("renamed %s to %s",
180 				    oldname, lastfile);
181 				audit_warn_closefile(lastfile);
182 			}
183 		} else
184 			auditd_log_err("Could not rename %s to %s", oldname,
185 			    lastfile);
186 		free(lastfile);
187 		free(oldname);
188 		lastfile = NULL;
189 	}
190 	return (0);
191 }
192 
193 /*
194  * Create the new file name, swap with existing audit file.
195  */
196 static int
197 swap_audit_file(void)
198 {
199 	int err;
200 	char *newfile, *name;
201 	char TS[TIMESTAMP_LEN + 1];
202 	time_t tt;
203 
204 	if (getTSstr(tt, TS, sizeof(TS)) != 0)
205 		return (-1);
206 	/*
207 	 * If prefix and suffix are the same, it means that records are
208 	 * being produced too fast. We don't want to rename now, because
209 	 * next trail file can get the same name and once that one is
210 	 * terminated also within one second it will overwrite the current
211 	 * one. Just keep writing to the same trail and wait for the next
212 	 * trigger from the kernel.
213 	 * FREEBSD KERNEL WAS UPDATED TO KEEP SENDING TRIGGERS, WHICH MIGHT
214 	 * NOT BE THE CASE FOR OTHER OSES.
215 	 * If the kernel will not keep sending triggers, trail file will not
216 	 * be terminated.
217 	 */
218 	if (lastfile == NULL) {
219 		name = NULL;
220 	} else {
221 		name = strrchr(lastfile, '/');
222 		if (name != NULL)
223 			name++;
224 	}
225 	if (name != NULL && strncmp(name, TS, TIMESTAMP_LEN) == 0) {
226 		auditd_log_debug("Not ready to terminate trail file yet.");
227 		return (0);
228 	}
229 	err = auditd_swap_trail(TS, &newfile, audit_review_gid,
230 	    audit_warn_getacdir);
231 	if (err != ADE_NOERR) {
232 		auditd_log_err("%s: %m", auditd_strerror(err));
233 		if (err != ADE_ACTL)
234 			return (-1);
235 	}
236 
237 	/*
238 	 * Only close the last file if were in an auditing state before
239 	 * calling swap_audit_file().  We may need to recover from a crash.
240 	 */
241 	if (auditd_get_state() == AUD_STATE_ENABLED)
242 		close_lastfile(TS);
243 
244 
245 	/*
246 	 * auditd_swap_trail() potentially enables auditing (if not already
247 	 * enabled) so updated the cached state as well.
248 	 */
249 	auditd_set_state(AUD_STATE_ENABLED);
250 
251 	/*
252 	 *  Create 'current' symlink.  Recover from crash, if needed.
253 	 */
254 	if (auditd_new_curlink(newfile) != 0)
255 		auditd_log_err("auditd_new_curlink(\"%s\") failed: %s: %m",
256 		    newfile, auditd_strerror(err));
257 
258 	lastfile = newfile;
259 	auditd_log_notice("New audit file is %s", newfile);
260 
261 	return (0);
262 }
263 
264 /*
265  * Create a new audit log trail file and swap with the current one, if any.
266  */
267 static int
268 do_trail_file(void)
269 {
270 	int err;
271 
272 	/*
273 	 * First, refresh the list of audit log directories.
274 	 */
275 	err = auditd_read_dirs(audit_warn_soft, audit_warn_hard);
276 	if (err) {
277 		auditd_log_err("auditd_read_dirs(): %s",
278 		    auditd_strerror(err));
279 		if (err == ADE_HARDLIM)
280 			audit_warn_allhard();
281 		if (err != ADE_SOFTLIM)
282 			return (-1);
283 		else
284 			audit_warn_allsoft();
285 			/* continue on with soft limit error */
286 	}
287 
288 	/*
289 	 * Create a new file and swap with the one being used in kernel.
290 	 */
291 	if (swap_audit_file() == -1) {
292 		/*
293 		 * XXX Faulty directory listing? - user should be given
294 		 * XXX an opportunity to change the audit_control file
295 		 * XXX switch to a reduced mode of auditing?
296 		 */
297 		return (-1);
298 	}
299 
300 	/*
301 	 * Finally, see if there are any trail files to expire.
302 	 */
303 	err = auditd_expire_trails(audit_warn_expired);
304 	if (err)
305 		auditd_log_err("auditd_expire_trails(): %s",
306 		    auditd_strerror(err));
307 
308 	return (0);
309 }
310 
311 /*
312  * Start up auditing.
313  */
314 static void
315 audit_setup(void)
316 {
317 	int err;
318 
319 	/* Configure trail files distribution. */
320 	err = auditd_set_dist();
321 	if (err) {
322 		auditd_log_err("auditd_set_dist() %s: %m",
323 		    auditd_strerror(err));
324 	} else
325 		auditd_log_debug("Configured trail files distribution.");
326 
327 	if (do_trail_file() == -1) {
328 		auditd_log_err("Error creating audit trail file");
329 		fail_exit();
330 	}
331 
332 	/* Generate an audit record. */
333 	err = auditd_gen_record(AUE_audit_startup, NULL);
334 	if (err)
335 		auditd_log_err("auditd_gen_record(AUE_audit_startup) %s: %m",
336 		    auditd_strerror(err));
337 
338 	if (auditd_config_controls() == 0)
339 		auditd_log_info("Audit controls init successful");
340 	else
341 		auditd_log_err("Audit controls init failed");
342 }
343 
344 
345 /*
346  * Close auditd pid file and trigger mechanism.
347  */
348 static int
349 close_misc(void)
350 {
351 
352 	auditd_close_dirs();
353 	if (unlink(AUDITD_PIDFILE) == -1 && errno != ENOENT) {
354 		auditd_log_err("Couldn't remove %s: %m", AUDITD_PIDFILE);
355 		return (1);
356 	}
357 	endac();
358 
359 	if (auditd_close_trigger() != 0) {
360 		auditd_log_err("Error closing trigger messaging mechanism");
361 		return (1);
362 	}
363 	return (0);
364 }
365 
366 /*
367  * Close all log files, control files, and tell the audit system.
368  */
369 static int
370 close_all(void)
371 {
372 	int err_ret = 0;
373 	char TS[TIMESTAMP_LEN + 1];
374 	int err;
375 	int cond;
376 	time_t tt;
377 
378 	err = auditd_gen_record(AUE_audit_shutdown, NULL);
379 	if (err)
380 		auditd_log_err("auditd_gen_record(AUE_audit_shutdown) %s: %m",
381 		    auditd_strerror(err));
382 
383 	/* Flush contents. */
384 	cond = AUC_DISABLED;
385 	err_ret = audit_set_cond(&cond);
386 	if (err_ret != 0) {
387 		auditd_log_err("Disabling audit failed! : %s", strerror(errno));
388 		err_ret = 1;
389 	}
390 
391 	/*
392 	 * Updated the cached state that auditing has been disabled.
393 	 */
394 	auditd_set_state(AUD_STATE_DISABLED);
395 
396 	if (getTSstr(tt, TS, sizeof(TS)) == 0)
397 		close_lastfile(TS);
398 	if (lastfile != NULL)
399 		free(lastfile);
400 
401 	err_ret += close_misc();
402 
403 	if (err_ret) {
404 		auditd_log_err("Could not unregister");
405 		audit_warn_postsigterm();
406 	}
407 
408 	auditd_log_info("Finished");
409 	return (err_ret);
410 }
411 
412 /*
413  * Register the daemon with the signal handler and the auditd pid file.
414  */
415 static int
416 register_daemon(void)
417 {
418 	FILE * pidfile;
419 	int fd;
420 	pid_t pid;
421 
422 	/* Set up the signal hander. */
423 	if (signal(SIGTERM, auditd_relay_signal) == SIG_ERR) {
424 		auditd_log_err(
425 		    "Could not set signal handler for SIGTERM");
426 		fail_exit();
427 	}
428 	if (signal(SIGCHLD, auditd_relay_signal) == SIG_ERR) {
429 		auditd_log_err(
430 		    "Could not set signal handler for SIGCHLD");
431 		fail_exit();
432 	}
433 	if (signal(SIGHUP, auditd_relay_signal) == SIG_ERR) {
434 		auditd_log_err(
435 		    "Could not set signal handler for SIGHUP");
436 		fail_exit();
437 	}
438 	if (signal(SIGALRM, auditd_relay_signal) == SIG_ERR) {
439 		auditd_log_err(
440 		    "Could not set signal handler for SIGALRM");
441 		fail_exit();
442 	}
443 
444 	if ((pidfile = fopen(AUDITD_PIDFILE, "a")) == NULL) {
445 		auditd_log_err("Could not open PID file");
446 		audit_warn_tmpfile();
447 		return (-1);
448 	}
449 
450 	/* Attempt to lock the pid file; if a lock is present, exit. */
451 	fd = fileno(pidfile);
452 	if (flock(fd, LOCK_EX | LOCK_NB) < 0) {
453 		auditd_log_err(
454 		    "PID file is locked (is another auditd running?).");
455 		audit_warn_ebusy();
456 		return (-1);
457 	}
458 
459 	pid = getpid();
460 	ftruncate(fd, 0);
461 	if (fprintf(pidfile, "%u\n", pid) < 0) {
462 		/* Should not start the daemon. */
463 		fail_exit();
464 	}
465 
466 	fflush(pidfile);
467 	return (0);
468 }
469 
470 /*
471  * Handle the audit trigger event.
472  *
473  * We suppress (ignore) duplicated triggers in close succession in order to
474  * try to avoid thrashing-like behavior.  However, not all triggers can be
475  * ignored, as triggers generally represent edge triggers, not level
476  * triggers, and won't be retransmitted if the condition persists.  Of
477  * specific concern is the rotate trigger -- if one is dropped, then it will
478  * not be retransmitted, and the log file will grow in an unbounded fashion.
479  */
480 #define	DUPLICATE_INTERVAL	30
481 void
482 auditd_handle_trigger(int trigger)
483 {
484 	static int last_trigger, last_warning;
485 	static time_t last_time;
486 	struct timeval ts;
487 	struct timezone tzp;
488 	time_t tt;
489 	int au_state;
490 	int err = 0;
491 
492 	/*
493 	 * Suppress duplicate messages from the kernel within the specified
494 	 * interval.
495 	 */
496 	if (gettimeofday(&ts, &tzp) == 0) {
497 		tt = (time_t)ts.tv_sec;
498 		switch (trigger) {
499 		case AUDIT_TRIGGER_LOW_SPACE:
500 		case AUDIT_TRIGGER_NO_SPACE:
501 			/*
502 			 * Triggers we can suppress.  Of course, we also need
503 			 * to rate limit the warnings, so apply the same
504 			 * interval limit on syslog messages.
505 			 */
506 			if ((trigger == last_trigger) &&
507 			    (tt < (last_time + DUPLICATE_INTERVAL))) {
508 				if (tt >= (last_warning + DUPLICATE_INTERVAL))
509 					auditd_log_info(
510 					    "Suppressing duplicate trigger %d",
511 					    trigger);
512 				return;
513 			}
514 			last_warning = tt;
515 			break;
516 
517 		case AUDIT_TRIGGER_ROTATE_KERNEL:
518 		case AUDIT_TRIGGER_ROTATE_USER:
519 		case AUDIT_TRIGGER_READ_FILE:
520 		case AUDIT_TRIGGER_CLOSE_AND_DIE:
521 		case AUDIT_TRIGGER_INITIALIZE:
522 			/*
523 			 * Triggers that we cannot suppress.
524 			 */
525 			break;
526 		}
527 
528 		/*
529 		 * Only update last_trigger after aborting due to a duplicate
530 		 * trigger, not before, or we will never allow that trigger
531 		 * again.
532 		 */
533 		last_trigger = trigger;
534 		last_time = tt;
535 	}
536 
537 	au_state = auditd_get_state();
538 
539 	/*
540 	 * Message processing is done here.
541 	 */
542 	switch(trigger) {
543 	case AUDIT_TRIGGER_LOW_SPACE:
544 		auditd_log_notice("Got low space trigger");
545 		if (do_trail_file() == -1)
546 			auditd_log_err("Error swapping audit file");
547 		break;
548 
549 	case AUDIT_TRIGGER_NO_SPACE:
550 		auditd_log_notice("Got no space trigger");
551 		if (do_trail_file() == -1)
552 			auditd_log_err("Error swapping audit file");
553 		break;
554 
555 	case AUDIT_TRIGGER_ROTATE_KERNEL:
556 	case AUDIT_TRIGGER_ROTATE_USER:
557 		auditd_log_info("Got open new trigger from %s", trigger ==
558 		    AUDIT_TRIGGER_ROTATE_KERNEL ? "kernel" : "user");
559 		if (au_state == AUD_STATE_ENABLED && do_trail_file() == -1)
560 			auditd_log_err("Error swapping audit file");
561 		break;
562 
563 	case AUDIT_TRIGGER_READ_FILE:
564 		auditd_log_info("Got read file trigger");
565 		if (au_state == AUD_STATE_ENABLED) {
566 			if (auditd_config_controls() == -1)
567 				auditd_log_err("Error setting audit controls");
568 			else if (do_trail_file() == -1)
569 				auditd_log_err("Error swapping audit file");
570 		}
571 		break;
572 
573 	case AUDIT_TRIGGER_CLOSE_AND_DIE:
574 		auditd_log_info("Got close and die trigger");
575 		if (au_state == AUD_STATE_ENABLED)
576 			err = close_all();
577 		/*
578 		 * Running under launchd don't exit.  Wait for launchd to
579 		 * send SIGTERM.
580 		 */
581 		if (!launchd_flag) {
582 			auditd_log_info("auditd exiting.");
583 			exit (err);
584 		}
585 		break;
586 
587 	case AUDIT_TRIGGER_INITIALIZE:
588 		auditd_log_info("Got audit initialize trigger");
589 		if (au_state == AUD_STATE_DISABLED)
590 			audit_setup();
591 		break;
592 
593 	case AUDIT_TRIGGER_EXPIRE_TRAILS:
594 		auditd_log_info("Got audit expire trails trigger");
595 		err = auditd_expire_trails(audit_warn_expired);
596 		if (err)
597 			auditd_log_err("auditd_expire_trails(): %s",
598 			    auditd_strerror(err));
599 		break;
600 
601 	default:
602 		auditd_log_err("Got unknown trigger %d", trigger);
603 		break;
604 	}
605 }
606 
607 /*
608  * Reap our children.
609  */
610 void
611 auditd_reap_children(void)
612 {
613 	pid_t child;
614 	int wstatus;
615 
616 	while ((child = waitpid(-1, &wstatus, WNOHANG)) > 0) {
617 		if (!wstatus)
618 			continue;
619 		auditd_log_info("warn process [pid=%d] %s %d.", child,
620 		    ((WIFEXITED(wstatus)) ? "exited with non-zero status" :
621 		    "exited as a result of signal"),
622 		    ((WIFEXITED(wstatus)) ? WEXITSTATUS(wstatus) :
623 		    WTERMSIG(wstatus)));
624 	}
625 }
626 
627 /*
628  * Reap any children and terminate.  If under launchd don't shutdown auditing
629  * but just the other stuff.
630  */
631 void
632 auditd_terminate(void)
633 {
634 	int ret;
635 
636 	auditd_reap_children();
637 
638 	if (launchd_flag)
639 		ret = close_misc();
640 	else
641 		ret = close_all();
642 
643 	exit(ret);
644 }
645 
646 /*
647  * Configure the audit controls in the kernel: the event to class mapping,
648  * kernel preselection mask, etc.
649  */
650 int
651 auditd_config_controls(void)
652 {
653 	int cnt, err;
654 	int ret = 0;
655 
656 	/*
657 	 * Configure event to class mappings in kernel.
658 	 */
659 	cnt = auditd_set_evcmap();
660 	if (cnt < 0) {
661 		auditd_log_err("auditd_set_evcmap() failed: %m");
662 		ret = -1;
663 	} else if (cnt == 0) {
664 		auditd_log_err("No events to class mappings registered.");
665 		ret = -1;
666 	} else
667 		auditd_log_debug("Registered %d event to class mappings.", cnt);
668 
669 	/*
670 	 * Configure non-attributable event mask in kernel.
671 	 */
672 	err = auditd_set_namask();
673 	if (err) {
674 		auditd_log_err("auditd_set_namask() %s: %m",
675 		    auditd_strerror(err));
676 		ret = -1;
677 	} else
678 		auditd_log_debug("Registered non-attributable event mask.");
679 
680 	/*
681 	 * Configure audit policy in kernel.
682 	 */
683 	err = auditd_set_policy();
684 	if (err) {
685 		auditd_log_err("auditd_set_policy() %s: %m",
686 		    auditd_strerror(err));
687 		ret = -1;
688 	} else
689 		auditd_log_debug("Set audit policy in kernel.");
690 
691 	/*
692 	 * Configure audit trail log size in kernel.
693 	 */
694 	err = auditd_set_fsize();
695 	if (err) {
696 		auditd_log_err("audit_set_fsize() %s: %m",
697 		    auditd_strerror(err));
698 		ret = -1;
699 	} else
700 		auditd_log_debug("Set audit trail size in kernel.");
701 
702 	/*
703 	 * Configure audit trail volume minimum free percentage of blocks in
704 	 * kernel.
705 	 */
706 	err = auditd_set_minfree();
707 	if (err) {
708 		auditd_log_err("auditd_set_minfree() %s: %m",
709 		    auditd_strerror(err));
710 		ret = -1;
711 	} else
712 		auditd_log_debug(
713 		    "Set audit trail min free percent in kernel.");
714 
715 	/*
716 	 * Configure host address in the audit kernel information.
717 	 */
718 	err = auditd_set_host();
719 	if (err) {
720 		if (err == ADE_PARSE) {
721 			auditd_log_notice(
722 			    "audit_control(5) may be missing 'host:' field");
723 		} else {
724 			auditd_log_err("auditd_set_host() %s: %m",
725 			    auditd_strerror(err));
726 			ret = -1;
727 		}
728 	} else
729 		auditd_log_debug(
730 		    "Set audit host address information in kernel.");
731 
732 	return (ret);
733 }
734 
735 /*
736  * Setup and initialize auditd.
737  */
738 static void
739 setup(void)
740 {
741 	int err;
742 
743 	if (auditd_open_trigger(launchd_flag) < 0) {
744 		auditd_log_err("Error opening trigger messaging mechanism");
745 		fail_exit();
746 	}
747 
748 	/*
749 	 * To prevent event feedback cycles and avoid auditd becoming
750 	 * stalled if auditing is suspended, auditd and its children run
751 	 * without their events being audited.  We allow the uid, tid, and
752 	 * mask fields to be implicitly set to zero, but do set the pid.  We
753 	 * run this after opening the trigger device to avoid configuring
754 	 * audit state without audit present in the system.
755 	 */
756 	err = auditd_prevent_audit();
757 	if (err) {
758 		auditd_log_err("auditd_prevent_audit() %s: %m",
759 		    auditd_strerror(err));
760 		fail_exit();
761 	}
762 
763 	/*
764 	 * Make sure auditd auditing state is correct.
765 	 */
766 	auditd_set_state(AUD_STATE_INIT);
767 
768 	/*
769 	 * If under launchd, don't start auditing.  Wait for a trigger to
770 	 * do so.
771 	 */
772 	if (!launchd_flag)
773 		audit_setup();
774 }
775 
776 int
777 main(int argc, char **argv)
778 {
779 	int ch;
780 	int debug = 0;
781 #ifdef AUDIT_REVIEW_GROUP
782 	struct group *grp;
783 #endif
784 
785 	while ((ch = getopt(argc, argv, "dl")) != -1) {
786 		switch(ch) {
787 		case 'd':
788 			/* Debug option. */
789 			debug = 1;
790 			break;
791 
792 		case 'l':
793 			/* Be launchd friendly. */
794 			launchd_flag = 1;
795 			break;
796 
797 		case '?':
798 		default:
799 			(void)fprintf(stderr,
800 			    "usage: auditd [-d] [-l]\n");
801 			exit(1);
802 		}
803 	}
804 
805 	audit_review_gid = getgid();
806 
807 #ifdef AUDIT_REVIEW_GROUP
808 	/*
809 	 * XXXRW: Currently, this code falls back to the daemon gid, which is
810 	 * likely the wheel group.  Is there a better way to deal with this?
811 	 */
812 	grp = getgrnam(AUDIT_REVIEW_GROUP);
813 	if (grp != NULL)
814 		audit_review_gid = grp->gr_gid;
815 #endif
816 
817 	auditd_openlog(debug, audit_review_gid);
818 
819 	if (launchd_flag)
820 		auditd_log_info("started by launchd...");
821 	else
822 		auditd_log_info("starting...");
823 
824 #ifdef AUDIT_REVIEW_GROUP
825 	if (grp == NULL)
826 		auditd_log_info(
827 		    "Audit review group '%s' not available, using daemon gid (%d)",
828 		    AUDIT_REVIEW_GROUP, audit_review_gid);
829 #endif
830 	if (debug == 0 && launchd_flag == 0 && daemon(0, 0) == -1) {
831 		auditd_log_err("Failed to daemonize");
832 		exit(1);
833 	}
834 
835 	if (register_daemon() == -1) {
836 		auditd_log_err("Could not register as daemon");
837 		exit(1);
838 	}
839 
840 	setup();
841 
842 	/*
843 	 * auditd_wait_for_events() shouldn't return unless something is wrong.
844 	 */
845 	auditd_wait_for_events();
846 
847 	auditd_log_err("abnormal exit.");
848 	close_all();
849 	exit(-1);
850 }
851