xref: /freebsd/sys/security/audit/audit.c (revision f3bb407b7c1b3faa88d0580541f01a8e6fb6cc68)
1 /*
2  * Copyright (c) 1999-2005 Apple Computer, Inc.
3  * Copyright (c) 2006 Robert N. M. Watson
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
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 Computer, 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
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR
22  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
27  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28  * POSSIBILITY OF SUCH DAMAGE.
29  *
30  * $FreeBSD$
31  */
32 
33 #include <sys/param.h>
34 #include <sys/condvar.h>
35 #include <sys/conf.h>
36 #include <sys/file.h>
37 #include <sys/filedesc.h>
38 #include <sys/fcntl.h>
39 #include <sys/ipc.h>
40 #include <sys/kernel.h>
41 #include <sys/kthread.h>
42 #include <sys/malloc.h>
43 #include <sys/mount.h>
44 #include <sys/namei.h>
45 #include <sys/priv.h>
46 #include <sys/proc.h>
47 #include <sys/queue.h>
48 #include <sys/socket.h>
49 #include <sys/socketvar.h>
50 #include <sys/protosw.h>
51 #include <sys/domain.h>
52 #include <sys/sysproto.h>
53 #include <sys/sysent.h>
54 #include <sys/systm.h>
55 #include <sys/ucred.h>
56 #include <sys/uio.h>
57 #include <sys/un.h>
58 #include <sys/unistd.h>
59 #include <sys/vnode.h>
60 
61 #include <bsm/audit.h>
62 #include <bsm/audit_internal.h>
63 #include <bsm/audit_kevents.h>
64 
65 #include <netinet/in.h>
66 #include <netinet/in_pcb.h>
67 
68 #include <security/audit/audit.h>
69 #include <security/audit/audit_private.h>
70 
71 #include <vm/uma.h>
72 
73 static uma_zone_t	audit_record_zone;
74 static MALLOC_DEFINE(M_AUDITPROC, "audit_proc", "Audit process storage");
75 MALLOC_DEFINE(M_AUDITDATA, "audit_data", "Audit data storage");
76 MALLOC_DEFINE(M_AUDITPATH, "audit_path", "Audit path storage");
77 MALLOC_DEFINE(M_AUDITTEXT, "audit_text", "Audit text storage");
78 
79 /*
80  * Audit control settings that are set/read by system calls and are
81  * hence non-static.
82  */
83 /*
84  * Define the audit control flags.
85  */
86 int			audit_enabled;
87 int			audit_suspended;
88 
89 /*
90  * Flags controlling behavior in low storage situations.  Should we panic if
91  * a write fails?  Should we fail stop if we're out of disk space?
92  */
93 int			audit_panic_on_write_fail;
94 int			audit_fail_stop;
95 int			audit_argv;
96 int			audit_arge;
97 
98 /*
99  * Are we currently "failing stop" due to out of disk space?
100  */
101 int			audit_in_failure;
102 
103 /*
104  * Global audit statistiscs.
105  */
106 struct audit_fstat	audit_fstat;
107 
108 /*
109  * Preselection mask for non-attributable events.
110  */
111 struct au_mask		audit_nae_mask;
112 
113 /*
114  * Mutex to protect global variables shared between various threads and
115  * processes.
116  */
117 struct mtx		audit_mtx;
118 
119 /*
120  * Queue of audit records ready for delivery to disk.  We insert new
121  * records at the tail, and remove records from the head.  Also,
122  * a count of the number of records used for checking queue depth.
123  * In addition, a counter of records that we have allocated but are
124  * not yet in the queue, which is needed to estimate the total
125  * size of the combined set of records outstanding in the system.
126  */
127 struct kaudit_queue	audit_q;
128 int			audit_q_len;
129 int			audit_pre_q_len;
130 
131 /*
132  * Audit queue control settings (minimum free, low/high water marks, etc.)
133  */
134 struct au_qctrl		audit_qctrl;
135 
136 /*
137  * Condition variable to signal to the worker that it has work to do:
138  * either new records are in the queue, or a log replacement is taking
139  * place.
140  */
141 struct cv		audit_worker_cv;
142 
143 /*
144  * Condition variable to flag when crossing the low watermark, meaning that
145  * threads blocked due to hitting the high watermark can wake up and continue
146  * to commit records.
147  */
148 struct cv		audit_watermark_cv;
149 
150 /*
151  * Condition variable for  auditing threads wait on when in fail-stop mode.
152  * Threads wait on this CV forever (and ever), never seeing the light of
153  * day again.
154  */
155 static struct cv	audit_fail_cv;
156 
157 /*
158  * Construct an audit record for the passed thread.
159  */
160 static int
161 audit_record_ctor(void *mem, int size, void *arg, int flags)
162 {
163 	struct kaudit_record *ar;
164 	struct thread *td;
165 
166 	KASSERT(sizeof(*ar) == size, ("audit_record_ctor: wrong size"));
167 
168 	td = arg;
169 	ar = mem;
170 	bzero(ar, sizeof(*ar));
171 	ar->k_ar.ar_magic = AUDIT_RECORD_MAGIC;
172 	nanotime(&ar->k_ar.ar_starttime);
173 
174 	/*
175 	 * Export the subject credential.
176 	 */
177 	cru2x(td->td_ucred, &ar->k_ar.ar_subj_cred);
178 	ar->k_ar.ar_subj_ruid = td->td_ucred->cr_ruid;
179 	ar->k_ar.ar_subj_rgid = td->td_ucred->cr_rgid;
180 	ar->k_ar.ar_subj_egid = td->td_ucred->cr_groups[0];
181 	PROC_LOCK(td->td_proc);
182 	ar->k_ar.ar_subj_auid = td->td_proc->p_au->ai_auid;
183 	ar->k_ar.ar_subj_asid = td->td_proc->p_au->ai_asid;
184 	ar->k_ar.ar_subj_pid = td->td_proc->p_pid;
185 	ar->k_ar.ar_subj_amask = td->td_proc->p_au->ai_mask;
186 	ar->k_ar.ar_subj_term = td->td_proc->p_au->ai_termid;
187 	bcopy(td->td_proc->p_comm, ar->k_ar.ar_subj_comm, MAXCOMLEN);
188 	PROC_UNLOCK(td->td_proc);
189 
190 	return (0);
191 }
192 
193 static void
194 audit_record_dtor(void *mem, int size, void *arg)
195 {
196 	struct kaudit_record *ar;
197 
198 	KASSERT(sizeof(*ar) == size, ("audit_record_dtor: wrong size"));
199 
200 	ar = mem;
201 	if (ar->k_ar.ar_arg_upath1 != NULL)
202 		free(ar->k_ar.ar_arg_upath1, M_AUDITPATH);
203 	if (ar->k_ar.ar_arg_upath2 != NULL)
204 		free(ar->k_ar.ar_arg_upath2, M_AUDITPATH);
205 	if (ar->k_ar.ar_arg_text != NULL)
206 		free(ar->k_ar.ar_arg_text, M_AUDITTEXT);
207 	if (ar->k_udata != NULL)
208 		free(ar->k_udata, M_AUDITDATA);
209 	if (ar->k_ar.ar_arg_argv != NULL)
210 		free(ar->k_ar.ar_arg_argv, M_AUDITTEXT);
211 	if (ar->k_ar.ar_arg_envv != NULL)
212 		free(ar->k_ar.ar_arg_envv, M_AUDITTEXT);
213 }
214 
215 /*
216  * Initialize the Audit subsystem: configuration state, work queue,
217  * synchronization primitives, worker thread, and trigger device node.  Also
218  * call into the BSM assembly code to initialize it.
219  */
220 static void
221 audit_init(void)
222 {
223 
224 	printf("Security auditing service present\n");
225 	audit_enabled = 0;
226 	audit_suspended = 0;
227 	audit_panic_on_write_fail = 0;
228 	audit_fail_stop = 0;
229 	audit_in_failure = 0;
230 	audit_argv = 0;
231 	audit_arge = 0;
232 
233 	audit_fstat.af_filesz = 0;	/* '0' means unset, unbounded */
234 	audit_fstat.af_currsz = 0;
235 	audit_nae_mask.am_success = AU_NULL;
236 	audit_nae_mask.am_failure = AU_NULL;
237 
238 	TAILQ_INIT(&audit_q);
239 	audit_q_len = 0;
240 	audit_pre_q_len = 0;
241 	audit_qctrl.aq_hiwater = AQ_HIWATER;
242 	audit_qctrl.aq_lowater = AQ_LOWATER;
243 	audit_qctrl.aq_bufsz = AQ_BUFSZ;
244 	audit_qctrl.aq_minfree = AU_FS_MINFREE;
245 
246 	mtx_init(&audit_mtx, "audit_mtx", NULL, MTX_DEF);
247 	cv_init(&audit_worker_cv, "audit_worker_cv");
248 	cv_init(&audit_watermark_cv, "audit_watermark_cv");
249 	cv_init(&audit_fail_cv, "audit_fail_cv");
250 
251 	audit_record_zone = uma_zcreate("audit_record",
252 	    sizeof(struct kaudit_record), audit_record_ctor,
253 	    audit_record_dtor, NULL, NULL, UMA_ALIGN_PTR, 0);
254 
255 	/* Initialize the BSM audit subsystem. */
256 	kau_init();
257 
258 	audit_trigger_init();
259 
260 	/* Register shutdown handler. */
261 	EVENTHANDLER_REGISTER(shutdown_pre_sync, audit_shutdown, NULL,
262 	    SHUTDOWN_PRI_FIRST);
263 
264 	/* Start audit worker thread. */
265 	audit_worker_init();
266 }
267 
268 SYSINIT(audit_init, SI_SUB_AUDIT, SI_ORDER_FIRST, audit_init, NULL)
269 
270 /*
271  * Drain the audit queue and close the log at shutdown.  Note that this can
272  * be called both from the system shutdown path and also from audit
273  * configuration syscalls, so 'arg' and 'howto' are ignored.
274  */
275 void
276 audit_shutdown(void *arg, int howto)
277 {
278 
279 	audit_rotate_vnode(NULL, NULL);
280 }
281 
282 /*
283  * Return the current thread's audit record, if any.
284  */
285 __inline__ struct kaudit_record *
286 currecord(void)
287 {
288 
289 	return (curthread->td_ar);
290 }
291 
292 /*
293  * XXXAUDIT: There are a number of races present in the code below due to
294  * release and re-grab of the mutex.  The code should be revised to become
295  * slightly less racy.
296  *
297  * XXXAUDIT: Shouldn't there be logic here to sleep waiting on available
298  * pre_q space, suspending the system call until there is room?
299  */
300 struct kaudit_record *
301 audit_new(int event, struct thread *td)
302 {
303 	struct kaudit_record *ar;
304 	int no_record;
305 
306 	mtx_lock(&audit_mtx);
307 	no_record = (audit_suspended || !audit_enabled);
308 	mtx_unlock(&audit_mtx);
309 	if (no_record)
310 		return (NULL);
311 
312 	/*
313 	 * Note: the number of outstanding uncommitted audit records is
314 	 * limited to the number of concurrent threads servicing system calls
315 	 * in the kernel.
316 	 */
317 	ar = uma_zalloc_arg(audit_record_zone, td, M_WAITOK);
318 	ar->k_ar.ar_event = event;
319 
320 	mtx_lock(&audit_mtx);
321 	audit_pre_q_len++;
322 	mtx_unlock(&audit_mtx);
323 
324 	return (ar);
325 }
326 
327 void
328 audit_free(struct kaudit_record *ar)
329 {
330 
331 	uma_zfree(audit_record_zone, ar);
332 }
333 
334 void
335 audit_commit(struct kaudit_record *ar, int error, int retval)
336 {
337 	au_event_t event;
338 	au_class_t class;
339 	au_id_t auid;
340 	int sorf;
341 	struct au_mask *aumask;
342 
343 	if (ar == NULL)
344 		return;
345 
346 	/*
347 	 * Decide whether to commit the audit record by checking the
348 	 * error value from the system call and using the appropriate
349 	 * audit mask.
350 	 *
351 	 * XXXAUDIT: Synchronize access to audit_nae_mask?
352 	 */
353 	if (ar->k_ar.ar_subj_auid == AU_DEFAUDITID)
354 		aumask = &audit_nae_mask;
355 	else
356 		aumask = &ar->k_ar.ar_subj_amask;
357 
358 	if (error)
359 		sorf = AU_PRS_FAILURE;
360 	else
361 		sorf = AU_PRS_SUCCESS;
362 
363 	switch(ar->k_ar.ar_event) {
364 
365 	case AUE_OPEN_RWTC:
366 		/* The open syscall always writes a AUE_OPEN_RWTC event; change
367 		 * it to the proper type of event based on the flags and the
368 		 * error value.
369 		 */
370 		ar->k_ar.ar_event = flags_and_error_to_openevent(
371 		    ar->k_ar.ar_arg_fflags, error);
372 		break;
373 
374 	case AUE_SYSCTL:
375 		ar->k_ar.ar_event = ctlname_to_sysctlevent(
376 		    ar->k_ar.ar_arg_ctlname, ar->k_ar.ar_valid_arg);
377 		break;
378 
379 	case AUE_AUDITON:
380 		/* Convert the auditon() command to an event */
381 		ar->k_ar.ar_event = auditon_command_event(ar->k_ar.ar_arg_cmd);
382 		break;
383 	}
384 
385 	auid = ar->k_ar.ar_subj_auid;
386 	event = ar->k_ar.ar_event;
387 	class = au_event_class(event);
388 
389 	ar->k_ar_commit |= AR_COMMIT_KERNEL;
390 	if (au_preselect(event, class, aumask, sorf) != 0)
391 		ar->k_ar_commit |= AR_PRESELECT_TRAIL;
392 	if (audit_pipe_preselect(auid, event, class, sorf,
393 	    ar->k_ar_commit & AR_PRESELECT_TRAIL) != 0)
394 		ar->k_ar_commit |= AR_PRESELECT_PIPE;
395 	if ((ar->k_ar_commit & (AR_PRESELECT_TRAIL | AR_PRESELECT_PIPE |
396 	    AR_PRESELECT_USER_TRAIL | AR_PRESELECT_USER_PIPE)) == 0) {
397 		mtx_lock(&audit_mtx);
398 		audit_pre_q_len--;
399 		mtx_unlock(&audit_mtx);
400 		audit_free(ar);
401 		return;
402 	}
403 
404 	ar->k_ar.ar_errno = error;
405 	ar->k_ar.ar_retval = retval;
406 
407 	/*
408 	 * We might want to do some system-wide post-filtering
409 	 * here at some point.
410 	 */
411 
412 	/*
413 	 * Timestamp system call end.
414 	 */
415 	nanotime(&ar->k_ar.ar_endtime);
416 
417 	mtx_lock(&audit_mtx);
418 
419 	/*
420 	 * Note: it could be that some records initiated while audit was
421 	 * enabled should still be committed?
422 	 */
423 	if (audit_suspended || !audit_enabled) {
424 		audit_pre_q_len--;
425 		mtx_unlock(&audit_mtx);
426 		audit_free(ar);
427 		return;
428 	}
429 
430 	/*
431 	 * Constrain the number of committed audit records based on
432 	 * the configurable parameter.
433 	 */
434 	while (audit_q_len >= audit_qctrl.aq_hiwater) {
435 		AUDIT_PRINTF(("audit_commit: sleeping to wait for "
436 		   "audit queue to drain below high water mark\n"));
437 		cv_wait(&audit_watermark_cv, &audit_mtx);
438 		AUDIT_PRINTF(("audit_commit: woke up waiting for "
439 		   "audit queue draining\n"));
440 	}
441 
442 	TAILQ_INSERT_TAIL(&audit_q, ar, k_q);
443 	audit_q_len++;
444 	audit_pre_q_len--;
445 	cv_signal(&audit_worker_cv);
446 	mtx_unlock(&audit_mtx);
447 }
448 
449 /*
450  * audit_syscall_enter() is called on entry to each system call.  It is
451  * responsible for deciding whether or not to audit the call (preselection),
452  * and if so, allocating a per-thread audit record.  audit_new() will fill in
453  * basic thread/credential properties.
454  */
455 void
456 audit_syscall_enter(unsigned short code, struct thread *td)
457 {
458 	struct au_mask *aumask;
459 	au_class_t class;
460 	au_event_t event;
461 	au_id_t auid;
462 
463 	KASSERT(td->td_ar == NULL, ("audit_syscall_enter: td->td_ar != NULL"));
464 
465 	/*
466 	 * In FreeBSD, each ABI has its own system call table, and hence
467 	 * mapping of system call codes to audit events.  Convert the code to
468 	 * an audit event identifier using the process system call table
469 	 * reference.  In Darwin, there's only one, so we use the global
470 	 * symbol for the system call table.  No audit record is generated
471 	 * for bad system calls, as no operation has been performed.
472 	 */
473 	if (code >= td->td_proc->p_sysent->sv_size)
474 		return;
475 
476 	event = td->td_proc->p_sysent->sv_table[code].sy_auevent;
477 	if (event == AUE_NULL)
478 		return;
479 
480 	/*
481 	 * Check which audit mask to use; either the kernel non-attributable
482 	 * event mask or the process audit mask.
483 	 */
484 	auid = td->td_proc->p_au->ai_auid;
485 	if (auid == AU_DEFAUDITID)
486 		aumask = &audit_nae_mask;
487 	else
488 		aumask = &td->td_proc->p_au->ai_mask;
489 
490 	/*
491 	 * Allocate an audit record, if preselection allows it, and store
492 	 * in the thread for later use.
493 	 */
494 	class = au_event_class(event);
495 	if (au_preselect(event, class, aumask, AU_PRS_BOTH)) {
496 		/*
497 		 * If we're out of space and need to suspend unprivileged
498 		 * processes, do that here rather than trying to allocate
499 		 * another audit record.
500 		 *
501 		 * Note: we might wish to be able to continue here in the
502 		 * future, if the system recovers.  That should be possible
503 		 * by means of checking the condition in a loop around
504 		 * cv_wait().  It might be desirable to reevaluate whether an
505 		 * audit record is still required for this event by
506 		 * re-calling au_preselect().
507 		 */
508 		if (audit_in_failure &&
509 		    priv_check(td, PRIV_AUDIT_FAILSTOP) != 0) {
510 			cv_wait(&audit_fail_cv, &audit_mtx);
511 			panic("audit_failing_stop: thread continued");
512 		}
513 		td->td_ar = audit_new(event, td);
514 	} else if (audit_pipe_preselect(auid, event, class, AU_PRS_BOTH, 0))
515 		td->td_ar = audit_new(event, td);
516 	else
517 		td->td_ar = NULL;
518 }
519 
520 /*
521  * audit_syscall_exit() is called from the return of every system call, or in
522  * the event of exit1(), during the execution of exit1().  It is responsible
523  * for committing the audit record, if any, along with return condition.
524  */
525 void
526 audit_syscall_exit(int error, struct thread *td)
527 {
528 	int retval;
529 
530 	/*
531 	 * Commit the audit record as desired; once we pass the record
532 	 * into audit_commit(), the memory is owned by the audit
533 	 * subsystem.
534 	 * The return value from the system call is stored on the user
535 	 * thread. If there was an error, the return value is set to -1,
536 	 * imitating the behavior of the cerror routine.
537 	 */
538 	if (error)
539 		retval = -1;
540 	else
541 		retval = td->td_retval[0];
542 
543 	audit_commit(td->td_ar, error, retval);
544 	if (td->td_ar != NULL)
545 		AUDIT_PRINTF(("audit record committed by pid %d\n",
546 			td->td_proc->p_pid));
547 	td->td_ar = NULL;
548 
549 }
550 
551 /*
552  * Allocate storage for a new process (init, or otherwise).
553  */
554 void
555 audit_proc_alloc(struct proc *p)
556 {
557 
558 	KASSERT(p->p_au == NULL, ("audit_proc_alloc: p->p_au != NULL (%d)",
559 	    p->p_pid));
560 	p->p_au = malloc(sizeof(*(p->p_au)), M_AUDITPROC, M_WAITOK);
561 }
562 
563 /*
564  * Allocate storage for a new thread.
565  */
566 void
567 audit_thread_alloc(struct thread *td)
568 {
569 
570 	td->td_ar = NULL;
571 }
572 
573 /*
574  * Thread destruction.
575  */
576 void
577 audit_thread_free(struct thread *td)
578 {
579 
580 	KASSERT(td->td_ar == NULL, ("audit_thread_free: td_ar != NULL"));
581 }
582 
583 /*
584  * Initialize audit information for the first kernel process (proc 0) and for
585  * the first user process (init).
586  *
587  * XXX It is not clear what the initial values should be for audit ID,
588  * session ID, etc.
589  */
590 void
591 audit_proc_kproc0(struct proc *p)
592 {
593 
594 	KASSERT(p->p_au != NULL, ("audit_proc_kproc0: p->p_au == NULL (%d)",
595 	    p->p_pid));
596 	bzero(p->p_au, sizeof(*(p)->p_au));
597 }
598 
599 void
600 audit_proc_init(struct proc *p)
601 {
602 
603 	KASSERT(p->p_au != NULL, ("audit_proc_init: p->p_au == NULL (%d)",
604 	    p->p_pid));
605 	bzero(p->p_au, sizeof(*(p)->p_au));
606 	p->p_au->ai_auid = AU_DEFAUDITID;
607 }
608 
609 /*
610  * Copy the audit info from the parent process to the child process when
611  * a fork takes place.
612  */
613 void
614 audit_proc_fork(struct proc *parent, struct proc *child)
615 {
616 
617 	PROC_LOCK_ASSERT(parent, MA_OWNED);
618 	PROC_LOCK_ASSERT(child, MA_OWNED);
619 	KASSERT(parent->p_au != NULL,
620 	    ("audit_proc_fork: parent->p_au == NULL (%d)", parent->p_pid));
621 	KASSERT(child->p_au != NULL,
622 	    ("audit_proc_fork: child->p_au == NULL (%d)", child->p_pid));
623 	bcopy(parent->p_au, child->p_au, sizeof(*child->p_au));
624 }
625 
626 /*
627  * Free the auditing structure for the process.
628  */
629 void
630 audit_proc_free(struct proc *p)
631 {
632 
633 	KASSERT(p->p_au != NULL, ("p->p_au == NULL (%d)", p->p_pid));
634 	free(p->p_au, M_AUDITPROC);
635 	p->p_au = NULL;
636 }
637