2 * Copyright 2004-09,2011,2013 Red Hat Inc., Durham, North Carolina.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 * Steve Grubb <sgrubb@redhat.com>
21 * Rickard E. (Rik) Faith <faith@redhat.com>
26 #include <sys/types.h>
33 #include <sys/resource.h>
39 #include <sys/utsname.h>
43 #include "auditd-event.h"
44 #include "auditd-config.h"
45 #include "auditd-dispatch.h"
46 #include "auditd-listen.h"
51 #define EV_STOP() ev_unloop (ev_default_loop (EVFLAG_AUTO), EVUNLOOP_ALL), stop = 1;
53 #define DEFAULT_BUF_SZ 448
54 #define DMSG_SIZE (DEFAULT_BUF_SZ + 48)
60 volatile int stop = 0;
64 static struct daemon_conf config;
65 static const char *pidfile = "/var/run/auditd.pid";
66 static int init_pipe[2];
67 static int do_fork = 1;
68 static struct auditd_reply_list *rep = NULL;
69 static int hup_info_requested = 0;
70 static int usr1_info_requested = 0, usr2_info_requested = 0;
71 static char subj[SUBJ_LEN];
73 /* Local function prototypes */
74 int send_audit_event(int type, const char *str);
75 static void close_down(void);
76 static void clean_exit(void);
77 static int get_reply(int fd, struct audit_reply *rep, int seq);
78 static char *getsubj(char *subj);
80 enum startup_state {startup_disable=0, startup_enable, startup_nochange,
82 static const char *startup_states[] = {"disable", "enable", "nochange"};
85 * Output a usage message
87 static void usage(void)
89 fprintf(stderr, "Usage: auditd [-f] [-l] [-n] [-s %s|%s|%s]\n",
90 startup_states[startup_disable],
91 startup_states[startup_enable],
92 startup_states[startup_nochange]);
101 static void term_handler(struct ev_loop *loop, struct ev_signal *sig,
108 * Used with sigalrm to force exit
110 static void thread_killer( int sig )
116 * Used with sigalrm to force exit
118 static void hup_handler( struct ev_loop *loop, struct ev_signal *sig, int revents )
122 rc = audit_request_signal_info(fd);
124 send_audit_event(AUDIT_DAEMON_CONFIG,
125 "auditd error getting hup info - no change, sending auid=? pid=? subj=? res=failed");
127 hup_info_requested = 1;
131 * Used to force log rotation
133 static void user1_handler(struct ev_loop *loop, struct ev_signal *sig,
138 rc = audit_request_signal_info(fd);
140 send_audit_event(AUDIT_DAEMON_ROTATE,
141 "auditd error getting usr1 info - no change, sending auid=? pid=? subj=? res=failed");
143 usr1_info_requested = 1;
147 * Used to resume logging
149 static void user2_handler( struct ev_loop *loop, struct ev_signal *sig, int revents )
153 rc = audit_request_signal_info(fd);
156 send_audit_event(AUDIT_DAEMON_RESUME,
157 "auditd resuming logging, sending auid=? pid=? subj=? res=success");
159 usr2_info_requested = 1;
163 * Used with email alerts to cleanup
165 static void child_handler(struct ev_loop *loop, struct ev_signal *sig,
170 while ((pid = waitpid(-1, NULL, WNOHANG)) > 0) {
171 if (pid == dispatcher_pid())
176 static void distribute_event(struct auditd_reply_list *rep)
180 /* Make first attempt to send to plugins */
181 if (dispatch_event(&rep->reply, attempt) == 1)
182 attempt++; /* Failed sending, retry after writing to disk */
184 /* End of Event is for realtime interface - skip local logging of it */
185 if (rep->reply.type != AUDIT_EOE) {
186 int yield = rep->reply.type <= AUDIT_LAST_DAEMON &&
187 rep->reply.type >= AUDIT_FIRST_DAEMON ? 1 : 0;
188 /* Write to local disk */
193 ts.tv_nsec = 2 * 1000 * 1000; // 2 milliseconds
194 nanosleep(&ts, NULL); // Let other thread try to log it
197 free(rep); // This function takes custody of the memory
199 // FIXME: This is commented out since it fails to work. The
200 // problem is that the logger thread free's the buffer. Probably
201 // need a way to flag in the buffer if logger thread should free or
202 // move the free to this function.
204 /* Last chance to send...maybe the pipe is empty now. */
206 // dispatch_event(&rep->reply, attempt);
210 * This function is used to send start, stop, and abort messages
213 static unsigned seq_num = 0;
214 int send_audit_event(int type, const char *str)
216 struct auditd_reply_list *rep;
219 if ((rep = malloc(sizeof(*rep))) == NULL) {
220 audit_msg(LOG_ERR, "Cannot allocate audit reply");
224 rep->reply.type = type;
225 rep->reply.message = (char *)malloc(DMSG_SIZE);
226 if (rep->reply.message == NULL) {
228 audit_msg(LOG_ERR, "Cannot allocate local event message");
233 seq_num = rand()%10000;
236 if (gettimeofday(&tv, NULL) == 0) {
237 rep->reply.len = snprintf((char *)rep->reply.message,
238 DMSG_SIZE, "audit(%lu.%03u:%u): %s",
239 tv.tv_sec, (unsigned)(tv.tv_usec/1000), seq_num, str);
241 rep->reply.len = snprintf((char *)rep->reply.message,
242 DMSG_SIZE, "audit(%lu.%03u:%u): %s",
243 (unsigned long)time(NULL), 0, seq_num, str);
245 if (rep->reply.len > DMSG_SIZE)
246 rep->reply.len = DMSG_SIZE;
248 distribute_event(rep);
252 static int write_pid_file(void)
257 len = snprintf(val, sizeof(val), "%u\n", getpid());
259 audit_msg(LOG_ERR, "Pid error (%s)", strerror(errno));
263 pidfd = open(pidfile, O_CREAT | O_TRUNC | O_NOFOLLOW | O_WRONLY, 0644);
265 audit_msg(LOG_ERR, "Unable to set pidfile (%s)",
270 if (write(pidfd, val, (unsigned int)len) != len) {
271 audit_msg(LOG_ERR, "Unable to write pidfile (%s)",
281 static void avoid_oom_killer(void)
286 /* New kernels use different technique */
287 if ((oomfd = open("/proc/self/oom_score_adj",
288 O_NOFOLLOW | O_WRONLY)) >= 0) {
290 } else if ((oomfd = open("/proc/self/oom_adj",
291 O_NOFOLLOW | O_WRONLY)) >= 0) {
294 audit_msg(LOG_NOTICE, "Cannot open out of memory adjuster");
299 rc = write(oomfd, score, len);
301 audit_msg(LOG_NOTICE, "Unable to adjust out of memory score");
307 * This function will take care of becoming a daemon. The parent
308 * will wait until the child notifies it by writing into a special
309 * pipe to signify that it successfully initialized. This prevents
310 * a race in the init script where rules get loaded before the daemon
311 * is ready and they wind up in syslog. The child returns 0 on success
312 * and nonzero on failure. The parent returns nonzero on failure. On
313 * success, the parent calls _exit with 0.
315 static int become_daemon(void)
322 if (pipe(init_pipe) ||
323 fcntl(init_pipe[0], F_SETFD, FD_CLOEXEC) ||
324 fcntl(init_pipe[0], F_SETFD, FD_CLOEXEC))
333 /* No longer need this... */
337 /* Open stdin,out,err to /dev/null */
338 fd = open("/dev/null", O_RDWR);
340 audit_msg(LOG_ERR, "Cannot open /dev/null");
343 if ((dup2(fd, 0) < 0) || (dup2(fd, 1) < 0) ||
346 "Cannot reassign descriptors to /dev/null");
356 "Cannot change working directory to /");
360 /* Become session/process group leader */
367 /* Wait for the child to say its done */
368 rc = read(init_pipe[0], &status, sizeof(status));
372 /* Success - die a happy death */
373 if (status == SUCCESS)
383 static void tell_parent(int status)
387 if (config.daemonize != D_BACKGROUND || do_fork == 0)
390 rc = write(init_pipe[1], &status, sizeof(status));
391 } while (rc < 0 && errno == EINTR);
394 static void netlink_handler(struct ev_loop *loop, struct ev_io *io,
398 if ((rep = malloc(sizeof(*rep))) == NULL) {
399 char emsg[DEFAULT_BUF_SZ];
401 snprintf(emsg, sizeof(emsg),
402 "auditd error halt, auid=%u pid=%d subj=%s res=failed",
403 audit_getloginuid(), getpid(), subj);
405 snprintf(emsg, sizeof(emsg),
406 "auditd error halt, auid=%u pid=%d res=failed",
407 audit_getloginuid(), getpid());
409 send_audit_event(AUDIT_DAEMON_ABORT, emsg);
411 "Cannot allocate audit reply, exiting");
415 shutdown_dispatcher();
419 if (audit_get_reply(fd, &rep->reply,
420 GET_REPLY_NONBLOCKING, 0) > 0) {
421 switch (rep->reply.type)
422 { /* For now dont process these */
426 case AUDIT_GET: /* Or these */
427 case AUDIT_LIST_RULES:
428 case AUDIT_FIRST_DAEMON...AUDIT_LAST_DAEMON:
430 case AUDIT_SIGNAL_INFO:
431 if (hup_info_requested) {
433 "HUP detected, starting config manager");
434 if (start_config_manager(rep)) {
437 "auditd error getting hup info - no change,"
438 " sending auid=? pid=? subj=? res=failed");
441 hup_info_requested = 0;
442 } else if (usr1_info_requested) {
443 char usr1[MAX_AUDIT_MESSAGE_LENGTH];
444 if (rep->reply.len == 24) {
445 snprintf(usr1, sizeof(usr1),
446 "auditd sending auid=? pid=? subj=?");
448 snprintf(usr1, sizeof(usr1),
449 "auditd sending auid=%u pid=%d subj=%s",
450 rep->reply.signal_info->uid,
451 rep->reply.signal_info->pid,
452 rep->reply.signal_info->ctx);
454 send_audit_event(AUDIT_DAEMON_ROTATE, usr1);
455 usr1_info_requested = 0;
456 } else if (usr2_info_requested) {
457 char usr2[MAX_AUDIT_MESSAGE_LENGTH];
458 if (rep->reply.len == 24) {
459 snprintf(usr2, sizeof(usr2),
460 "auditd resuming logging, "
461 "sending auid=? pid=? subj=? "
464 snprintf(usr2, sizeof(usr2),
465 "auditd resuming logging, "
466 "sending auid=%u pid=%d subj=%s res=success",
467 rep->reply.signal_info->uid,
468 rep->reply.signal_info->pid,
469 rep->reply.signal_info->ctx);
472 send_audit_event(AUDIT_DAEMON_RESUME, usr2);
473 usr2_info_requested = 0;
477 distribute_event(rep);
482 if (errno == EFBIG) {
483 // FIXME do err action
488 int main(int argc, char *argv[])
493 int opt_foreground = 0, opt_allow_links = 0;
494 enum startup_state opt_startup = startup_enable;
497 struct ev_loop *loop;
498 struct ev_io netlink_watcher;
499 struct ev_signal sigterm_watcher;
500 struct ev_signal sighup_watcher;
501 struct ev_signal sigusr1_watcher;
502 struct ev_signal sigusr2_watcher;
503 struct ev_signal sigchld_watcher;
505 /* Get params && set mode */
506 while ((c = getopt(argc, argv, "flns:")) != -1) {
518 for (i=0; i<startup_INVALID; i++) {
519 if (strncmp(optarg, startup_states[i],
520 strlen(optarg)) == 0) {
525 if (i == startup_INVALID) {
526 fprintf(stderr, "unknown startup mode '%s'\n",
536 /* check for trailing command line following options */
544 if (opt_foreground) {
545 config.daemonize = D_FOREGROUND;
546 set_aumessage_mode(MSG_STDERR, DBG_YES);
548 config.daemonize = D_BACKGROUND;
549 set_aumessage_mode(MSG_SYSLOG, DBG_NO);
550 (void) umask( umask( 077 ) | 022 );
554 /* Make sure we are root */
556 fprintf(stderr, "You must be root to run this program.\n");
561 /* Register sighandlers */
563 sigemptyset( &sa.sa_mask ) ;
564 /* Ignore all signals by default */
565 sa.sa_handler = SIG_IGN;
566 for (i=1; i<NSIG; i++)
567 sigaction( i, &sa, NULL );
571 /* Raise the rlimits in case we're being started from a shell
572 * with restrictions. Not a fatal error. */
573 limit.rlim_cur = RLIM_INFINITY;
574 limit.rlim_max = RLIM_INFINITY;
575 setrlimit(RLIMIT_FSIZE, &limit);
576 setrlimit(RLIMIT_CPU, &limit);
578 /* Load the Configuration File */
579 if (load_config(&config, TEST_AUDITD))
582 if (config.priority_boost != 0) {
584 rc = nice((int)-config.priority_boost);
585 if (rc == -1 && errno) {
586 audit_msg(LOG_ERR, "Cannot change priority (%s)",
592 /* Daemonize or stay in foreground for debugging */
593 if (config.daemonize == D_BACKGROUND) {
594 if (become_daemon() != 0) {
595 audit_msg(LOG_ERR, "Cannot daemonize (%s)",
597 tell_parent(FAILURE);
600 openlog("auditd", LOG_PID, LOG_DAEMON);
604 if ((fd = audit_open()) < 0) {
605 audit_msg(LOG_ERR, "Cannot open netlink audit socket");
606 tell_parent(FAILURE);
610 /* Init the event handler thread */
612 if (init_event(&config)) {
615 tell_parent(FAILURE);
619 if (init_dispatcher(&config)) {
622 tell_parent(FAILURE);
626 /* Get machine name ready for use */
627 if (resolve_node(&config)) {
630 tell_parent(FAILURE);
634 /* Write message to log that we are alive */
637 char start[DEFAULT_BUF_SZ];
638 const char *fmt = audit_lookup_format((int)config.log_format);
641 if (uname(&ubuf) != 0) {
644 tell_parent(FAILURE);
648 snprintf(start, sizeof(start),
649 "auditd start, ver=%s format=%s "
650 "kernel=%.56s auid=%u pid=%d subj=%s res=success",
651 VERSION, fmt, ubuf.release,
652 audit_getloginuid(), getpid(), subj);
654 snprintf(start, sizeof(start),
655 "auditd start, ver=%s format=%s "
656 "kernel=%.56s auid=%u pid=%d res=success",
657 VERSION, fmt, ubuf.release,
658 audit_getloginuid(), getpid());
659 if (send_audit_event(AUDIT_DAEMON_START, start)) {
660 audit_msg(LOG_ERR, "Cannot send start message");
663 shutdown_dispatcher();
664 tell_parent(FAILURE);
669 /* Tell kernel not to kill us */
672 /* let config manager init */
673 init_config_manager();
675 if (opt_startup != startup_nochange && (audit_is_enabled(fd) < 2) &&
676 audit_set_enabled(fd, (int)opt_startup) < 0) {
677 char emsg[DEFAULT_BUF_SZ];
679 snprintf(emsg, sizeof(emsg),
680 "auditd error halt, auid=%u pid=%d subj=%s res=failed",
681 audit_getloginuid(), getpid(), subj);
683 snprintf(emsg, sizeof(emsg),
684 "auditd error halt, auid=%u pid=%d res=failed",
685 audit_getloginuid(), getpid());
687 send_audit_event(AUDIT_DAEMON_ABORT, emsg);
689 "Unable to set initial audit startup state to '%s', exiting",
690 startup_states[opt_startup]);
694 shutdown_dispatcher();
695 tell_parent(FAILURE);
699 /* Tell the kernel we are alive */
700 if (audit_set_pid(fd, getpid(), WAIT_YES) < 0) {
701 char emsg[DEFAULT_BUF_SZ];
703 snprintf(emsg, sizeof(emsg),
704 "auditd error halt, auid=%u pid=%d subj=%s res=failed",
705 audit_getloginuid(), getpid(), subj);
707 snprintf(emsg, sizeof(emsg),
708 "auditd error halt, auid=%u pid=%d res=failed",
709 audit_getloginuid(), getpid());
711 send_audit_event(AUDIT_DAEMON_ABORT, emsg);
712 audit_msg(LOG_ERR, "Unable to set audit pid, exiting");
716 shutdown_dispatcher();
717 tell_parent(FAILURE);
721 /* Depending on value of opt_startup (-s) set initial audit state */
722 loop = ev_default_loop (EVFLAG_NOENV);
724 ev_io_init (&netlink_watcher, netlink_handler, fd, EV_READ);
725 ev_io_start (loop, &netlink_watcher);
727 ev_signal_init (&sigterm_watcher, term_handler, SIGTERM);
728 ev_signal_start (loop, &sigterm_watcher);
730 ev_signal_init (&sighup_watcher, hup_handler, SIGHUP);
731 ev_signal_start (loop, &sighup_watcher);
733 ev_signal_init (&sigusr1_watcher, user1_handler, SIGUSR1);
734 ev_signal_start (loop, &sigusr1_watcher);
736 ev_signal_init (&sigusr2_watcher, user2_handler, SIGUSR2);
737 ev_signal_start (loop, &sigusr2_watcher);
739 ev_signal_init (&sigchld_watcher, child_handler, SIGCHLD);
740 ev_signal_start (loop, &sigchld_watcher);
742 if (auditd_tcp_listen_init (loop, &config)) {
743 char emsg[DEFAULT_BUF_SZ];
745 snprintf(emsg, sizeof(emsg),
746 "auditd error halt, auid=%u pid=%d subj=%s res=failed",
747 audit_getloginuid(), getpid(), subj);
749 snprintf(emsg, sizeof(emsg),
750 "auditd error halt, auid=%u pid=%d res=failed",
751 audit_getloginuid(), getpid());
753 send_audit_event(AUDIT_DAEMON_ABORT, emsg);
754 tell_parent(FAILURE);
756 /* Now tell parent that everything went OK */
757 tell_parent(SUCCESS);
758 audit_msg(LOG_NOTICE,
759 "Init complete, auditd %s listening for events (startup state %s)",
761 startup_states[opt_startup]);
764 /* Parent should be gone by now... */
768 // Init complete, start event loop
772 auditd_tcp_listen_uninit (loop, &config);
774 // Tear down IO watchers Part 1
775 ev_signal_stop (loop, &sighup_watcher);
776 ev_signal_stop (loop, &sigusr1_watcher);
777 ev_signal_stop (loop, &sigusr2_watcher);
778 ev_signal_stop (loop, &sigterm_watcher);
780 /* Write message to log that we are going down */
781 rc = audit_request_signal_info(fd);
783 struct audit_reply trep;
785 rc = get_reply(fd, &trep, rc);
787 char txt[MAX_AUDIT_MESSAGE_LENGTH];
788 snprintf(txt, sizeof(txt),
789 "auditd normal halt, sending auid=%u "
790 "pid=%d subj=%s res=success",
791 trep.signal_info->uid,
792 trep.signal_info->pid,
793 trep.signal_info->ctx);
794 send_audit_event(AUDIT_DAEMON_END, txt);
798 send_audit_event(AUDIT_DAEMON_END,
799 "auditd normal halt, sending auid=? "
800 "pid=? subj=? res=success");
803 // Tear down IO watchers Part 2
804 ev_io_stop (loop, &netlink_watcher);
806 // Give DAEMON_END event a little time to be sent in case
808 usleep(10000); // 10 milliseconds
809 shutdown_dispatcher();
811 // Tear down IO watchers Part 3
812 ev_signal_stop (loop, &sigchld_watcher);
815 free_config(&config);
816 ev_default_destroy();
821 static void close_down(void)
825 /* We are going down. Give the event thread a chance to shutdown.
826 Just in case it hangs, set a timer to get us out of trouble. */
828 sigemptyset( &sa.sa_mask ) ;
829 sa.sa_handler = thread_killer;
830 sigaction( SIGALRM, &sa, NULL );
836 * A clean exit means :
837 * 1) we log that we are going down
838 * 2) deregister with kernel
839 * 3) close the netlink socket
841 static void clean_exit(void)
843 audit_msg(LOG_INFO, "The audit daemon is exiting.");
845 audit_set_pid(fd, 0, WAIT_NO);
854 * This function is used to get the reply for term info.
855 * Returns 1 on success & -1 on failure.
857 static int get_reply(int fd, struct audit_reply *rep, int seq)
860 int timeout = 30; /* tenths of seconds */
862 for (i = 0; i < timeout; i++) {
867 t.tv_usec = 100000; /* .1 second */
869 FD_SET(fd, &read_mask);
871 rc = select(fd+1, &read_mask, NULL, NULL, &t);
872 } while (rc < 0 && errno == EINTR);
873 rc = audit_get_reply(fd, rep,
874 GET_REPLY_NONBLOCKING, 0);
876 /* Don't make decisions based on wrong packet */
877 if (rep->nlh->nlmsg_seq != seq)
880 /* If its not what we are expecting, keep looping */
881 if (rep->type == AUDIT_SIGNAL_INFO)
884 /* If we get done or error, break out */
885 if (rep->type == NLMSG_DONE || rep->type == NLMSG_ERROR)
892 //get the subj of the daemon
893 static char *getsubj(char *subj)
895 pid_t pid = getpid();
900 snprintf(filename, sizeof(filename), "/proc/%u/attr/current", pid);
901 fd = open(filename, O_RDONLY);
907 num_read = read(fd, subj, SUBJ_LEN-1);
908 } while (num_read < 0 && errno == EINTR);
914 subj[num_read] = '\0';