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