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