Imported Upstream version 2.4.3
[platform/upstream/audit.git] / src / auditd.c
1 /* auditd.c -- 
2  * Copyright 2004-09,2011,2013 Red Hat Inc., Durham, North Carolina.
3  * All Rights Reserved.
4  *
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.
9  *
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.
14  *
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
18  *
19  * Authors:
20  *   Steve Grubb <sgrubb@redhat.com>
21  *   Rickard E. (Rik) Faith <faith@redhat.com>
22  */
23
24 #include "config.h"
25 #include <stdio.h>
26 #include <sys/types.h>
27 #include <unistd.h>
28 #include <stdlib.h>
29 #include <signal.h>
30 #include <errno.h>
31 #include <string.h>
32 #include <time.h>
33 #include <sys/resource.h>
34 #include <sys/time.h>
35 #include <sys/stat.h>
36 #include <sys/wait.h>
37 #include <fcntl.h>
38 #include <pthread.h>
39 #include <sys/utsname.h>
40 #include <getopt.h>
41
42 #include "libaudit.h"
43 #include "auditd-event.h"
44 #include "auditd-config.h"
45 #include "auditd-dispatch.h"
46 #include "auditd-listen.h"
47 #include "private.h"
48
49 #include "ev.h"
50
51 #define EV_STOP() ev_unloop (ev_default_loop (EVFLAG_AUTO), EVUNLOOP_ALL), stop = 1;
52
53 #define DEFAULT_BUF_SZ  448
54 #define DMSG_SIZE (DEFAULT_BUF_SZ + 48) 
55 #define SUCCESS 0
56 #define FAILURE 1
57 #define SUBJ_LEN 4097
58
59 /* Global Data */
60 volatile int stop = 0;
61
62 /* Local data */
63 static int fd = -1;
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];
72
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);
79
80 enum startup_state {startup_disable=0, startup_enable, startup_nochange,
81         startup_INVALID};
82 static const char *startup_states[] = {"disable", "enable", "nochange"};
83
84 /*
85  * Output a usage message
86  */
87 static void usage(void)
88 {
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]);
93
94         exit(2);
95 }
96
97
98 /*
99  * SIGTERM handler
100  */ 
101 static void term_handler(struct ev_loop *loop, struct ev_signal *sig,
102                         int revents)
103 {
104         EV_STOP ();
105 }
106
107 /*
108  * Used with sigalrm to force exit
109  */
110 static void thread_killer( int sig )
111 {
112         exit(0);
113 }
114
115 /*
116  * Used with sigalrm to force exit
117  */
118 static void hup_handler( struct ev_loop *loop, struct ev_signal *sig, int revents )
119 {
120         int rc;
121
122         rc = audit_request_signal_info(fd);
123         if (rc < 0)
124                 send_audit_event(AUDIT_DAEMON_CONFIG, 
125                                  "auditd error getting hup info - no change, sending auid=? pid=? subj=? res=failed");
126         else
127                 hup_info_requested = 1;
128 }
129
130 /*
131  * Used to force log rotation
132  */
133 static void user1_handler(struct ev_loop *loop, struct ev_signal *sig,
134                         int revents)
135 {
136         int rc;
137
138         rc = audit_request_signal_info(fd);
139         if (rc < 0)
140                 send_audit_event(AUDIT_DAEMON_ROTATE, 
141                                  "auditd error getting usr1 info - no change, sending auid=? pid=? subj=? res=failed");
142         else
143                 usr1_info_requested = 1;
144 }
145
146 /*
147  * Used to resume logging
148  */
149 static void user2_handler( struct ev_loop *loop, struct ev_signal *sig, int revents )
150 {
151         int rc;
152
153         rc = audit_request_signal_info(fd);
154         if (rc < 0) {
155                 resume_logging();
156                 send_audit_event(AUDIT_DAEMON_RESUME, 
157                          "auditd resuming logging, sending auid=? pid=? subj=? res=success");
158         } else
159                 usr2_info_requested = 1;
160 }
161
162 /*
163  * Used with email alerts to cleanup
164  */
165 static void child_handler(struct ev_loop *loop, struct ev_signal *sig,
166                         int revents)
167 {
168         int pid;
169
170         while ((pid = waitpid(-1, NULL, WNOHANG)) > 0) {
171                 if (pid == dispatcher_pid())
172                         dispatcher_reaped();
173         }
174 }
175
176 static void distribute_event(struct auditd_reply_list *rep)
177 {
178         int attempt = 0;
179
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 */
183
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 */
189                 enqueue_event(rep);
190                 if (yield) {
191                         struct timespec ts;
192                         ts.tv_sec = 0;
193                         ts.tv_nsec = 2 * 1000 * 1000; // 2 milliseconds
194                         nanosleep(&ts, NULL); // Let other thread try to log it
195                 }
196         } else
197                 free(rep);      // This function takes custody of the memory
198
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.
203
204         /* Last chance to send...maybe the pipe is empty now. */
205 //      if (attempt) 
206 //              dispatch_event(&rep->reply, attempt);
207 }
208
209 /*
210  * This function is used to send start, stop, and abort messages 
211  * to the audit log.
212  */
213 static unsigned seq_num = 0;
214 int send_audit_event(int type, const char *str)
215 {
216         struct auditd_reply_list *rep;
217         struct timeval tv;
218         
219         if ((rep = malloc(sizeof(*rep))) == NULL) {
220                 audit_msg(LOG_ERR, "Cannot allocate audit reply");
221                 return 1;
222         }
223
224         rep->reply.type = type;
225         rep->reply.message = (char *)malloc(DMSG_SIZE);
226         if (rep->reply.message == NULL) {
227                 free(rep);
228                 audit_msg(LOG_ERR, "Cannot allocate local event message");
229                 return 1;
230         }
231         if (seq_num == 0) {
232                 srand(time(NULL));
233                 seq_num = rand()%10000;
234         } else
235                 seq_num++;
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);
240         } else {
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);
244         }
245         if (rep->reply.len > DMSG_SIZE)
246                 rep->reply.len = DMSG_SIZE;
247
248         distribute_event(rep);
249         return 0;
250 }
251
252 static int write_pid_file(void)
253 {
254         int pidfd, len;
255         char val[16];
256
257         len = snprintf(val, sizeof(val), "%u\n", getpid());
258         if (len <= 0) {
259                 audit_msg(LOG_ERR, "Pid error (%s)", strerror(errno));
260                 pidfile = 0;
261                 return 1;
262         }
263         pidfd = open(pidfile, O_CREAT | O_TRUNC | O_NOFOLLOW | O_WRONLY, 0644);
264         if (pidfd < 0) {
265                 audit_msg(LOG_ERR, "Unable to set pidfile (%s)",
266                         strerror(errno));
267                 pidfile = 0;
268                 return 1;
269         }
270         if (write(pidfd, val, (unsigned int)len) != len) {
271                 audit_msg(LOG_ERR, "Unable to write pidfile (%s)",
272                         strerror(errno));
273                 close(pidfd);
274                 pidfile = 0;
275                 return 1;
276         }
277         close(pidfd);
278         return 0;
279 }
280
281 static void avoid_oom_killer(void)
282 {
283         int oomfd, len, rc;
284         char *score = NULL;
285
286         /* New kernels use different technique */       
287         if ((oomfd = open("/proc/self/oom_score_adj",
288                                 O_NOFOLLOW | O_WRONLY)) >= 0) {
289                 score = "-1000";
290         } else if ((oomfd = open("/proc/self/oom_adj",
291                                 O_NOFOLLOW | O_WRONLY)) >= 0) {
292                 score = "-17";
293         } else {
294                 audit_msg(LOG_NOTICE, "Cannot open out of memory adjuster");
295                 return;
296         }
297
298         len = strlen(score);
299         rc = write(oomfd, score, len);
300         if (rc != len)
301                 audit_msg(LOG_NOTICE, "Unable to adjust out of memory score");
302
303         close(oomfd);
304 }
305
306 /*
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.
314  */ 
315 static int become_daemon(void)
316 {
317         int fd, rc;
318         pid_t pid;
319         int status;
320
321         if (do_fork) {
322                 if (pipe(init_pipe) || 
323                                 fcntl(init_pipe[0], F_SETFD, FD_CLOEXEC) ||
324                                 fcntl(init_pipe[0], F_SETFD, FD_CLOEXEC))
325                         return -1;
326                 pid = fork();
327         } else
328                 pid = 0;
329
330         switch (pid)
331         {
332                 case 0:
333                         /* No longer need this...   */
334                         if (do_fork) 
335                                 close(init_pipe[0]);
336
337                         /* Open stdin,out,err to /dev/null */
338                         fd = open("/dev/null", O_RDWR);
339                         if (fd < 0) {
340                                 audit_msg(LOG_ERR, "Cannot open /dev/null");
341                                 return -1;
342                         }
343                         if ((dup2(fd, 0) < 0) || (dup2(fd, 1) < 0) ||
344                                                         (dup2(fd, 2) < 0)) {
345                                 audit_msg(LOG_ERR,
346                                     "Cannot reassign descriptors to /dev/null");
347                                 close(fd);
348                                 return -1;
349                         }
350                         close(fd);
351
352                         /* Change to '/' */
353                         rc = chdir("/");
354                         if (rc < 0) {
355                                 audit_msg(LOG_ERR,
356                                         "Cannot change working directory to /");
357                                 return -1;
358                         }
359
360                         /* Become session/process group leader */
361                         setsid();
362                         break;
363                 case -1:
364                         return -1;
365                         break;
366                 default:
367                         /* Wait for the child to say its done */
368                         rc = read(init_pipe[0], &status, sizeof(status));
369                         if (rc < 0)
370                                 return -1;
371
372                         /* Success - die a happy death */
373                         if (status == SUCCESS)
374                                 _exit(0);
375                         else
376                                 return -1;
377                         break;
378         }
379
380         return 0;
381 }
382
383 static void tell_parent(int status)
384 {
385         int rc;
386
387         if (config.daemonize != D_BACKGROUND || do_fork == 0)
388                 return;
389         do {
390                 rc = write(init_pipe[1], &status, sizeof(status));
391         } while (rc < 0 && errno == EINTR);
392 }
393
394 static void netlink_handler(struct ev_loop *loop, struct ev_io *io,
395                         int revents)
396 {
397         if (rep == NULL) { 
398                 if ((rep = malloc(sizeof(*rep))) == NULL) {
399                         char emsg[DEFAULT_BUF_SZ];
400                         if (*subj)
401                                 snprintf(emsg, sizeof(emsg),
402                         "auditd error halt, auid=%u pid=%d subj=%s res=failed",
403                                         audit_getloginuid(), getpid(), subj);
404                         else
405                                 snprintf(emsg, sizeof(emsg),
406                                  "auditd error halt, auid=%u pid=%d res=failed",
407                                          audit_getloginuid(), getpid());
408                         EV_STOP ();
409                         send_audit_event(AUDIT_DAEMON_ABORT, emsg);
410                         audit_msg(LOG_ERR, 
411                                   "Cannot allocate audit reply, exiting");
412                         close_down();
413                         if (pidfile)
414                                 unlink(pidfile);
415                         shutdown_dispatcher();
416                         return;
417                 }
418         }
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 */
423                 case NLMSG_NOOP:
424                 case NLMSG_DONE:
425                 case NLMSG_ERROR:
426                 case AUDIT_GET: /* Or these */
427                 case AUDIT_LIST_RULES:
428                 case AUDIT_FIRST_DAEMON...AUDIT_LAST_DAEMON:
429                         break;
430                 case AUDIT_SIGNAL_INFO:
431                         if (hup_info_requested) {
432                                 audit_msg(LOG_DEBUG,
433                                     "HUP detected, starting config manager");
434                                 if (start_config_manager(rep)) {
435                                         send_audit_event(
436                                                 AUDIT_DAEMON_CONFIG, 
437                                   "auditd error getting hup info - no change,"
438                                   " sending auid=? pid=? subj=? res=failed");
439                                 }
440                                 rep = NULL;
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=?");
447                                 } else {
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);
453                                 }
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=? "
462                                                 "res=success");
463                                 } else {
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);
470                                 }
471                                 resume_logging();
472                                 send_audit_event(AUDIT_DAEMON_RESUME, usr2); 
473                                 usr2_info_requested = 0;
474                         }
475                         break;
476                 default:
477                         distribute_event(rep);
478                         rep = NULL;
479                         break;
480                 }
481         } else {
482                 if (errno == EFBIG) {
483                         // FIXME do err action
484                 }
485         }
486 }
487
488 int main(int argc, char *argv[])
489 {
490         struct sigaction sa;
491         struct rlimit limit;
492         int i, c, rc;
493         int opt_foreground = 0, opt_allow_links = 0;
494         enum startup_state opt_startup = startup_enable;
495         extern char *optarg;
496         extern int optind;
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;
504
505         /* Get params && set mode */
506         while ((c = getopt(argc, argv, "flns:")) != -1) {
507                 switch (c) {
508                 case 'f':
509                         opt_foreground = 1;
510                         break;
511                 case 'l':
512                         opt_allow_links=1;
513                         break;
514                 case 'n':
515                         do_fork = 0;
516                         break;
517                 case 's':
518                         for (i=0; i<startup_INVALID; i++) {
519                                 if (strncmp(optarg, startup_states[i],
520                                         strlen(optarg)) == 0) {
521                                         opt_startup = i;
522                                         break;
523                                 }
524                         }
525                         if (i == startup_INVALID) {
526                                 fprintf(stderr, "unknown startup mode '%s'\n",
527                                         optarg);
528                                 usage();
529                         }
530                         break;
531                 default:
532                         usage();
533                 }
534         }
535
536         /* check for trailing command line following options */
537         if (optind < argc) {
538                 usage();
539         }
540
541         if (opt_allow_links)
542                 set_allow_links(1);
543
544         if (opt_foreground) {
545                 config.daemonize = D_FOREGROUND;
546                 set_aumessage_mode(MSG_STDERR, DBG_YES);
547         } else {
548                 config.daemonize = D_BACKGROUND;
549                 set_aumessage_mode(MSG_SYSLOG, DBG_NO);
550                 (void) umask( umask( 077 ) | 022 );
551         }
552
553 #ifndef DEBUG
554         /* Make sure we are root */
555         if (getuid() != 0) {
556                 fprintf(stderr, "You must be root to run this program.\n");
557                 return 4;
558         }
559 #endif
560
561         /* Register sighandlers */
562         sa.sa_flags = 0 ;
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 );
568
569         atexit(clean_exit);
570
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);
577
578         /* Load the Configuration File */
579         if (load_config(&config, TEST_AUDITD))
580                 return 6;
581
582         if (config.priority_boost != 0) {
583                 errno = 0;
584                 rc = nice((int)-config.priority_boost);
585                 if (rc == -1 && errno) {
586                         audit_msg(LOG_ERR, "Cannot change priority (%s)", 
587                                         strerror(errno));
588                         return 1;
589                 }
590         } 
591         
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)",
596                                 strerror(errno));
597                         tell_parent(FAILURE);
598                         return 1;
599                 } 
600                 openlog("auditd", LOG_PID, LOG_DAEMON);
601         }
602
603         /* Init netlink */
604         if ((fd = audit_open()) < 0) {
605                 audit_msg(LOG_ERR, "Cannot open netlink audit socket");
606                 tell_parent(FAILURE);
607                 return 1;
608         }
609
610         /* Init the event handler thread */
611         write_pid_file();
612         if (init_event(&config)) {
613                 if (pidfile)
614                         unlink(pidfile);
615                 tell_parent(FAILURE);
616                 return 1;
617         }
618
619         if (init_dispatcher(&config)) {
620                 if (pidfile)
621                         unlink(pidfile);
622                 tell_parent(FAILURE);
623                 return 1;
624         }
625
626         /* Get machine name ready for use */
627         if (resolve_node(&config)) {
628                 if (pidfile)
629                         unlink(pidfile);
630                 tell_parent(FAILURE);
631                 return 1;
632         }
633
634         /* Write message to log that we are alive */
635         {
636                 struct utsname ubuf;
637                 char start[DEFAULT_BUF_SZ];
638                 const char *fmt = audit_lookup_format((int)config.log_format);
639                 if (fmt == NULL)
640                         fmt = "UNKNOWN";
641                 if (uname(&ubuf) != 0) {
642                         if (pidfile)
643                                 unlink(pidfile);
644                         tell_parent(FAILURE);
645                         return 1;
646                 }
647                 if (getsubj(subj))
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);
653                 else
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");
661                         if (pidfile)
662                                 unlink(pidfile);
663                         shutdown_dispatcher();
664                         tell_parent(FAILURE);
665                         return 1;
666                 }
667         }
668
669         /* Tell kernel not to kill us */
670         avoid_oom_killer();
671
672         /* let config manager init */
673         init_config_manager();
674
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];
678                 if (*subj)
679                         snprintf(emsg, sizeof(emsg),
680                         "auditd error halt, auid=%u pid=%d subj=%s res=failed",
681                                 audit_getloginuid(), getpid(), subj);
682                 else
683                         snprintf(emsg, sizeof(emsg),
684                                 "auditd error halt, auid=%u pid=%d res=failed",
685                                 audit_getloginuid(), getpid());
686                 stop = 1;
687                 send_audit_event(AUDIT_DAEMON_ABORT, emsg);
688                 audit_msg(LOG_ERR,
689                 "Unable to set initial audit startup state to '%s', exiting",
690                         startup_states[opt_startup]);
691                 close_down();
692                 if (pidfile)
693                         unlink(pidfile);
694                 shutdown_dispatcher();
695                 tell_parent(FAILURE);
696                 return 1;
697         }
698
699         /* Tell the kernel we are alive */
700         if (audit_set_pid(fd, getpid(), WAIT_YES) < 0) {
701                 char emsg[DEFAULT_BUF_SZ];
702                 if (*subj)
703                         snprintf(emsg, sizeof(emsg),
704                         "auditd error halt, auid=%u pid=%d subj=%s res=failed",
705                                 audit_getloginuid(), getpid(), subj);
706                 else
707                         snprintf(emsg, sizeof(emsg),
708                                 "auditd error halt, auid=%u pid=%d res=failed",
709                                 audit_getloginuid(), getpid());
710                 stop = 1;
711                 send_audit_event(AUDIT_DAEMON_ABORT, emsg);
712                 audit_msg(LOG_ERR, "Unable to set audit pid, exiting");
713                 close_down();
714                 if (pidfile)
715                         unlink(pidfile);
716                 shutdown_dispatcher();
717                 tell_parent(FAILURE);
718                 return 1;
719         }
720
721         /* Depending on value of opt_startup (-s) set initial audit state */
722         loop = ev_default_loop (EVFLAG_NOENV);
723
724         ev_io_init (&netlink_watcher, netlink_handler, fd, EV_READ);
725         ev_io_start (loop, &netlink_watcher);
726
727         ev_signal_init (&sigterm_watcher, term_handler, SIGTERM);
728         ev_signal_start (loop, &sigterm_watcher);
729
730         ev_signal_init (&sighup_watcher, hup_handler, SIGHUP);
731         ev_signal_start (loop, &sighup_watcher);
732
733         ev_signal_init (&sigusr1_watcher, user1_handler, SIGUSR1);
734         ev_signal_start (loop, &sigusr1_watcher);
735
736         ev_signal_init (&sigusr2_watcher, user2_handler, SIGUSR2);
737         ev_signal_start (loop, &sigusr2_watcher);
738
739         ev_signal_init (&sigchld_watcher, child_handler, SIGCHLD);
740         ev_signal_start (loop, &sigchld_watcher);
741
742         if (auditd_tcp_listen_init (loop, &config)) {
743                 char emsg[DEFAULT_BUF_SZ];
744                 if (*subj)
745                         snprintf(emsg, sizeof(emsg),
746                         "auditd error halt, auid=%u pid=%d subj=%s res=failed",
747                                 audit_getloginuid(), getpid(), subj);
748                 else
749                         snprintf(emsg, sizeof(emsg),
750                                 "auditd error halt, auid=%u pid=%d res=failed",
751                                 audit_getloginuid(), getpid());
752                 stop = 1;
753                 send_audit_event(AUDIT_DAEMON_ABORT, emsg);
754                 tell_parent(FAILURE);
755         } else {
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)",
760                         VERSION,
761                         startup_states[opt_startup]);
762         }
763
764         /* Parent should be gone by now...   */
765         if (do_fork)
766                 close(init_pipe[1]);
767
768         // Init complete, start event loop
769         if (!stop)
770                 ev_loop (loop, 0);
771
772         auditd_tcp_listen_uninit (loop, &config);
773
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);
779
780         /* Write message to log that we are going down */
781         rc = audit_request_signal_info(fd);
782         if (rc > 0) {
783                 struct audit_reply trep;
784
785                 rc = get_reply(fd, &trep, rc);
786                 if (rc > 0) {
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);
795                 } 
796         } 
797         if (rc <= 0)
798                 send_audit_event(AUDIT_DAEMON_END, 
799                                 "auditd normal halt, sending auid=? "
800                                 "pid=? subj=? res=success");
801         free(rep);
802
803         // Tear down IO watchers Part 2
804         ev_io_stop (loop, &netlink_watcher);
805
806         // Give DAEMON_END event a little time to be sent in case
807         // of remote logging
808         usleep(10000); // 10 milliseconds
809         shutdown_dispatcher();
810
811         // Tear down IO watchers Part 3
812         ev_signal_stop (loop, &sigchld_watcher);
813
814         close_down();
815         free_config(&config);
816         ev_default_destroy();
817
818         return 0;
819 }
820
821 static void close_down(void)
822 {
823         struct sigaction sa;
824
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. */
827         sa.sa_flags = 0 ;
828         sigemptyset( &sa.sa_mask ) ;
829         sa.sa_handler = thread_killer;
830         sigaction( SIGALRM, &sa, NULL );
831         shutdown_events();
832 }
833
834
835 /*
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
840  */
841 static void clean_exit(void)
842 {
843         audit_msg(LOG_INFO, "The audit daemon is exiting.");
844         if (fd >= 0) {
845                 audit_set_pid(fd, 0, WAIT_NO);
846                 audit_close(fd);
847         }
848         if (pidfile)
849                 unlink(pidfile);
850         closelog();
851 }
852
853 /*
854  * This function is used to get the reply for term info.
855  * Returns 1 on success & -1 on failure.
856  */
857 static int get_reply(int fd, struct audit_reply *rep, int seq)
858 {
859         int rc, i;
860         int timeout = 30; /* tenths of seconds */
861
862         for (i = 0; i < timeout; i++) {
863                 struct timeval t;
864                 fd_set read_mask;
865
866                 t.tv_sec  = 0;
867                 t.tv_usec = 100000; /* .1 second */
868                 FD_ZERO(&read_mask);
869                 FD_SET(fd, &read_mask);
870                 do {
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);
875                 if (rc > 0) {
876                         /* Don't make decisions based on wrong packet */
877                         if (rep->nlh->nlmsg_seq != seq)
878                                 continue;
879
880                         /* If its not what we are expecting, keep looping */
881                         if (rep->type == AUDIT_SIGNAL_INFO)
882                                 return 1;
883
884                         /* If we get done or error, break out */
885                         if (rep->type == NLMSG_DONE || rep->type == NLMSG_ERROR)
886                                 break;
887                 }
888         }
889         return -1;
890 }
891
892 //get the subj of the daemon
893 static char *getsubj(char *subj)
894 {
895         pid_t pid = getpid();
896         char filename[48];
897         ssize_t num_read;
898         int fd;
899
900         snprintf(filename, sizeof(filename), "/proc/%u/attr/current", pid);
901         fd = open(filename, O_RDONLY);
902         if(fd == -1) {
903                 subj[0] = 0;
904                 return NULL;
905         }
906         do {
907                 num_read = read(fd, subj, SUBJ_LEN-1);
908         } while (num_read < 0 && errno == EINTR);
909         close(fd);
910         if(num_read <= 0) {
911                 subj[0] = 0;
912                 return NULL;
913         }
914         subj[num_read] = '\0';
915         return subj;
916 }
917