xref: /xnu-12377.41.6/bsd/security/audit/audit_session.c (revision bbb1b6f9e71b8cdde6e5cd6f4841f207dee3d828)
1 /*-
2  * Copyright (c) 2008-2009 Apple Inc.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1.  Redistributions of source code must retain the above copyright
9  *     notice, this list of conditions and the following disclaimer.
10  * 2.  Redistributions in binary form must reproduce the above copyright
11  *     notice, this list of conditions and the following disclaimer in the
12  *     documentation and/or other materials provided with the distribution.
13  * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
14  *     its contributors may be used to endorse or promote products derived
15  *     from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS 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 APPLE OR ITS CONTRIBUTORS BE LIABLE FOR
21  * 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,
25  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
26  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27  * POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 #include <stdarg.h>
31 
32 #include <sys/kernel.h>
33 #include <sys/fcntl.h>
34 #include <sys/kauth.h>
35 #include <sys/conf.h>
36 #include <sys/poll.h>
37 #include <sys/priv.h>
38 #include <sys/queue.h>
39 #include <sys/signalvar.h>
40 #include <sys/syscall.h>
41 #include <sys/sysent.h>
42 #include <sys/sysproto.h>
43 #include <sys/systm.h>
44 #include <sys/ucred.h>
45 #include <sys/user.h>
46 
47 #include <miscfs/devfs/devfs.h>
48 
49 #include <libkern/OSAtomic.h>
50 
51 #include <bsm/audit.h>
52 #include <bsm/audit_internal.h>
53 #include <bsm/audit_kevents.h>
54 
55 #include <security/audit/audit.h>
56 #include <security/audit/audit_bsd.h>
57 #include <security/audit/audit_ioctl.h>
58 #include <security/audit/audit_private.h>
59 
60 #include <vm/vm_protos.h>
61 #include <mach/mach_port.h>
62 #include <kern/audit_sessionport.h>
63 #include <kern/ipc_kobject.h>
64 
65 #include <libkern/OSDebug.h>
66 
67 /*
68  * Audit Session Entry.  This is treated as an object with public and private
69  * data.   The se_auinfo field is the only information that is public and
70  * needs to be the first entry.
71  */
72 struct au_sentry {
73 	auditinfo_addr_t        se_auinfo;      /* Public audit session data. */
74 #define se_asid         se_auinfo.ai_asid
75 #define se_auid         se_auinfo.ai_auid
76 #define se_mask         se_auinfo.ai_mask
77 #define se_termid       se_auinfo.ai_termid
78 #define se_flags        se_auinfo.ai_flags
79 
80 	long                    se_refcnt;      /* Reference count. */
81 	long                    se_procnt;      /* Processes in session. */
82 	ipc_port_t              se_port;        /* Session port. */
83 	union {
84 		LIST_ENTRY(au_sentry)   se_link;        /* Hash bucket link list (1) */
85 		struct smr_node         se_smr_node;
86 	};
87 };
88 typedef struct au_sentry au_sentry_t;
89 
90 #define AU_SENTRY_PTR(aia_p)    ((au_sentry_t *)(aia_p))
91 
92 /*
93  * The default au_sentry/auditinfo_addr entry for ucred.
94  */
95 
96 static au_sentry_t audit_default_se = {
97 	.se_auinfo = {
98 		.ai_auid = AU_DEFAUDITID,
99 		.ai_asid = AU_DEFAUDITSID,
100 		.ai_termid = { .at_type = AU_IPv4, },
101 	},
102 	.se_refcnt = 1,
103 	.se_procnt = 1,
104 };
105 
106 struct auditinfo_addr * const audit_default_aia_p = &audit_default_se.se_auinfo;
107 
108 #if CONFIG_AUDIT
109 
110 
111 /*
112  * Currently the hash table is a fixed size.
113  */
114 #define HASH_TABLE_SIZE         97
115 #define HASH_ASID(asid)         (audit_session_hash(asid) % HASH_TABLE_SIZE)
116 
117 static struct rwlock    se_entry_lck;           /* (1) lock for se_link above */
118 
119 LIST_HEAD(au_sentry_head, au_sentry);
120 static struct au_sentry_head *au_sentry_bucket = NULL;
121 
122 #define AU_HISTORY_LOGGING 0
123 #if AU_HISTORY_LOGGING
124 typedef enum au_history_event {
125 	AU_HISTORY_EVENT_UNKNOWN = 0,
126 	AU_HISTORY_EVENT_REF     = 1,
127 	AU_HISTORY_EVENT_UNREF   = 2,
128 	AU_HISTORY_EVENT_BIRTH   = 3,
129 	AU_HISTORY_EVENT_DEATH   = 4,
130 	AU_HISTORY_EVENT_FIND    = 5
131 } au_history_event_t;
132 
133 #define AU_HISTORY_MAX_STACK_DEPTH 8
134 
135 struct au_history {
136 	struct au_sentry        *ptr;
137 	struct au_sentry         se;
138 	void                    *stack[AU_HISTORY_MAX_STACK_DEPTH];
139 	unsigned int             stack_depth;
140 	au_history_event_t       event;
141 };
142 
143 static struct au_history *au_history;
144 static size_t             au_history_size = 65536;
145 static unsigned int       au_history_index;
146 
147 static inline unsigned int
au_history_entries(void)148 au_history_entries(void)
149 {
150 	if (au_history_index >= au_history_size) {
151 		return au_history_size;
152 	} else {
153 		return au_history_index;
154 	}
155 }
156 
157 static inline void
au_history_record(au_sentry_t * se,au_history_event_t event)158 au_history_record(au_sentry_t *se, au_history_event_t event)
159 {
160 	struct au_history *p;
161 	unsigned int i;
162 
163 	i = OSAddAtomic(1, &au_history_index);
164 	p = &au_history[i % au_history_size];
165 
166 	bzero(p, sizeof(*p));
167 	p->event = event;
168 	bcopy(se, &p->se, sizeof(p->se));
169 	p->stack_depth = OSBacktrace(&p->stack[0], AU_HISTORY_MAX_STACK_DEPTH);
170 	p->ptr = se;
171 }
172 #else
173 #define au_history_record(se, event) do {} while (0)
174 #endif
175 
176 MALLOC_DEFINE(M_AU_SESSION, "audit_session", "Audit session data");
177 
178 static void     audit_ref_session(au_sentry_t *se);
179 static void     audit_unref_session(au_sentry_t *se);
180 
181 static void     audit_session_event(int event, auditinfo_addr_t *aia_p);
182 
183 /*
184  * Audit session device.
185  */
186 
187 static MALLOC_DEFINE(M_AUDIT_SDEV, "audit_sdev", "Audit sdevs");
188 static MALLOC_DEFINE(M_AUDIT_SDEV_ENTRY, "audit_sdevent",
189     "Audit sdev entries and buffers");
190 
191 /*
192  * Default audit sdev buffer parameters.
193  */
194 #define AUDIT_SDEV_QLIMIT_DEFAULT       128
195 #define AUDIT_SDEV_QLIMIT_MIN           1
196 #define AUDIT_SDEV_QLIMIT_MAX           1024
197 
198 /*
199  * Entry structure.
200  */
201 struct  audit_sdev_entry {
202 	void                            *ase_record;
203 	u_int                            ase_record_len;
204 	TAILQ_ENTRY(audit_sdev_entry)    ase_queue;
205 };
206 
207 /*
208  * Per audit sdev structure.
209  */
210 
211 struct audit_sdev {
212 	int             asdev_open;
213 
214 #define AUDIT_SDEV_ASYNC        0x00000001
215 #define AUDIT_SDEV_NBIO         0x00000002
216 
217 #define AUDIT_SDEV_ALLSESSIONS  0x00010000
218 	u_int           asdev_flags;
219 
220 	struct selinfo  asdev_selinfo;
221 	pid_t           asdev_sigio;
222 
223 	au_id_t         asdev_auid;
224 	au_asid_t       asdev_asid;
225 
226 	/* Per-sdev mutex for most fields in this struct. */
227 	struct mtx      asdev_mtx;
228 
229 	/*
230 	 * Per-sdev sleep lock serializing user-generated reads and
231 	 * flushes. uiomove() is called to copy out the current head
232 	 * record's data whie the record remains in the queue, so we
233 	 * prevent other threads from removing it using this lock.
234 	 */
235 	struct slck     asdev_sx;
236 
237 	/*
238 	 * Condition variable to signal when data has been delivered to
239 	 * a sdev.
240 	 */
241 	struct cv       asdev_cv;
242 
243 	/* Count and bound of records in the queue. */
244 	u_int           asdev_qlen;
245 	u_int           asdev_qlimit;
246 
247 	/* The number of bytes of data across all records. */
248 	u_int           asdev_qbyteslen;
249 
250 	/*
251 	 * The amount read so far of the first record in the queue.
252 	 * (The number of bytes available for reading in the queue is
253 	 * qbyteslen - qoffset.)
254 	 */
255 	u_int           asdev_qoffset;
256 
257 	/*
258 	 * Per-sdev operation statistics.
259 	 */
260 	u_int64_t       asdev_inserts;  /* Records added. */
261 	u_int64_t       asdev_reads;    /* Records read. */
262 	u_int64_t       asdev_drops;    /* Records dropped. */
263 
264 	/*
265 	 * Current pending record list.  This is protected by a
266 	 * combination of asdev_mtx and asdev_sx.  Note that both
267 	 * locks are required to remove a record from the head of the
268 	 * queue, as an in-progress read may sleep while copying and,
269 	 * therefore, cannot hold asdev_mtx.
270 	 */
271 	TAILQ_HEAD(, audit_sdev_entry)  asdev_queue;
272 
273 	/* Global sdev list. */
274 	TAILQ_ENTRY(audit_sdev)         asdev_list;
275 };
276 
277 #define AUDIT_SDEV_LOCK(asdev)          mtx_lock(&(asdev)->asdev_mtx)
278 #define AUDIT_SDEV_LOCK_ASSERT(asdev)   mtx_assert(&(asdev)->asdev_mtx, \
279 	                                    MA_OWNED)
280 #define AUDIT_SDEV_LOCK_DESTROY(asdev)  mtx_destroy(&(asdev)->asdev_mtx)
281 #define AUDIT_SDEV_LOCK_INIT(asdev)     mtx_init(&(asdev)->asdev_mtx, \
282 	                                    "audit_sdev_mtx", NULL, MTX_DEF)
283 #define AUDIT_SDEV_UNLOCK(asdev)        mtx_unlock(&(asdev)->asdev_mtx)
284 #define AUDIT_SDEV_MTX(asdev)           (&(asdev)->asdev_mtx)
285 
286 #define AUDIT_SDEV_SX_LOCK_DESTROY(asd) slck_destroy(&(asd)->asdev_sx)
287 #define AUDIT_SDEV_SX_LOCK_INIT(asd)    slck_init(&(asd)->asdev_sx, \
288 	                                    "audit_sdev_sx")
289 #define AUDIT_SDEV_SX_XLOCK_ASSERT(asd) slck_assert(&(asd)->asdev_sx, \
290 	                                    SA_XLOCKED)
291 #define AUDIT_SDEV_SX_XLOCK_SIG(asd)    slck_lock_sig(&(asd)->asdev_sx)
292 #define AUDIT_SDEV_SX_XUNLOCK(asd)      slck_unlock(&(asd)->asdev_sx)
293 
294 /*
295  * Cloning variables and constants.
296  */
297 #define AUDIT_SDEV_NAME         "auditsessions"
298 #define MAX_AUDIT_SDEVS         32
299 
300 static int audit_sdev_major;
301 static void *devnode;
302 
303 /*
304  * Global list of audit sdevs.  The list is protected by a rw lock.
305  * Individaul record queues are protected by  per-sdev locks.  These
306  * locks synchronize between threads walking the list to deliver to
307  * individual sdevs and adds/removes of sdevs.
308  */
309 static TAILQ_HEAD(, audit_sdev) audit_sdev_list;
310 static struct rwlock            audit_sdev_lock;
311 
312 #define AUDIT_SDEV_LIST_LOCK_INIT()     rw_init(&audit_sdev_lock, \
313 	                                    "audit_sdev_list_lock")
314 #define AUDIT_SDEV_LIST_RLOCK()         rw_rlock(&audit_sdev_lock)
315 #define AUDIT_SDEV_LIST_RUNLOCK()       rw_runlock(&audit_sdev_lock)
316 #define AUDIT_SDEV_LIST_WLOCK()         rw_wlock(&audit_sdev_lock)
317 #define AUDIT_SDEV_LIST_WLOCK_ASSERT()  rw_assert(&audit_sdev_lock, \
318 	                                    RA_WLOCKED)
319 #define AUDIT_SDEV_LIST_WUNLOCK()       rw_wunlock(&audit_sdev_lock)
320 
321 /*
322  * dev_t doesn't have a pointer for "softc" data so we have to keep track of
323  * it with the following global array (indexed by the minor number).
324  *
325  * XXX We may want to dynamically grow this as need.
326  */
327 static struct audit_sdev        *audit_sdev_dtab[MAX_AUDIT_SDEVS];
328 
329 /*
330  * Special device methods and definition.
331  */
332 static open_close_fcn_t         audit_sdev_open;
333 static open_close_fcn_t         audit_sdev_close;
334 static read_write_fcn_t         audit_sdev_read;
335 static ioctl_fcn_t              audit_sdev_ioctl;
336 static select_fcn_t             audit_sdev_poll;
337 
338 static const struct cdevsw audit_sdev_cdevsw = {
339 	.d_open      =          audit_sdev_open,
340 	.d_close     =          audit_sdev_close,
341 	.d_read      =          audit_sdev_read,
342 	.d_write     =          eno_rdwrt,
343 	.d_ioctl     =          audit_sdev_ioctl,
344 	.d_stop      =          eno_stop,
345 	.d_reset     =          eno_reset,
346 	.d_ttys      =          NULL,
347 	.d_select    =          audit_sdev_poll,
348 	.d_mmap      =          eno_mmap,
349 	.d_strategy  =          eno_strat,
350 	.d_type      =          0
351 };
352 
353 /*
354  * Global statistics on audit sdevs.
355  */
356 static int              audit_sdev_count;       /* Current number of sdevs. */
357 static u_int64_t        audit_sdev_ever;        /* Sdevs ever allocated. */
358 static u_int64_t        audit_sdev_records;     /* Total records seen. */
359 static u_int64_t        audit_sdev_drops;       /* Global record drop count. */
360 
361 static int audit_sdev_init(void);
362 
363 #define AUDIT_SENTRY_RWLOCK_INIT()      rw_init(&se_entry_lck, \
364 	                                    "se_entry_lck")
365 #define AUDIT_SENTRY_RLOCK()            rw_rlock(&se_entry_lck)
366 #define AUDIT_SENTRY_WLOCK()            rw_wlock(&se_entry_lck)
367 #define AUDIT_SENTRY_RWLOCK_ASSERT()    rw_assert(&se_entry_lck, RA_LOCKED)
368 #define AUDIT_SENTRY_RUNLOCK()          rw_runlock(&se_entry_lck)
369 #define AUDIT_SENTRY_WUNLOCK()          rw_wunlock(&se_entry_lck)
370 
371 /*
372  * Access control on the auditinfo_addr.ai_flags member.
373  */
374 static const uint64_t audit_session_superuser_set_sflags_mask = AU_SESSION_FLAG_HAS_GRAPHIC_ACCESS | AU_SESSION_FLAG_HAS_CONSOLE_ACCESS | AU_SESSION_FLAG_HAS_AUTHENTICATED;
375 static const uint64_t audit_session_superuser_clear_sflags_mask = AU_SESSION_FLAG_HAS_GRAPHIC_ACCESS | AU_SESSION_FLAG_HAS_CONSOLE_ACCESS | AU_SESSION_FLAG_HAS_AUTHENTICATED;
376 static const uint64_t audit_session_member_set_sflags_mask = 0;
377 static const uint64_t audit_session_member_clear_sflags_mask = AU_SESSION_FLAG_HAS_AUTHENTICATED;
378 
379 #define AUDIT_SESSION_DEBUG     0
380 #if     AUDIT_SESSION_DEBUG
381 /*
382  * The following is debugging code that can be used to get a snapshot of the
383  * session state.  The audit session information is read out using sysctl:
384  *
385  * error = sysctlbyname("kern.audit_session_debug", buffer_ptr, &buffer_len,
386  *              NULL, 0);
387  */
388 #include <kern/kalloc.h>
389 
390 /*
391  * The per session record structure for the snapshot data.
392  */
393 struct au_sentry_debug {
394 	auditinfo_addr_t        se_auinfo;
395 	int64_t                 se_refcnt;      /* refereence count */
396 	int64_t                 se_procnt;      /* process count */
397 	int64_t                 se_ptcnt;       /* process count from
398 	                                         *  proc table */
399 };
400 typedef struct au_sentry_debug au_sentry_debug_t;
401 
402 static int audit_sysctl_session_debug(struct sysctl_oid *oidp, void *arg1,
403     int arg2, struct sysctl_req *req);
404 
405 SYSCTL_PROC(_kern, OID_AUTO, audit_session_debug, CTLFLAG_RD | CTLFLAG_LOCKED,
406     NULL, 0, audit_sysctl_session_debug, "S,audit_session_debug",
407     "Current session debug info for auditing.");
408 
409 /*
410  * Callouts for proc_interate() which is used to reconcile the audit session
411  * proc state information with the proc table.  We get everything we need
412  * in the filterfn while the proc_lock() is held so we really don't need the
413  * callout() function.
414  */
415 static int
audit_session_debug_callout(__unused proc_t p,__unused void * arg)416 audit_session_debug_callout(__unused proc_t p, __unused void *arg)
417 {
418 	return PROC_RETURNED_DONE;
419 }
420 
421 static int
audit_session_debug_filterfn(proc_t p,void * st)422 audit_session_debug_filterfn(proc_t p, void *st)
423 {
424 	kauth_cred_t cred = kauth_cred_get();
425 	auditinfo_addr_t *aia_p = cred->cr_audit.as_aia_p;
426 	au_sentry_debug_t *sed_tab = (au_sentry_debug_t *) st;
427 	au_sentry_debug_t  *sdtp;
428 	au_sentry_t *se;
429 
430 	if (IS_VALID_SESSION(aia_p)) {
431 		sdtp = &sed_tab[0];
432 		do {
433 			if (aia_p->ai_asid == sdtp->se_asid) {
434 				sdtp->se_ptcnt++;
435 
436 				/* Do some santy checks. */
437 				se = AU_SENTRY_PTR(aia_p);
438 				if (se->se_refcnt != sdtp->se_refcnt) {
439 					sdtp->se_refcnt =
440 					    (int64_t)se->se_refcnt;
441 				}
442 				if (se->se_procnt != sdtp->se_procnt) {
443 					sdtp->se_procnt =
444 					    (int64_t)se->se_procnt;
445 				}
446 				break;
447 			}
448 			sdtp++;
449 		} while (sdtp->se_asid != 0 && sdtp->se_auid != 0);
450 	} else {
451 		/* add it to the default sesison */
452 		sed_tab->se_ptcnt++;
453 	}
454 
455 	return 0;
456 }
457 
458 /*
459  * Copy out the session debug info via the sysctl interface.
460  *
461  */
462 static int
audit_sysctl_session_debug(__unused struct sysctl_oid * oidp,__unused void * arg1,__unused int arg2,struct sysctl_req * req)463 audit_sysctl_session_debug(__unused struct sysctl_oid *oidp,
464     __unused void *arg1, __unused int arg2, struct sysctl_req *req)
465 {
466 	au_sentry_t *se;
467 	au_sentry_debug_t *sed_tab, *next_sed;
468 	int i, entry_cnt = 0;
469 	size_t sz;
470 	int err = 0;
471 
472 	/*
473 	 * This provides a read-only node.
474 	 */
475 	if (req->newptr != USER_ADDR_NULL) {
476 		return EPERM;
477 	}
478 
479 	/*
480 	 * Walk the audit session hash table to determine the size.
481 	 */
482 	AUDIT_SENTRY_RLOCK();
483 	for (i = 0; i < HASH_TABLE_SIZE; i++) {
484 		LIST_FOREACH(se, &au_sentry_bucket[i], se_link)
485 		if (se != NULL) {
486 			entry_cnt++;
487 		}
488 	}
489 
490 	entry_cnt++;  /* add one for the default entry */
491 	/*
492 	 * If just querying then return the space required.  There is an
493 	 * obvious race condition here so we just fudge this by 3 in case
494 	 * the audit session table grows.
495 	 */
496 	if (req->oldptr == USER_ADDR_NULL) {
497 		req->oldidx = (entry_cnt + 3) * sizeof(au_sentry_debug_t);
498 		AUDIT_SENTRY_RUNLOCK();
499 		return 0;
500 	}
501 
502 	/*
503 	 * Alloc a temporary buffer.
504 	 */
505 	if (req->oldlen < (entry_cnt * sizeof(au_sentry_debug_t))) {
506 		AUDIT_SENTRY_RUNLOCK();
507 		return ENOMEM;
508 	}
509 	/*
510 	 * We hold the lock over the alloc since we don't want the table to
511 	 * grow on us.   Therefore, use the non-blocking version of kalloc().
512 	 */
513 	sed_tab = kalloc_data(entry_cnt * sizeof(au_sentry_debug_t),
514 	    Z_NOWAIT | Z_ZERO);
515 	if (sed_tab == NULL) {
516 		AUDIT_SENTRY_RUNLOCK();
517 		return ENOMEM;
518 	}
519 
520 	/*
521 	 * Walk the audit session hash table and build the record array.
522 	 */
523 	sz = 0;
524 	next_sed = sed_tab;
525 	/* add the first entry for processes not tracked in sessions. */
526 	bcopy(audit_default_aia_p, &next_sed->se_auinfo, sizeof(au_sentry_t));
527 	next_sed->se_refcnt = (int64_t)audit_default_se.se_refcnt;
528 	next_sed->se_procnt = (int64_t)audit_default_se.se_procnt;
529 	next_sed++;
530 	sz += sizeof(au_sentry_debug_t);
531 	for (i = 0; i < HASH_TABLE_SIZE; i++) {
532 		LIST_FOREACH(se, &au_sentry_bucket[i], se_link) {
533 			if (se != NULL) {
534 				next_sed->se_auinfo = se->se_auinfo;
535 				next_sed->se_refcnt = (int64_t)se->se_refcnt;
536 				next_sed->se_procnt = (int64_t)se->se_procnt;
537 				next_sed++;
538 				sz += sizeof(au_sentry_debug_t);
539 			}
540 		}
541 	}
542 	AUDIT_SENTRY_RUNLOCK();
543 
544 	/* Reconcile with the process table. */
545 	proc_iterate(PROC_ALLPROCLIST | PROC_ZOMBPROCLIST,
546 	    audit_session_debug_callout, NULL,
547 	    audit_session_debug_filterfn, (void *)&sed_tab[0]);
548 
549 
550 	req->oldlen = sz;
551 	err = SYSCTL_OUT(req, sed_tab, sz);
552 	kfree_data(sed_tab, entry_cnt * sizeof(au_sentry_debug_t));
553 
554 	return err;
555 }
556 
557 #endif /* AUDIT_SESSION_DEBUG */
558 
559 /*
560  * Create and commit a session audit event. The proc and se arguments needs to
561  * be that of the subject and not necessarily the current process.
562  */
563 static void
audit_session_event(int event,auditinfo_addr_t * aia_p)564 audit_session_event(int event, auditinfo_addr_t *aia_p)
565 {
566 	struct kaudit_record *ar;
567 
568 	KASSERT(AUE_SESSION_START == event || AUE_SESSION_UPDATE == event ||
569 	    AUE_SESSION_END == event || AUE_SESSION_CLOSE == event,
570 	    ("audit_session_event: invalid event: %d", event));
571 
572 	if (NULL == aia_p) {
573 		return;
574 	}
575 
576 	/*
577 	 * Create a new audit record.  The record will contain the subject
578 	 * ruid, rgid, egid, pid, auid, asid, amask, and term_addr
579 	 * (implicitly added by audit_new).
580 	 */
581 	ar = audit_new(event, PROC_NULL, /* Not used */ NULL);
582 	if (NULL == ar) {
583 		return;
584 	}
585 
586 	/*
587 	 * Audit session events are always generated because they are used
588 	 * by some userland consumers so just set the preselect flag.
589 	 */
590 	ar->k_ar_commit |= AR_PRESELECT_FILTER;
591 
592 	/*
593 	 * Populate the subject information.  Note that the ruid, rgid,
594 	 * egid, and pid values are incorrect. We only need the  auditinfo_addr
595 	 * information.
596 	 */
597 	ar->k_ar.ar_subj_ruid = 0;
598 	ar->k_ar.ar_subj_rgid = 0;
599 	ar->k_ar.ar_subj_egid = 0;
600 	ar->k_ar.ar_subj_pid = 0;
601 	ar->k_ar.ar_subj_auid = aia_p->ai_auid;
602 	ar->k_ar.ar_subj_asid = aia_p->ai_asid;
603 	bcopy(&aia_p->ai_termid, &ar->k_ar.ar_subj_term_addr,
604 	    sizeof(struct au_tid_addr));
605 
606 	/* Add the audit masks to the record. */
607 	ar->k_ar.ar_arg_amask.am_success = aia_p->ai_mask.am_success;
608 	ar->k_ar.ar_arg_amask.am_failure = aia_p->ai_mask.am_failure;
609 	ARG_SET_VALID(ar, ARG_AMASK);
610 
611 	/* Add the audit session flags to the record. */
612 	ar->k_ar.ar_arg_value64 = aia_p->ai_flags;
613 	ARG_SET_VALID(ar, ARG_VALUE64);
614 
615 
616 	/* Commit the record to the queue. */
617 	audit_commit(ar, 0, 0);
618 }
619 
620 /*
621  * Hash the audit session ID using a simple 32-bit mix.
622  */
623 static inline uint32_t
audit_session_hash(au_asid_t asid)624 audit_session_hash(au_asid_t asid)
625 {
626 	uint32_t a = (uint32_t) asid;
627 
628 	a = (a - (a << 6)) ^ (a >> 17);
629 	a = (a - (a << 9)) ^ (a << 4);
630 	a = (a - (a << 3)) ^ (a << 10);
631 	a = a ^ (a >> 15);
632 
633 	return a;
634 }
635 
636 /*
637  * Do an hash lookup and find the session entry for a given ASID.  Return NULL
638  * if not found. If the session is found then audit_session_find takes a
639  * reference.
640  */
641 static au_sentry_t *
audit_session_find(au_asid_t asid)642 audit_session_find(au_asid_t asid)
643 {
644 	uint32_t         hkey;
645 	au_sentry_t     *found_se;
646 
647 	AUDIT_SENTRY_RWLOCK_ASSERT();
648 
649 	hkey = HASH_ASID(asid);
650 
651 	LIST_FOREACH(found_se, &au_sentry_bucket[hkey], se_link)
652 	if (found_se->se_asid == asid) {
653 		au_history_record(found_se, AU_HISTORY_EVENT_FIND);
654 		audit_ref_session(found_se);
655 		return found_se;
656 	}
657 	return NULL;
658 }
659 
660 static void
audit_session_free(smr_node_t node)661 audit_session_free(smr_node_t node)
662 {
663 	au_sentry_t *se = __container_of(node, au_sentry_t, se_smr_node);
664 
665 	kfree_type(au_sentry_t, se);
666 }
667 
668 /*
669  * Remove the given audit_session entry from the hash table.
670  */
671 static void
audit_session_remove(au_sentry_t * se)672 audit_session_remove(au_sentry_t *se)
673 {
674 	uint32_t         hkey;
675 	au_sentry_t     *found_se, *tmp_se;
676 
677 	au_history_record(se, AU_HISTORY_EVENT_DEATH);
678 	KASSERT(se->se_refcnt == 0, ("audit_session_remove: ref count != 0"));
679 	KASSERT(se != &audit_default_se,
680 	    ("audit_session_remove: removing default session"));
681 
682 	hkey = HASH_ASID(se->se_asid);
683 
684 	AUDIT_SENTRY_WLOCK();
685 	/*
686 	 * Check and see if someone got a reference before we got the lock.
687 	 */
688 	if (se->se_refcnt != 0) {
689 		AUDIT_SENTRY_WUNLOCK();
690 		return;
691 	}
692 
693 	audit_session_portdestroy(&se->se_port);
694 	LIST_FOREACH_SAFE(found_se, &au_sentry_bucket[hkey], se_link, tmp_se) {
695 		if (found_se == se) {
696 			/*
697 			 * Generate an audit event to notify userland of the
698 			 * session close.
699 			 */
700 			audit_session_event(AUE_SESSION_CLOSE,
701 			    &found_se->se_auinfo);
702 
703 			LIST_REMOVE(found_se, se_link);
704 			AUDIT_SENTRY_WUNLOCK();
705 			smr_call(&smr_proc_task, &found_se->se_smr_node,
706 			    sizeof(found_se), audit_session_free);
707 			return;
708 		}
709 	}
710 	AUDIT_SENTRY_WUNLOCK();
711 }
712 
713 /*
714  * Reference the session by incrementing the sentry ref count.
715  */
716 static void
audit_ref_session(au_sentry_t * se)717 audit_ref_session(au_sentry_t *se)
718 {
719 	long old_val;
720 
721 	if (se == NULL || se == &audit_default_se) {
722 		return;
723 	}
724 
725 	au_history_record(se, AU_HISTORY_EVENT_REF);
726 
727 	old_val = OSAddAtomicLong(1, &se->se_refcnt);
728 	KASSERT(old_val < 100000,
729 	    ("audit_ref_session: Too many references on session."));
730 }
731 
732 /*
733  * Decrement the sentry ref count and remove the session entry if last one.
734  */
735 static void
audit_unref_session(au_sentry_t * se)736 audit_unref_session(au_sentry_t *se)
737 {
738 	long old_val;
739 
740 	if (se == NULL || se == &audit_default_se) {
741 		return;
742 	}
743 
744 	au_history_record(se, AU_HISTORY_EVENT_UNREF);
745 
746 	old_val = OSAddAtomicLong(-1, &se->se_refcnt);
747 	if (old_val == 1) {
748 		audit_session_remove(se);
749 	}
750 	KASSERT(old_val > 0,
751 	    ("audit_unref_session: Too few references on session."));
752 }
753 
754 /*
755  * Increment the process count in the session.
756  */
757 static void
audit_inc_procount(au_sentry_t * se)758 audit_inc_procount(au_sentry_t *se)
759 {
760 	long old_val;
761 
762 	if (se == NULL || se == &audit_default_se) {
763 		return;
764 	}
765 
766 	old_val = OSAddAtomicLong(1, &se->se_procnt);
767 	KASSERT(old_val <= PID_MAX,
768 	    ("audit_inc_procount: proc count > PID_MAX"));
769 }
770 
771 /*
772  * Decrement the process count and add a knote if it is the last process
773  * to exit the session.
774  */
775 static void
audit_dec_procount(au_sentry_t * se)776 audit_dec_procount(au_sentry_t *se)
777 {
778 	long old_val;
779 
780 	if (se == NULL || se == &audit_default_se) {
781 		return;
782 	}
783 
784 	old_val = OSAddAtomicLong(-1, &se->se_procnt);
785 	/*
786 	 * If this was the last process generate an audit event to notify
787 	 * userland of the session ending.
788 	 */
789 	if (old_val == 1) {
790 		audit_session_event(AUE_SESSION_END, &se->se_auinfo);
791 	}
792 	KASSERT(old_val >= 1,
793 	    ("audit_dec_procount: proc count < 0"));
794 }
795 
796 /*
797  * Update the session entry and check to see if anything was updated.
798  * Returns:
799  *    0    Nothing was updated (We don't care about process preselection masks)
800  *    1    Something was updated.
801  */
802 static int
audit_update_sentry(au_sentry_t * se,auditinfo_addr_t * new_aia)803 audit_update_sentry(au_sentry_t *se, auditinfo_addr_t *new_aia)
804 {
805 	auditinfo_addr_t *aia = &se->se_auinfo;
806 	int update;
807 
808 	KASSERT(new_aia != audit_default_aia_p,
809 	    ("audit_update_sentry: Trying to update the default aia."));
810 
811 	update = (aia->ai_auid != new_aia->ai_auid ||
812 	    bcmp(&aia->ai_termid, &new_aia->ai_termid,
813 	    sizeof(new_aia->ai_termid)) ||
814 	    aia->ai_flags != new_aia->ai_flags);
815 
816 	if (update) {
817 		bcopy(new_aia, aia, sizeof(*aia));
818 	}
819 
820 	return update;
821 }
822 
823 /*
824  * Return the next session ID.  The range of kernel generated audit session IDs
825  * is ASSIGNED_ASID_MIN to ASSIGNED_ASID_MAX.
826  */
827 static uint32_t
audit_session_nextid(void)828 audit_session_nextid(void)
829 {
830 	static uint32_t next_asid = ASSIGNED_ASID_MIN;
831 
832 	AUDIT_SENTRY_RWLOCK_ASSERT();
833 
834 	if (next_asid > ASSIGNED_ASID_MAX) {
835 		next_asid = ASSIGNED_ASID_MIN;
836 	}
837 
838 	return next_asid++;
839 }
840 
841 /*
842  * Allocated a new audit_session entry and add it to the hash table.  If the
843  * given ASID is set to AU_ASSIGN_ASID then audit_session_new() will pick an
844  * audit session ID.  Otherwise, it attempts use the one given. It creates a
845  * reference to the entry that must be unref'ed.
846  */
847 static auditinfo_addr_t *
audit_session_new(auditinfo_addr_t * new_aia_p,auditinfo_addr_t * old_aia_p)848 audit_session_new(auditinfo_addr_t *new_aia_p, auditinfo_addr_t *old_aia_p)
849 {
850 	au_asid_t new_asid;
851 	au_sentry_t *se = NULL;
852 	au_sentry_t *found_se = NULL;
853 	auditinfo_addr_t *aia = NULL;
854 
855 	KASSERT(new_aia_p != NULL, ("audit_session_new: new_aia_p == NULL"));
856 
857 	new_asid = new_aia_p->ai_asid;
858 
859 	/*
860 	 * Alloc a new session entry now so we don't wait holding the lock.
861 	 */
862 	se = kalloc_type(au_sentry_t, Z_WAITOK | Z_ZERO | Z_NOFAIL);
863 
864 	/*
865 	 * Find an unique session ID, if desired.
866 	 */
867 	AUDIT_SENTRY_WLOCK();
868 	if (new_asid == AU_ASSIGN_ASID) {
869 		do {
870 			new_asid = (au_asid_t)audit_session_nextid();
871 			found_se = audit_session_find(new_asid);
872 
873 			/*
874 			 * If the session ID is currently active then drop the
875 			 * reference and try again.
876 			 */
877 			if (found_se != NULL) {
878 				audit_unref_session(found_se);
879 			} else {
880 				break;
881 			}
882 		} while (1);
883 	} else {
884 		/*
885 		 * Check to see if the requested ASID is already in the
886 		 * hash table.  If so, update it with the new auditinfo.
887 		 */
888 		if ((found_se = audit_session_find(new_asid)) != NULL) {
889 			int updated;
890 
891 			updated = audit_update_sentry(found_se, new_aia_p);
892 
893 			AUDIT_SENTRY_WUNLOCK();
894 			kfree_type(au_sentry_t, se);
895 
896 			/* If a different session then add this process in. */
897 			if (new_aia_p != old_aia_p) {
898 				audit_inc_procount(found_se);
899 			}
900 
901 			/*
902 			 * If the session information was updated then
903 			 * generate an audit event to notify userland.
904 			 */
905 			if (updated) {
906 				audit_session_event(AUE_SESSION_UPDATE,
907 				    &found_se->se_auinfo);
908 			}
909 
910 			return &found_se->se_auinfo;
911 		}
912 	}
913 
914 	/*
915 	 * Start the reference and proc count at 1 to account for the process
916 	 * that invoked this via setaudit_addr() (or friends).
917 	 */
918 	se->se_refcnt = se->se_procnt = 1;
919 
920 	/*
921 	 * Populate the new session entry.  Note that process masks are stored
922 	 * in kauth ucred so just zero them here.
923 	 */
924 	se->se_port = IPC_PORT_NULL;
925 	aia = &se->se_auinfo;
926 	aia->ai_asid = new_asid;
927 	aia->ai_auid = new_aia_p->ai_auid;
928 	bzero(&new_aia_p->ai_mask, sizeof(new_aia_p->ai_mask));
929 	bcopy(&new_aia_p->ai_termid, &aia->ai_termid, sizeof(aia->ai_termid));
930 	aia->ai_flags = new_aia_p->ai_flags;
931 
932 	/*
933 	 * Add it to the hash table.
934 	 */
935 	LIST_INSERT_HEAD(&au_sentry_bucket[HASH_ASID(new_asid)], se, se_link);
936 	AUDIT_SENTRY_WUNLOCK();
937 
938 	/*
939 	 * Generate an audit event to notify userland of the new session.
940 	 */
941 	audit_session_event(AUE_SESSION_START, aia);
942 	au_history_record(se, AU_HISTORY_EVENT_BIRTH);
943 	return aia;
944 }
945 
946 /*
947  * Lookup an existing session.  A copy of the audit session info for a given
948  * ASID is returned in ret_aia.  Returns 0 on success.
949  */
950 int
audit_session_lookup(au_asid_t asid,auditinfo_addr_t * ret_aia)951 audit_session_lookup(au_asid_t asid, auditinfo_addr_t *ret_aia)
952 {
953 	au_sentry_t *se = NULL;
954 
955 	if ((uint32_t)asid > ASSIGNED_ASID_MAX) {
956 		return -1;
957 	}
958 	AUDIT_SENTRY_RLOCK();
959 	if ((se = audit_session_find(asid)) == NULL) {
960 		AUDIT_SENTRY_RUNLOCK();
961 		return 1;
962 	}
963 	/* We have a reference on the session so it is safe to drop the lock. */
964 	AUDIT_SENTRY_RUNLOCK();
965 	if (ret_aia != NULL) {
966 		bcopy(&se->se_auinfo, ret_aia, sizeof(*ret_aia));
967 	}
968 	audit_unref_session(se);
969 
970 	return 0;
971 }
972 
973 void
audit_session_aiaref(auditinfo_addr_t * aia_p)974 audit_session_aiaref(auditinfo_addr_t *aia_p)
975 {
976 	audit_ref_session(AU_SENTRY_PTR(aia_p));
977 }
978 
979 /*
980  * Add a reference to the session entry.
981  */
982 void
audit_session_ref(kauth_cred_t cred)983 audit_session_ref(kauth_cred_t cred)
984 {
985 	auditinfo_addr_t *aia_p;
986 
987 	KASSERT(IS_VALID_CRED(cred),
988 	    ("audit_session_ref: Invalid kauth_cred."));
989 
990 	aia_p = cred->cr_audit.as_aia_p;
991 	audit_session_aiaref(aia_p);
992 }
993 
994 void
audit_session_aiaunref(auditinfo_addr_t * aia_p)995 audit_session_aiaunref(auditinfo_addr_t *aia_p)
996 {
997 	audit_unref_session(AU_SENTRY_PTR(aia_p));
998 }
999 
1000 /*
1001  * Remove a reference to the session entry.
1002  */
1003 void
audit_session_unref(kauth_cred_t cred)1004 audit_session_unref(kauth_cred_t cred)
1005 {
1006 	auditinfo_addr_t *aia_p;
1007 
1008 	KASSERT(IS_VALID_CRED(cred),
1009 	    ("audit_session_unref: Invalid kauth_cred."));
1010 
1011 	aia_p = cred->cr_audit.as_aia_p;
1012 	audit_session_aiaunref(aia_p);
1013 }
1014 
1015 /*
1016  * Increment the per audit session process count.  Assumes that the caller has
1017  * a reference on the process' cred.
1018  */
1019 void
audit_session_procnew(proc_t p)1020 audit_session_procnew(proc_t p)
1021 {
1022 	kauth_cred_t cred = proc_ucred_unsafe(p); /* during create */
1023 	auditinfo_addr_t *aia_p;
1024 
1025 	KASSERT(IS_VALID_CRED(cred),
1026 	    ("audit_session_procnew: Invalid kauth_cred."));
1027 
1028 	aia_p = cred->cr_audit.as_aia_p;
1029 
1030 	audit_inc_procount(AU_SENTRY_PTR(aia_p));
1031 }
1032 
1033 /*
1034  * Decrement the per audit session process count.  Assumes that the caller has
1035  * a reference on the cred.
1036  */
1037 void
audit_session_procexit(proc_t p)1038 audit_session_procexit(proc_t p)
1039 {
1040 	kauth_cred_t cred = proc_ucred_unsafe(p); /* during exit */
1041 	auditinfo_addr_t *aia_p;
1042 
1043 	KASSERT(IS_VALID_CRED(cred),
1044 	    ("audit_session_procexit: Invalid kauth_cred."));
1045 
1046 	aia_p = cred->cr_audit.as_aia_p;
1047 
1048 	audit_dec_procount(AU_SENTRY_PTR(aia_p));
1049 }
1050 
1051 /*
1052  * Init the audit session code.
1053  */
1054 void
audit_session_init(void)1055 audit_session_init(void)
1056 {
1057 	int i;
1058 
1059 	KASSERT((ASSIGNED_ASID_MAX - ASSIGNED_ASID_MIN) > PID_MAX,
1060 	    ("audit_session_init: ASSIGNED_ASID_MAX is not large enough."));
1061 
1062 	AUDIT_SENTRY_RWLOCK_INIT();
1063 
1064 	au_sentry_bucket = zalloc_permanent(sizeof(struct au_sentry) *
1065 	    HASH_TABLE_SIZE, ZALIGN_PTR);
1066 
1067 	for (i = 0; i < HASH_TABLE_SIZE; i++) {
1068 		LIST_INIT(&au_sentry_bucket[i]);
1069 	}
1070 
1071 	(void)audit_sdev_init();
1072 #if AU_HISTORY_LOGGING
1073 	au_history = zalloc_permanent(sizeof(struct au_history) * au_history_size,
1074 	    ZALIGN_PTR);
1075 #endif
1076 }
1077 
1078 static int
audit_session_update_check(kauth_cred_t cred,auditinfo_addr_t * old,auditinfo_addr_t * new)1079 audit_session_update_check(kauth_cred_t cred, auditinfo_addr_t *old,
1080     auditinfo_addr_t *new)
1081 {
1082 	uint64_t n;
1083 
1084 	/* If the current audit ID is not the default then it is immutable. */
1085 	if (old->ai_auid != AU_DEFAUDITID && old->ai_auid != new->ai_auid) {
1086 		return EINVAL;
1087 	}
1088 
1089 	/* If the current termid is not the default then it is immutable. */
1090 	if ((old->ai_termid.at_type != AU_IPv4 ||
1091 	    old->ai_termid.at_port != 0 ||
1092 	    old->ai_termid.at_addr[0] != 0) &&
1093 	    (old->ai_termid.at_port != new->ai_termid.at_port ||
1094 	    old->ai_termid.at_type != new->ai_termid.at_type ||
1095 	    0 != bcmp(&old->ai_termid.at_addr, &new->ai_termid.at_addr,
1096 	    sizeof(old->ai_termid.at_addr)))) {
1097 		return EINVAL;
1098 	}
1099 
1100 	/* The flags may be set only according to the
1101 	 * audit_session_*_set_sflags_masks.
1102 	 */
1103 	n = ~old->ai_flags & new->ai_flags;
1104 	if (0 != n &&
1105 	    !((n == (audit_session_superuser_set_sflags_mask & n) &&
1106 	    kauth_cred_issuser(cred)) ||
1107 	    (n == (audit_session_member_set_sflags_mask & n) &&
1108 	    old->ai_asid == new->ai_asid))) {
1109 		return EINVAL;
1110 	}
1111 
1112 	/* The flags may be cleared only according to the
1113 	 * audit_session_*_clear_sflags_masks.
1114 	 */
1115 	n = ~new->ai_flags & old->ai_flags;
1116 	if (0 != n &&
1117 	    !((n == (audit_session_superuser_clear_sflags_mask & n) &&
1118 	    kauth_cred_issuser(cred)) ||
1119 	    (n == (audit_session_member_clear_sflags_mask & n) &&
1120 	    old->ai_asid == new->ai_asid))) {
1121 		return EINVAL;
1122 	}
1123 
1124 	/* The audit masks are mutable. */
1125 	return 0;
1126 }
1127 
1128 /*
1129  * Protect updates to proc->cred->session
1130  *
1131  * The lifecycle of sessions and kauth creds do not compose well,
1132  * so this lock makes sure that even in the presence of concurrent
1133  * updates to the proc's credential, sessions stay stable.
1134  *
1135  * This lock is only used to serialize audit_session_setaia()
1136  * and audit_session_join_internal() with each other,
1137  * which are called from posix_spawn() or regular syscall context.
1138  *
1139  * Once the session is established in the cred, this lock
1140  * is no longer required, it is only about avoiding racing
1141  * updates and lifetime bugs due to the discrepancy between
1142  * audit sessions and creds.
1143  */
1144 static void
proc_audit_session_lock(proc_t p)1145 proc_audit_session_lock(proc_t p)
1146 {
1147 	lck_mtx_lock(&p->p_audit_mlock);
1148 }
1149 
1150 static void
proc_audit_session_unlock(proc_t p)1151 proc_audit_session_unlock(proc_t p)
1152 {
1153 	lck_mtx_unlock(&p->p_audit_mlock);
1154 }
1155 
1156 /*
1157  * Safely update kauth cred of the given process with new the given audit info.
1158  */
1159 int
audit_session_setaia(proc_t p,auditinfo_addr_t * new_aia_p)1160 audit_session_setaia(proc_t p, auditinfo_addr_t *new_aia_p)
1161 {
1162 	kauth_cred_t my_cred;
1163 	struct au_session as, *asp = &as;
1164 	auditinfo_addr_t caia, *old_aia_p;
1165 	int ret;
1166 
1167 	proc_audit_session_lock(p);
1168 	my_cred = kauth_cred_proc_ref(p);
1169 
1170 	/*
1171 	 * If this is going to modify an existing session then do some
1172 	 * immutable checks.
1173 	 */
1174 	if (audit_session_lookup(new_aia_p->ai_asid, &caia) == 0) {
1175 		ret = audit_session_update_check(my_cred, &caia, new_aia_p);
1176 		if (ret) {
1177 			proc_audit_session_unlock(p);
1178 			kauth_cred_unref(&my_cred);
1179 			return ret;
1180 		}
1181 	}
1182 
1183 	bcopy(&new_aia_p->ai_mask, &as.as_mask, sizeof(as.as_mask));
1184 	old_aia_p = my_cred->cr_audit.as_aia_p;
1185 	/* audit_session_new() adds a reference on the session */
1186 	as.as_aia_p = audit_session_new(new_aia_p, old_aia_p);
1187 
1188 	kauth_cred_proc_update(p, PROC_SETTOKEN_LAZY,
1189 	    ^bool (kauth_cred_t parent __unused, kauth_cred_t model) {
1190 		return kauth_cred_model_setauditinfo(model, asp);
1191 	});
1192 
1193 	proc_audit_session_unlock(p);
1194 	kauth_cred_unref(&my_cred);
1195 
1196 	/* If the process left a session then update the process count. */
1197 	if (old_aia_p != new_aia_p) {
1198 		audit_dec_procount(AU_SENTRY_PTR(old_aia_p));
1199 	}
1200 
1201 	/* Drop the reference taken by audit_session_new() above. */
1202 	audit_unref_session(AU_SENTRY_PTR(as.as_aia_p));
1203 
1204 	return 0;
1205 }
1206 
1207 /*
1208  * audit_session_self  (system call)
1209  *
1210  * Description: Obtain a Mach send right for the current session.
1211  *
1212  * Parameters:	p		Process calling audit_session_self().
1213  *
1214  * Returns:	*ret_port	Named Mach send right, which may be
1215  *                              MACH_PORT_NULL in the failure case.
1216  *
1217  * Errno:	0		Success
1218  *              EINVAL		The calling process' session has not be set.
1219  *              ESRCH		Bad process, can't get valid cred for process.
1220  *              ENOMEM		Port allocation failed due to no free memory.
1221  */
1222 int
audit_session_self(proc_t p,__unused struct audit_session_self_args * uap,mach_port_name_t * ret_port)1223 audit_session_self(proc_t p, __unused struct audit_session_self_args *uap,
1224     mach_port_name_t *ret_port)
1225 {
1226 	ipc_port_t sendport = IPC_PORT_NULL;
1227 	kauth_cred_t cred = NULL;
1228 	auditinfo_addr_t *aia_p;
1229 	au_sentry_t *se;
1230 	int err = 0;
1231 
1232 	cred = kauth_cred_proc_ref(p);
1233 	if (!IS_VALID_CRED(cred)) {
1234 		err = ESRCH;
1235 		goto done;
1236 	}
1237 
1238 	aia_p = cred->cr_audit.as_aia_p;
1239 	if (!IS_VALID_SESSION(aia_p)) {
1240 		/* Can't join the default session. */
1241 		err = EINVAL;
1242 		goto done;
1243 	}
1244 
1245 	se = AU_SENTRY_PTR(aia_p);
1246 
1247 	/*
1248 	 * Processes that join using this mach port will inherit this process'
1249 	 * pre-selection masks.
1250 	 */
1251 	if (se->se_port == IPC_PORT_NULL) {
1252 		bcopy(&cred->cr_audit.as_mask, &se->se_mask,
1253 		    sizeof(se->se_mask));
1254 	}
1255 
1256 	/*
1257 	 * Get a send right to the session's Mach port and insert it in the
1258 	 * process' mach port namespace.
1259 	 */
1260 	sendport = audit_session_mksend(aia_p, &se->se_port);
1261 	*ret_port = ipc_port_copyout_send(sendport, get_task_ipcspace(proc_task(p)));
1262 
1263 done:
1264 	if (cred != NULL) {
1265 		kauth_cred_unref(&cred);
1266 	}
1267 	if (err != 0) {
1268 		*ret_port = MACH_PORT_NULL;
1269 	}
1270 	return err;
1271 }
1272 
1273 /*
1274  * audit_session_port  (system call)
1275  *
1276  * Description: Obtain a Mach send right for the given session ID.
1277  *
1278  * Parameters:	p		Process calling audit_session_port().
1279  *              uap->asid       The target audit session ID.  The special
1280  *                              value -1 can be used to target the process's
1281  *                              own session.
1282  *              uap->portnamep  User address at which to place port name.
1283  *
1284  * Returns:	0		Success
1285  *              EINVAL		The calling process' session has not be set.
1286  *              EINVAL		The given session ID could not be found.
1287  *              EINVAL		The Mach port right could not be copied out.
1288  *              ESRCH		Bad process, can't get valid cred for process.
1289  *              EPERM		Only the superuser can reference sessions other
1290  *                              than the process's own.
1291  *              ENOMEM		Port allocation failed due to no free memory.
1292  */
1293 int
audit_session_port(proc_t p,struct audit_session_port_args * uap,__unused int * retval)1294 audit_session_port(proc_t p, struct audit_session_port_args *uap,
1295     __unused int *retval)
1296 {
1297 	ipc_port_t sendport = IPC_PORT_NULL;
1298 	mach_port_name_t portname = MACH_PORT_NULL;
1299 	kauth_cred_t cred = NULL;
1300 	auditinfo_addr_t *aia_p = NULL;
1301 	au_sentry_t *se = NULL;
1302 	int err = 0;
1303 
1304 	/* Note: Currently this test will never be true, because
1305 	 * ASSIGNED_ASID_MAX is effectively (uint32_t)-2.
1306 	 */
1307 	if (uap->asid != -1 && (uint32_t)uap->asid > ASSIGNED_ASID_MAX) {
1308 		err = EINVAL;
1309 		goto done;
1310 	}
1311 	cred = kauth_cred_proc_ref(p);
1312 	if (!IS_VALID_CRED(cred)) {
1313 		err = ESRCH;
1314 		goto done;
1315 	}
1316 	aia_p = cred->cr_audit.as_aia_p;
1317 
1318 	/* Find the session corresponding to the requested audit
1319 	 * session ID.  If found, take a reference on it so that
1320 	 * the session is not dropped until the join is later done.
1321 	 */
1322 	if (uap->asid == (au_asid_t)-1 ||
1323 	    uap->asid == aia_p->ai_asid) {
1324 		if (!IS_VALID_SESSION(aia_p)) {
1325 			/* Can't join the default session. */
1326 			err = EINVAL;
1327 			goto done;
1328 		}
1329 
1330 		/* No privilege is required to obtain a port for our
1331 		 * own session.
1332 		 */
1333 		se = AU_SENTRY_PTR(aia_p);
1334 		audit_ref_session(se);
1335 	} else {
1336 		/*
1337 		 * Only privileged processes may obtain a port for
1338 		 * any existing session.
1339 		 */
1340 		err = priv_check_cred(cred, PRIV_AUDIT_SESSION_PORT, 0);
1341 		if (err != 0) {
1342 			goto done;
1343 		}
1344 		AUDIT_SENTRY_RLOCK();
1345 		se = audit_session_find(uap->asid);
1346 		AUDIT_SENTRY_RUNLOCK();
1347 		if (NULL == se) {
1348 			err = EINVAL;
1349 			goto done;
1350 		}
1351 		aia_p = &se->se_auinfo;
1352 	}
1353 
1354 	/*
1355 	 * Processes that join using this mach port will inherit this process'
1356 	 * pre-selection masks.
1357 	 */
1358 	if (se->se_port == IPC_PORT_NULL) {
1359 		bcopy(&cred->cr_audit.as_mask, &se->se_mask,
1360 		    sizeof(se->se_mask));
1361 	}
1362 
1363 	/*
1364 	 * Use the session reference to create a mach port reference for the
1365 	 * session (at which point we are free to drop the session reference)
1366 	 * and then copy out the mach port to the process' mach port namespace.
1367 	 */
1368 	sendport = audit_session_mksend(aia_p, &se->se_port);
1369 	portname = ipc_port_copyout_send(sendport, get_task_ipcspace(proc_task(p)));
1370 	if (!MACH_PORT_VALID(portname)) {
1371 		err = EINVAL;
1372 		goto done;
1373 	}
1374 	err = copyout(&portname, uap->portnamep, sizeof(mach_port_name_t));
1375 done:
1376 	if (cred != NULL) {
1377 		kauth_cred_unref(&cred);
1378 	}
1379 	if (NULL != se) {
1380 		audit_unref_session(se);
1381 	}
1382 	if (MACH_PORT_VALID(portname) && 0 != err) {
1383 		(void)mach_port_deallocate(get_task_ipcspace(proc_task(p)),
1384 		    portname);
1385 	}
1386 
1387 	return err;
1388 }
1389 
1390 static int
audit_session_join_internal(proc_t p,ipc_port_t port,au_asid_t * new_asid)1391 audit_session_join_internal(proc_t p, ipc_port_t port, au_asid_t *new_asid)
1392 {
1393 	__block auditinfo_addr_t *old_aia_p = NULL;
1394 	auditinfo_addr_t *new_aia_p;
1395 	int err = 0;
1396 
1397 	if ((new_aia_p = audit_session_porttoaia(port)) == NULL) {
1398 		err = EINVAL;
1399 		*new_asid = AU_DEFAUDITSID;
1400 		goto done;
1401 	}
1402 
1403 	/* Increment the proc count of new session */
1404 	audit_inc_procount(AU_SENTRY_PTR(new_aia_p));
1405 
1406 	proc_audit_session_lock(p);
1407 
1408 	kauth_cred_proc_update(p, PROC_SETTOKEN_LAZY,
1409 	    ^bool (kauth_cred_t parent __unused, kauth_cred_t model) {
1410 		struct au_session new_as;
1411 
1412 		old_aia_p = model->cr_audit.as_aia_p;
1413 
1414 		if (old_aia_p->ai_asid == new_aia_p->ai_asid) {
1415 		        return false;
1416 		}
1417 
1418 		bcopy(&new_aia_p->ai_mask, &new_as.as_mask,
1419 		sizeof(new_as.as_mask));
1420 		new_as.as_aia_p = new_aia_p;
1421 
1422 		return kauth_cred_model_setauditinfo(model, &new_as);
1423 	});
1424 
1425 	proc_audit_session_unlock(p);
1426 
1427 	/* Decrement the process count of the former session. */
1428 	audit_dec_procount(AU_SENTRY_PTR(old_aia_p));
1429 
1430 	*new_asid = new_aia_p->ai_asid;
1431 
1432 done:
1433 	if (port != IPC_PORT_NULL) {
1434 		ipc_typed_port_release_send(port, IKOT_AU_SESSIONPORT);
1435 	}
1436 
1437 	return err;
1438 }
1439 
1440 /*
1441  * audit_session_spawnjoin
1442  *
1443  * Description: posix_spawn() interface to audit_session_join_internal().
1444  *
1445  * Returns:	0		Success
1446  *              EINVAL		Invalid Mach port name.
1447  *              ESRCH		Invalid calling process/cred.
1448  */
1449 int
audit_session_spawnjoin(proc_t p,ipc_port_t port)1450 audit_session_spawnjoin(proc_t p, ipc_port_t port)
1451 {
1452 	au_asid_t new_asid;
1453 
1454 	return audit_session_join_internal(p, port, &new_asid);
1455 }
1456 
1457 /*
1458  * audit_session_join  (system call)
1459  *
1460  * Description:	Join the session for a given Mach port send right.
1461  *
1462  * Parameters:	p		Process calling session join.
1463  *              uap->port	A Mach send right.
1464  *
1465  * Returns:	*ret_asid	Audit session ID of new session.
1466  *				In the failure case the return value will be -1
1467  *				and 'errno' will be set to a non-zero value
1468  *				described below.
1469  *
1470  * Errno:	0		Success
1471  *              EINVAL		Invalid Mach port name.
1472  *              ESRCH		Invalid calling process/cred.
1473  */
1474 int
audit_session_join(proc_t p,struct audit_session_join_args * uap,au_asid_t * ret_asid)1475 audit_session_join(proc_t p, struct audit_session_join_args *uap,
1476     au_asid_t *ret_asid)
1477 {
1478 	ipc_port_t port = IPC_PORT_NULL;
1479 	mach_port_name_t send = uap->port;
1480 	int err = 0;
1481 
1482 
1483 	if (ipc_typed_port_copyin_send(get_task_ipcspace(proc_task(p)), send,
1484 	    IKOT_AU_SESSIONPORT, &port) != KERN_SUCCESS) {
1485 		*ret_asid = AU_DEFAUDITSID;
1486 		err = EINVAL;
1487 	} else {
1488 		err = audit_session_join_internal(p, port, ret_asid);
1489 	}
1490 
1491 	return err;
1492 }
1493 
1494 /*
1495  * Audit session device.
1496  */
1497 
1498 /*
1499  * Free an audit sdev entry.
1500  */
1501 static void
audit_sdev_entry_free(struct audit_sdev_entry * ase)1502 audit_sdev_entry_free(struct audit_sdev_entry *ase)
1503 {
1504 	kfree_data(ase->ase_record, ase->ase_record_len);
1505 	kfree_type(struct audit_sdev_entry, ase);
1506 }
1507 
1508 /*
1509  * Append individual record to a queue.  Allocate queue-local buffer and
1510  * add to the queue.  If the queue is full or we can't allocate memory,
1511  * drop the newest record.
1512  */
1513 static void
audit_sdev_append(struct audit_sdev * asdev,void * record,u_int record_len)1514 audit_sdev_append(struct audit_sdev *asdev, void *record, u_int record_len)
1515 {
1516 	struct audit_sdev_entry *ase;
1517 
1518 	AUDIT_SDEV_LOCK_ASSERT(asdev);
1519 
1520 	if (asdev->asdev_qlen >= asdev->asdev_qlimit) {
1521 		asdev->asdev_drops++;
1522 		audit_sdev_drops++;
1523 		return;
1524 	}
1525 
1526 	ase = kalloc_type(struct audit_sdev_entry, Z_NOWAIT | Z_ZERO);
1527 	if (NULL == ase) {
1528 		asdev->asdev_drops++;
1529 		audit_sdev_drops++;
1530 		return;
1531 	}
1532 
1533 	ase->ase_record = kalloc_data(record_len, Z_NOWAIT);
1534 	if (NULL == ase->ase_record) {
1535 		kfree_type(struct audit_sdev_entry, ase);
1536 		asdev->asdev_drops++;
1537 		audit_sdev_drops++;
1538 		return;
1539 	}
1540 
1541 	bcopy(record, ase->ase_record, record_len);
1542 	ase->ase_record_len = record_len;
1543 
1544 	TAILQ_INSERT_TAIL(&asdev->asdev_queue, ase, ase_queue);
1545 	asdev->asdev_inserts++;
1546 	asdev->asdev_qlen++;
1547 	asdev->asdev_qbyteslen += ase->ase_record_len;
1548 	selwakeup(&asdev->asdev_selinfo);
1549 	if (asdev->asdev_flags & AUDIT_SDEV_ASYNC) {
1550 		pgsigio(asdev->asdev_sigio, SIGIO);
1551 	}
1552 
1553 	cv_broadcast(&asdev->asdev_cv);
1554 }
1555 
1556 /*
1557  * Submit an audit record to be queued in the audit session device.
1558  */
1559 void
audit_sdev_submit(__unused au_id_t auid,__unused au_asid_t asid,void * record,u_int record_len)1560 audit_sdev_submit(__unused au_id_t auid, __unused au_asid_t asid, void *record,
1561     u_int record_len)
1562 {
1563 	struct audit_sdev *asdev;
1564 
1565 	/*
1566 	 * Lockless read to avoid lock overhead if sessio devices are not in
1567 	 * use.
1568 	 */
1569 	if (NULL == TAILQ_FIRST(&audit_sdev_list)) {
1570 		return;
1571 	}
1572 
1573 	AUDIT_SDEV_LIST_RLOCK();
1574 	TAILQ_FOREACH(asdev, &audit_sdev_list, asdev_list) {
1575 		AUDIT_SDEV_LOCK(asdev);
1576 
1577 		/*
1578 		 * Only append to the sdev queue if the AUID and ASID match that
1579 		 * of the process that opened this session device or if the
1580 		 * ALLSESSIONS flag is set.
1581 		 */
1582 		if ((/* XXXss auid == asdev->asdev_auid && */
1583 			    asid == asdev->asdev_asid) ||
1584 		    (asdev->asdev_flags & AUDIT_SDEV_ALLSESSIONS) != 0) {
1585 			audit_sdev_append(asdev, record, record_len);
1586 		}
1587 		AUDIT_SDEV_UNLOCK(asdev);
1588 	}
1589 	AUDIT_SDEV_LIST_RUNLOCK();
1590 
1591 	/* Unlocked increment. */
1592 	audit_sdev_records++;
1593 }
1594 
1595 /*
1596  * Allocate a new audit sdev.  Connects the sdev, on succes, to the global
1597  * list and updates statistics.
1598  */
1599 static struct audit_sdev *
audit_sdev_alloc(void)1600 audit_sdev_alloc(void)
1601 {
1602 	struct audit_sdev *asdev;
1603 
1604 	AUDIT_SDEV_LIST_WLOCK_ASSERT();
1605 
1606 	asdev = kalloc_type(struct audit_sdev, Z_ZERO | Z_WAITOK | Z_NOFAIL);
1607 	asdev->asdev_qlimit = AUDIT_SDEV_QLIMIT_DEFAULT;
1608 	TAILQ_INIT(&asdev->asdev_queue);
1609 	AUDIT_SDEV_LOCK_INIT(asdev);
1610 	AUDIT_SDEV_SX_LOCK_INIT(asdev);
1611 	cv_init(&asdev->asdev_cv, "audit_sdev_cv");
1612 
1613 	/*
1614 	 * Add to global list and update global statistics.
1615 	 */
1616 	TAILQ_INSERT_HEAD(&audit_sdev_list, asdev, asdev_list);
1617 	audit_sdev_count++;
1618 	audit_sdev_ever++;
1619 
1620 	return asdev;
1621 }
1622 
1623 /*
1624  * Flush all records currently present in an audit sdev.
1625  */
1626 static void
audit_sdev_flush(struct audit_sdev * asdev)1627 audit_sdev_flush(struct audit_sdev *asdev)
1628 {
1629 	struct audit_sdev_entry *ase;
1630 
1631 	AUDIT_SDEV_LOCK_ASSERT(asdev);
1632 
1633 	while ((ase = TAILQ_FIRST(&asdev->asdev_queue)) != NULL) {
1634 		TAILQ_REMOVE(&asdev->asdev_queue, ase, ase_queue);
1635 		asdev->asdev_qbyteslen -= ase->ase_record_len;
1636 		audit_sdev_entry_free(ase);
1637 		asdev->asdev_qlen--;
1638 	}
1639 	asdev->asdev_qoffset = 0;
1640 
1641 	KASSERT(0 == asdev->asdev_qlen, ("audit_sdev_flush: asdev_qlen"));
1642 	KASSERT(0 == asdev->asdev_qbyteslen,
1643 	    ("audit_sdev_flush: asdev_qbyteslen"));
1644 }
1645 
1646 /*
1647  * Free an audit sdev.
1648  */
1649 static void
audit_sdev_free(struct audit_sdev * asdev)1650 audit_sdev_free(struct audit_sdev *asdev)
1651 {
1652 	AUDIT_SDEV_LIST_WLOCK_ASSERT();
1653 	AUDIT_SDEV_LOCK_ASSERT(asdev);
1654 
1655 	/* XXXss - preselect hook here */
1656 	audit_sdev_flush(asdev);
1657 	cv_destroy(&asdev->asdev_cv);
1658 	AUDIT_SDEV_SX_LOCK_DESTROY(asdev);
1659 	AUDIT_SDEV_UNLOCK(asdev);
1660 	AUDIT_SDEV_LOCK_DESTROY(asdev);
1661 
1662 	TAILQ_REMOVE(&audit_sdev_list, asdev, asdev_list);
1663 	kfree_type(struct audit_sdev, asdev);
1664 	audit_sdev_count--;
1665 }
1666 
1667 /*
1668  * Get the auditinfo_addr of the proc and check to see if suser.  Will return
1669  * non-zero if not suser.
1670  */
1671 static int
audit_sdev_get_aia(proc_t p,struct auditinfo_addr * aia_p)1672 audit_sdev_get_aia(proc_t p, struct auditinfo_addr *aia_p)
1673 {
1674 	int error;
1675 	kauth_cred_t scred;
1676 
1677 	scred = kauth_cred_proc_ref(p);
1678 	error = suser(scred, &p->p_acflag);
1679 
1680 	if (NULL != aia_p) {
1681 		bcopy(scred->cr_audit.as_aia_p, aia_p, sizeof(*aia_p));
1682 	}
1683 	kauth_cred_unref(&scred);
1684 
1685 	return error;
1686 }
1687 
1688 /*
1689  * Audit session dev open method.
1690  */
1691 static int
audit_sdev_open(dev_t dev,__unused int flags,__unused int devtype,proc_t p)1692 audit_sdev_open(dev_t dev, __unused int flags, __unused int devtype, proc_t p)
1693 {
1694 	struct audit_sdev *asdev;
1695 	struct auditinfo_addr aia;
1696 	int u;
1697 
1698 	u = minor(dev);
1699 	if (u < 0 || u >= MAX_AUDIT_SDEVS) {
1700 		return ENXIO;
1701 	}
1702 
1703 	(void) audit_sdev_get_aia(p, &aia);
1704 
1705 	AUDIT_SDEV_LIST_WLOCK();
1706 	asdev = audit_sdev_dtab[u];
1707 	if (NULL == asdev) {
1708 		asdev = audit_sdev_alloc();
1709 		if (NULL == asdev) {
1710 			AUDIT_SDEV_LIST_WUNLOCK();
1711 			return ENOMEM;
1712 		}
1713 		audit_sdev_dtab[u] = asdev;
1714 	} else {
1715 		KASSERT(asdev->asdev_open, ("audit_sdev_open: Already open"));
1716 		AUDIT_SDEV_LIST_WUNLOCK();
1717 		return EBUSY;
1718 	}
1719 	asdev->asdev_open = 1;
1720 	asdev->asdev_auid = aia.ai_auid;
1721 	asdev->asdev_asid = aia.ai_asid;
1722 	asdev->asdev_flags = 0;
1723 
1724 	AUDIT_SDEV_LIST_WUNLOCK();
1725 
1726 	return 0;
1727 }
1728 
1729 /*
1730  * Audit session dev close method.
1731  */
1732 static int
audit_sdev_close(dev_t dev,__unused int flags,__unused int devtype,__unused proc_t p)1733 audit_sdev_close(dev_t dev, __unused int flags, __unused int devtype,
1734     __unused proc_t p)
1735 {
1736 	struct audit_sdev *asdev;
1737 	int u;
1738 
1739 	u = minor(dev);
1740 	asdev = audit_sdev_dtab[u];
1741 
1742 	KASSERT(asdev != NULL, ("audit_sdev_close: asdev == NULL"));
1743 	KASSERT(asdev->asdev_open, ("audit_sdev_close: !asdev_open"));
1744 
1745 	AUDIT_SDEV_LIST_WLOCK();
1746 	AUDIT_SDEV_LOCK(asdev);
1747 	asdev->asdev_open = 0;
1748 	audit_sdev_free(asdev);  /* sdev lock unlocked in audit_sdev_free() */
1749 	audit_sdev_dtab[u] = NULL;
1750 	AUDIT_SDEV_LIST_WUNLOCK();
1751 
1752 	return 0;
1753 }
1754 
1755 /*
1756  * Audit session dev ioctl method.
1757  */
1758 static int
audit_sdev_ioctl(dev_t dev,u_long cmd,caddr_t data,__unused int flag,proc_t p)1759 audit_sdev_ioctl(dev_t dev, u_long cmd, caddr_t data,
1760     __unused int flag, proc_t p)
1761 {
1762 	struct audit_sdev *asdev;
1763 	int error;
1764 
1765 	asdev = audit_sdev_dtab[minor(dev)];
1766 	KASSERT(asdev != NULL, ("audit_sdev_ioctl: asdev == NULL"));
1767 
1768 	error = 0;
1769 
1770 	switch (cmd) {
1771 	case FIONBIO:
1772 		AUDIT_SDEV_LOCK(asdev);
1773 		if (*(int *)data) {
1774 			asdev->asdev_flags |= AUDIT_SDEV_NBIO;
1775 		} else {
1776 			asdev->asdev_flags &= ~AUDIT_SDEV_NBIO;
1777 		}
1778 		AUDIT_SDEV_UNLOCK(asdev);
1779 		break;
1780 
1781 	case FIONREAD:
1782 		AUDIT_SDEV_LOCK(asdev);
1783 		*(int *)data = asdev->asdev_qbyteslen - asdev->asdev_qoffset;
1784 		AUDIT_SDEV_UNLOCK(asdev);
1785 		break;
1786 
1787 	case AUDITSDEV_GET_QLEN:
1788 		*(u_int *)data = asdev->asdev_qlen;
1789 		break;
1790 
1791 	case AUDITSDEV_GET_QLIMIT:
1792 		*(u_int *)data = asdev->asdev_qlimit;
1793 		break;
1794 
1795 	case AUDITSDEV_SET_QLIMIT:
1796 		if (*(u_int *)data >= AUDIT_SDEV_QLIMIT_MIN ||
1797 		    *(u_int *)data <= AUDIT_SDEV_QLIMIT_MAX) {
1798 			asdev->asdev_qlimit = *(u_int *)data;
1799 		} else {
1800 			error = EINVAL;
1801 		}
1802 		break;
1803 
1804 	case AUDITSDEV_GET_QLIMIT_MIN:
1805 		*(u_int *)data = AUDIT_SDEV_QLIMIT_MIN;
1806 		break;
1807 
1808 	case AUDITSDEV_GET_QLIMIT_MAX:
1809 		*(u_int *)data = AUDIT_SDEV_QLIMIT_MAX;
1810 		break;
1811 
1812 	case AUDITSDEV_FLUSH:
1813 		if (AUDIT_SDEV_SX_XLOCK_SIG(asdev) != 0) {
1814 			return EINTR;
1815 		}
1816 		AUDIT_SDEV_LOCK(asdev);
1817 		audit_sdev_flush(asdev);
1818 		AUDIT_SDEV_UNLOCK(asdev);
1819 		AUDIT_SDEV_SX_XUNLOCK(asdev);
1820 		break;
1821 
1822 	case AUDITSDEV_GET_MAXDATA:
1823 		*(u_int *)data = MAXAUDITDATA;
1824 		break;
1825 
1826 	/* XXXss these should be 64 bit, maybe. */
1827 	case AUDITSDEV_GET_INSERTS:
1828 		*(u_int *)data = asdev->asdev_inserts;
1829 		break;
1830 
1831 	case AUDITSDEV_GET_READS:
1832 		*(u_int *)data = asdev->asdev_reads;
1833 		break;
1834 
1835 	case AUDITSDEV_GET_DROPS:
1836 		*(u_int *)data = asdev->asdev_drops;
1837 		break;
1838 
1839 	case AUDITSDEV_GET_ALLSESSIONS:
1840 		error = audit_sdev_get_aia(p, NULL);
1841 		if (error) {
1842 			break;
1843 		}
1844 		*(u_int *)data = (asdev->asdev_flags & AUDIT_SDEV_ALLSESSIONS) ?
1845 		    1 : 0;
1846 		break;
1847 
1848 	case AUDITSDEV_SET_ALLSESSIONS:
1849 		error = audit_sdev_get_aia(p, NULL);
1850 		if (error) {
1851 			break;
1852 		}
1853 
1854 		AUDIT_SDEV_LOCK(asdev);
1855 		if (*(int *)data) {
1856 			asdev->asdev_flags |= AUDIT_SDEV_ALLSESSIONS;
1857 		} else {
1858 			asdev->asdev_flags &= ~AUDIT_SDEV_ALLSESSIONS;
1859 		}
1860 		AUDIT_SDEV_UNLOCK(asdev);
1861 		break;
1862 
1863 	default:
1864 		error = ENOTTY;
1865 	}
1866 
1867 	return error;
1868 }
1869 
1870 /*
1871  * Audit session dev read method.
1872  */
1873 static int
audit_sdev_read(dev_t dev,struct uio * uio,__unused int flag)1874 audit_sdev_read(dev_t dev, struct uio *uio, __unused int flag)
1875 {
1876 	struct audit_sdev_entry *ase;
1877 	struct audit_sdev *asdev;
1878 	u_int toread;
1879 	int error;
1880 
1881 	asdev = audit_sdev_dtab[minor(dev)];
1882 	KASSERT(NULL != asdev, ("audit_sdev_read: asdev == NULL"));
1883 
1884 	/*
1885 	 * We hold a sleep lock over read and flush because we rely on the
1886 	 * stability of a record in the queue during uiomove.
1887 	 */
1888 	if (0 != AUDIT_SDEV_SX_XLOCK_SIG(asdev)) {
1889 		return EINTR;
1890 	}
1891 	AUDIT_SDEV_LOCK(asdev);
1892 	while (TAILQ_EMPTY(&asdev->asdev_queue)) {
1893 		if (asdev->asdev_flags & AUDIT_SDEV_NBIO) {
1894 			AUDIT_SDEV_UNLOCK(asdev);
1895 			AUDIT_SDEV_SX_XUNLOCK(asdev);
1896 			return EAGAIN;
1897 		}
1898 		error = cv_wait_sig(&asdev->asdev_cv, AUDIT_SDEV_MTX(asdev));
1899 		if (error) {
1900 			AUDIT_SDEV_UNLOCK(asdev);
1901 			AUDIT_SDEV_SX_XUNLOCK(asdev);
1902 			return error;
1903 		}
1904 	}
1905 
1906 	/*
1907 	 * Copy as many remaining bytes from the current record to userspace
1908 	 * as we can. Keep processing records until we run out of records in
1909 	 * the queue or until the user buffer runs out of space.
1910 	 *
1911 	 * We rely on the sleep lock to maintain ase's stability here.
1912 	 */
1913 	asdev->asdev_reads++;
1914 	while ((ase = TAILQ_FIRST(&asdev->asdev_queue)) != NULL &&
1915 	    uio_resid(uio) > 0) {
1916 		AUDIT_SDEV_LOCK_ASSERT(asdev);
1917 
1918 		KASSERT(ase->ase_record_len > asdev->asdev_qoffset,
1919 		    ("audit_sdev_read: record_len > qoffset (1)"));
1920 		toread = MIN((int)(ase->ase_record_len - asdev->asdev_qoffset),
1921 		    uio_resid(uio));
1922 		AUDIT_SDEV_UNLOCK(asdev);
1923 		error = uiomove((char *) ase->ase_record + asdev->asdev_qoffset,
1924 		    toread, uio);
1925 		if (error) {
1926 			AUDIT_SDEV_SX_XUNLOCK(asdev);
1927 			return error;
1928 		}
1929 
1930 		/*
1931 		 * If the copy succeeded then update book-keeping, and if no
1932 		 * bytes remain in the current record then free it.
1933 		 */
1934 		AUDIT_SDEV_LOCK(asdev);
1935 		KASSERT(TAILQ_FIRST(&asdev->asdev_queue) == ase,
1936 		    ("audit_sdev_read: queue out of sync after uiomove"));
1937 		asdev->asdev_qoffset += toread;
1938 		KASSERT(ase->ase_record_len >= asdev->asdev_qoffset,
1939 		    ("audit_sdev_read: record_len >= qoffset (2)"));
1940 		if (asdev->asdev_qoffset == ase->ase_record_len) {
1941 			TAILQ_REMOVE(&asdev->asdev_queue, ase, ase_queue);
1942 			asdev->asdev_qbyteslen -= ase->ase_record_len;
1943 			audit_sdev_entry_free(ase);
1944 			asdev->asdev_qlen--;
1945 			asdev->asdev_qoffset = 0;
1946 		}
1947 	}
1948 	AUDIT_SDEV_UNLOCK(asdev);
1949 	AUDIT_SDEV_SX_XUNLOCK(asdev);
1950 	return 0;
1951 }
1952 
1953 /*
1954  * Audit session device poll method.
1955  */
1956 static int
audit_sdev_poll(dev_t dev,int events,void * wql,struct proc * p)1957 audit_sdev_poll(dev_t dev, int events, void *wql, struct proc *p)
1958 {
1959 	struct audit_sdev *asdev;
1960 	int revents;
1961 
1962 	revents = 0;
1963 	asdev = audit_sdev_dtab[minor(dev)];
1964 	KASSERT(NULL != asdev, ("audit_sdev_poll: asdev == NULL"));
1965 
1966 	if (events & (POLLIN | POLLRDNORM)) {
1967 		AUDIT_SDEV_LOCK(asdev);
1968 		if (NULL != TAILQ_FIRST(&asdev->asdev_queue)) {
1969 			revents |= events & (POLLIN | POLLRDNORM);
1970 		} else {
1971 			selrecord(p, &asdev->asdev_selinfo, wql);
1972 		}
1973 		AUDIT_SDEV_UNLOCK(asdev);
1974 	}
1975 	return revents;
1976 }
1977 
1978 /*
1979  * Audit sdev clone routine.  Provides a new minor number or returns -1.
1980  * This called with DEVFS_LOCK held.
1981  */
1982 static int
audit_sdev_clone(__unused dev_t dev,int action)1983 audit_sdev_clone(__unused dev_t dev, int action)
1984 {
1985 	int i;
1986 
1987 	if (DEVFS_CLONE_ALLOC == action) {
1988 		for (i = 0; i < MAX_AUDIT_SDEVS; i++) {
1989 			if (NULL == audit_sdev_dtab[i]) {
1990 				return i;
1991 			}
1992 		}
1993 
1994 		/*
1995 		 * This really should return -1 here but that seems to
1996 		 * hang things in devfs.  We instead return 0 and let
1997 		 * audit_sdev_open tell userland the bad news.
1998 		 */
1999 		return 0;
2000 	}
2001 
2002 	return -1;
2003 }
2004 
2005 static int
audit_sdev_init(void)2006 audit_sdev_init(void)
2007 {
2008 	dev_t dev;
2009 
2010 	TAILQ_INIT(&audit_sdev_list);
2011 	AUDIT_SDEV_LIST_LOCK_INIT();
2012 
2013 	audit_sdev_major = cdevsw_add(-1, &audit_sdev_cdevsw);
2014 	if (audit_sdev_major < 0) {
2015 		return KERN_FAILURE;
2016 	}
2017 
2018 	dev = makedev(audit_sdev_major, 0);
2019 	devnode = devfs_make_node_clone(dev, DEVFS_CHAR, UID_ROOT, GID_WHEEL,
2020 	    0644, audit_sdev_clone, AUDIT_SDEV_NAME);
2021 
2022 	if (NULL == devnode) {
2023 		return KERN_FAILURE;
2024 	}
2025 
2026 	return KERN_SUCCESS;
2027 }
2028 
2029 /* XXXss
2030  *  static int
2031  *  audit_sdev_shutdown(void)
2032  *  {
2033  *
2034  *       devfs_remove(devnode);
2035  *       (void) cdevsw_remove(audit_sdev_major, &audit_sdev_cdevsw);
2036  *
2037  *       return (KERN_SUCCESS);
2038  *  }
2039  */
2040 
2041 #else
2042 
2043 int
audit_session_self(proc_t p,struct audit_session_self_args * uap,mach_port_name_t * ret_port)2044 audit_session_self(proc_t p, struct audit_session_self_args *uap,
2045     mach_port_name_t *ret_port)
2046 {
2047 #pragma unused(p, uap, ret_port)
2048 
2049 	return ENOSYS;
2050 }
2051 
2052 int
audit_session_join(proc_t p,struct audit_session_join_args * uap,au_asid_t * ret_asid)2053 audit_session_join(proc_t p, struct audit_session_join_args *uap,
2054     au_asid_t *ret_asid)
2055 {
2056 #pragma unused(p, uap, ret_asid)
2057 
2058 	return ENOSYS;
2059 }
2060 
2061 int
audit_session_port(proc_t p,struct audit_session_port_args * uap,int * retval)2062 audit_session_port(proc_t p, struct audit_session_port_args *uap, int *retval)
2063 {
2064 #pragma unused(p, uap, retval)
2065 
2066 	return ENOSYS;
2067 }
2068 
2069 #endif /* CONFIG_AUDIT */
2070