1/*-
2 * SPDX-License-Identifier: BSD-3-Clause
3 *
4 * Copyright (c) 1999-2008 Apple Inc.
5 * Copyright (c) 2006-2008, 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/file.h>
42#include <sys/filedesc.h>
43#include <sys/fcntl.h>
44#include <sys/ipc.h>
45#include <sys/kernel.h>
46#include <sys/kthread.h>
47#include <sys/malloc.h>
48#include <sys/mount.h>
49#include <sys/namei.h>
50#include <sys/proc.h>
51#include <sys/queue.h>
52#include <sys/socket.h>
53#include <sys/socketvar.h>
54#include <sys/protosw.h>
55#include <sys/domain.h>
56#include <sys/sx.h>
57#include <sys/sysproto.h>
58#include <sys/sysent.h>
59#include <sys/systm.h>
60#include <sys/ucred.h>
61#include <sys/uio.h>
62#include <sys/un.h>
63#include <sys/unistd.h>
64#include <sys/vnode.h>
65
66#include <bsm/audit.h>
67#include <bsm/audit_internal.h>
68#include <bsm/audit_kevents.h>
69
70#include <netinet/in.h>
71#include <netinet/in_pcb.h>
72
73#include <security/audit/audit.h>
74#include <security/audit/audit_private.h>
75
76#include <vm/uma.h>
77
78#include <machine/stdarg.h>
79
80/*
81 * Worker thread that will schedule disk I/O, etc.
82 */
83static struct proc		*audit_thread;
84
85/*
86 * audit_cred and audit_vp are the stored credential and vnode to use for
87 * active audit trail.  They are protected by the audit worker lock, which
88 * will be held across all I/O and all rotation to prevent them from being
89 * replaced (rotated) while in use.  The audit_file_rotate_wait flag is set
90 * when the kernel has delivered a trigger to auditd to rotate the trail, and
91 * is cleared when the next rotation takes place.  It is also protected by
92 * the audit worker lock.
93 */
94static int		 audit_file_rotate_wait;
95static struct ucred	*audit_cred;
96static struct vnode	*audit_vp;
97static off_t		 audit_size;
98static struct sx	 audit_worker_lock;
99
100#define	AUDIT_WORKER_LOCK_INIT()	sx_init(&audit_worker_lock, \
101					    "audit_worker_lock");
102#define	AUDIT_WORKER_LOCK_ASSERT()	sx_assert(&audit_worker_lock, \
103					    SA_XLOCKED)
104#define	AUDIT_WORKER_LOCK()		sx_xlock(&audit_worker_lock)
105#define	AUDIT_WORKER_UNLOCK()		sx_xunlock(&audit_worker_lock)
106
107static void
108audit_worker_sync_vp(struct vnode *vp, struct mount *mp, const char *fmt, ...)
109{
110	struct mount *mp1;
111	int error;
112	va_list va;
113
114	va_start(va, fmt);
115	error = vn_start_write(vp, &mp1, 0);
116	if (error == 0) {
117		VOP_LOCK(vp, LK_EXCLUSIVE | LK_RETRY);
118		(void)VOP_FSYNC(vp, MNT_WAIT, curthread);
119		VOP_UNLOCK(vp);
120		vn_finished_write(mp1);
121	}
122	vfs_unbusy(mp);
123	vpanic(fmt, va);
124	va_end(va);
125}
126
127/*
128 * Write an audit record to a file, performed as the last stage after both
129 * preselection and BSM conversion.  Both space management and write failures
130 * are handled in this function.
131 *
132 * No attempt is made to deal with possible failure to deliver a trigger to
133 * the audit daemon, since the message is asynchronous anyway.
134 */
135static void
136audit_record_write(struct vnode *vp, struct ucred *cred, void *data,
137    size_t len)
138{
139	static struct timeval last_lowspace_trigger;
140	static struct timeval last_fail;
141	static int cur_lowspace_trigger;
142	struct statfs *mnt_stat;
143	struct mount *mp;
144	int error;
145	static int cur_fail;
146	long temp;
147
148	AUDIT_WORKER_LOCK_ASSERT();
149
150	if (vp == NULL)
151		return;
152
153	mp = vp->v_mount;
154	if (mp == NULL) {
155		error = EINVAL;
156		goto fail;
157	}
158	error = vfs_busy(mp, 0);
159	if (error != 0) {
160		mp = NULL;
161		goto fail;
162	}
163	mnt_stat = &mp->mnt_stat;
164
165	/*
166	 * First, gather statistics on the audit log file and file system so
167	 * that we know how we're doing on space.  Consider failure of these
168	 * operations to indicate a future inability to write to the file.
169	 */
170	error = VFS_STATFS(mp, mnt_stat);
171	if (error != 0)
172		goto fail;
173
174	/*
175	 * We handle four different space-related limits:
176	 *
177	 * - A fixed (hard) limit on the minimum free blocks we require on
178	 *   the file system, and results in record loss, a trigger, and
179	 *   possible fail stop due to violating invariants.
180	 *
181	 * - An administrative (soft) limit, which when fallen below, results
182	 *   in the kernel notifying the audit daemon of low space.
183	 *
184	 * - An audit trail size limit, which when gone above, results in the
185	 *   kernel notifying the audit daemon that rotation is desired.
186	 *
187	 * - The total depth of the kernel audit record exceeding free space,
188	 *   which can lead to possible fail stop (with drain), in order to
189	 *   prevent violating invariants.  Failure here doesn't halt
190	 *   immediately, but prevents new records from being generated.
191	 *
192	 * Possibly, the last of these should be handled differently, always
193	 * allowing a full queue to be lost, rather than trying to prevent
194	 * loss.
195	 *
196	 * First, handle the hard limit, which generates a trigger and may
197	 * fail stop.  This is handled in the same manner as ENOSPC from
198	 * VOP_WRITE, and results in record loss.
199	 */
200	if (mnt_stat->f_bfree < AUDIT_HARD_LIMIT_FREE_BLOCKS) {
201		error = ENOSPC;
202		goto fail_enospc;
203	}
204
205	/*
206	 * Second, handle falling below the soft limit, if defined; we send
207	 * the daemon a trigger and continue processing the record.  Triggers
208	 * are limited to 1/sec.
209	 */
210	if (audit_qctrl.aq_minfree != 0) {
211		temp = mnt_stat->f_blocks / (100 / audit_qctrl.aq_minfree);
212		if (mnt_stat->f_bfree < temp) {
213			if (ppsratecheck(&last_lowspace_trigger,
214			    &cur_lowspace_trigger, 1)) {
215				(void)audit_send_trigger(
216				    AUDIT_TRIGGER_LOW_SPACE);
217				printf("Warning: disk space low (< %d%% free) "
218				    "on audit log file-system\n",
219				    audit_qctrl.aq_minfree);
220			}
221		}
222	}
223
224	/*
225	 * If the current file is getting full, generate a rotation trigger
226	 * to the daemon.  This is only approximate, which is fine as more
227	 * records may be generated before the daemon rotates the file.
228	 */
229	if (audit_fstat.af_filesz != 0 &&
230	    audit_size >= audit_fstat.af_filesz * (audit_file_rotate_wait + 1)) {
231		AUDIT_WORKER_LOCK_ASSERT();
232
233		audit_file_rotate_wait++;
234		(void)audit_send_trigger(AUDIT_TRIGGER_ROTATE_KERNEL);
235	}
236
237	/*
238	 * If the estimated amount of audit data in the audit event queue
239	 * (plus records allocated but not yet queued) has reached the amount
240	 * of free space on the disk, then we need to go into an audit fail
241	 * stop state, in which we do not permit the allocation/committing of
242	 * any new audit records.  We continue to process records but don't
243	 * allow any activities that might generate new records.  In the
244	 * future, we might want to detect when space is available again and
245	 * allow operation to continue, but this behavior is sufficient to
246	 * meet fail stop requirements in CAPP.
247	 */
248	if (audit_fail_stop) {
249		if ((unsigned long)((audit_q_len + audit_pre_q_len + 1) *
250		    MAX_AUDIT_RECORD_SIZE) / mnt_stat->f_bsize >=
251		    (unsigned long)(mnt_stat->f_bfree)) {
252			if (ppsratecheck(&last_fail, &cur_fail, 1))
253				printf("audit_record_write: free space "
254				    "below size of audit queue, failing "
255				    "stop\n");
256			audit_in_failure = 1;
257		} else if (audit_in_failure) {
258			/*
259			 * Note: if we want to handle recovery, this is the
260			 * spot to do it: unset audit_in_failure, and issue a
261			 * wakeup on the cv.
262			 */
263		}
264	}
265
266	error = vn_rdwr(UIO_WRITE, vp, data, len, (off_t)0, UIO_SYSSPACE,
267	    IO_APPEND|IO_UNIT, cred, NULL, NULL, curthread);
268	if (error == ENOSPC)
269		goto fail_enospc;
270	else if (error)
271		goto fail;
272	AUDIT_WORKER_LOCK_ASSERT();
273	audit_size += len;
274
275	/*
276	 * Catch completion of a queue drain here; if we're draining and the
277	 * queue is now empty, fail stop.  That audit_fail_stop is implicitly
278	 * true, since audit_in_failure can only be set of audit_fail_stop is
279	 * set.
280	 *
281	 * Note: if we handle recovery from audit_in_failure, then we need to
282	 * make panic here conditional.
283	 */
284	if (audit_in_failure) {
285		if (audit_q_len == 0 && audit_pre_q_len == 0) {
286			audit_worker_sync_vp(vp, mp,
287			    "Audit store overflow; record queue drained.");
288		}
289	}
290
291	vfs_unbusy(mp);
292	return;
293
294fail_enospc:
295	/*
296	 * ENOSPC is considered a special case with respect to failures, as
297	 * this can reflect either our preemptive detection of insufficient
298	 * space, or ENOSPC returned by the vnode write call.
299	 */
300	if (audit_fail_stop) {
301		audit_worker_sync_vp(vp, mp,
302		    "Audit log space exhausted and fail-stop set.");
303	}
304	(void)audit_send_trigger(AUDIT_TRIGGER_NO_SPACE);
305	audit_trail_suspended = 1;
306	audit_syscalls_enabled_update();
307
308	/* FALLTHROUGH */
309fail:
310	/*
311	 * We have failed to write to the file, so the current record is
312	 * lost, which may require an immediate system halt.
313	 */
314	if (audit_panic_on_write_fail) {
315		audit_worker_sync_vp(vp, mp,
316		    "audit_worker: write error %d\n", error);
317	} else if (ppsratecheck(&last_fail, &cur_fail, 1))
318		printf("audit_worker: write error %d\n", error);
319	if (mp != NULL)
320		vfs_unbusy(mp);
321}
322
323/*
324 * Given a kernel audit record, process as required.  Kernel audit records
325 * are converted to one, or possibly two, BSM records, depending on whether
326 * there is a user audit record present also.  Kernel records need be
327 * converted to BSM before they can be written out.  Both types will be
328 * written to disk, and audit pipes.
329 */
330static void
331audit_worker_process_record(struct kaudit_record *ar)
332{
333	struct au_record *bsm;
334	au_class_t class;
335	au_event_t event;
336	au_id_t auid;
337	int error, sorf;
338	int locked;
339
340	/*
341	 * We hold the audit worker lock over both writes, if there are two,
342	 * so that the two records won't be split across a rotation and end
343	 * up in two different trail files.
344	 */
345	if (((ar->k_ar_commit & AR_COMMIT_USER) &&
346	    (ar->k_ar_commit & AR_PRESELECT_USER_TRAIL)) ||
347	    (ar->k_ar_commit & AR_PRESELECT_TRAIL)) {
348		AUDIT_WORKER_LOCK();
349		locked = 1;
350	} else
351		locked = 0;
352
353	/*
354	 * First, handle the user record, if any: commit to the system trail
355	 * and audit pipes as selected.
356	 */
357	if ((ar->k_ar_commit & AR_COMMIT_USER) &&
358	    (ar->k_ar_commit & AR_PRESELECT_USER_TRAIL)) {
359		AUDIT_WORKER_LOCK_ASSERT();
360		audit_record_write(audit_vp, audit_cred, ar->k_udata,
361		    ar->k_ulen);
362	}
363
364	if ((ar->k_ar_commit & AR_COMMIT_USER) &&
365	    (ar->k_ar_commit & AR_PRESELECT_USER_PIPE))
366		audit_pipe_submit_user(ar->k_udata, ar->k_ulen);
367
368	if (!(ar->k_ar_commit & AR_COMMIT_KERNEL) ||
369	    ((ar->k_ar_commit & AR_PRESELECT_PIPE) == 0 &&
370	    (ar->k_ar_commit & AR_PRESELECT_TRAIL) == 0 &&
371	    (ar->k_ar_commit & AR_PRESELECT_DTRACE) == 0))
372		goto out;
373
374	auid = ar->k_ar.ar_subj_auid;
375	event = ar->k_ar.ar_event;
376	class = au_event_class(event);
377	if (ar->k_ar.ar_errno == 0)
378		sorf = AU_PRS_SUCCESS;
379	else
380		sorf = AU_PRS_FAILURE;
381
382	error = kaudit_to_bsm(ar, &bsm);
383	switch (error) {
384	case BSM_NOAUDIT:
385		goto out;
386
387	case BSM_FAILURE:
388		printf("audit_worker_process_record: BSM_FAILURE\n");
389		goto out;
390
391	case BSM_SUCCESS:
392		break;
393
394	default:
395		panic("kaudit_to_bsm returned %d", error);
396	}
397
398	if (ar->k_ar_commit & AR_PRESELECT_TRAIL) {
399		AUDIT_WORKER_LOCK_ASSERT();
400		audit_record_write(audit_vp, audit_cred, bsm->data, bsm->len);
401	}
402
403	if (ar->k_ar_commit & AR_PRESELECT_PIPE)
404		audit_pipe_submit(auid, event, class, sorf,
405		    ar->k_ar_commit & AR_PRESELECT_TRAIL, bsm->data,
406		    bsm->len);
407
408#ifdef KDTRACE_HOOKS
409	/*
410	 * Version of the dtaudit commit hook that accepts BSM.
411	 */
412	if (ar->k_ar_commit & AR_PRESELECT_DTRACE) {
413		if (dtaudit_hook_bsm != NULL)
414			dtaudit_hook_bsm(ar, auid, event, class, sorf,
415			    bsm->data, bsm->len);
416	}
417#endif
418
419	kau_free(bsm);
420out:
421	if (locked)
422		AUDIT_WORKER_UNLOCK();
423}
424
425/*
426 * The audit_worker thread is responsible for watching the event queue,
427 * dequeueing records, converting them to BSM format, and committing them to
428 * disk.  In order to minimize lock thrashing, records are dequeued in sets
429 * to a thread-local work queue.
430 *
431 * Note: this means that the effect bound on the size of the pending record
432 * queue is 2x the length of the global queue.
433 */
434static void
435audit_worker(void *arg)
436{
437	struct kaudit_queue ar_worklist;
438	struct kaudit_record *ar;
439	int lowater_signal;
440
441	TAILQ_INIT(&ar_worklist);
442	mtx_lock(&audit_mtx);
443	while (1) {
444		mtx_assert(&audit_mtx, MA_OWNED);
445
446		/*
447		 * Wait for a record.
448		 */
449		while (TAILQ_EMPTY(&audit_q))
450			cv_wait(&audit_worker_cv, &audit_mtx);
451
452		/*
453		 * If there are records in the global audit record queue,
454		 * transfer them to a thread-local queue and process them
455		 * one by one.  If we cross the low watermark threshold,
456		 * signal any waiting processes that they may wake up and
457		 * continue generating records.
458		 */
459		lowater_signal = 0;
460		while ((ar = TAILQ_FIRST(&audit_q))) {
461			TAILQ_REMOVE(&audit_q, ar, k_q);
462			audit_q_len--;
463			if (audit_q_len == audit_qctrl.aq_lowater)
464				lowater_signal++;
465			TAILQ_INSERT_TAIL(&ar_worklist, ar, k_q);
466		}
467		if (lowater_signal)
468			cv_broadcast(&audit_watermark_cv);
469
470		mtx_unlock(&audit_mtx);
471		while ((ar = TAILQ_FIRST(&ar_worklist))) {
472			TAILQ_REMOVE(&ar_worklist, ar, k_q);
473			audit_worker_process_record(ar);
474			audit_free(ar);
475		}
476		mtx_lock(&audit_mtx);
477	}
478}
479
480/*
481 * audit_rotate_vnode() is called by a user or kernel thread to configure or
482 * de-configure auditing on a vnode.  The arguments are the replacement
483 * credential (referenced) and vnode (referenced and opened) to substitute
484 * for the current credential and vnode, if any.  If either is set to NULL,
485 * both should be NULL, and this is used to indicate that audit is being
486 * disabled.  Any previous cred/vnode will be closed and freed.  We re-enable
487 * generating rotation requests to auditd.
488 */
489void
490audit_rotate_vnode(struct ucred *cred, struct vnode *vp)
491{
492	struct ucred *old_audit_cred;
493	struct vnode *old_audit_vp;
494	struct vattr vattr;
495
496	KASSERT((cred != NULL && vp != NULL) || (cred == NULL && vp == NULL),
497	    ("audit_rotate_vnode: cred %p vp %p", cred, vp));
498
499	if (vp != NULL) {
500		vn_lock(vp, LK_SHARED | LK_RETRY);
501		if (VOP_GETATTR(vp, &vattr, cred) != 0)
502			vattr.va_size = 0;
503		VOP_UNLOCK(vp);
504	} else {
505		vattr.va_size = 0;
506	}
507
508	/*
509	 * Rotate the vnode/cred, and clear the rotate flag so that we will
510	 * send a rotate trigger if the new file fills.
511	 */
512	AUDIT_WORKER_LOCK();
513	old_audit_cred = audit_cred;
514	old_audit_vp = audit_vp;
515	audit_cred = cred;
516	audit_vp = vp;
517	audit_size = vattr.va_size;
518	audit_file_rotate_wait = 0;
519	audit_trail_enabled = (audit_vp != NULL);
520	audit_syscalls_enabled_update();
521	AUDIT_WORKER_UNLOCK();
522
523	/*
524	 * If there was an old vnode/credential, close and free.
525	 */
526	if (old_audit_vp != NULL) {
527		vn_close(old_audit_vp, AUDIT_CLOSE_FLAGS, old_audit_cred,
528		    curthread);
529		crfree(old_audit_cred);
530	}
531}
532
533void
534audit_worker_init(void)
535{
536	int error;
537
538	AUDIT_WORKER_LOCK_INIT();
539	error = kproc_create(audit_worker, NULL, &audit_thread, RFHIGHPID,
540	    0, "audit");
541	if (error)
542		panic("audit_worker_init: kproc_create returned %d", error);
543}
544