xref: /freebsd/sys/security/audit/audit.c (revision fdafd315)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1999-2005 Apple Inc.
5  * Copyright (c) 2006-2007, 2016-2018 Robert N. M. Watson
6  * All rights reserved.
7  *
8  * Portions of this software were developed by BAE Systems, the University of
9  * Cambridge Computer Laboratory, and Memorial University under DARPA/AFRL
10  * contract FA8650-15-C-7558 ("CADETS"), as part of the DARPA Transparent
11  * Computing (TC) research program.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1.  Redistributions of source code must retain the above copyright
17  *     notice, this list of conditions and the following disclaimer.
18  * 2.  Redistributions in binary form must reproduce the above copyright
19  *     notice, this list of conditions and the following disclaimer in the
20  *     documentation and/or other materials provided with the distribution.
21  * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
22  *     its contributors may be used to endorse or promote products derived
23  *     from this software without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR
29  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
33  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
34  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35  * POSSIBILITY OF SUCH DAMAGE.
36  */
37 
38 #include <sys/param.h>
39 #include <sys/condvar.h>
40 #include <sys/conf.h>
41 #include <sys/eventhandler.h>
42 #include <sys/file.h>
43 #include <sys/filedesc.h>
44 #include <sys/fcntl.h>
45 #include <sys/ipc.h>
46 #include <sys/jail.h>
47 #include <sys/kernel.h>
48 #include <sys/kthread.h>
49 #include <sys/malloc.h>
50 #include <sys/mount.h>
51 #include <sys/namei.h>
52 #include <sys/priv.h>
53 #include <sys/proc.h>
54 #include <sys/queue.h>
55 #include <sys/socket.h>
56 #include <sys/socketvar.h>
57 #include <sys/protosw.h>
58 #include <sys/domain.h>
59 #include <sys/sysctl.h>
60 #include <sys/sysproto.h>
61 #include <sys/sysent.h>
62 #include <sys/systm.h>
63 #include <sys/ucred.h>
64 #include <sys/uio.h>
65 #include <sys/un.h>
66 #include <sys/unistd.h>
67 #include <sys/vnode.h>
68 
69 #include <bsm/audit.h>
70 #include <bsm/audit_internal.h>
71 #include <bsm/audit_kevents.h>
72 
73 #include <netinet/in.h>
74 #include <netinet/in_pcb.h>
75 
76 #include <security/audit/audit.h>
77 #include <security/audit/audit_private.h>
78 
79 #include <vm/uma.h>
80 
81 FEATURE(audit, "BSM audit support");
82 
83 static uma_zone_t	audit_record_zone;
84 static MALLOC_DEFINE(M_AUDITCRED, "audit_cred", "Audit cred storage");
85 MALLOC_DEFINE(M_AUDITDATA, "audit_data", "Audit data storage");
86 MALLOC_DEFINE(M_AUDITPATH, "audit_path", "Audit path storage");
87 MALLOC_DEFINE(M_AUDITTEXT, "audit_text", "Audit text storage");
88 MALLOC_DEFINE(M_AUDITGIDSET, "audit_gidset", "Audit GID set storage");
89 
90 static SYSCTL_NODE(_security, OID_AUTO, audit, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
91     "TrustedBSD audit controls");
92 
93 /*
94  * Audit control settings that are set/read by system calls and are hence
95  * non-static.
96  *
97  * Define the audit control flags.
98  */
99 int			audit_trail_enabled;
100 int			audit_trail_suspended;
101 #ifdef KDTRACE_HOOKS
102 u_int			audit_dtrace_enabled;
103 #endif
104 bool __read_frequently	audit_syscalls_enabled;
105 
106 /*
107  * Flags controlling behavior in low storage situations.  Should we panic if
108  * a write fails?  Should we fail stop if we're out of disk space?
109  */
110 int			audit_panic_on_write_fail;
111 int			audit_fail_stop;
112 int			audit_argv;
113 int			audit_arge;
114 
115 /*
116  * Are we currently "failing stop" due to out of disk space?
117  */
118 int			audit_in_failure;
119 
120 /*
121  * Global audit statistics.
122  */
123 struct audit_fstat	audit_fstat;
124 
125 /*
126  * Preselection mask for non-attributable events.
127  */
128 struct au_mask		audit_nae_mask;
129 
130 /*
131  * Mutex to protect global variables shared between various threads and
132  * processes.
133  */
134 struct mtx		audit_mtx;
135 
136 /*
137  * Queue of audit records ready for delivery to disk.  We insert new records
138  * at the tail, and remove records from the head.  Also, a count of the
139  * number of records used for checking queue depth.  In addition, a counter
140  * of records that we have allocated but are not yet in the queue, which is
141  * needed to estimate the total size of the combined set of records
142  * outstanding in the system.
143  */
144 struct kaudit_queue	audit_q;
145 int			audit_q_len;
146 int			audit_pre_q_len;
147 
148 /*
149  * Audit queue control settings (minimum free, low/high water marks, etc.)
150  */
151 struct au_qctrl		audit_qctrl;
152 
153 /*
154  * Condition variable to signal to the worker that it has work to do: either
155  * new records are in the queue, or a log replacement is taking place.
156  */
157 struct cv		audit_worker_cv;
158 
159 /*
160  * Condition variable to flag when crossing the low watermark, meaning that
161  * threads blocked due to hitting the high watermark can wake up and continue
162  * to commit records.
163  */
164 struct cv		audit_watermark_cv;
165 
166 /*
167  * Condition variable for  auditing threads wait on when in fail-stop mode.
168  * Threads wait on this CV forever (and ever), never seeing the light of day
169  * again.
170  */
171 static struct cv	audit_fail_cv;
172 
173 /*
174  * Optional DTrace audit provider support: function pointers for preselection
175  * and commit events.
176  */
177 #ifdef KDTRACE_HOOKS
178 void	*(*dtaudit_hook_preselect)(au_id_t auid, au_event_t event,
179 	    au_class_t class);
180 int	(*dtaudit_hook_commit)(struct kaudit_record *kar, au_id_t auid,
181 	    au_event_t event, au_class_t class, int sorf);
182 void	(*dtaudit_hook_bsm)(struct kaudit_record *kar, au_id_t auid,
183 	    au_event_t event, au_class_t class, int sorf,
184 	    void *bsm_data, size_t bsm_lenlen);
185 #endif
186 
187 /*
188  * Kernel audit information.  This will store the current audit address
189  * or host information that the kernel will use when it's generating
190  * audit records.  This data is modified by the A_GET{SET}KAUDIT auditon(2)
191  * command.
192  */
193 static struct auditinfo_addr	audit_kinfo;
194 static struct rwlock		audit_kinfo_lock;
195 
196 #define	KINFO_LOCK_INIT()	rw_init(&audit_kinfo_lock, \
197 				    "audit_kinfo_lock")
198 #define	KINFO_RLOCK()		rw_rlock(&audit_kinfo_lock)
199 #define	KINFO_WLOCK()		rw_wlock(&audit_kinfo_lock)
200 #define	KINFO_RUNLOCK()		rw_runlock(&audit_kinfo_lock)
201 #define	KINFO_WUNLOCK()		rw_wunlock(&audit_kinfo_lock)
202 
203 /*
204  * Check various policies to see if we should enable system-call audit hooks.
205  * Note that despite the mutex being held, we want to assign a value exactly
206  * once, as checks of the flag are performed lock-free for performance
207  * reasons.  The mutex is used to get a consistent snapshot of policy state --
208  * e.g., safely accessing the two audit_trail flags.
209  */
210 void
audit_syscalls_enabled_update(void)211 audit_syscalls_enabled_update(void)
212 {
213 
214 	mtx_lock(&audit_mtx);
215 #ifdef KDTRACE_HOOKS
216 	if (audit_dtrace_enabled)
217 		audit_syscalls_enabled = true;
218 	else {
219 #endif
220 		if (audit_trail_enabled && !audit_trail_suspended)
221 			audit_syscalls_enabled = true;
222 		else
223 			audit_syscalls_enabled = false;
224 #ifdef KDTRACE_HOOKS
225 	}
226 #endif
227 	mtx_unlock(&audit_mtx);
228 }
229 
230 void
audit_set_kinfo(struct auditinfo_addr * ak)231 audit_set_kinfo(struct auditinfo_addr *ak)
232 {
233 
234 	KASSERT(ak->ai_termid.at_type == AU_IPv4 ||
235 	    ak->ai_termid.at_type == AU_IPv6,
236 	    ("audit_set_kinfo: invalid address type"));
237 
238 	KINFO_WLOCK();
239 	audit_kinfo = *ak;
240 	KINFO_WUNLOCK();
241 }
242 
243 void
audit_get_kinfo(struct auditinfo_addr * ak)244 audit_get_kinfo(struct auditinfo_addr *ak)
245 {
246 
247 	KASSERT(audit_kinfo.ai_termid.at_type == AU_IPv4 ||
248 	    audit_kinfo.ai_termid.at_type == AU_IPv6,
249 	    ("audit_set_kinfo: invalid address type"));
250 
251 	KINFO_RLOCK();
252 	*ak = audit_kinfo;
253 	KINFO_RUNLOCK();
254 }
255 
256 /*
257  * Construct an audit record for the passed thread.
258  */
259 static int
audit_record_ctor(void * mem,int size,void * arg,int flags)260 audit_record_ctor(void *mem, int size, void *arg, int flags)
261 {
262 	struct kaudit_record *ar;
263 	struct thread *td;
264 	struct ucred *cred;
265 	struct prison *pr;
266 
267 	KASSERT(sizeof(*ar) == size, ("audit_record_ctor: wrong size"));
268 
269 	td = arg;
270 	ar = mem;
271 	bzero(ar, sizeof(*ar));
272 	ar->k_ar.ar_magic = AUDIT_RECORD_MAGIC;
273 	nanotime(&ar->k_ar.ar_starttime);
274 
275 	/*
276 	 * Export the subject credential.
277 	 */
278 	cred = td->td_ucred;
279 	cru2x(cred, &ar->k_ar.ar_subj_cred);
280 	ar->k_ar.ar_subj_ruid = cred->cr_ruid;
281 	ar->k_ar.ar_subj_rgid = cred->cr_rgid;
282 	ar->k_ar.ar_subj_egid = cred->cr_groups[0];
283 	ar->k_ar.ar_subj_auid = cred->cr_audit.ai_auid;
284 	ar->k_ar.ar_subj_asid = cred->cr_audit.ai_asid;
285 	ar->k_ar.ar_subj_pid = td->td_proc->p_pid;
286 	ar->k_ar.ar_subj_amask = cred->cr_audit.ai_mask;
287 	ar->k_ar.ar_subj_term_addr = cred->cr_audit.ai_termid;
288 	/*
289 	 * If this process is jailed, make sure we capture the name of the
290 	 * jail so we can use it to generate a zonename token when we covert
291 	 * this record to BSM.
292 	 */
293 	if (jailed(cred)) {
294 		pr = cred->cr_prison;
295 		(void) strlcpy(ar->k_ar.ar_jailname, pr->pr_name,
296 		    sizeof(ar->k_ar.ar_jailname));
297 	} else
298 		ar->k_ar.ar_jailname[0] = '\0';
299 	return (0);
300 }
301 
302 static void
audit_record_dtor(void * mem,int size,void * arg)303 audit_record_dtor(void *mem, int size, void *arg)
304 {
305 	struct kaudit_record *ar;
306 
307 	KASSERT(sizeof(*ar) == size, ("audit_record_dtor: wrong size"));
308 
309 	ar = mem;
310 	if (ar->k_ar.ar_arg_upath1 != NULL)
311 		free(ar->k_ar.ar_arg_upath1, M_AUDITPATH);
312 	if (ar->k_ar.ar_arg_upath2 != NULL)
313 		free(ar->k_ar.ar_arg_upath2, M_AUDITPATH);
314 	if (ar->k_ar.ar_arg_text != NULL)
315 		free(ar->k_ar.ar_arg_text, M_AUDITTEXT);
316 	if (ar->k_udata != NULL)
317 		free(ar->k_udata, M_AUDITDATA);
318 	if (ar->k_ar.ar_arg_argv != NULL)
319 		free(ar->k_ar.ar_arg_argv, M_AUDITTEXT);
320 	if (ar->k_ar.ar_arg_envv != NULL)
321 		free(ar->k_ar.ar_arg_envv, M_AUDITTEXT);
322 	if (ar->k_ar.ar_arg_groups.gidset != NULL)
323 		free(ar->k_ar.ar_arg_groups.gidset, M_AUDITGIDSET);
324 }
325 
326 /*
327  * Initialize the Audit subsystem: configuration state, work queue,
328  * synchronization primitives, worker thread, and trigger device node.  Also
329  * call into the BSM assembly code to initialize it.
330  */
331 static void
audit_init(void)332 audit_init(void)
333 {
334 
335 	audit_trail_enabled = 0;
336 	audit_trail_suspended = 0;
337 	audit_syscalls_enabled = false;
338 	audit_panic_on_write_fail = 0;
339 	audit_fail_stop = 0;
340 	audit_in_failure = 0;
341 	audit_argv = 0;
342 	audit_arge = 0;
343 
344 	audit_fstat.af_filesz = 0;	/* '0' means unset, unbounded. */
345 	audit_fstat.af_currsz = 0;
346 	audit_nae_mask.am_success = 0;
347 	audit_nae_mask.am_failure = 0;
348 
349 	TAILQ_INIT(&audit_q);
350 	audit_q_len = 0;
351 	audit_pre_q_len = 0;
352 	audit_qctrl.aq_hiwater = AQ_HIWATER;
353 	audit_qctrl.aq_lowater = AQ_LOWATER;
354 	audit_qctrl.aq_bufsz = AQ_BUFSZ;
355 	audit_qctrl.aq_minfree = AU_FS_MINFREE;
356 
357 	audit_kinfo.ai_termid.at_type = AU_IPv4;
358 	audit_kinfo.ai_termid.at_addr[0] = INADDR_ANY;
359 
360 	mtx_init(&audit_mtx, "audit_mtx", NULL, MTX_DEF);
361 	KINFO_LOCK_INIT();
362 	cv_init(&audit_worker_cv, "audit_worker_cv");
363 	cv_init(&audit_watermark_cv, "audit_watermark_cv");
364 	cv_init(&audit_fail_cv, "audit_fail_cv");
365 
366 	audit_record_zone = uma_zcreate("audit_record",
367 	    sizeof(struct kaudit_record), audit_record_ctor,
368 	    audit_record_dtor, NULL, NULL, UMA_ALIGN_PTR, 0);
369 
370 	/* First initialisation of audit_syscalls_enabled. */
371 	audit_syscalls_enabled_update();
372 
373 	/* Initialize the BSM audit subsystem. */
374 	kau_init();
375 
376 	audit_trigger_init();
377 
378 	/* Register shutdown handler. */
379 	EVENTHANDLER_REGISTER(shutdown_pre_sync, audit_shutdown, NULL,
380 	    SHUTDOWN_PRI_FIRST);
381 
382 	/* Start audit worker thread. */
383 	audit_worker_init();
384 }
385 
386 SYSINIT(audit_init, SI_SUB_AUDIT, SI_ORDER_FIRST, audit_init, NULL);
387 
388 /*
389  * Drain the audit queue and close the log at shutdown.  Note that this can
390  * be called both from the system shutdown path and also from audit
391  * configuration syscalls, so 'arg' and 'howto' are ignored.
392  *
393  * XXXRW: In FreeBSD 7.x and 8.x, this fails to wait for the record queue to
394  * drain before returning, which could lead to lost records on shutdown.
395  */
396 void
audit_shutdown(void * arg,int howto)397 audit_shutdown(void *arg, int howto)
398 {
399 
400 	audit_rotate_vnode(NULL, NULL);
401 }
402 
403 /*
404  * Return the current thread's audit record, if any.
405  */
406 struct kaudit_record *
currecord(void)407 currecord(void)
408 {
409 
410 	return (curthread->td_ar);
411 }
412 
413 /*
414  * XXXAUDIT: Shouldn't there be logic here to sleep waiting on available
415  * pre_q space, suspending the system call until there is room?
416  */
417 struct kaudit_record *
audit_new(int event,struct thread * td)418 audit_new(int event, struct thread *td)
419 {
420 	struct kaudit_record *ar;
421 
422 	/*
423 	 * Note: the number of outstanding uncommitted audit records is
424 	 * limited to the number of concurrent threads servicing system calls
425 	 * in the kernel.
426 	 */
427 	ar = uma_zalloc_arg(audit_record_zone, td, M_WAITOK);
428 	ar->k_ar.ar_event = event;
429 
430 	mtx_lock(&audit_mtx);
431 	audit_pre_q_len++;
432 	mtx_unlock(&audit_mtx);
433 
434 	return (ar);
435 }
436 
437 void
audit_free(struct kaudit_record * ar)438 audit_free(struct kaudit_record *ar)
439 {
440 
441 	uma_zfree(audit_record_zone, ar);
442 }
443 
444 void
audit_commit(struct kaudit_record * ar,int error,int retval)445 audit_commit(struct kaudit_record *ar, int error, int retval)
446 {
447 	au_event_t event;
448 	au_class_t class;
449 	au_id_t auid;
450 	int sorf;
451 	struct au_mask *aumask;
452 
453 	if (ar == NULL)
454 		return;
455 
456 	ar->k_ar.ar_errno = error;
457 	ar->k_ar.ar_retval = retval;
458 	nanotime(&ar->k_ar.ar_endtime);
459 
460 	/*
461 	 * Decide whether to commit the audit record by checking the error
462 	 * value from the system call and using the appropriate audit mask.
463 	 */
464 	if (ar->k_ar.ar_subj_auid == AU_DEFAUDITID)
465 		aumask = &audit_nae_mask;
466 	else
467 		aumask = &ar->k_ar.ar_subj_amask;
468 
469 	if (error)
470 		sorf = AU_PRS_FAILURE;
471 	else
472 		sorf = AU_PRS_SUCCESS;
473 
474 	/*
475 	 * syscalls.master sometimes contains a prototype event number, which
476 	 * we will transform into a more specific event number now that we
477 	 * have more complete information gathered during the system call.
478 	 */
479 	switch(ar->k_ar.ar_event) {
480 	case AUE_OPEN_RWTC:
481 		ar->k_ar.ar_event = audit_flags_and_error_to_openevent(
482 		    ar->k_ar.ar_arg_fflags, error);
483 		break;
484 
485 	case AUE_OPENAT_RWTC:
486 		ar->k_ar.ar_event = audit_flags_and_error_to_openatevent(
487 		    ar->k_ar.ar_arg_fflags, error);
488 		break;
489 
490 	case AUE_SYSCTL:
491 		ar->k_ar.ar_event = audit_ctlname_to_sysctlevent(
492 		    ar->k_ar.ar_arg_ctlname, ar->k_ar.ar_valid_arg);
493 		break;
494 
495 	case AUE_AUDITON:
496 		/* Convert the auditon() command to an event. */
497 		ar->k_ar.ar_event = auditon_command_event(ar->k_ar.ar_arg_cmd);
498 		break;
499 
500 	case AUE_MSGSYS:
501 		if (ARG_IS_VALID(ar, ARG_SVIPC_WHICH))
502 			ar->k_ar.ar_event =
503 			    audit_msgsys_to_event(ar->k_ar.ar_arg_svipc_which);
504 		break;
505 
506 	case AUE_SEMSYS:
507 		if (ARG_IS_VALID(ar, ARG_SVIPC_WHICH))
508 			ar->k_ar.ar_event =
509 			    audit_semsys_to_event(ar->k_ar.ar_arg_svipc_which);
510 		break;
511 
512 	case AUE_SHMSYS:
513 		if (ARG_IS_VALID(ar, ARG_SVIPC_WHICH))
514 			ar->k_ar.ar_event =
515 			    audit_shmsys_to_event(ar->k_ar.ar_arg_svipc_which);
516 		break;
517 	}
518 
519 	auid = ar->k_ar.ar_subj_auid;
520 	event = ar->k_ar.ar_event;
521 	class = au_event_class(event);
522 
523 	ar->k_ar_commit |= AR_COMMIT_KERNEL;
524 	if (au_preselect(event, class, aumask, sorf) != 0)
525 		ar->k_ar_commit |= AR_PRESELECT_TRAIL;
526 	if (audit_pipe_preselect(auid, event, class, sorf,
527 	    ar->k_ar_commit & AR_PRESELECT_TRAIL) != 0)
528 		ar->k_ar_commit |= AR_PRESELECT_PIPE;
529 #ifdef KDTRACE_HOOKS
530 	/*
531 	 * Expose the audit record to DTrace, both to allow the "commit" probe
532 	 * to fire if it's desirable, and also to allow a decision to be made
533 	 * about later firing with BSM in the audit worker.
534 	 */
535 	if (dtaudit_hook_commit != NULL) {
536 		if (dtaudit_hook_commit(ar, auid, event, class, sorf) != 0)
537 			ar->k_ar_commit |= AR_PRESELECT_DTRACE;
538 	}
539 #endif
540 
541 	if ((ar->k_ar_commit & (AR_PRESELECT_TRAIL | AR_PRESELECT_PIPE |
542 	    AR_PRESELECT_USER_TRAIL | AR_PRESELECT_USER_PIPE |
543 	    AR_PRESELECT_DTRACE)) == 0) {
544 		mtx_lock(&audit_mtx);
545 		audit_pre_q_len--;
546 		mtx_unlock(&audit_mtx);
547 		audit_free(ar);
548 		return;
549 	}
550 
551 	/*
552 	 * Note: it could be that some records initiated while audit was
553 	 * enabled should still be committed?
554 	 *
555 	 * NB: The check here is not for audit_syscalls because any
556 	 * DTrace-related obligations have been fulfilled above -- we're just
557 	 * down to the trail and pipes now.
558 	 */
559 	mtx_lock(&audit_mtx);
560 	if (audit_trail_suspended || !audit_trail_enabled) {
561 		audit_pre_q_len--;
562 		mtx_unlock(&audit_mtx);
563 		audit_free(ar);
564 		return;
565 	}
566 
567 	/*
568 	 * Constrain the number of committed audit records based on the
569 	 * configurable parameter.
570 	 */
571 	while (audit_q_len >= audit_qctrl.aq_hiwater)
572 		cv_wait(&audit_watermark_cv, &audit_mtx);
573 
574 	TAILQ_INSERT_TAIL(&audit_q, ar, k_q);
575 	audit_q_len++;
576 	audit_pre_q_len--;
577 	cv_signal(&audit_worker_cv);
578 	mtx_unlock(&audit_mtx);
579 }
580 
581 /*
582  * audit_syscall_enter() is called on entry to each system call.  It is
583  * responsible for deciding whether or not to audit the call (preselection),
584  * and if so, allocating a per-thread audit record.  audit_new() will fill in
585  * basic thread/credential properties.
586  *
587  * This function will be entered only if audit_syscalls_enabled was set in the
588  * macro wrapper for this function.  It could be cleared by the time this
589  * function runs, but that is an acceptable race.
590  */
591 void
audit_syscall_enter(unsigned short code,struct thread * td)592 audit_syscall_enter(unsigned short code, struct thread *td)
593 {
594 	struct au_mask *aumask;
595 #ifdef KDTRACE_HOOKS
596 	void *dtaudit_state;
597 #endif
598 	au_class_t class;
599 	au_event_t event;
600 	au_id_t auid;
601 	int record_needed;
602 
603 	KASSERT(td->td_ar == NULL, ("audit_syscall_enter: td->td_ar != NULL"));
604 	KASSERT((td->td_pflags & TDP_AUDITREC) == 0,
605 	    ("audit_syscall_enter: TDP_AUDITREC set"));
606 
607 	/*
608 	 * In FreeBSD, each ABI has its own system call table, and hence
609 	 * mapping of system call codes to audit events.  Convert the code to
610 	 * an audit event identifier using the process system call table
611 	 * reference.  In Darwin, there's only one, so we use the global
612 	 * symbol for the system call table.  No audit record is generated
613 	 * for bad system calls, as no operation has been performed.
614 	 */
615 	if (code >= td->td_proc->p_sysent->sv_size)
616 		return;
617 
618 	event = td->td_proc->p_sysent->sv_table[code].sy_auevent;
619 	if (event == AUE_NULL)
620 		return;
621 
622 	/*
623 	 * Check which audit mask to use; either the kernel non-attributable
624 	 * event mask or the process audit mask.
625 	 */
626 	auid = td->td_ucred->cr_audit.ai_auid;
627 	if (auid == AU_DEFAUDITID)
628 		aumask = &audit_nae_mask;
629 	else
630 		aumask = &td->td_ucred->cr_audit.ai_mask;
631 
632 	/*
633 	 * Determine whether trail or pipe preselection would like an audit
634 	 * record allocated for this system call.
635 	 */
636 	class = au_event_class(event);
637 	if (au_preselect(event, class, aumask, AU_PRS_BOTH)) {
638 		/*
639 		 * If we're out of space and need to suspend unprivileged
640 		 * processes, do that here rather than trying to allocate
641 		 * another audit record.
642 		 *
643 		 * Note: we might wish to be able to continue here in the
644 		 * future, if the system recovers.  That should be possible
645 		 * by means of checking the condition in a loop around
646 		 * cv_wait().  It might be desirable to reevaluate whether an
647 		 * audit record is still required for this event by
648 		 * re-calling au_preselect().
649 		 */
650 		if (audit_in_failure &&
651 		    priv_check(td, PRIV_AUDIT_FAILSTOP) != 0) {
652 			cv_wait(&audit_fail_cv, &audit_mtx);
653 			panic("audit_failing_stop: thread continued");
654 		}
655 		record_needed = 1;
656 	} else if (audit_pipe_preselect(auid, event, class, AU_PRS_BOTH, 0)) {
657 		record_needed = 1;
658 	} else {
659 		record_needed = 0;
660 	}
661 
662 	/*
663 	 * After audit trails and pipes have made their policy choices, DTrace
664 	 * may request that records be generated as well.  This is a slightly
665 	 * complex affair, as the DTrace audit provider needs the audit
666 	 * framework to maintain some state on the audit record, which has not
667 	 * been allocated at the point where the decision has to be made.
668 	 * This hook must run even if we are not changing the decision, as
669 	 * DTrace may want to stick event state onto a record we were going to
670 	 * produce due to the trail or pipes.  The event state returned by the
671 	 * DTrace provider must be safe without locks held between here and
672 	 * below -- i.e., dtaudit_state must must refer to stable memory.
673 	 */
674 #ifdef KDTRACE_HOOKS
675 	dtaudit_state = NULL;
676         if (dtaudit_hook_preselect != NULL) {
677 		dtaudit_state = dtaudit_hook_preselect(auid, event, class);
678 		if (dtaudit_state != NULL)
679 			record_needed = 1;
680 	}
681 #endif
682 
683 	/*
684 	 * If a record is required, allocate it and attach it to the thread
685 	 * for use throughout the system call.  Also attach DTrace state if
686 	 * required.
687 	 *
688 	 * XXXRW: If we decide to reference count the evname_elem underlying
689 	 * dtaudit_state, we will need to free here if no record is allocated
690 	 * or allocatable.
691 	 */
692 	if (record_needed) {
693 		td->td_ar = audit_new(event, td);
694 		if (td->td_ar != NULL) {
695 			td->td_pflags |= TDP_AUDITREC;
696 #ifdef KDTRACE_HOOKS
697 			td->td_ar->k_dtaudit_state = dtaudit_state;
698 #endif
699 		}
700 	} else
701 		td->td_ar = NULL;
702 }
703 
704 /*
705  * audit_syscall_exit() is called from the return of every system call, or in
706  * the event of exit1(), during the execution of exit1().  It is responsible
707  * for committing the audit record, if any, along with return condition.
708  */
709 void
audit_syscall_exit(int error,struct thread * td)710 audit_syscall_exit(int error, struct thread *td)
711 {
712 	int retval;
713 
714 	/*
715 	 * Commit the audit record as desired; once we pass the record into
716 	 * audit_commit(), the memory is owned by the audit subsystem.  The
717 	 * return value from the system call is stored on the user thread.
718 	 * If there was an error, the return value is set to -1, imitating
719 	 * the behavior of the cerror routine.
720 	 */
721 	if (error)
722 		retval = -1;
723 	else
724 		retval = td->td_retval[0];
725 
726 	audit_commit(td->td_ar, error, retval);
727 	td->td_ar = NULL;
728 	td->td_pflags &= ~TDP_AUDITREC;
729 }
730 
731 void
audit_cred_copy(struct ucred * src,struct ucred * dest)732 audit_cred_copy(struct ucred *src, struct ucred *dest)
733 {
734 
735 	bcopy(&src->cr_audit, &dest->cr_audit, sizeof(dest->cr_audit));
736 }
737 
738 void
audit_cred_destroy(struct ucred * cred)739 audit_cred_destroy(struct ucred *cred)
740 {
741 
742 }
743 
744 void
audit_cred_init(struct ucred * cred)745 audit_cred_init(struct ucred *cred)
746 {
747 
748 	bzero(&cred->cr_audit, sizeof(cred->cr_audit));
749 }
750 
751 /*
752  * Initialize audit information for the first kernel process (proc 0) and for
753  * the first user process (init).
754  */
755 void
audit_cred_kproc0(struct ucred * cred)756 audit_cred_kproc0(struct ucred *cred)
757 {
758 
759 	cred->cr_audit.ai_auid = AU_DEFAUDITID;
760 	cred->cr_audit.ai_termid.at_type = AU_IPv4;
761 }
762 
763 void
audit_cred_proc1(struct ucred * cred)764 audit_cred_proc1(struct ucred *cred)
765 {
766 
767 	cred->cr_audit.ai_auid = AU_DEFAUDITID;
768 	cred->cr_audit.ai_termid.at_type = AU_IPv4;
769 }
770 
771 void
audit_thread_alloc(struct thread * td)772 audit_thread_alloc(struct thread *td)
773 {
774 
775 	td->td_ar = NULL;
776 }
777 
778 void
audit_thread_free(struct thread * td)779 audit_thread_free(struct thread *td)
780 {
781 
782 	KASSERT(td->td_ar == NULL, ("audit_thread_free: td_ar != NULL"));
783 	KASSERT((td->td_pflags & TDP_AUDITREC) == 0,
784 	    ("audit_thread_free: TDP_AUDITREC set"));
785 }
786 
787 void
audit_proc_coredump(struct thread * td,char * path,int errcode)788 audit_proc_coredump(struct thread *td, char *path, int errcode)
789 {
790 	struct kaudit_record *ar;
791 	struct au_mask *aumask;
792 	struct ucred *cred;
793 	au_class_t class;
794 	int ret, sorf;
795 	char **pathp;
796 	au_id_t auid;
797 
798 	ret = 0;
799 
800 	/*
801 	 * Make sure we are using the correct preselection mask.
802 	 */
803 	cred = td->td_ucred;
804 	auid = cred->cr_audit.ai_auid;
805 	if (auid == AU_DEFAUDITID)
806 		aumask = &audit_nae_mask;
807 	else
808 		aumask = &cred->cr_audit.ai_mask;
809 	/*
810 	 * It's possible for coredump(9) generation to fail.  Make sure that
811 	 * we handle this case correctly for preselection.
812 	 */
813 	if (errcode != 0)
814 		sorf = AU_PRS_FAILURE;
815 	else
816 		sorf = AU_PRS_SUCCESS;
817 	class = au_event_class(AUE_CORE);
818 	if (au_preselect(AUE_CORE, class, aumask, sorf) == 0 &&
819 	    audit_pipe_preselect(auid, AUE_CORE, class, sorf, 0) == 0)
820 		return;
821 
822 	/*
823 	 * If we are interested in seeing this audit record, allocate it.
824 	 * Where possible coredump records should contain a pathname and arg32
825 	 * (signal) tokens.
826 	 */
827 	ar = audit_new(AUE_CORE, td);
828 	if (ar == NULL)
829 		return;
830 	if (path != NULL) {
831 		pathp = &ar->k_ar.ar_arg_upath1;
832 		*pathp = malloc(MAXPATHLEN, M_AUDITPATH, M_WAITOK);
833 		audit_canon_path(td, AT_FDCWD, path, *pathp);
834 		ARG_SET_VALID(ar, ARG_UPATH1);
835 	}
836 	ar->k_ar.ar_arg_signum = td->td_proc->p_sig;
837 	ARG_SET_VALID(ar, ARG_SIGNUM);
838 	if (errcode != 0)
839 		ret = 1;
840 	audit_commit(ar, errcode, ret);
841 }
842