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