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