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