audit_pipe.c revision 186662
1/*-
2 * Copyright (c) 2006 Robert N. M. Watson
3 * Copyright (c) 2008 Apple, Inc.
4 * All rights reserved.
5 *
6 * This software was developed by Robert Watson for the TrustedBSD Project.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 */
29
30#include <sys/cdefs.h>
31__FBSDID("$FreeBSD: head/sys/security/audit/audit_pipe.c 186662 2008-12-31 23:22:45Z rwatson $");
32
33#include <sys/param.h>
34#include <sys/condvar.h>
35#include <sys/conf.h>
36#include <sys/eventhandler.h>
37#include <sys/filio.h>
38#include <sys/kernel.h>
39#include <sys/lock.h>
40#include <sys/malloc.h>
41#include <sys/mutex.h>
42#include <sys/poll.h>
43#include <sys/proc.h>
44#include <sys/queue.h>
45#include <sys/rwlock.h>
46#include <sys/selinfo.h>
47#include <sys/sigio.h>
48#include <sys/signal.h>
49#include <sys/signalvar.h>
50#include <sys/sx.h>
51#include <sys/systm.h>
52#include <sys/uio.h>
53
54#include <security/audit/audit.h>
55#include <security/audit/audit_ioctl.h>
56#include <security/audit/audit_private.h>
57
58/*
59 * Implementation of a clonable special device providing a live stream of BSM
60 * audit data.  Consumers receive a "tee" of the system audit trail by
61 * default, but may also define alternative event selections using ioctls.
62 * This interface provides unreliable but timely access to audit events.
63 * Consumers should be very careful to avoid introducing event cycles.
64 */
65
66/*
67 * Memory types.
68 */
69static MALLOC_DEFINE(M_AUDIT_PIPE, "audit_pipe", "Audit pipes");
70static MALLOC_DEFINE(M_AUDIT_PIPE_ENTRY, "audit_pipeent",
71    "Audit pipe entries and buffers");
72static MALLOC_DEFINE(M_AUDIT_PIPE_PRESELECT, "audit_pipe_presel",
73    "Audit pipe preselection structure");
74
75/*
76 * Audit pipe buffer parameters.
77 */
78#define	AUDIT_PIPE_QLIMIT_DEFAULT	(128)
79#define	AUDIT_PIPE_QLIMIT_MIN		(0)
80#define	AUDIT_PIPE_QLIMIT_MAX		(1024)
81
82/*
83 * Description of an entry in an audit_pipe.
84 */
85struct audit_pipe_entry {
86	void				*ape_record;
87	u_int				 ape_record_len;
88	TAILQ_ENTRY(audit_pipe_entry)	 ape_queue;
89};
90
91/*
92 * Audit pipes allow processes to express "interest" in the set of records
93 * that are delivered via the pipe.  They do this in a similar manner to the
94 * mechanism for audit trail configuration, by expressing two global masks,
95 * and optionally expressing per-auid masks.  The following data structure is
96 * the per-auid mask description.  The global state is stored in the audit
97 * pipe data structure.
98 *
99 * We may want to consider a more space/time-efficient data structure once
100 * usage patterns for per-auid specifications are clear.
101 */
102struct audit_pipe_preselect {
103	au_id_t					 app_auid;
104	au_mask_t				 app_mask;
105	TAILQ_ENTRY(audit_pipe_preselect)	 app_list;
106};
107
108/*
109 * Description of an individual audit_pipe.  Consists largely of a bounded
110 * length queue.
111 */
112#define	AUDIT_PIPE_ASYNC	0x00000001
113#define	AUDIT_PIPE_NBIO		0x00000002
114struct audit_pipe {
115	int				 ap_open;	/* Device open? */
116	u_int				 ap_flags;
117
118	struct selinfo			 ap_selinfo;
119	struct sigio			*ap_sigio;
120
121	/*
122	 * Per-pipe mutex protecting most fields in this data structure.
123	 */
124	struct mtx			 ap_mtx;
125
126	/*
127	 * Per-pipe sleep lock serializing user-generated reads and flushes.
128	 * uiomove() is called to copy out the current head record's data
129	 * while the record remains in the queue, so we prevent other threads
130	 * from removing it using this lock.
131	 */
132	struct sx			 ap_sx;
133
134	/*
135	 * Condition variable to signal when data has been delivered to a
136	 * pipe.
137	 */
138	struct cv			 ap_cv;
139
140	/*
141	 * Various queue-reated variables: qlen and qlimit are a count of
142	 * records in the queue; qbyteslen is the number of bytes of data
143	 * across all records, and qoffset is the amount read so far of the
144	 * first record in the queue.  The number of bytes available for
145	 * reading in the queue is qbyteslen - qoffset.
146	 */
147	u_int				 ap_qlen;
148	u_int				 ap_qlimit;
149	u_int				 ap_qbyteslen;
150	u_int				 ap_qoffset;
151
152	/*
153	 * Per-pipe operation statistics.
154	 */
155	u_int64_t			 ap_inserts;	/* Records added. */
156	u_int64_t			 ap_reads;	/* Records read. */
157	u_int64_t			 ap_drops;	/* Records dropped. */
158
159	/*
160	 * Fields relating to pipe interest: global masks for unmatched
161	 * processes (attributable, non-attributable), and a list of specific
162	 * interest specifications by auid.
163	 */
164	int				 ap_preselect_mode;
165	au_mask_t			 ap_preselect_flags;
166	au_mask_t			 ap_preselect_naflags;
167	TAILQ_HEAD(, audit_pipe_preselect)	ap_preselect_list;
168
169	/*
170	 * Current pending record list.  Protected by a combination of ap_mtx
171	 * and ap_sx.  Note particularly that *both* locks are required to
172	 * remove a record from the head of the queue, as an in-progress read
173	 * may sleep while copying and therefore cannot hold ap_mtx.
174	 */
175	TAILQ_HEAD(, audit_pipe_entry)	 ap_queue;
176
177	/*
178	 * Global pipe list.
179	 */
180	TAILQ_ENTRY(audit_pipe)		 ap_list;
181};
182
183#define	AUDIT_PIPE_LOCK(ap)		mtx_lock(&(ap)->ap_mtx)
184#define	AUDIT_PIPE_LOCK_ASSERT(ap)	mtx_assert(&(ap)->ap_mtx, MA_OWNED)
185#define	AUDIT_PIPE_LOCK_DESTROY(ap)	mtx_destroy(&(ap)->ap_mtx)
186#define	AUDIT_PIPE_LOCK_INIT(ap)	mtx_init(&(ap)->ap_mtx, \
187					    "audit_pipe_mtx", NULL, MTX_DEF)
188#define	AUDIT_PIPE_UNLOCK(ap)		mtx_unlock(&(ap)->ap_mtx)
189#define	AUDIT_PIPE_MTX(ap)		(&(ap)->ap_mtx)
190
191#define	AUDIT_PIPE_SX_LOCK_DESTROY(ap)	sx_destroy(&(ap)->ap_sx)
192#define	AUDIT_PIPE_SX_LOCK_INIT(ap)	sx_init(&(ap)->ap_sx, "audit_pipe_sx")
193#define	AUDIT_PIPE_SX_XLOCK_ASSERT(ap)	sx_assert(&(ap)->ap_sx, SA_XLOCKED)
194#define	AUDIT_PIPE_SX_XLOCK_SIG(ap)	sx_xlock_sig(&(ap)->ap_sx)
195#define	AUDIT_PIPE_SX_XUNLOCK(ap)	sx_xunlock(&(ap)->ap_sx)
196
197/*
198 * Global list of audit pipes, rwlock to protect it.  Individual record
199 * queues on pipes are protected by per-pipe locks; these locks synchronize
200 * between threads walking the list to deliver to individual pipes and add/
201 * remove of pipes, and are mostly acquired for read.
202 */
203static TAILQ_HEAD(, audit_pipe)	 audit_pipe_list;
204static struct rwlock		 audit_pipe_lock;
205
206#define	AUDIT_PIPE_LIST_LOCK_INIT()	rw_init(&audit_pipe_lock, \
207					    "audit_pipe_list_lock")
208#define	AUDIT_PIPE_LIST_RLOCK()		rw_rlock(&audit_pipe_lock)
209#define	AUDIT_PIPE_LIST_RUNLOCK()	rw_runlock(&audit_pipe_lock)
210#define	AUDIT_PIPE_LIST_WLOCK()		rw_wlock(&audit_pipe_lock)
211#define	AUDIT_PIPE_LIST_WLOCK_ASSERT()	rw_assert(&audit_pipe_lock, \
212					    RA_WLOCKED)
213#define	AUDIT_PIPE_LIST_WUNLOCK()	rw_wunlock(&audit_pipe_lock)
214
215/*
216 * Cloning related variables and constants.
217 */
218#define	AUDIT_PIPE_NAME		"auditpipe"
219static eventhandler_tag		 audit_pipe_eh_tag;
220static struct clonedevs		*audit_pipe_clones;
221
222/*
223 * Special device methods and definition.
224 */
225static d_open_t		audit_pipe_open;
226static d_close_t	audit_pipe_close;
227static d_read_t		audit_pipe_read;
228static d_ioctl_t	audit_pipe_ioctl;
229static d_poll_t		audit_pipe_poll;
230static d_kqfilter_t	audit_pipe_kqfilter;
231
232static struct cdevsw	audit_pipe_cdevsw = {
233	.d_version =	D_VERSION,
234	.d_flags =	D_PSEUDO | D_NEEDGIANT | D_NEEDMINOR,
235	.d_open =	audit_pipe_open,
236	.d_close =	audit_pipe_close,
237	.d_read =	audit_pipe_read,
238	.d_ioctl =	audit_pipe_ioctl,
239	.d_poll =	audit_pipe_poll,
240	.d_kqfilter =	audit_pipe_kqfilter,
241	.d_name =	AUDIT_PIPE_NAME,
242};
243
244static int	audit_pipe_kqread(struct knote *note, long hint);
245static void	audit_pipe_kqdetach(struct knote *note);
246
247static struct filterops audit_pipe_read_filterops = {
248	.f_isfd =	1,
249	.f_attach =	NULL,
250	.f_detach =	audit_pipe_kqdetach,
251	.f_event =	audit_pipe_kqread,
252};
253
254/*
255 * Some global statistics on audit pipes.
256 */
257static int		audit_pipe_count;	/* Current number of pipes. */
258static u_int64_t	audit_pipe_ever;	/* Pipes ever allocated. */
259static u_int64_t	audit_pipe_records;	/* Records seen. */
260static u_int64_t	audit_pipe_drops;	/* Global record drop count. */
261
262/*
263 * Free an audit pipe entry.
264 */
265static void
266audit_pipe_entry_free(struct audit_pipe_entry *ape)
267{
268
269	free(ape->ape_record, M_AUDIT_PIPE_ENTRY);
270	free(ape, M_AUDIT_PIPE_ENTRY);
271}
272
273/*
274 * Find an audit pipe preselection specification for an auid, if any.
275 */
276static struct audit_pipe_preselect *
277audit_pipe_preselect_find(struct audit_pipe *ap, au_id_t auid)
278{
279	struct audit_pipe_preselect *app;
280
281	AUDIT_PIPE_LOCK_ASSERT(ap);
282
283	TAILQ_FOREACH(app, &ap->ap_preselect_list, app_list) {
284		if (app->app_auid == auid)
285			return (app);
286	}
287	return (NULL);
288}
289
290/*
291 * Query the per-pipe mask for a specific auid.
292 */
293static int
294audit_pipe_preselect_get(struct audit_pipe *ap, au_id_t auid,
295    au_mask_t *maskp)
296{
297	struct audit_pipe_preselect *app;
298	int error;
299
300	AUDIT_PIPE_LOCK(ap);
301	app = audit_pipe_preselect_find(ap, auid);
302	if (app != NULL) {
303		*maskp = app->app_mask;
304		error = 0;
305	} else
306		error = ENOENT;
307	AUDIT_PIPE_UNLOCK(ap);
308	return (error);
309}
310
311/*
312 * Set the per-pipe mask for a specific auid.  Add a new entry if needed;
313 * otherwise, update the current entry.
314 */
315static void
316audit_pipe_preselect_set(struct audit_pipe *ap, au_id_t auid, au_mask_t mask)
317{
318	struct audit_pipe_preselect *app, *app_new;
319
320	/*
321	 * Pessimistically assume that the auid doesn't already have a mask
322	 * set, and allocate.  We will free it if it is unneeded.
323	 */
324	app_new = malloc(sizeof(*app_new), M_AUDIT_PIPE_PRESELECT, M_WAITOK);
325	AUDIT_PIPE_LOCK(ap);
326	app = audit_pipe_preselect_find(ap, auid);
327	if (app == NULL) {
328		app = app_new;
329		app_new = NULL;
330		app->app_auid = auid;
331		TAILQ_INSERT_TAIL(&ap->ap_preselect_list, app, app_list);
332	}
333	app->app_mask = mask;
334	AUDIT_PIPE_UNLOCK(ap);
335	if (app_new != NULL)
336		free(app_new, M_AUDIT_PIPE_PRESELECT);
337}
338
339/*
340 * Delete a per-auid mask on an audit pipe.
341 */
342static int
343audit_pipe_preselect_delete(struct audit_pipe *ap, au_id_t auid)
344{
345	struct audit_pipe_preselect *app;
346	int error;
347
348	AUDIT_PIPE_LOCK(ap);
349	app = audit_pipe_preselect_find(ap, auid);
350	if (app != NULL) {
351		TAILQ_REMOVE(&ap->ap_preselect_list, app, app_list);
352		error = 0;
353	} else
354		error = ENOENT;
355	AUDIT_PIPE_UNLOCK(ap);
356	if (app != NULL)
357		free(app, M_AUDIT_PIPE_PRESELECT);
358	return (error);
359}
360
361/*
362 * Delete all per-auid masks on an audit pipe.
363 */
364static void
365audit_pipe_preselect_flush_locked(struct audit_pipe *ap)
366{
367	struct audit_pipe_preselect *app;
368
369	AUDIT_PIPE_LOCK_ASSERT(ap);
370
371	while ((app = TAILQ_FIRST(&ap->ap_preselect_list)) != NULL) {
372		TAILQ_REMOVE(&ap->ap_preselect_list, app, app_list);
373		free(app, M_AUDIT_PIPE_PRESELECT);
374	}
375}
376
377static void
378audit_pipe_preselect_flush(struct audit_pipe *ap)
379{
380
381	AUDIT_PIPE_LOCK(ap);
382	audit_pipe_preselect_flush_locked(ap);
383	AUDIT_PIPE_UNLOCK(ap);
384}
385
386/*-
387 * Determine whether a specific audit pipe matches a record with these
388 * properties.  Algorithm is as follows:
389 *
390 * - If the pipe is configured to track the default trail configuration, then
391 *   use the results of global preselection matching.
392 * - If not, search for a specifically configured auid entry matching the
393 *   event.  If an entry is found, use that.
394 * - Otherwise, use the default flags or naflags configured for the pipe.
395 */
396static int
397audit_pipe_preselect_check(struct audit_pipe *ap, au_id_t auid,
398    au_event_t event, au_class_t class, int sorf, int trail_preselect)
399{
400	struct audit_pipe_preselect *app;
401
402	AUDIT_PIPE_LOCK_ASSERT(ap);
403
404	switch (ap->ap_preselect_mode) {
405	case AUDITPIPE_PRESELECT_MODE_TRAIL:
406		return (trail_preselect);
407
408	case AUDITPIPE_PRESELECT_MODE_LOCAL:
409		app = audit_pipe_preselect_find(ap, auid);
410		if (app == NULL) {
411			if (auid == AU_DEFAUDITID)
412				return (au_preselect(event, class,
413				    &ap->ap_preselect_naflags, sorf));
414			else
415				return (au_preselect(event, class,
416				    &ap->ap_preselect_flags, sorf));
417		} else
418			return (au_preselect(event, class, &app->app_mask,
419			    sorf));
420
421	default:
422		panic("audit_pipe_preselect_check: mode %d",
423		    ap->ap_preselect_mode);
424	}
425
426	return (0);
427}
428
429/*
430 * Determine whether there exists a pipe interested in a record with specific
431 * properties.
432 */
433int
434audit_pipe_preselect(au_id_t auid, au_event_t event, au_class_t class,
435    int sorf, int trail_preselect)
436{
437	struct audit_pipe *ap;
438
439	AUDIT_PIPE_LIST_RLOCK();
440	TAILQ_FOREACH(ap, &audit_pipe_list, ap_list) {
441		AUDIT_PIPE_LOCK(ap);
442		if (audit_pipe_preselect_check(ap, auid, event, class, sorf,
443		    trail_preselect)) {
444			AUDIT_PIPE_UNLOCK(ap);
445			AUDIT_PIPE_LIST_RUNLOCK();
446			return (1);
447		}
448		AUDIT_PIPE_UNLOCK(ap);
449	}
450	AUDIT_PIPE_LIST_RUNLOCK();
451	return (0);
452}
453
454/*
455 * Append individual record to a queue -- allocate queue-local buffer, and
456 * add to the queue.  If the queue is full or we can't allocate memory, drop
457 * the newest record.
458 */
459static void
460audit_pipe_append(struct audit_pipe *ap, void *record, u_int record_len)
461{
462	struct audit_pipe_entry *ape;
463
464	AUDIT_PIPE_LOCK_ASSERT(ap);
465
466	if (ap->ap_qlen >= ap->ap_qlimit) {
467		ap->ap_drops++;
468		audit_pipe_drops++;
469		return;
470	}
471
472	ape = malloc(sizeof(*ape), M_AUDIT_PIPE_ENTRY, M_NOWAIT | M_ZERO);
473	if (ape == NULL) {
474		ap->ap_drops++;
475		audit_pipe_drops++;
476		return;
477	}
478
479	ape->ape_record = malloc(record_len, M_AUDIT_PIPE_ENTRY, M_NOWAIT);
480	if (ape->ape_record == NULL) {
481		free(ape, M_AUDIT_PIPE_ENTRY);
482		ap->ap_drops++;
483		audit_pipe_drops++;
484		return;
485	}
486
487	bcopy(record, ape->ape_record, record_len);
488	ape->ape_record_len = record_len;
489
490	TAILQ_INSERT_TAIL(&ap->ap_queue, ape, ape_queue);
491	ap->ap_inserts++;
492	ap->ap_qlen++;
493	ap->ap_qbyteslen += ape->ape_record_len;
494	selwakeuppri(&ap->ap_selinfo, PSOCK);
495	KNOTE_LOCKED(&ap->ap_selinfo.si_note, 0);
496	if (ap->ap_flags & AUDIT_PIPE_ASYNC)
497		pgsigio(&ap->ap_sigio, SIGIO, 0);
498	cv_broadcast(&ap->ap_cv);
499}
500
501/*
502 * audit_pipe_submit(): audit_worker submits audit records via this
503 * interface, which arranges for them to be delivered to pipe queues.
504 */
505void
506audit_pipe_submit(au_id_t auid, au_event_t event, au_class_t class, int sorf,
507    int trail_select, void *record, u_int record_len)
508{
509	struct audit_pipe *ap;
510
511	/*
512	 * Lockless read to avoid lock overhead if pipes are not in use.
513	 */
514	if (TAILQ_FIRST(&audit_pipe_list) == NULL)
515		return;
516
517	AUDIT_PIPE_LIST_RLOCK();
518	TAILQ_FOREACH(ap, &audit_pipe_list, ap_list) {
519		AUDIT_PIPE_LOCK(ap);
520		if (audit_pipe_preselect_check(ap, auid, event, class, sorf,
521		    trail_select))
522			audit_pipe_append(ap, record, record_len);
523		AUDIT_PIPE_UNLOCK(ap);
524	}
525	AUDIT_PIPE_LIST_RUNLOCK();
526
527	/* Unlocked increment. */
528	audit_pipe_records++;
529}
530
531/*
532 * audit_pipe_submit_user(): the same as audit_pipe_submit(), except that
533 * since we don't currently have selection information available, it is
534 * delivered to the pipe unconditionally.
535 *
536 * XXXRW: This is a bug.  The BSM check routine for submitting a user record
537 * should parse that information and return it.
538 */
539void
540audit_pipe_submit_user(void *record, u_int record_len)
541{
542	struct audit_pipe *ap;
543
544	/*
545	 * Lockless read to avoid lock overhead if pipes are not in use.
546	 */
547	if (TAILQ_FIRST(&audit_pipe_list) == NULL)
548		return;
549
550	AUDIT_PIPE_LIST_RLOCK();
551	TAILQ_FOREACH(ap, &audit_pipe_list, ap_list) {
552		AUDIT_PIPE_LOCK(ap);
553		audit_pipe_append(ap, record, record_len);
554		AUDIT_PIPE_UNLOCK(ap);
555	}
556	AUDIT_PIPE_LIST_RUNLOCK();
557
558	/* Unlocked increment. */
559	audit_pipe_records++;
560}
561
562/*
563 * Allocate a new audit pipe.  Connects the pipe, on success, to the global
564 * list and updates statistics.
565 */
566static struct audit_pipe *
567audit_pipe_alloc(void)
568{
569	struct audit_pipe *ap;
570
571	AUDIT_PIPE_LIST_WLOCK_ASSERT();
572
573	ap = malloc(sizeof(*ap), M_AUDIT_PIPE, M_NOWAIT | M_ZERO);
574	if (ap == NULL)
575		return (NULL);
576	ap->ap_qlimit = AUDIT_PIPE_QLIMIT_DEFAULT;
577	TAILQ_INIT(&ap->ap_queue);
578	knlist_init(&ap->ap_selinfo.si_note, AUDIT_PIPE_MTX(ap), NULL, NULL,
579	    NULL);
580	AUDIT_PIPE_LOCK_INIT(ap);
581	AUDIT_PIPE_SX_LOCK_INIT(ap);
582	cv_init(&ap->ap_cv, "audit_pipe");
583
584	/*
585	 * Default flags, naflags, and auid-specific preselection settings to
586	 * 0.  Initialize the mode to the global trail so that if praudit(1)
587	 * is run on /dev/auditpipe, it sees events associated with the
588	 * default trail.  Pipe-aware application can clear the flag, set
589	 * custom masks, and flush the pipe as needed.
590	 */
591	bzero(&ap->ap_preselect_flags, sizeof(ap->ap_preselect_flags));
592	bzero(&ap->ap_preselect_naflags, sizeof(ap->ap_preselect_naflags));
593	TAILQ_INIT(&ap->ap_preselect_list);
594	ap->ap_preselect_mode = AUDITPIPE_PRESELECT_MODE_TRAIL;
595
596	/*
597	 * Add to global list and update global statistics.
598	 */
599	TAILQ_INSERT_HEAD(&audit_pipe_list, ap, ap_list);
600	audit_pipe_count++;
601	audit_pipe_ever++;
602
603	return (ap);
604}
605
606/*
607 * Flush all records currently present in an audit pipe; assume mutex is held.
608 */
609static void
610audit_pipe_flush(struct audit_pipe *ap)
611{
612	struct audit_pipe_entry *ape;
613
614	AUDIT_PIPE_LOCK_ASSERT(ap);
615
616	while ((ape = TAILQ_FIRST(&ap->ap_queue)) != NULL) {
617		TAILQ_REMOVE(&ap->ap_queue, ape, ape_queue);
618		ap->ap_qbyteslen -= ape->ape_record_len;
619		audit_pipe_entry_free(ape);
620		ap->ap_qlen--;
621	}
622	ap->ap_qoffset = 0;
623
624	KASSERT(ap->ap_qlen == 0, ("audit_pipe_free: ap_qbyteslen"));
625	KASSERT(ap->ap_qbyteslen == 0, ("audit_pipe_flush: ap_qbyteslen"));
626}
627
628/*
629 * Free an audit pipe; this means freeing all preselection state and all
630 * records in the pipe.  Assumes global write lock and pipe mutex are held to
631 * prevent any new records from being inserted during the free, and that the
632 * audit pipe is still on the global list.
633 */
634static void
635audit_pipe_free(struct audit_pipe *ap)
636{
637
638	AUDIT_PIPE_LIST_WLOCK_ASSERT();
639	AUDIT_PIPE_LOCK_ASSERT(ap);
640
641	audit_pipe_preselect_flush_locked(ap);
642	audit_pipe_flush(ap);
643	cv_destroy(&ap->ap_cv);
644	AUDIT_PIPE_SX_LOCK_DESTROY(ap);
645	AUDIT_PIPE_LOCK_DESTROY(ap);
646	knlist_destroy(&ap->ap_selinfo.si_note);
647	TAILQ_REMOVE(&audit_pipe_list, ap, ap_list);
648	free(ap, M_AUDIT_PIPE);
649	audit_pipe_count--;
650}
651
652/*
653 * Audit pipe clone routine -- provide specific requested audit pipe, or a
654 * fresh one if a specific one is not requested.
655 */
656static void
657audit_pipe_clone(void *arg, struct ucred *cred, char *name, int namelen,
658    struct cdev **dev)
659{
660	int i, u;
661
662	if (*dev != NULL)
663		return;
664
665	if (strcmp(name, AUDIT_PIPE_NAME) == 0)
666		u = -1;
667	else if (dev_stdclone(name, NULL, AUDIT_PIPE_NAME, &u) != 1)
668		return;
669
670	i = clone_create(&audit_pipe_clones, &audit_pipe_cdevsw, &u, dev, 0);
671	if (i) {
672		*dev = make_dev(&audit_pipe_cdevsw, u, UID_ROOT,
673		    GID_WHEEL, 0600, "%s%d", AUDIT_PIPE_NAME, u);
674		if (*dev != NULL) {
675			dev_ref(*dev);
676			(*dev)->si_flags |= SI_CHEAPCLONE;
677		}
678	}
679}
680
681/*
682 * Audit pipe open method.  Explicit privilege check isn't used as this
683 * allows file permissions on the special device to be used to grant audit
684 * review access.  Those file permissions should be managed carefully.
685 */
686static int
687audit_pipe_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
688{
689	struct audit_pipe *ap;
690
691	AUDIT_PIPE_LIST_WLOCK();
692	ap = dev->si_drv1;
693	if (ap == NULL) {
694		ap = audit_pipe_alloc();
695		if (ap == NULL) {
696			AUDIT_PIPE_LIST_WUNLOCK();
697			return (ENOMEM);
698		}
699		dev->si_drv1 = ap;
700	} else {
701		KASSERT(ap->ap_open, ("audit_pipe_open: ap && !ap_open"));
702		AUDIT_PIPE_LIST_WUNLOCK();
703		return (EBUSY);
704	}
705	ap->ap_open = 1;	/* No lock required yet. */
706	AUDIT_PIPE_LIST_WUNLOCK();
707	fsetown(td->td_proc->p_pid, &ap->ap_sigio);
708	return (0);
709}
710
711/*
712 * Close audit pipe, tear down all records, etc.
713 */
714static int
715audit_pipe_close(struct cdev *dev, int fflag, int devtype, struct thread *td)
716{
717	struct audit_pipe *ap;
718
719	ap = dev->si_drv1;
720	KASSERT(ap != NULL, ("audit_pipe_close: ap == NULL"));
721	KASSERT(ap->ap_open, ("audit_pipe_close: !ap_open"));
722
723	funsetown(&ap->ap_sigio);
724	AUDIT_PIPE_LIST_WLOCK();
725	AUDIT_PIPE_LOCK(ap);
726	ap->ap_open = 0;
727	audit_pipe_free(ap);
728	dev->si_drv1 = NULL;
729	AUDIT_PIPE_LIST_WUNLOCK();
730	return (0);
731}
732
733/*
734 * Audit pipe ioctl() routine.  Handle file descriptor and audit pipe layer
735 * commands.
736 */
737static int
738audit_pipe_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag,
739    struct thread *td)
740{
741	struct auditpipe_ioctl_preselect *aip;
742	struct audit_pipe *ap;
743	au_mask_t *maskp;
744	int error, mode;
745	au_id_t auid;
746
747	ap = dev->si_drv1;
748	KASSERT(ap != NULL, ("audit_pipe_ioctl: ap == NULL"));
749
750	/*
751	 * Audit pipe ioctls: first come standard device node ioctls, then
752	 * manipulation of pipe settings, and finally, statistics query
753	 * ioctls.
754	 */
755	switch (cmd) {
756	case FIONBIO:
757		AUDIT_PIPE_LOCK(ap);
758		if (*(int *)data)
759			ap->ap_flags |= AUDIT_PIPE_NBIO;
760		else
761			ap->ap_flags &= ~AUDIT_PIPE_NBIO;
762		AUDIT_PIPE_UNLOCK(ap);
763		error = 0;
764		break;
765
766	case FIONREAD:
767		AUDIT_PIPE_LOCK(ap);
768		*(int *)data = ap->ap_qbyteslen - ap->ap_qoffset;
769		AUDIT_PIPE_UNLOCK(ap);
770		error = 0;
771		break;
772
773	case FIOASYNC:
774		AUDIT_PIPE_LOCK(ap);
775		if (*(int *)data)
776			ap->ap_flags |= AUDIT_PIPE_ASYNC;
777		else
778			ap->ap_flags &= ~AUDIT_PIPE_ASYNC;
779		AUDIT_PIPE_UNLOCK(ap);
780		error = 0;
781		break;
782
783	case FIOSETOWN:
784		error = fsetown(*(int *)data, &ap->ap_sigio);
785		break;
786
787	case FIOGETOWN:
788		*(int *)data = fgetown(&ap->ap_sigio);
789		error = 0;
790		break;
791
792	case AUDITPIPE_GET_QLEN:
793		*(u_int *)data = ap->ap_qlen;
794		error = 0;
795		break;
796
797	case AUDITPIPE_GET_QLIMIT:
798		*(u_int *)data = ap->ap_qlimit;
799		error = 0;
800		break;
801
802	case AUDITPIPE_SET_QLIMIT:
803		/* Lockless integer write. */
804		if (*(u_int *)data >= AUDIT_PIPE_QLIMIT_MIN ||
805		    *(u_int *)data <= AUDIT_PIPE_QLIMIT_MAX) {
806			ap->ap_qlimit = *(u_int *)data;
807			error = 0;
808		} else
809			error = EINVAL;
810		break;
811
812	case AUDITPIPE_GET_QLIMIT_MIN:
813		*(u_int *)data = AUDIT_PIPE_QLIMIT_MIN;
814		error = 0;
815		break;
816
817	case AUDITPIPE_GET_QLIMIT_MAX:
818		*(u_int *)data = AUDIT_PIPE_QLIMIT_MAX;
819		error = 0;
820		break;
821
822	case AUDITPIPE_GET_PRESELECT_FLAGS:
823		AUDIT_PIPE_LOCK(ap);
824		maskp = (au_mask_t *)data;
825		*maskp = ap->ap_preselect_flags;
826		AUDIT_PIPE_UNLOCK(ap);
827		error = 0;
828		break;
829
830	case AUDITPIPE_SET_PRESELECT_FLAGS:
831		AUDIT_PIPE_LOCK(ap);
832		maskp = (au_mask_t *)data;
833		ap->ap_preselect_flags = *maskp;
834		AUDIT_PIPE_UNLOCK(ap);
835		error = 0;
836		break;
837
838	case AUDITPIPE_GET_PRESELECT_NAFLAGS:
839		AUDIT_PIPE_LOCK(ap);
840		maskp = (au_mask_t *)data;
841		*maskp = ap->ap_preselect_naflags;
842		AUDIT_PIPE_UNLOCK(ap);
843		error = 0;
844		break;
845
846	case AUDITPIPE_SET_PRESELECT_NAFLAGS:
847		AUDIT_PIPE_LOCK(ap);
848		maskp = (au_mask_t *)data;
849		ap->ap_preselect_naflags = *maskp;
850		AUDIT_PIPE_UNLOCK(ap);
851		error = 0;
852		break;
853
854	case AUDITPIPE_GET_PRESELECT_AUID:
855		aip = (struct auditpipe_ioctl_preselect *)data;
856		error = audit_pipe_preselect_get(ap, aip->aip_auid,
857		    &aip->aip_mask);
858		break;
859
860	case AUDITPIPE_SET_PRESELECT_AUID:
861		aip = (struct auditpipe_ioctl_preselect *)data;
862		audit_pipe_preselect_set(ap, aip->aip_auid, aip->aip_mask);
863		error = 0;
864		break;
865
866	case AUDITPIPE_DELETE_PRESELECT_AUID:
867		auid = *(au_id_t *)data;
868		error = audit_pipe_preselect_delete(ap, auid);
869		break;
870
871	case AUDITPIPE_FLUSH_PRESELECT_AUID:
872		audit_pipe_preselect_flush(ap);
873		error = 0;
874		break;
875
876	case AUDITPIPE_GET_PRESELECT_MODE:
877		AUDIT_PIPE_LOCK(ap);
878		*(int *)data = ap->ap_preselect_mode;
879		AUDIT_PIPE_UNLOCK(ap);
880		error = 0;
881		break;
882
883	case AUDITPIPE_SET_PRESELECT_MODE:
884		mode = *(int *)data;
885		switch (mode) {
886		case AUDITPIPE_PRESELECT_MODE_TRAIL:
887		case AUDITPIPE_PRESELECT_MODE_LOCAL:
888			AUDIT_PIPE_LOCK(ap);
889			ap->ap_preselect_mode = mode;
890			AUDIT_PIPE_UNLOCK(ap);
891			error = 0;
892			break;
893
894		default:
895			error = EINVAL;
896		}
897		break;
898
899	case AUDITPIPE_FLUSH:
900		if (AUDIT_PIPE_SX_XLOCK_SIG(ap) != 0)
901			return (EINTR);
902		AUDIT_PIPE_LOCK(ap);
903		audit_pipe_flush(ap);
904		AUDIT_PIPE_UNLOCK(ap);
905		AUDIT_PIPE_SX_XUNLOCK(ap);
906		error = 0;
907		break;
908
909	case AUDITPIPE_GET_MAXAUDITDATA:
910		*(u_int *)data = MAXAUDITDATA;
911		error = 0;
912		break;
913
914	case AUDITPIPE_GET_INSERTS:
915		*(u_int *)data = ap->ap_inserts;
916		error = 0;
917		break;
918
919	case AUDITPIPE_GET_READS:
920		*(u_int *)data = ap->ap_reads;
921		error = 0;
922		break;
923
924	case AUDITPIPE_GET_DROPS:
925		*(u_int *)data = ap->ap_drops;
926		error = 0;
927		break;
928
929	case AUDITPIPE_GET_TRUNCATES:
930		*(u_int *)data = 0;
931		error = 0;
932		break;
933
934	default:
935		error = ENOTTY;
936	}
937	return (error);
938}
939
940/*
941 * Audit pipe read.  Read one or more partial or complete records to user
942 * memory.
943 */
944static int
945audit_pipe_read(struct cdev *dev, struct uio *uio, int flag)
946{
947	struct audit_pipe_entry *ape;
948	struct audit_pipe *ap;
949	u_int toread;
950	int error;
951
952	ap = dev->si_drv1;
953	KASSERT(ap != NULL, ("audit_pipe_read: ap == NULL"));
954
955	/*
956	 * We hold an sx(9) lock over read and flush because we rely on the
957	 * stability of a record in the queue during uiomove(9).
958	 */
959	if (AUDIT_PIPE_SX_XLOCK_SIG(ap) != 0)
960		return (EINTR);
961	AUDIT_PIPE_LOCK(ap);
962	while (TAILQ_EMPTY(&ap->ap_queue)) {
963		if (ap->ap_flags & AUDIT_PIPE_NBIO) {
964			AUDIT_PIPE_UNLOCK(ap);
965			AUDIT_PIPE_SX_XUNLOCK(ap);
966			return (EAGAIN);
967		}
968		error = cv_wait_sig(&ap->ap_cv, AUDIT_PIPE_MTX(ap));
969		if (error) {
970			AUDIT_PIPE_UNLOCK(ap);
971			AUDIT_PIPE_SX_XUNLOCK(ap);
972			return (error);
973		}
974	}
975
976	/*
977	 * Copy as many remaining bytes from the current record to userspace
978	 * as we can.  Keep processing records until we run out of records in
979	 * the queue, or until the user buffer runs out of space.
980	 *
981	 * Note: we rely on the SX lock to maintain ape's stability here.
982	 */
983	ap->ap_reads++;
984	while ((ape = TAILQ_FIRST(&ap->ap_queue)) != NULL &&
985	    uio->uio_resid > 0) {
986		AUDIT_PIPE_LOCK_ASSERT(ap);
987
988		KASSERT(ape->ape_record_len > ap->ap_qoffset,
989		    ("audit_pipe_read: record_len > qoffset (1)"));
990		toread = MIN(ape->ape_record_len - ap->ap_qoffset,
991		    uio->uio_resid);
992		AUDIT_PIPE_UNLOCK(ap);
993		error = uiomove((char *)ape->ape_record + ap->ap_qoffset,
994		    toread, uio);
995		if (error) {
996			AUDIT_PIPE_SX_XUNLOCK(ap);
997			return (error);
998		}
999
1000		/*
1001		 * If the copy succeeded, update book-keeping, and if no
1002		 * bytes remain in the current record, free it.
1003		 */
1004		AUDIT_PIPE_LOCK(ap);
1005		KASSERT(TAILQ_FIRST(&ap->ap_queue) == ape,
1006		    ("audit_pipe_read: queue out of sync after uiomove"));
1007		ap->ap_qoffset += toread;
1008		KASSERT(ape->ape_record_len >= ap->ap_qoffset,
1009		    ("audit_pipe_read: record_len >= qoffset (2)"));
1010		if (ap->ap_qoffset == ape->ape_record_len) {
1011			TAILQ_REMOVE(&ap->ap_queue, ape, ape_queue);
1012			ap->ap_qbyteslen -= ape->ape_record_len;
1013			audit_pipe_entry_free(ape);
1014			ap->ap_qlen--;
1015			ap->ap_qoffset = 0;
1016		}
1017	}
1018	AUDIT_PIPE_UNLOCK(ap);
1019	AUDIT_PIPE_SX_XUNLOCK(ap);
1020	return (0);
1021}
1022
1023/*
1024 * Audit pipe poll.
1025 */
1026static int
1027audit_pipe_poll(struct cdev *dev, int events, struct thread *td)
1028{
1029	struct audit_pipe *ap;
1030	int revents;
1031
1032	revents = 0;
1033	ap = dev->si_drv1;
1034	KASSERT(ap != NULL, ("audit_pipe_poll: ap == NULL"));
1035
1036	if (events & (POLLIN | POLLRDNORM)) {
1037		AUDIT_PIPE_LOCK(ap);
1038		if (TAILQ_FIRST(&ap->ap_queue) != NULL)
1039			revents |= events & (POLLIN | POLLRDNORM);
1040		else
1041			selrecord(td, &ap->ap_selinfo);
1042		AUDIT_PIPE_UNLOCK(ap);
1043	}
1044	return (revents);
1045}
1046
1047/*
1048 * Audit pipe kqfilter.
1049 */
1050static int
1051audit_pipe_kqfilter(struct cdev *dev, struct knote *kn)
1052{
1053	struct audit_pipe *ap;
1054
1055	ap = dev->si_drv1;
1056	KASSERT(ap != NULL, ("audit_pipe_kqfilter: ap == NULL"));
1057
1058	if (kn->kn_filter != EVFILT_READ)
1059		return (EINVAL);
1060
1061	kn->kn_fop = &audit_pipe_read_filterops;
1062	kn->kn_hook = ap;
1063
1064	AUDIT_PIPE_LOCK(ap);
1065	knlist_add(&ap->ap_selinfo.si_note, kn, 1);
1066	AUDIT_PIPE_UNLOCK(ap);
1067	return (0);
1068}
1069
1070/*
1071 * Return true if there are records available for reading on the pipe.
1072 */
1073static int
1074audit_pipe_kqread(struct knote *kn, long hint)
1075{
1076	struct audit_pipe_entry *ape;
1077	struct audit_pipe *ap;
1078
1079	ap = (struct audit_pipe *)kn->kn_hook;
1080	KASSERT(ap != NULL, ("audit_pipe_kqread: ap == NULL"));
1081
1082	AUDIT_PIPE_LOCK_ASSERT(ap);
1083
1084	if (ap->ap_qlen != 0) {
1085		ape = TAILQ_FIRST(&ap->ap_queue);
1086		KASSERT(ape != NULL, ("audit_pipe_kqread: ape == NULL"));
1087
1088		kn->kn_data = ap->ap_qbyteslen - ap->ap_qoffset;
1089		return (1);
1090	} else {
1091		kn->kn_data = 0;
1092		return (0);
1093	}
1094}
1095
1096/*
1097 * Detach kqueue state from audit pipe.
1098 */
1099static void
1100audit_pipe_kqdetach(struct knote *kn)
1101{
1102	struct audit_pipe *ap;
1103
1104	ap = (struct audit_pipe *)kn->kn_hook;
1105	KASSERT(ap != NULL, ("audit_pipe_kqdetach: ap == NULL"));
1106
1107	AUDIT_PIPE_LOCK(ap);
1108	knlist_remove(&ap->ap_selinfo.si_note, kn, 1);
1109	AUDIT_PIPE_UNLOCK(ap);
1110}
1111
1112/*
1113 * Initialize the audit pipe system.
1114 */
1115static void
1116audit_pipe_init(void *unused)
1117{
1118
1119	TAILQ_INIT(&audit_pipe_list);
1120	AUDIT_PIPE_LIST_LOCK_INIT();
1121
1122	clone_setup(&audit_pipe_clones);
1123	audit_pipe_eh_tag = EVENTHANDLER_REGISTER(dev_clone,
1124	    audit_pipe_clone, 0, 1000);
1125	if (audit_pipe_eh_tag == NULL)
1126		panic("audit_pipe_init: EVENTHANDLER_REGISTER");
1127}
1128
1129SYSINIT(audit_pipe_init, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, audit_pipe_init,
1130    NULL);
1131