1/*-
2 * Copyright (c) 1999-2016 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/param.h>
32#include <sys/fcntl.h>
33#include <sys/kernel.h>
34#include <sys/lock.h>
35#include <sys/namei.h>
36#include <sys/proc_internal.h>
37#include <sys/kauth.h>
38#include <sys/queue.h>
39#include <sys/systm.h>
40#include <sys/time.h>
41#include <sys/ucred.h>
42#include <sys/uio.h>
43#include <sys/unistd.h>
44#include <sys/file_internal.h>
45#include <sys/vnode_internal.h>
46#include <sys/user.h>
47#include <sys/syscall.h>
48#include <sys/un.h>
49#include <sys/sysent.h>
50#include <sys/sysproto.h>
51#include <sys/vfs_context.h>
52#include <sys/domain.h>
53#include <sys/protosw.h>
54#include <sys/socketvar.h>
55
56#include <bsm/audit.h>
57#include <bsm/audit_internal.h>
58#include <bsm/audit_kevents.h>
59
60#include <security/audit/audit.h>
61#include <security/audit/audit_bsd.h>
62#include <security/audit/audit_private.h>
63
64#include <mach/host_priv.h>
65#include <mach/host_special_ports.h>
66#include <mach/audit_triggers_server.h>
67
68#include <kern/host.h>
69#include <kern/zalloc.h>
70#include <kern/sched_prim.h>
71#include <kern/task.h>
72
73#include <net/route.h>
74
75#include <netinet/in.h>
76#include <netinet/in_pcb.h>
77
78/*
79 * Worker thread that will schedule disk I/O, etc.
80 */
81static thread_t audit_thread;
82
83/*
84 * audit_ctx and audit_vp are the stored credential and vnode to use for
85 * active audit trail. They are protected by audit_worker_sl, which will be
86 * held across all I/O and all rotation to prevent them from being replaced
87 * (rotated) while in use. The audit_file_rotate_wait flag is set when the
88 * kernel has delivered a trigger to auditd to rotate the trail, and is
89 * cleared when the next rotation takes place. It is also protected by
90 * audit_worker_sl.
91 */
92static int audit_file_rotate_wait;
93static struct slck audit_worker_sl;
94static struct vfs_context audit_ctx;
95static struct vnode *audit_vp;
96
97#define AUDIT_WORKER_SX_INIT() slck_init(&audit_worker_sl, \
98 "audit_worker_sl")
99#define AUDIT_WORKER_SX_XLOCK() slck_lock(&audit_worker_sl)
100#define AUDIT_WORKER_SX_XUNLOCK() slck_unlock(&audit_worker_sl)
101#define AUDIT_WORKER_SX_ASSERT() slck_assert(&audit_worker_sl, SL_OWNED)
102#define AUDIT_WORKER_SX_DESTROY() slck_destroy(&audit_worker_sl)
103
104/*
105 * The audit_q_draining flag is set when audit is disabled and the audit
106 * worker queue is being drained.
107 */
108static int audit_q_draining;
109
110/*
111 * The special kernel audit record, audit_drain_kar, is used to mark the end of
112 * the queue when draining it.
113 */
114static struct kaudit_record audit_drain_kar = {
115 .k_ar = {
116 .ar_event = AUE_NULL,
117 },
118 .k_ar_commit = AR_DRAIN_QUEUE,
119};
120
121/*
122 * Write an audit record to a file, performed as the last stage after both
123 * preselection and BSM conversion. Both space management and write failures
124 * are handled in this function.
125 *
126 * No attempt is made to deal with possible failure to deliver a trigger to
127 * the audit daemon, since the message is asynchronous anyway.
128 */
129static void
130audit_record_write(struct vnode *vp, struct vfs_context *ctx, void *data,
131 size_t len)
132{
133 static struct timeval last_lowspace_trigger;
134 static struct timeval last_fail;
135 static int cur_lowspace_trigger;
136 struct vfsstatfs *mnt_stat;
137 int error;
138 static int cur_fail;
139 uint64_t temp;
140 off_t file_size;
141
142 AUDIT_WORKER_SX_ASSERT(); /* audit_file_rotate_wait. */
143
144 if (vp == NULL) {
145 return;
146 }
147
148 if (vnode_getwithref(vp)) {
149 return /*(ENOENT)*/;
150 }
151
152 mnt_stat = &vp->v_mount->mnt_vfsstat;
153
154 /*
155 * First, gather statistics on the audit log file and file system so
156 * that we know how we're doing on space. Consider failure of these
157 * operations to indicate a future inability to write to the file.
158 */
159 error = vfs_update_vfsstat(mp: vp->v_mount, ctx, VFS_KERNEL_EVENT);
160 if (error) {
161 goto fail;
162 }
163 error = vnode_size(vp, &file_size, ctx);
164 if (error) {
165 goto fail;
166 }
167 audit_fstat.af_currsz = (u_quad_t)file_size;
168
169 /*
170 * We handle four different space-related limits:
171 *
172 * - A fixed (hard) limit on the minimum free blocks we require on
173 * the file system, and results in record loss, a trigger, and
174 * possible fail stop due to violating invariants.
175 *
176 * - An administrative (soft) limit, which when fallen below, results
177 * in the kernel notifying the audit daemon of low space.
178 *
179 * - An audit trail size limit, which when gone above, results in the
180 * kernel notifying the audit daemon that rotation is desired.
181 *
182 * - The total depth of the kernel audit record exceeding free space,
183 * which can lead to possible fail stop (with drain), in order to
184 * prevent violating invariants. Failure here doesn't halt
185 * immediately, but prevents new records from being generated.
186 *
187 * Possibly, the last of these should be handled differently, always
188 * allowing a full queue to be lost, rather than trying to prevent
189 * loss.
190 *
191 * First, handle the hard limit, which generates a trigger and may
192 * fail stop. This is handled in the same manner as ENOSPC from
193 * VOP_WRITE, and results in record loss.
194 */
195 if (mnt_stat->f_bfree < AUDIT_HARD_LIMIT_FREE_BLOCKS) {
196 error = ENOSPC;
197 goto fail_enospc;
198 }
199
200 /*
201 * Second, handle falling below the soft limit, if defined; we send
202 * the daemon a trigger and continue processing the record. Triggers
203 * are limited to 1/sec.
204 */
205 if (audit_qctrl.aq_minfree != 0) {
206 temp = mnt_stat->f_blocks / (100 / audit_qctrl.aq_minfree);
207 if (mnt_stat->f_bfree < temp &&
208 ppsratecheck(&last_lowspace_trigger,
209 &cur_lowspace_trigger, 1)) {
210 (void)audit_send_trigger(
211 AUDIT_TRIGGER_LOW_SPACE);
212 }
213 }
214
215 /*
216 * If the current file is getting full, generate a rotation trigger
217 * to the daemon. This is only approximate, which is fine as more
218 * records may be generated before the daemon rotates the file.
219 */
220 if ((audit_fstat.af_filesz != 0) && (audit_file_rotate_wait == 0) &&
221 ((u_quad_t)file_size >= audit_fstat.af_filesz)) {
222 AUDIT_WORKER_SX_ASSERT();
223
224 audit_file_rotate_wait = 1;
225 (void)audit_send_trigger(AUDIT_TRIGGER_ROTATE_KERNEL);
226 }
227
228 /*
229 * If the estimated amount of audit data in the audit event queue
230 * (plus records allocated but not yet queued) has reached the amount
231 * of free space on the disk, then we need to go into an audit fail
232 * stop state, in which we do not permit the allocation/committing of
233 * any new audit records. We continue to process records but don't
234 * allow any activities that might generate new records. In the
235 * future, we might want to detect when space is available again and
236 * allow operation to continue, but this behavior is sufficient to
237 * meet fail stop requirements in CAPP.
238 */
239 if (audit_fail_stop) {
240 if ((unsigned long)((audit_q_len + audit_pre_q_len + 1) *
241 MAX_AUDIT_RECORD_SIZE) / mnt_stat->f_bsize >=
242 (unsigned long)(mnt_stat->f_bfree)) {
243 if (ppsratecheck(&last_fail, &cur_fail, 1)) {
244 printf("audit_record_write: free space "
245 "below size of audit queue, failing "
246 "stop\n");
247 }
248 audit_in_failure = 1;
249 } else if (audit_in_failure) {
250 /*
251 * Note: if we want to handle recovery, this is the
252 * spot to do it: unset audit_in_failure, and issue a
253 * wakeup on the cv.
254 */
255 }
256 }
257
258 error = vn_rdwr(rw: UIO_WRITE, vp, base: data, len, offset: (off_t)0, segflg: UIO_SYSSPACE,
259 IO_APPEND | IO_UNIT, cred: vfs_context_ucred(ctx), NULL,
260 p: vfs_context_proc(ctx));
261 if (error == ENOSPC) {
262 goto fail_enospc;
263 } else if (error) {
264 goto fail;
265 }
266
267 /*
268 * Catch completion of a queue drain here; if we're draining and the
269 * queue is now empty, fail stop. That audit_fail_stop is implicitly
270 * true, since audit_in_failure can only be set of audit_fail_stop is
271 * set.
272 *
273 * Note: if we handle recovery from audit_in_failure, then we need to
274 * make panic here conditional.
275 */
276 if (audit_in_failure) {
277 if (audit_q_len == 0 && audit_pre_q_len == 0) {
278 (void)VNOP_FSYNC(vp, MNT_WAIT, ctx);
279 panic("Audit store overflow; record queue drained.");
280 }
281 }
282
283 vnode_put(vp);
284 return;
285
286fail_enospc:
287 /*
288 * ENOSPC is considered a special case with respect to failures, as
289 * this can reflect either our preemptive detection of insufficient
290 * space, or ENOSPC returned by the vnode write call.
291 */
292 if (audit_fail_stop) {
293 (void)VNOP_FSYNC(vp, MNT_WAIT, ctx);
294 panic("Audit log space exhausted and fail-stop set.");
295 }
296 (void)audit_send_trigger(AUDIT_TRIGGER_NO_SPACE);
297 audit_suspended = 1;
298
299 /* FALLTHROUGH */
300fail:
301 /*
302 * We have failed to write to the file, so the current record is
303 * lost, which may require an immediate system halt.
304 */
305 if (audit_panic_on_write_fail) {
306 (void)VNOP_FSYNC(vp, MNT_WAIT, ctx);
307 panic("audit_worker: write error %d", error);
308 } else if (ppsratecheck(&last_fail, &cur_fail, 1)) {
309 printf("audit_worker: write error %d\n", error);
310 }
311 vnode_put(vp);
312}
313
314/*
315 * Given a kernel audit record, process as required. Kernel audit records
316 * are converted to one, or possibly two, BSM records, depending on whether
317 * there is a user audit record present also. Kernel records need be
318 * converted to BSM before they can be written out. Both types will be
319 * written to disk, and audit pipes.
320 */
321static void
322audit_worker_process_record(struct kaudit_record *ar)
323{
324 struct au_record *bsm;
325 au_class_t class;
326 au_event_t event;
327 au_id_t auid;
328 int error, sorf;
329 int trail_locked;
330
331 /*
332 * We hold the audit_worker_sl lock over both writes, if there are
333 * two, so that the two records won't be split across a rotation and
334 * end up in two different trail files.
335 */
336 if (((ar->k_ar_commit & AR_COMMIT_USER) &&
337 (ar->k_ar_commit & AR_PRESELECT_USER_TRAIL)) ||
338 (ar->k_ar_commit & AR_PRESELECT_TRAIL)) {
339 AUDIT_WORKER_SX_XLOCK();
340 trail_locked = 1;
341 } else {
342 trail_locked = 0;
343 }
344
345 /*
346 * First, handle the user record, if any: commit to the system trail
347 * and audit pipes as selected.
348 */
349 if ((ar->k_ar_commit & AR_COMMIT_USER) &&
350 (ar->k_ar_commit & AR_PRESELECT_USER_TRAIL)) {
351 AUDIT_WORKER_SX_ASSERT();
352 audit_record_write(vp: audit_vp, ctx: &audit_ctx, data: ar->k_udata,
353 len: ar->k_ulen);
354 }
355
356 if ((ar->k_ar_commit & AR_COMMIT_USER) &&
357 (ar->k_ar_commit & AR_PRESELECT_USER_PIPE)) {
358 audit_pipe_submit_user(record: ar->k_udata, record_len: ar->k_ulen);
359 }
360
361 if (!(ar->k_ar_commit & AR_COMMIT_KERNEL) ||
362 ((ar->k_ar_commit & AR_PRESELECT_PIPE) == 0 &&
363 (ar->k_ar_commit & AR_PRESELECT_TRAIL) == 0 &&
364 (ar->k_ar_commit & AR_PRESELECT_FILTER) == 0)) {
365 goto out;
366 }
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
377 error = kaudit_to_bsm(kar: ar, pau: &bsm);
378 switch (error) {
379 case BSM_NOAUDIT:
380 goto out;
381
382 case BSM_FAILURE:
383 printf("audit_worker_process_record: BSM_FAILURE\n");
384 goto out;
385
386 case BSM_SUCCESS:
387 break;
388
389 default:
390 panic("kaudit_to_bsm returned %d", error);
391 }
392
393 if (ar->k_ar_commit & AR_PRESELECT_TRAIL) {
394 AUDIT_WORKER_SX_ASSERT();
395 audit_record_write(vp: audit_vp, ctx: &audit_ctx, data: bsm->data, len: bsm->len);
396 }
397
398 if (ar->k_ar_commit & AR_PRESELECT_PIPE) {
399 audit_pipe_submit(auid, event, class, sorf,
400 trail_select: ar->k_ar_commit & AR_PRESELECT_TRAIL, record: bsm->data,
401 record_len: bsm->len);
402 }
403
404 if (ar->k_ar_commit & AR_PRESELECT_FILTER) {
405 /*
406 * XXXss - This needs to be generalized so new filters can
407 * be easily plugged in.
408 */
409 audit_sdev_submit(auid, asid: ar->k_ar.ar_subj_asid, record: bsm->data,
410 record_len: bsm->len);
411 }
412
413 kau_free(rec: bsm);
414out:
415 if (trail_locked) {
416 AUDIT_WORKER_SX_XUNLOCK();
417 }
418}
419
420/*
421 * The audit_worker thread is responsible for watching the event queue,
422 * dequeueing records, converting them to BSM format, and committing them to
423 * disk. In order to minimize lock thrashing, records are dequeued in sets
424 * to a thread-local work queue.
425 *
426 * Note: this means that the effect bound on the size of the pending record
427 * queue is 2x the length of the global queue.
428 */
429__attribute__((noreturn))
430static void
431audit_worker(void)
432{
433 struct kaudit_queue ar_worklist;
434 struct kaudit_record *ar;
435 int lowater_signal;
436
437 if (audit_ctx.vc_thread == NULL) {
438 audit_ctx.vc_thread = current_thread();
439 }
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_continuation(&audit_worker_cv, &audit_mtx,
451 (thread_continue_t)audit_worker);
452 }
453
454 /*
455 * If there are records in the global audit record queue,
456 * transfer them to a thread-local queue and process them
457 * one by one. If we cross the low watermark threshold,
458 * signal any waiting processes that they may wake up and
459 * continue generating records.
460 */
461 lowater_signal = 0;
462 while ((ar = TAILQ_FIRST(&audit_q))) {
463 TAILQ_REMOVE(&audit_q, ar, k_q);
464 audit_q_len--;
465 if (audit_q_len == audit_qctrl.aq_lowater) {
466 lowater_signal++;
467 }
468 TAILQ_INSERT_TAIL(&ar_worklist, ar, k_q);
469 }
470 if (lowater_signal) {
471 cv_broadcast(&audit_watermark_cv);
472 }
473
474 mtx_unlock(&audit_mtx);
475 while ((ar = TAILQ_FIRST(&ar_worklist))) {
476 TAILQ_REMOVE(&ar_worklist, ar, k_q);
477 if (ar->k_ar_commit & AR_DRAIN_QUEUE) {
478 audit_q_draining = 0;
479 cv_broadcast(&audit_drain_cv);
480 } else {
481 audit_worker_process_record(ar);
482 audit_free(ar);
483 }
484 }
485 mtx_lock(&audit_mtx);
486 }
487}
488
489/*
490 * audit_rotate_vnode() is called by a user or kernel thread to configure or
491 * de-configure auditing on a vnode. The arguments are the replacement
492 * credential (referenced) and vnode (referenced and opened) to substitute
493 * for the current credential and vnode, if any. If either is set to NULL,
494 * both should be NULL, and this is used to indicate that audit is being
495 * disabled. Any previous cred/vnode will be closed and freed. We re-enable
496 * generating rotation requests to auditd.
497 */
498void
499audit_rotate_vnode(kauth_cred_t cred, struct vnode *vp)
500{
501 kauth_cred_t old_audit_cred;
502 struct vnode *old_audit_vp;
503
504 KASSERT((cred != NULL && vp != NULL) || (cred == NULL && vp == NULL),
505 ("audit_rotate_vnode: cred %p vp %p", cred, vp));
506
507
508 mtx_lock(&audit_mtx);
509 if (audit_enabled && (NULL == vp)) {
510 /* Auditing is currently enabled but will be disabled. */
511
512 /*
513 * Disable auditing now so nothing more is added while the
514 * audit worker thread is draining the audit record queue.
515 */
516 audit_enabled = 0;
517
518 /*
519 * Drain the auditing queue by inserting a drain record at the
520 * end of the queue and waiting for the audit worker thread
521 * to find this record and signal that it is done before
522 * we close the audit trail.
523 */
524 audit_q_draining = 1;
525 while (audit_q_len >= audit_qctrl.aq_hiwater) {
526 cv_wait(&audit_watermark_cv, &audit_mtx);
527 }
528 TAILQ_INSERT_TAIL(&audit_q, &audit_drain_kar, k_q);
529 audit_q_len++;
530 cv_signal(&audit_worker_cv);
531 }
532
533 /* If the audit queue is draining then wait here until it's done. */
534 while (audit_q_draining) {
535 cv_wait(&audit_drain_cv, &audit_mtx);
536 }
537 mtx_unlock(&audit_mtx);
538
539
540 /*
541 * Rotate the vnode/cred, and clear the rotate flag so that we will
542 * send a rotate trigger if the new file fills.
543 */
544 AUDIT_WORKER_SX_XLOCK();
545 old_audit_cred = audit_ctx.vc_ucred;
546 old_audit_vp = audit_vp;
547 audit_ctx.vc_ucred = cred;
548 audit_vp = vp;
549 audit_file_rotate_wait = 0;
550 audit_enabled = (audit_vp != NULL);
551 AUDIT_WORKER_SX_XUNLOCK();
552
553 /*
554 * If there was an old vnode/credential, close and free.
555 */
556 if (old_audit_vp != NULL) {
557 if (vnode_get(old_audit_vp) == 0) {
558 vn_close(old_audit_vp, AUDIT_CLOSE_FLAGS,
559 ctx: vfs_context_kernel());
560 vnode_put(vp: old_audit_vp);
561 } else {
562 printf("audit_rotate_vnode: Couldn't close "
563 "audit file.\n");
564 }
565 kauth_cred_unref(&old_audit_cred);
566 }
567}
568
569void
570audit_worker_init(void)
571{
572 AUDIT_WORKER_SX_INIT();
573 kernel_thread_start(continuation: (thread_continue_t)audit_worker, NULL,
574 new_thread: &audit_thread);
575 if (audit_thread == THREAD_NULL) {
576 panic("audit_worker_init: Couldn't create audit_worker thread");
577 }
578}
579