xref: /illumos-gate/usr/src/lib/libbsm/common/adt.c (revision 055d7c804dc8f1263f0b3166ba459c65996b8697)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 #include <bsm/adt.h>
29 #include <bsm/adt_event.h>
30 #include <assert.h>
31 #include <bsm/audit.h>
32 #include <bsm/audit_record.h>
33 #include <bsm/libbsm.h>
34 #include <door.h>
35 #include <errno.h>
36 #include <generic.h>
37 #include <md5.h>
38 #include <sys/mkdev.h>
39 #include <netdb.h>
40 #include <nss_dbdefs.h>
41 #include <pwd.h>
42 #include <sys/stat.h>
43 #include <time.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <synch.h>
47 #include <sys/systeminfo.h>
48 #include <syslog.h>
49 #include <thread.h>
50 #include <unistd.h>
51 #include <adt_xlate.h>
52 #include <adt_ucred.h>
53 
54 static int adt_selected(struct adt_event_state *, au_event_t, int);
55 static int adt_init(adt_internal_state_t *, int);
56 static int adt_import(adt_internal_state_t *, const adt_export_data_t *);
57 static m_label_t *adt_ucred_label(ucred_t *);
58 
59 #ifdef C2_DEBUG
60 #define	DPRINTF(x) {printf x; }
61 #define	DFLUSH fflush(stdout);
62 #else
63 #define	DPRINTF(x)
64 #define	DFLUSH
65 #endif
66 
67 extern int _mutex_lock(mutex_t *);
68 extern int _mutex_unlock(mutex_t *);
69 
70 static int auditstate = AUC_DISABLED;	/* default state */
71 
72 /*
73  * adt_write_syslog
74  *
75  * errors that are not the user's fault (bugs or whatever in
76  * the underlying audit code are noted in syslog.)
77  *
78  * Avoid calling adt_write_syslog for things that can happen
79  * at high volume.
80  *
81  * syslog's open (openlog) and close (closelog) are interesting;
82  * openlog *may* create a file descriptor and is optional.  closelog
83  * *will* close any open file descriptors and is also optional.
84  *
85  * Since syslog may also be used by the calling application, the
86  * choice is to avoid openlog, which sets some otherwise useful
87  * parameters, and to embed "Solaris_audit" in the log message.
88  */
89 
90 void
91 adt_write_syslog(const char *message, int err)
92 {
93 	int	save_errno;
94 	int	mask_priority;
95 
96 	save_errno = errno;
97 	errno = err;
98 
99 	DPRINTF(("syslog called: %s\n", message));
100 
101 	mask_priority = setlogmask(LOG_MASK(LOG_ALERT));
102 	syslog(LOG_ALERT, "Solaris_audit %s: %m", message, err);
103 	(void) setlogmask(mask_priority);
104 	errno = save_errno;
105 }
106 
107 /*
108  * return true if audit is enabled.  "Enabled" is any state
109  * other than AUC_DISABLED.
110  *
111  * states are
112  *		AUC_INIT_AUDIT	-- c2audit queuing enabled.
113  *		AUC_AUDITING	-- up and running
114  *		AUC_DISABLED	-- no audit subsystem loaded
115  *		AUC_UNSET	-- early boot state
116  *		AUC_NOAUDIT	-- subsystem loaded, turned off via
117  *				   auditon(A_SETCOND...)
118  *		AUC_NOSPACE	-- up and running, but log partitions are full
119  *
120  *	For purpose of this API, anything but AUC_DISABLED or
121  *	AUC_UNSET is enabled; however one never actually sees
122  *	AUC_DISABLED since auditon returns EINVAL in that case.  Any
123  *	auditon error is considered the same as EINVAL for our
124  *	purpose.  auditstate is not changed by auditon if an error
125  *	is returned.
126  */
127 
128 boolean_t
129 adt_audit_enabled(void) {
130 
131 	(void) auditon(A_GETCOND, (caddr_t)&auditstate, sizeof (auditstate));
132 
133 	return (auditstate != AUC_DISABLED);
134 }
135 
136 /*
137  * The man page for getpwuid_r says the buffer must be big enough
138  * or ERANGE will be returned, but offers no guidance for how big
139  * the buffer should be or a way to calculate it.  If you get
140  * ERANGE, double pwd_buff's size.
141  *
142  * This may be called even when auditing is off.
143  */
144 
145 #define	NAFLAG_LEN 512
146 
147 static int
148 adt_get_mask_from_user(uid_t uid, au_mask_t *mask)
149 {
150 	struct passwd	pwd;
151 	char		pwd_buff[NSS_BUFSIZ];
152 	char		naflag_buf[NAFLAG_LEN];
153 
154 	if (auditstate == AUC_DISABLED) {
155 		mask->am_success = 0;
156 		mask->am_failure = 0;
157 	} else if (uid >= 0) {
158 		if (getpwuid_r(uid, &pwd, pwd_buff, NSS_BUFSIZ) == NULL) {
159 			/*
160 			 * getpwuid_r returns NULL without setting
161 			 * errno if the user does not exist; only
162 			 * if the input is the wrong length does it
163 			 * set errno.
164 			 */
165 			if (errno != ERANGE)
166 				errno = EINVAL;
167 			return (-1);
168 		}
169 		if (au_user_mask(pwd.pw_name, mask)) {
170 			errno = EFAULT; /* undetermined failure */
171 			return (-1);
172 		}
173 	} else if (getacna(naflag_buf, NAFLAG_LEN - 1) == 0) {
174 		if (getauditflagsbin(naflag_buf, mask))
175 			return (-1);
176 	} else {
177 		return (-1);
178 	}
179 	return (0);
180 }
181 
182 /*
183  * adt_get_unique_id -- generate a hopefully unique 32 bit value
184  *
185  * there will be a follow up to replace this with the use of /dev/random
186  *
187  * An MD5 hash is taken on a buffer of
188  *     hostname . audit id . unix time . pid . count
189  *
190  * "count = noise++;" is subject to a race condition but I don't
191  * see a need to put a lock around it.
192  */
193 
194 static au_id_t
195 adt_get_unique_id(uid_t uid)
196 {
197 	char		hostname[MAXHOSTNAMELEN];
198 	union {
199 		au_id_t		v[4];
200 		unsigned char	obuff[128/8];
201 	} output;
202 	MD5_CTX	context;
203 
204 	static int	noise = 0;
205 
206 	int		count = noise++;
207 	time_t		timebits = time(NULL);
208 	pid_t		pidbits = getpid();
209 	au_id_t		retval = 0;
210 
211 	if (gethostname(hostname, MAXHOSTNAMELEN)) {
212 		adt_write_syslog("gethostname call failed", errno);
213 		(void) strncpy(hostname, "invalidHostName", MAXHOSTNAMELEN);
214 	}
215 
216 	while (retval == 0) {  /* 0 is the only invalid result */
217 		MD5Init(&context);
218 
219 		MD5Update(&context, (unsigned char *)hostname,
220 		    (unsigned int) strlen((const char *)hostname));
221 
222 		MD5Update(&context, (unsigned char *) &uid, sizeof (uid_t));
223 
224 		MD5Update(&context,
225 		    (unsigned char *) &timebits, sizeof (time_t));
226 
227 		MD5Update(&context, (unsigned char *) &pidbits,
228 		    sizeof (pid_t));
229 
230 		MD5Update(&context, (unsigned char *) &(count), sizeof (int));
231 		MD5Final(output.obuff, &context);
232 
233 		retval = output.v[count % 4];
234 	}
235 	return (retval);
236 }
237 
238 /*
239  * the following "port" function deals with the following issues:
240  *
241  * 1    the kernel and ucred deal with a dev_t as a 64 bit value made
242  *      up from a 32 bit major and 32 bit minor.
243  * 2    User space deals with a dev_t as either the above 64 bit value
244  *      or a 32 bit value made from a 14 bit major and an 18 bit minor.
245  * 3    The various audit interfaces (except ucred) pass the 32 or
246  *      64 bit version depending the architecture of the userspace
247  *      application.  If you get a port value from ucred and pass it
248  *      to the kernel via auditon(), it must be squeezed into a 32
249  *      bit value because the kernel knows the userspace app's bit
250  *      size.
251  *
252  * The internal state structure for adt (adt_internal_state_t) uses
253  * dev_t, so adt converts data from ucred to fit.  The import/export
254  * functions, however, can't know if they are importing/exporting
255  * from 64 or 32 bit applications, so they always send 64 bits and
256  * the 32 bit end(s) are responsible to convert 32 -> 64 -> 32 as
257  * appropriate.
258  */
259 
260 /*
261  * adt_cpy_tid() -- if lib is 64 bit, just copy it (dev_t and port are
262  * both 64 bits).  If lib is 32 bits, squeeze the two-int port into
263  * a 32 bit dev_t.  A port fits in the "minor" part of au_port_t,
264  * so it isn't broken up into pieces.  (When it goes to the kernel
265  * and back, however, it will have been split into major/minor
266  * pieces.)
267  */
268 
269 static void
270 adt_cpy_tid(au_tid_addr_t *dest, const au_tid64_addr_t *src)
271 {
272 #ifdef _LP64
273 	(void) memcpy(dest, src, sizeof (au_tid_addr_t));
274 #else
275 	dest->at_type = src->at_type;
276 
277 	dest->at_port  = src->at_port.at_minor & MAXMIN32;
278 	dest->at_port |= (src->at_port.at_major & MAXMAJ32) <<
279 	    NBITSMINOR32;
280 
281 	(void) memcpy(dest->at_addr, src->at_addr, 4 * sizeof (uint32_t));
282 #endif
283 }
284 
285 /*
286  * adt_start_session -- create interface handle, create context
287  *
288  * The imported_state input is normally NULL, if not, it represents
289  * a continued session; its values obviate the need for a subsequent
290  * call to adt_set_user().
291  *
292  * The flag is used to decide how to set the initial state of the session.
293  * If 0, the session is "no audit" until a call to adt_set_user; if
294  * ADT_USE_PROC_DATA, the session is built from the process audit
295  * characteristics obtained from the kernel.  If imported_state is
296  * not NULL, the resulting audit mask is an OR of the current process
297  * audit mask and that passed in.
298  *
299  * The basic model is that the caller can use the pointer returned
300  * by adt_start_session whether or not auditing is enabled or an
301  * error was returned.  The functions that take the session handle
302  * as input generally return without doing anything if auditing is
303  * disabled.
304  */
305 
306 int
307 adt_start_session(adt_session_data_t **new_session,
308     const adt_export_data_t *imported_state, adt_session_flags_t flags)
309 {
310 	adt_internal_state_t	*state;
311 	adt_session_flags_t	flgmask = ADT_FLAGS_ALL;
312 
313 	*new_session = NULL;	/* assume failure */
314 
315 	/* ensure that auditstate is set */
316 	(void) adt_audit_enabled();
317 
318 	if ((flags & ~flgmask) != 0) {
319 		errno = EINVAL;
320 		goto return_err;
321 	}
322 	state = calloc(1, sizeof (adt_internal_state_t));
323 
324 	if (state == NULL)
325 		goto return_err;
326 
327 	if (adt_init(state, flags & ADT_USE_PROC_DATA) != 0)
328 		goto return_err_free;    /* errno from adt_init() */
329 
330 	/*
331 	 * The imported state overwrites the initial state if the
332 	 * imported state represents a valid audit trail
333 	 */
334 
335 	if (imported_state != NULL) {
336 		if (adt_import(state, imported_state) != 0) {
337 			goto return_err_free;
338 		}
339 	} else if (flags & ADT_USE_PROC_DATA) {
340 		state->as_session_model = ADT_PROCESS_MODEL;
341 	}
342 	state->as_flags = flags;
343 	DPRINTF(("(%d) Starting session id = %08X\n",
344 	    getpid(), state->as_info.ai_asid));
345 
346 	if (state->as_audit_enabled) {
347 		*new_session = (adt_session_data_t *)state;
348 	} else {
349 		free(state);
350 	}
351 
352 	return (0);
353 return_err_free:
354 	free(state);
355 return_err:
356 	adt_write_syslog("audit session create failed", errno);
357 	return (-1);
358 }
359 
360 /*
361  * adt_get_asid() and adt_set_asid()
362  *
363  * if you use this interface, you are responsible to insure that the
364  * rest of the session data is populated correctly before calling
365  * adt_proccess_attr()
366  *
367  * neither of these are intended for general use and will likely
368  * remain private interfaces for a long time.  Forever is a long
369  * time.  In the case of adt_set_asid(), you should have a very,
370  * very good reason for setting your own session id.  The process
371  * audit characteristics are not changed by put, use adt_set_proc().
372  *
373  * These are "volatile" (more changable than "evolving") and will
374  * probably change in the S10 period.
375  */
376 
377 void
378 adt_get_asid(const adt_session_data_t *session_data, au_asid_t *asid)
379 {
380 
381 	if (session_data == NULL) {
382 		*asid = 0;
383 	} else {
384 		assert(((adt_internal_state_t *)session_data)->as_check ==
385 		    ADT_VALID);
386 
387 		*asid = ((adt_internal_state_t *)session_data)->as_info.ai_asid;
388 	}
389 }
390 
391 void
392 adt_set_asid(const adt_session_data_t *session_data, const au_asid_t session_id)
393 {
394 
395 	if (session_data != NULL) {
396 		assert(((adt_internal_state_t *)session_data)->as_check ==
397 		    ADT_VALID);
398 
399 		((adt_internal_state_t *)session_data)->as_have_user_data |=
400 		    ADT_HAVE_ASID;
401 		((adt_internal_state_t *)session_data)->as_info.ai_asid =
402 		    session_id;
403 	}
404 }
405 
406 /*
407  * adt_get_auid() and adt_set_auid()
408  *
409  * neither of these are intended for general use and will likely
410  * remain private interfaces for a long time.  Forever is a long
411  * time.  In the case of adt_set_auid(), you should have a very,
412  * very good reason for setting your own audit id.  The process
413  * audit characteristics are not changed by put, use adt_set_proc().
414  */
415 
416 void
417 adt_get_auid(const adt_session_data_t *session_data, au_id_t *auid)
418 {
419 
420 	if (session_data == NULL) {
421 		*auid = AU_NOAUDITID;
422 	} else {
423 		assert(((adt_internal_state_t *)session_data)->as_check ==
424 		    ADT_VALID);
425 
426 		*auid = ((adt_internal_state_t *)session_data)->as_info.ai_auid;
427 	}
428 }
429 
430 void
431 adt_set_auid(const adt_session_data_t *session_data, const au_id_t audit_id)
432 {
433 
434 	if (session_data != NULL) {
435 		assert(((adt_internal_state_t *)session_data)->as_check ==
436 		    ADT_VALID);
437 
438 		((adt_internal_state_t *)session_data)->as_have_user_data |=
439 		    ADT_HAVE_AUID;
440 		((adt_internal_state_t *)session_data)->as_info.ai_auid =
441 		    audit_id;
442 	}
443 }
444 
445 /*
446  * adt_get_termid(), adt_set_termid()
447  *
448  * if you use this interface, you are responsible to insure that the
449  * rest of the session data is populated correctly before calling
450  * adt_proccess_attr()
451  *
452  * The process  audit characteristics are not changed by put, use
453  * adt_set_proc().
454  */
455 
456 void
457 adt_get_termid(const adt_session_data_t *session_data, au_tid_addr_t *termid)
458 {
459 
460 	if (session_data == NULL) {
461 		(void) memset(termid, 0, sizeof (au_tid_addr_t));
462 		termid->at_type = AU_IPv4;
463 	} else {
464 		assert(((adt_internal_state_t *)session_data)->as_check ==
465 		    ADT_VALID);
466 
467 		*termid =
468 		    ((adt_internal_state_t *)session_data)->as_info.ai_termid;
469 	}
470 }
471 
472 void
473 adt_set_termid(const adt_session_data_t *session_data,
474     const au_tid_addr_t *termid)
475 {
476 
477 	if (session_data != NULL) {
478 		assert(((adt_internal_state_t *)session_data)->as_check ==
479 		    ADT_VALID);
480 
481 		((adt_internal_state_t *)session_data)->as_info.ai_termid =
482 			*termid;
483 
484 		((adt_internal_state_t *)session_data)->as_have_user_data |=
485 			ADT_HAVE_TID;
486 	}
487 }
488 
489 /*
490  * adt_get_mask(), adt_set_mask()
491  *
492  * if you use this interface, you are responsible to insure that the
493  * rest of the session data is populated correctly before calling
494  * adt_proccess_attr()
495  *
496  * The process  audit characteristics are not changed by put, use
497  * adt_set_proc().
498  */
499 
500 void
501 adt_get_mask(const adt_session_data_t *session_data, au_mask_t *mask)
502 {
503 
504 	if (session_data == NULL) {
505 		mask->am_success = 0;
506 		mask->am_failure = 0;
507 	} else {
508 		assert(((adt_internal_state_t *)session_data)->as_check ==
509 		    ADT_VALID);
510 
511 		*mask = ((adt_internal_state_t *)session_data)->as_info.ai_mask;
512 	}
513 }
514 
515 void
516 adt_set_mask(const adt_session_data_t *session_data, const au_mask_t *mask)
517 {
518 
519 	if (session_data != NULL) {
520 		assert(((adt_internal_state_t *)session_data)->as_check ==
521 		    ADT_VALID);
522 
523 		((adt_internal_state_t *)session_data)->as_info.ai_mask = *mask;
524 
525 		((adt_internal_state_t *)session_data)->as_have_user_data |=
526 		    ADT_HAVE_MASK;
527 	}
528 }
529 
530 /*
531  * helpers for adt_load_termid
532  */
533 
534 static void
535 adt_do_ipv6_address(struct sockaddr_in6 *peer, struct sockaddr_in6 *sock,
536     au_tid_addr_t *termid)
537 {
538 
539 	termid->at_port = ((peer->sin6_port<<16) | (sock->sin6_port));
540 	termid->at_type = AU_IPv6;
541 	(void) memcpy(termid->at_addr, &peer->sin6_addr, 4 * sizeof (uint_t));
542 }
543 
544 static void
545 adt_do_ipv4_address(struct sockaddr_in *peer, struct sockaddr_in *sock,
546     au_tid_addr_t *termid)
547 {
548 
549 	termid->at_port = ((peer->sin_port<<16) | (sock->sin_port));
550 
551 	termid->at_type = AU_IPv4;
552 	termid->at_addr[0] = (uint32_t)peer->sin_addr.s_addr;
553 	(void) memset(&(termid->at_addr[1]), 0, 3 * sizeof (uint_t));
554 }
555 
556 /*
557  * adt_load_termid:  convenience function; inputs file handle and
558  * outputs an au_tid_addr struct.
559  *
560  * This code was stolen from audit_settid.c; it differs from audit_settid()
561  * in that it does not write the terminal id to the process.
562  */
563 
564 int
565 adt_load_termid(int fd, adt_termid_t **termid)
566 {
567 	au_tid_addr_t		*p_term;
568 	struct sockaddr_in6	peer;
569 	struct sockaddr_in6	sock;
570 	int			peerlen = sizeof (peer);
571 	int			socklen = sizeof (sock);
572 
573 	*termid = NULL;
574 
575 	/* get peer name if its a socket, else assume local terminal */
576 
577 	if (getpeername(fd, (struct sockaddr *)&peer, (socklen_t *)&peerlen)
578 	    < 0) {
579 		if (errno == ENOTSOCK)
580 			return (adt_load_hostname(NULL, termid));
581 		goto return_err;
582 	}
583 
584 	if ((p_term = calloc(1, sizeof (au_tid_addr_t))) == NULL)
585 		goto return_err;
586 
587 	/* get sock name */
588 	if (getsockname(fd, (struct sockaddr *)&sock,
589 	    (socklen_t *)&socklen) < 0)
590 		goto return_err_free;
591 
592 	if (peer.sin6_family == AF_INET6) {
593 		adt_do_ipv6_address(&peer, &sock, p_term);
594 	} else {
595 		adt_do_ipv4_address((struct sockaddr_in *)&peer,
596 		    (struct sockaddr_in *)&sock, p_term);
597 	}
598 	*termid = (adt_termid_t *)p_term;
599 
600 	return (0);
601 
602 return_err_free:
603 	free(p_term);
604 return_err:
605 	return (-1);
606 }
607 
608 static boolean_t
609 adt_have_termid(au_tid_addr_t *dest)
610 {
611 	struct auditinfo_addr	audit_data;
612 
613 	if (getaudit_addr(&audit_data, sizeof (audit_data)) < 0) {
614 		adt_write_syslog("getaudit failed", errno);
615 		return (B_FALSE);
616 	}
617 
618 	if ((audit_data.ai_termid.at_type == 0) ||
619 	    (audit_data.ai_termid.at_addr[0] |
620 	    audit_data.ai_termid.at_addr[1]  |
621 	    audit_data.ai_termid.at_addr[2]  |
622 	    audit_data.ai_termid.at_addr[3]) == 0)
623 		return (B_FALSE);
624 
625 	(void) memcpy(dest, &(audit_data.ai_termid),
626 	    sizeof (au_tid_addr_t));
627 
628 	return (B_TRUE);
629 }
630 
631 static int
632 adt_get_hostIP(const char *hostname, au_tid_addr_t *p_term)
633 {
634 	struct addrinfo	*ai;
635 	void		*p;
636 
637 	if (getaddrinfo(hostname, NULL, NULL, &ai) != 0)
638 		return (-1);
639 
640 	switch (ai->ai_family) {
641 		case AF_INET:
642 			/* LINTED */
643 			p = &((struct sockaddr_in *)ai->ai_addr)->sin_addr;
644 			(void) memcpy(p_term->at_addr, p,
645 			    sizeof (((struct sockaddr_in *)NULL)->sin_addr));
646 			p_term->at_type = AU_IPv4;
647 			break;
648 		case AF_INET6:
649 			/* LINTED */
650 			p = &((struct sockaddr_in6 *)ai->ai_addr)->sin6_addr,
651 			(void) memcpy(p_term->at_addr, p,
652 			    sizeof (((struct sockaddr_in6 *)NULL)->sin6_addr));
653 			p_term->at_type = AU_IPv6;
654 			break;
655 		default:
656 			return (-1);
657 	}
658 
659 	freeaddrinfo(ai);
660 
661 	return (0);
662 }
663 
664 /*
665  * adt_load_hostname() is called when the caller does not have a file
666  * handle that gives access to the socket info or any other way to
667  * pass in both port and ip address.  The hostname input is ignored if
668  * the terminal id has already been set; instead it returns the
669  * existing terminal id.
670  *
671  * If audit is off and the hostname lookup fails, no error is
672  * returned, since an error may be interpreted by the caller
673  * as grounds for denying a login.  Otherwise the caller would
674  * need to be aware of the audit state.
675  */
676 
677 int
678 adt_load_hostname(const char *hostname, adt_termid_t **termid)
679 {
680 	char		localhost[ADT_STRING_MAX + 1];
681 	au_tid_addr_t	*p_term;
682 
683 	*termid = NULL;
684 
685 	if (!adt_audit_enabled())
686 		return (0);
687 
688 	if ((p_term = calloc(1, sizeof (au_tid_addr_t))) == NULL)
689 		goto return_err;
690 
691 	if (adt_have_termid(p_term)) {
692 		*termid = (adt_termid_t *)p_term;
693 		return (0);
694 	}
695 	p_term->at_port = 0;
696 
697 	if (hostname == NULL || *hostname == '\0') {
698 		(void) sysinfo(SI_HOSTNAME, localhost, ADT_STRING_MAX);
699 		hostname = localhost;
700 	}
701 	if (adt_get_hostIP(hostname, p_term))
702 		goto return_err_free;
703 
704 	*termid = (adt_termid_t *)p_term;
705 	return (0);
706 
707 return_err_free:
708 	free(p_term);
709 
710 return_err:
711 	if ((auditstate == AUC_DISABLED) ||
712 	    (auditstate == AUC_NOAUDIT))
713 		return (0);
714 
715 	return (-1);
716 }
717 
718 /*
719  * adt_load_ttyname() is called when the caller does not have a file
720  * handle that gives access to the local terminal or any other way
721  * of determining the device id.  The ttyname input is ignored if
722  * the terminal id has already been set; instead it returns the
723  * existing terminal id.
724  *
725  * If audit is off and the ttyname lookup fails, no error is
726  * returned, since an error may be interpreted by the caller
727  * as grounds for denying a login.  Otherwise the caller would
728  * need to be aware of the audit state.
729  */
730 
731 int
732 adt_load_ttyname(const char *ttyname, adt_termid_t **termid)
733 {
734 	char		localhost[ADT_STRING_MAX + 1];
735 	au_tid_addr_t	*p_term;
736 	struct stat	stat_buf;
737 
738 	*termid = NULL;
739 
740 	if (!adt_audit_enabled())
741 		return (0);
742 
743 	if ((p_term = calloc(1, sizeof (au_tid_addr_t))) == NULL)
744 		goto return_err;
745 
746 	if (adt_have_termid(p_term)) {
747 		*termid = (adt_termid_t *)p_term;
748 		return (0);
749 	}
750 
751 	p_term->at_port = 0;
752 
753 	if (sysinfo(SI_HOSTNAME, localhost, ADT_STRING_MAX) < 0)
754 		goto return_err_free; /* errno from sysinfo */
755 
756 	if (ttyname != NULL) {
757 		if (stat(ttyname, &stat_buf) < 0)
758 			goto return_err_free;
759 
760 		p_term->at_port = stat_buf.st_rdev;
761 	}
762 
763 	if (adt_get_hostIP(localhost, p_term))
764 		goto return_err_free;
765 
766 	*termid = (adt_termid_t *)p_term;
767 	return (0);
768 
769 return_err_free:
770 	free(p_term);
771 
772 return_err:
773 	if ((auditstate == AUC_DISABLED) ||
774 	    (auditstate == AUC_NOAUDIT))
775 		return (0);
776 
777 	return (-1);
778 }
779 
780 /*
781  * adt_get_session_id returns a stringified representation of
782  * the audit session id.  See also adt_get_asid() for how to
783  * get the unexpurgated version.  No guarantees as to how long
784  * the returned string will be or its general form; hex for now.
785  *
786  * An empty string is returned if auditing is off; length = 1
787  * and the pointer is valid.
788  *
789  * returns strlen + 1 if buffer is valid; else 0 and errno.
790  */
791 
792 size_t
793 adt_get_session_id(const adt_session_data_t *session_data, char **buff)
794 {
795 	au_asid_t	session_id;
796 	size_t		length;
797 	/*
798 	 * output is 0x followed by
799 	 * two characters per byte
800 	 * plus terminator,
801 	 * except leading 0's are suppressed, so a few bytes may
802 	 * be unused.
803 	 */
804 	length = 2 + (2 * sizeof (session_id)) + 1;
805 	*buff = malloc(length);
806 
807 	if (*buff == NULL) {
808 		return (0);
809 	}
810 	if (session_data == NULL) { /* NULL is not an error */
811 		**buff = '\0';
812 		return (1);
813 	}
814 	adt_get_asid(session_data, &session_id);
815 
816 	length = snprintf(*buff, length, "0x%X", (int)session_id);
817 
818 	/* length < 1 is a bug: the session data type may have changed */
819 	assert(length > 0);
820 
821 	return (length);
822 }
823 
824 /*
825  * adt_end_session -- close handle, clear context
826  *
827  * if as_check is invalid, no harm, no foul, EXCEPT that this could
828  * be an attempt to free data already free'd, so output to syslog
829  * to help explain why the process cored dumped.
830  */
831 
832 int
833 adt_end_session(adt_session_data_t *session_data)
834 {
835 	adt_internal_state_t	*state;
836 
837 	if (session_data != NULL) {
838 		state = (adt_internal_state_t *)session_data;
839 		if (state->as_check != ADT_VALID) {
840 			adt_write_syslog("freeing invalid data", EINVAL);
841 		} else {
842 			state->as_check = 0;
843 			m_label_free(state->as_label);
844 			free(session_data);
845 		}
846 	}
847 	/* no errors yet defined */
848 	return (0);
849 }
850 
851 /*
852  * adt_dup_session -- copy the session data
853  */
854 
855 int
856 adt_dup_session(const adt_session_data_t *source, adt_session_data_t **dest)
857 {
858 	adt_internal_state_t	*source_state;
859 	adt_internal_state_t	*dest_state = NULL;
860 	int			rc = 0;
861 
862 	if (source != NULL) {
863 		source_state = (adt_internal_state_t *)source;
864 		assert(source_state->as_check == ADT_VALID);
865 
866 		dest_state = malloc(sizeof (adt_internal_state_t));
867 		if (dest_state == NULL) {
868 			rc = -1;
869 			goto return_rc;
870 		}
871 		(void) memcpy(dest_state, source,
872 		    sizeof (struct adt_internal_state));
873 
874 		if (source_state->as_label != NULL) {
875 			dest_state->as_label = NULL;
876 			if ((rc = m_label_dup(&dest_state->as_label,
877 			    source_state->as_label)) != 0) {
878 				free(dest_state);
879 				dest_state = NULL;
880 			}
881 		}
882 	}
883 return_rc:
884 	*dest = (adt_session_data_t *)dest_state;
885 	return (rc);
886 }
887 
888 /*
889  * from_export_format()
890  * read from a network order buffer into struct adt_session_data
891  */
892 
893 static size_t
894 adt_from_export_format(adt_internal_state_t *internal,
895     const adt_export_data_t *external)
896 {
897 	struct export_header	head;
898 	struct export_link	link;
899 	adr_t			context;
900 	int32_t 		offset;
901 	int32_t 		length;
902 	int32_t 		version;
903 	size_t			label_len;
904 	char			*p = (char *)external;
905 
906 	adrm_start(&context, (char *)external);
907 	adrm_int32(&context, (int *)&head, 4);
908 
909 	if ((internal->as_check = head.ax_check) != ADT_VALID) {
910 		errno = EINVAL;
911 		return (0);
912 	}
913 	offset = head.ax_link.ax_offset;
914 	version = head.ax_link.ax_version;
915 	length = head.ax_buffer_length;
916 
917 	/*
918 	 * Skip newer versions.
919 	 */
920 	while (version > PROTOCOL_VERSION_2) {
921 		if (offset < 1) {
922 			return (0);	/* failed to match version */
923 		}
924 		p += offset;		/* point to next version # */
925 
926 		if (p > (char *)external + length) {
927 			return (0);
928 		}
929 		adrm_start(&context, p);
930 		adrm_int32(&context, (int *)&link, 2);
931 		offset = link.ax_offset;
932 		version = link.ax_version;
933 		assert(version != 0);
934 	}
935 	/*
936 	 * Adjust buffer pointer to the first data item (euid).
937 	 */
938 	if (p == (char *)external) {
939 		adrm_start(&context, (char *)(p + sizeof (head)));
940 	} else {
941 		adrm_start(&context, (char *)(p + sizeof (link)));
942 	}
943 	/*
944 	 * if down rev version, neither pid nor label are included
945 	 * in v1 ax_size_of_tsol_data intentionally ignored
946 	 */
947 	if (version == PROTOCOL_VERSION_1) {
948 		adrm_int32(&context, (int *)&(internal->as_euid), 1);
949 		adrm_int32(&context, (int *)&(internal->as_ruid), 1);
950 		adrm_int32(&context, (int *)&(internal->as_egid), 1);
951 		adrm_int32(&context, (int *)&(internal->as_rgid), 1);
952 		adrm_int32(&context, (int *)&(internal->as_info.ai_auid), 1);
953 		adrm_int32(&context,
954 		    (int *)&(internal->as_info.ai_mask.am_success), 2);
955 		adrm_int32(&context,
956 		    (int *)&(internal->as_info.ai_termid.at_port), 1);
957 		adrm_int32(&context,
958 		    (int *)&(internal->as_info.ai_termid.at_type), 1);
959 		adrm_int32(&context,
960 		    (int *)&(internal->as_info.ai_termid.at_addr[0]), 4);
961 		adrm_int32(&context, (int *)&(internal->as_info.ai_asid), 1);
962 		adrm_int32(&context, (int *)&(internal->as_audit_enabled), 1);
963 		internal->as_pid = (pid_t)-1;
964 		internal->as_label = NULL;
965 	} else if (version == PROTOCOL_VERSION_2) {
966 		adrm_int32(&context, (int *)&(internal->as_euid), 1);
967 		adrm_int32(&context, (int *)&(internal->as_ruid), 1);
968 		adrm_int32(&context, (int *)&(internal->as_egid), 1);
969 		adrm_int32(&context, (int *)&(internal->as_rgid), 1);
970 		adrm_int32(&context, (int *)&(internal->as_info.ai_auid), 1);
971 		adrm_int32(&context,
972 		    (int *)&(internal->as_info.ai_mask.am_success), 2);
973 		adrm_int32(&context,
974 		    (int *)&(internal->as_info.ai_termid.at_port), 1);
975 		adrm_int32(&context,
976 		    (int *)&(internal->as_info.ai_termid.at_type), 1);
977 		adrm_int32(&context,
978 		    (int *)&(internal->as_info.ai_termid.at_addr[0]), 4);
979 		adrm_int32(&context, (int *)&(internal->as_info.ai_asid), 1);
980 		adrm_int32(&context, (int *)&(internal->as_audit_enabled), 1);
981 		adrm_int32(&context, (int *)&(internal->as_pid), 1);
982 		adrm_int32(&context, (int *)&label_len, 1);
983 		if (label_len > 0) {
984 			/* read in and deal with different sized labels. */
985 			size_t	my_label_len = blabel_size();
986 
987 			if ((internal->as_label =
988 			    m_label_alloc(MAC_LABEL)) == NULL) {
989 				return (0);
990 			}
991 			if (label_len > my_label_len) {
992 				errno = EINVAL;
993 				m_label_free(internal->as_label);
994 				return (0);
995 			}
996 			(void) memset(internal->as_label, 0, my_label_len);
997 			adrm_int32(&context, (int *)(internal->as_label),
998 			    label_len / sizeof (int32_t));
999 		} else {
1000 			internal->as_label = NULL;
1001 		}
1002 	}
1003 
1004 	return (length);
1005 }
1006 
1007 /*
1008  * adt_to_export_format
1009  * read from struct adt_session_data into a network order buffer.
1010  *
1011  * (network order 'cause this data may be shared with a remote host.)
1012  */
1013 
1014 static size_t
1015 adt_to_export_format(adt_export_data_t *external,
1016     adt_internal_state_t *internal)
1017 {
1018 	struct export_header	head;
1019 	struct export_link	tail;
1020 	adr_t			context;
1021 	size_t			label_len = 0;
1022 
1023 	adrm_start(&context, (char *)external);
1024 
1025 	if (internal->as_label != NULL) {
1026 		label_len = blabel_size();
1027 	}
1028 
1029 	head.ax_check = ADT_VALID;
1030 	head.ax_buffer_length = sizeof (struct adt_export_data) + label_len;
1031 
1032 	/* version 2 first */
1033 
1034 	head.ax_link.ax_version = PROTOCOL_VERSION_2;
1035 	head.ax_link.ax_offset = sizeof (struct export_header) +
1036 	    sizeof (struct adt_export_v2) + label_len;
1037 
1038 	adrm_putint32(&context, (int *)&head, 4);
1039 
1040 	adrm_putint32(&context, (int *)&(internal->as_euid), 1);
1041 	adrm_putint32(&context, (int *)&(internal->as_ruid), 1);
1042 	adrm_putint32(&context, (int *)&(internal->as_egid), 1);
1043 	adrm_putint32(&context, (int *)&(internal->as_rgid), 1);
1044 	adrm_putint32(&context, (int *)&(internal->as_info.ai_auid), 1);
1045 	adrm_putint32(&context,
1046 	    (int *)&(internal->as_info.ai_mask.am_success), 2);
1047 	adrm_putint32(&context,
1048 	    (int *)&(internal->as_info.ai_termid.at_port), 1);
1049 	adrm_putint32(&context,
1050 	    (int *)&(internal->as_info.ai_termid.at_type), 1);
1051 	adrm_putint32(&context,
1052 	    (int *)&(internal->as_info.ai_termid.at_addr[0]), 4);
1053 	adrm_putint32(&context, (int *)&(internal->as_info.ai_asid), 1);
1054 	adrm_putint32(&context, (int *)&(internal->as_audit_enabled), 1);
1055 	adrm_putint32(&context, (int *)&(internal->as_pid), 1);
1056 	adrm_putint32(&context, (int *)&label_len, 1);
1057 	if (internal->as_label != NULL) {
1058 		/* serialize the label */
1059 		adrm_putint32(&context, (int *)(internal->as_label),
1060 		    (label_len / sizeof (int32_t)));
1061 	}
1062 
1063 	/* now version 1 */
1064 
1065 	tail.ax_version = PROTOCOL_VERSION_1;
1066 	tail.ax_offset = 0;
1067 
1068 	adrm_putint32(&context, (int *)&tail, 2);
1069 
1070 	adrm_putint32(&context, (int *)&(internal->as_euid), 1);
1071 	adrm_putint32(&context, (int *)&(internal->as_ruid), 1);
1072 	adrm_putint32(&context, (int *)&(internal->as_egid), 1);
1073 	adrm_putint32(&context, (int *)&(internal->as_rgid), 1);
1074 	adrm_putint32(&context, (int *)&(internal->as_info.ai_auid), 1);
1075 	adrm_putint32(&context,
1076 	    (int *)&(internal->as_info.ai_mask.am_success), 2);
1077 	adrm_putint32(&context,
1078 	    (int *)&(internal->as_info.ai_termid.at_port), 1);
1079 	adrm_putint32(&context,
1080 	    (int *)&(internal->as_info.ai_termid.at_type), 1);
1081 	adrm_putint32(&context,
1082 	    (int *)&(internal->as_info.ai_termid.at_addr[0]), 4);
1083 	adrm_putint32(&context, (int *)&(internal->as_info.ai_asid), 1);
1084 	adrm_putint32(&context, (int *)&(internal->as_audit_enabled), 1);
1085 	/* ignored in v1 */
1086 	adrm_putint32(&context, (int *)&label_len, 1);
1087 
1088 	/* finally terminator */
1089 
1090 	tail.ax_version = 0; /* invalid version number */
1091 	tail.ax_offset = 0;
1092 
1093 	adrm_putint32(&context, (int *)&tail, 2);
1094 
1095 	return (head.ax_buffer_length);
1096 }
1097 
1098 
1099 /*
1100  * adt_import_proc() is used by a server acting on behalf
1101  * of a client which has connected via an ipc mechanism such as
1102  * a door.
1103  *
1104  * Since the interface is via ucred, the info.ap_termid.port
1105  * value is always the 64 bit version.  What is stored depends
1106  * on how libbsm is compiled.
1107  */
1108 
1109 size_t
1110 adt_import_proc(pid_t pid, uid_t euid, gid_t egid, uid_t ruid, gid_t rgid,
1111     adt_export_data_t **external)
1112 {
1113 	size_t			length = 0;
1114 	adt_internal_state_t	*state;
1115 	ucred_t			*ucred;
1116 	const au_tid64_addr_t	*tid;
1117 
1118 	state = calloc(1, sizeof (adt_internal_state_t));
1119 
1120 	if (state == NULL)
1121 		return (0);
1122 
1123 	if (adt_init(state, 0) != 0)
1124 		goto return_length_free;    /* errno from adt_init() */
1125 
1126 	/*
1127 	 * ucred_getauid() returns AU_NOAUDITID if audit is off, which
1128 	 * is the right answer for adt_import_proc().
1129 	 *
1130 	 * Create a local context as near as possible.
1131 	 */
1132 
1133 	ucred = ucred_get(pid);
1134 
1135 	if (ucred == NULL)
1136 		goto return_length_free;
1137 
1138 	state->as_ruid = ruid != ADT_NO_CHANGE ? ruid : ucred_getruid(ucred);
1139 	state->as_euid = euid != ADT_NO_CHANGE ? euid : ucred_geteuid(ucred);
1140 	state->as_rgid = rgid != ADT_NO_CHANGE ? rgid : ucred_getrgid(ucred);
1141 	state->as_egid = egid != ADT_NO_CHANGE ? egid : ucred_getegid(ucred);
1142 
1143 	state->as_info.ai_auid = ucred_getauid(ucred);
1144 
1145 	if (state->as_info.ai_auid == AU_NOAUDITID) {
1146 		state->as_info.ai_asid = adt_get_unique_id(ruid);
1147 
1148 		if (adt_get_mask_from_user(ruid, &(state->as_info.ai_mask)))
1149 			goto return_all_free;
1150 	} else {
1151 		const au_mask_t *mask = ucred_getamask(ucred);
1152 
1153 		if (mask != NULL)
1154 			state->as_info.ai_mask = *mask;
1155 		else
1156 			goto return_all_free;
1157 
1158 		state->as_info.ai_asid = ucred_getasid(ucred);
1159 	}
1160 
1161 	tid = ucred_getatid(ucred);
1162 
1163 	if (tid != NULL) {
1164 		adt_cpy_tid(&(state->as_info.ai_termid), tid);
1165 	} else {
1166 		(void) memset((void *)&(state->as_info.ai_termid), 0,
1167 		    sizeof (au_tid_addr_t));
1168 		state->as_info.ai_termid.at_type = AU_IPv4;
1169 	}
1170 
1171 	DPRINTF(("import_proc/asid = %X %u\n", state->as_info.ai_asid,
1172 	    state->as_info.ai_asid));
1173 
1174 	DPRINTF(("import_proc/masks = %X %X\n",
1175 	    state->as_info.ai_mask.am_success,
1176 	    state->as_info.ai_mask.am_failure));
1177 
1178 	if (state->as_label == NULL) {
1179 		*external = malloc(sizeof (adt_export_data_t));
1180 	} else {
1181 		*external = malloc(sizeof (adt_export_data_t) + blabel_size());
1182 	}
1183 
1184 	if (*external == NULL)
1185 		goto return_all_free;
1186 
1187 	length = adt_to_export_format(*external, state);
1188 	/*
1189 	 * yes, state is supposed to be free'd for both pass and fail
1190 	 */
1191 return_all_free:
1192 	ucred_free(ucred);
1193 return_length_free:
1194 	free(state);
1195 	return (length);
1196 }
1197 
1198 /*
1199  * adt_ucred_label() -- if label is available, duplicate it.
1200  */
1201 
1202 static m_label_t *
1203 adt_ucred_label(ucred_t *uc)
1204 {
1205 	m_label_t	*ul = NULL;
1206 
1207 	if (ucred_getlabel(uc) != NULL) {
1208 		(void) m_label_dup(&ul, ucred_getlabel(uc));
1209 	}
1210 
1211 	return (ul);
1212 }
1213 
1214 /*
1215  * adt_import() -- convert from network order to machine-specific order
1216  */
1217 
1218 static int
1219 adt_import(adt_internal_state_t *internal, const adt_export_data_t *external)
1220 {
1221 	au_mask_t mask;
1222 
1223 	/* save local audit enabled state */
1224 	int	local_audit_enabled = internal->as_audit_enabled;
1225 
1226 	if (adt_from_export_format(internal, external) < 1)
1227 		return (-1); /* errno from adt_from_export_format */
1228 
1229 	/*
1230 	 * If audit isn't enabled on the remote, they were unable
1231 	 * to generate the audit mask, so generate it based on
1232 	 * local configuration.  If the user id has changed, the
1233 	 * resulting mask may miss some subtleties that occurred
1234 	 * on the remote system.
1235 	 *
1236 	 * If the remote failed to generate a terminal id, it is not
1237 	 * recoverable.
1238 	 */
1239 
1240 	if (!internal->as_audit_enabled) {
1241 		if (adt_get_mask_from_user(internal->as_info.ai_auid,
1242 		    &(internal->as_info.ai_mask)))
1243 			return (-1);
1244 		if (internal->as_info.ai_auid != internal->as_ruid) {
1245 			if (adt_get_mask_from_user(internal->as_info.ai_auid,
1246 			    &mask))
1247 				return (-1);
1248 			internal->as_info.ai_mask.am_success |=
1249 			    mask.am_success;
1250 			internal->as_info.ai_mask.am_failure |=
1251 			    mask.am_failure;
1252 		}
1253 	}
1254 	internal->as_audit_enabled = local_audit_enabled;
1255 
1256 	DPRINTF(("(%d)imported asid = %X %u\n", getpid(),
1257 	    internal->as_info.ai_asid,
1258 	    internal->as_info.ai_asid));
1259 
1260 	internal->as_have_user_data = ADT_HAVE_ALL;
1261 
1262 	return (0);
1263 }
1264 
1265 /*
1266  * adt_export_session_data()
1267  * copies a adt_session_data struct into a network order buffer
1268  *
1269  * In a misconfigured network, the local host may have auditing
1270  * off while the destination may have auditing on, so if there
1271  * is sufficient memory, a buffer will be returned even in the
1272  * audit off case.
1273  */
1274 
1275 size_t
1276 adt_export_session_data(const adt_session_data_t *internal,
1277     adt_export_data_t **external)
1278 {
1279 	size_t			length = 0;
1280 
1281 	if (((adt_internal_state_t *)internal)->as_label != NULL) {
1282 		length = blabel_size();
1283 	}
1284 
1285 	*external = malloc(sizeof (adt_export_data_t) + length);
1286 
1287 	if (*external == NULL)
1288 		return (0);
1289 
1290 	if (internal == NULL) {
1291 		adt_internal_state_t	*dummy;
1292 
1293 		dummy = malloc(sizeof (adt_internal_state_t));
1294 		if (dummy == NULL)
1295 			goto return_length_free;
1296 
1297 		if (adt_init(dummy, 0)) { /* 0 == don't copy from proc */
1298 			free(dummy);
1299 			goto return_length_free;
1300 		}
1301 		length = adt_to_export_format(*external, dummy);
1302 		free(dummy);
1303 	} else {
1304 		length = adt_to_export_format(*external,
1305 		    (adt_internal_state_t *)internal);
1306 	}
1307 	return (length);
1308 
1309 return_length_free:
1310 	free(*external);
1311 	*external = NULL;
1312 	return (0);
1313 }
1314 
1315 static void
1316 adt_setto_unaudited(adt_internal_state_t *state)
1317 {
1318 	state->as_ruid = AU_NOAUDITID;
1319 	state->as_euid = AU_NOAUDITID;
1320 	state->as_rgid = AU_NOAUDITID;
1321 	state->as_egid = AU_NOAUDITID;
1322 	state->as_pid = (pid_t)-1;
1323 	state->as_label = NULL;
1324 
1325 	if (state->as_audit_enabled) {
1326 		state->as_info.ai_asid = 0;
1327 		state->as_info.ai_auid = AU_NOAUDITID;
1328 
1329 		(void) memset((void *)&(state->as_info.ai_termid), 0,
1330 		    sizeof (au_tid_addr_t));
1331 		state->as_info.ai_termid.at_type = AU_IPv4;
1332 
1333 		(void) memset((void *)&(state->as_info.ai_mask), 0,
1334 		    sizeof (au_mask_t));
1335 		state->as_have_user_data = 0;
1336 	}
1337 }
1338 
1339 /*
1340  * adt_init -- set session context by copying the audit characteristics
1341  * from the proc and picking up current uid/tid information.
1342  *
1343  * By default, an audit session is based on the process; the default
1344  * is overriden by adt_set_user()
1345  */
1346 
1347 static int
1348 adt_init(adt_internal_state_t *state, int use_proc_data)
1349 {
1350 
1351 	state->as_audit_enabled = (auditstate == AUC_DISABLED) ? 0 : 1;
1352 
1353 	if (use_proc_data) {
1354 		state->as_ruid = getuid();
1355 		state->as_euid = geteuid();
1356 		state->as_rgid = getgid();
1357 		state->as_egid = getegid();
1358 		state->as_pid = getpid();
1359 
1360 		if (state->as_audit_enabled) {
1361 			const au_tid64_addr_t	*tid;
1362 			const au_mask_t		*mask;
1363 			ucred_t			*ucred = ucred_get(P_MYID);
1364 
1365 			/*
1366 			 * Even if the ucred is NULL, the underlying
1367 			 * credential may have a valid terminal id; if the
1368 			 * terminal id is set, then that's good enough.  An
1369 			 * example of where this matters is failed login,
1370 			 * where rlogin/telnet sets the terminal id before
1371 			 * calling login; login does not load the credential
1372 			 * since auth failed.
1373 			 */
1374 			if (ucred == NULL) {
1375 				if (!adt_have_termid(
1376 				    &(state->as_info.ai_termid)))
1377 					return (-1);
1378 			} else {
1379 				mask = ucred_getamask(ucred);
1380 				if (mask != NULL) {
1381 					state->as_info.ai_mask = *mask;
1382 				} else {
1383 					ucred_free(ucred);
1384 					return (-1);
1385 				}
1386 				tid = ucred_getatid(ucred);
1387 				if (tid != NULL) {
1388 					adt_cpy_tid(&(state->as_info.ai_termid),
1389 					    tid);
1390 				} else {
1391 					ucred_free(ucred);
1392 					return (-1);
1393 				}
1394 				state->as_info.ai_asid = ucred_getasid(ucred);
1395 				state->as_info.ai_auid = ucred_getauid(ucred);
1396 				state->as_label = adt_ucred_label(ucred);
1397 				ucred_free(ucred);
1398 			}
1399 			state->as_have_user_data = ADT_HAVE_ALL;
1400 		}
1401 	} else {
1402 		adt_setto_unaudited(state);
1403 	}
1404 	state->as_session_model = ADT_SESSION_MODEL;	/* default */
1405 
1406 	if (state->as_audit_enabled &&
1407 	    auditon(A_GETPOLICY, (caddr_t)&(state->as_kernel_audit_policy),
1408 	    sizeof (state->as_kernel_audit_policy))) {
1409 		return (-1);  /* errno set by auditon */
1410 	}
1411 	state->as_check = ADT_VALID;
1412 	return (0);
1413 }
1414 
1415 /*
1416  * adt_set_proc
1417  *
1418  * Copy the current session state to the process.  If this function
1419  * is called, the model becomes a process model rather than a
1420  * session model.
1421  *
1422  * In the current implementation, the value state->as_have_user_data
1423  * must contain all of: ADT_HAVE_{AUID,MASK,TID,ASID}.  These are all set
1424  * by adt_set_user() when the ADT_SETTID or ADT_NEW flag is passed in.
1425  *
1426  */
1427 
1428 int
1429 adt_set_proc(const adt_session_data_t *session_data)
1430 {
1431 	int			rc;
1432 	adt_internal_state_t	*state;
1433 
1434 	if (auditstate == AUC_DISABLED || (session_data == NULL))
1435 		return (0);
1436 
1437 	state = (adt_internal_state_t *)session_data;
1438 
1439 	assert(state->as_check == ADT_VALID);
1440 
1441 	if ((state->as_have_user_data & (ADT_HAVE_ALL & ~ADT_HAVE_IDS)) !=
1442 	    (ADT_HAVE_ALL & ~ADT_HAVE_IDS)) {
1443 		errno = EINVAL;
1444 		goto return_err;
1445 	}
1446 
1447 	rc = setaudit_addr((auditinfo_addr_t *)&(state->as_info),
1448 	    sizeof (auditinfo_addr_t));
1449 
1450 	if (rc < 0)
1451 		goto return_err;	/* errno set by setaudit_addr() */
1452 
1453 	state->as_session_model = ADT_PROCESS_MODEL;
1454 
1455 	return (0);
1456 
1457 return_err:
1458 	adt_write_syslog("failed to set process audit characteristics", errno);
1459 	return (-1);
1460 }
1461 
1462 static int
1463 adt_newuser(adt_internal_state_t *state, uid_t ruid, au_tid_addr_t *termid)
1464 {
1465 	au_tid_addr_t	no_tid = {0, AU_IPv4, 0, 0, 0, 0};
1466 	au_mask_t	no_mask = {0, 0};
1467 
1468 	if (ruid == ADT_NO_AUDIT) {
1469 		state->as_info.ai_auid = AU_NOAUDITID;
1470 		state->as_info.ai_asid = 0;
1471 		state->as_info.ai_termid = no_tid;
1472 		state->as_info.ai_mask = no_mask;
1473 		return (0);
1474 	}
1475 	state->as_info.ai_auid = ruid;
1476 	state->as_info.ai_asid = adt_get_unique_id(ruid);
1477 	if (termid != NULL)
1478 		state->as_info.ai_termid = *termid;
1479 
1480 	if (adt_get_mask_from_user(ruid, &(state->as_info.ai_mask)))
1481 		return (-1);
1482 
1483 	return (0);
1484 }
1485 
1486 static int
1487 adt_changeuser(adt_internal_state_t *state, uid_t ruid)
1488 {
1489 	au_mask_t		mask;
1490 
1491 	if (!(state->as_have_user_data & ADT_HAVE_AUID))
1492 		state->as_info.ai_auid = ruid;
1493 	if (!(state->as_have_user_data & ADT_HAVE_ASID))
1494 		state->as_info.ai_asid = adt_get_unique_id(ruid);
1495 
1496 	if (ruid >= 0) {
1497 		if (adt_get_mask_from_user(ruid, &mask))
1498 			return (-1);
1499 
1500 		state->as_info.ai_mask.am_success |= mask.am_success;
1501 		state->as_info.ai_mask.am_failure |= mask.am_failure;
1502 	}
1503 	DPRINTF(("changed mask to %08X/%08X for ruid=%d\n",
1504 		state->as_info.ai_mask.am_success,
1505 		state->as_info.ai_mask.am_failure,
1506 		ruid));
1507 	return (0);
1508 }
1509 
1510 /*
1511  * adt_set_user -- see also adt_set_from_ucred()
1512  *
1513  * ADT_NO_ATTRIB is a valid uid/gid meaning "not known" or
1514  * "unattributed."  If ruid, change the model to session.
1515  *
1516  * ADT_NO_CHANGE is a valid uid/gid meaning "do not change this value"
1517  * only valid with ADT_UPDATE.
1518  *
1519  * ADT_NO_AUDIT is the external equivalent to AU_NOAUDITID -- there
1520  * isn't a good reason to call adt_set_user() with it unless you don't
1521  * have a good value yet and intend to replace it later; auid will be
1522  * AU_NOAUDITID.
1523  *
1524  * adt_set_user should be called even if auditing is not enabled
1525  * so that adt_export_session_data() will have useful stuff to
1526  * work with.
1527  *
1528  * See the note preceding adt_set_proc() about the use of ADT_HAVE_TID
1529  * and ADT_HAVE_ALL.
1530  */
1531 
1532 int
1533 adt_set_user(const adt_session_data_t *session_data, uid_t euid, gid_t egid,
1534     uid_t ruid, gid_t rgid, const adt_termid_t *termid,
1535     enum adt_user_context user_context)
1536 {
1537 	adt_internal_state_t	*state;
1538 	int			rc;
1539 
1540 	if (session_data == NULL) /* no session exists to audit */
1541 		return (0);
1542 
1543 	state = (adt_internal_state_t *)session_data;
1544 	assert(state->as_check == ADT_VALID);
1545 
1546 	switch (user_context) {
1547 	case ADT_NEW:
1548 		if (ruid == ADT_NO_CHANGE || euid == ADT_NO_CHANGE ||
1549 		    rgid == ADT_NO_CHANGE || egid == ADT_NO_CHANGE) {
1550 			errno = EINVAL;
1551 			return (-1);
1552 		}
1553 		if ((rc = adt_newuser(state, ruid,
1554 		    (au_tid_addr_t *)termid)) != 0)
1555 			return (rc);
1556 
1557 		state->as_have_user_data = ADT_HAVE_ALL;
1558 		break;
1559 	case ADT_UPDATE:
1560 		if (state->as_have_user_data != ADT_HAVE_ALL) {
1561 			errno = EINVAL;
1562 			return (-1);
1563 		}
1564 
1565 		if (ruid != ADT_NO_CHANGE)
1566 			if ((rc = adt_changeuser(state, ruid)) != 0)
1567 				return (rc);
1568 		break;
1569 	case ADT_USER:
1570 		if (state->as_have_user_data != ADT_HAVE_ALL) {
1571 			errno = EINVAL;
1572 			return (-1);
1573 		}
1574 		break;
1575 	case ADT_SETTID:
1576 		assert(termid != NULL);
1577 		state->as_info.ai_termid = *((au_tid_addr_t *)termid);
1578 		/* avoid fooling pam_setcred()... */
1579 		state->as_info.ai_auid = AU_NOAUDITID;
1580 		state->as_info.ai_asid = 0;
1581 		state->as_info.ai_mask.am_failure = 0;
1582 		state->as_info.ai_mask.am_success = 0;
1583 		state->as_have_user_data = ADT_HAVE_TID |
1584 		    ADT_HAVE_AUID | ADT_HAVE_ASID | ADT_HAVE_MASK;
1585 		return (0);
1586 	default:
1587 		errno = EINVAL;
1588 		return (-1);
1589 	}
1590 
1591 	if (ruid == ADT_NO_AUDIT) {
1592 		state->as_ruid = AU_NOAUDITID;
1593 		state->as_euid = AU_NOAUDITID;
1594 		state->as_rgid = AU_NOAUDITID;
1595 		state->as_egid = AU_NOAUDITID;
1596 	} else {
1597 		if (ruid != ADT_NO_CHANGE)
1598 			state->as_ruid = ruid;
1599 		if (euid != ADT_NO_CHANGE)
1600 			state->as_euid = euid;
1601 		if (rgid != ADT_NO_CHANGE)
1602 			state->as_rgid = rgid;
1603 		if (egid != ADT_NO_CHANGE)
1604 			state->as_egid = egid;
1605 	}
1606 
1607 	if (ruid == ADT_NO_ATTRIB) {
1608 		state->as_session_model = ADT_SESSION_MODEL;
1609 	}
1610 
1611 	return (0);
1612 }
1613 
1614 /*
1615  * adt_set_from_ucred()
1616  *
1617  * an alternate to adt_set_user that fills the same role but uses
1618  * a pointer to a ucred rather than a list of id's.  If the ucred
1619  * pointer is NULL, use the credential from the this process.
1620  *
1621  * A key difference is that for ADT_NEW, adt_set_from_ucred() does
1622  * not overwrite the asid and auid unless auid has not been set.
1623  * ADT_NEW differs from ADT_UPDATE in that it does not OR together
1624  * the incoming audit mask with the one that already exists.
1625  *
1626  * adt_set_from_ucred should be called even if auditing is not enabled
1627  * so that adt_export_session_data() will have useful stuff to
1628  * work with.
1629  */
1630 
1631 int
1632 adt_set_from_ucred(const adt_session_data_t *session_data, const ucred_t *uc,
1633     enum adt_user_context user_context)
1634 {
1635 	adt_internal_state_t	*state;
1636 	int			rc = -1;
1637 	const au_tid64_addr_t		*tid64;
1638 	au_tid_addr_t		termid, *tid;
1639 	ucred_t	*ucred = (ucred_t *)uc;
1640 	boolean_t	local_uc = B_FALSE;
1641 
1642 	if (session_data == NULL) /* no session exists to audit */
1643 		return (0);
1644 
1645 	state = (adt_internal_state_t *)session_data;
1646 	assert(state->as_check == ADT_VALID);
1647 
1648 	if (ucred == NULL) {
1649 		ucred = ucred_get(getpid());
1650 
1651 		if (ucred == NULL)
1652 			goto return_rc;
1653 		local_uc = B_TRUE;
1654 	}
1655 
1656 	switch (user_context) {
1657 	case ADT_NEW:
1658 		tid64 = ucred_getatid(ucred);
1659 		if (tid64 != NULL) {
1660 			adt_cpy_tid(&termid, tid64);
1661 			tid = &termid;
1662 		} else {
1663 			tid = NULL;
1664 		}
1665 		/* if unaudited, adt_newuser cleans up */
1666 		if (ucred_getauid(ucred) == AU_NOAUDITID) {
1667 			if ((rc = adt_newuser(state, ucred_getruid(ucred),
1668 			    tid)) != 0)
1669 				goto return_rc;
1670 		} else {
1671 			state->as_info.ai_auid = ucred_getauid(ucred);
1672 			state->as_info.ai_asid = ucred_getasid(ucred);
1673 			state->as_info.ai_mask = *ucred_getamask(ucred);
1674 			state->as_info.ai_termid = *tid;
1675 		}
1676 		state->as_have_user_data = ADT_HAVE_ALL;
1677 		break;
1678 	case ADT_UPDATE:
1679 		if (state->as_have_user_data != ADT_HAVE_ALL) {
1680 			errno = EINVAL;
1681 			goto return_rc;
1682 		}
1683 
1684 		if ((rc = adt_changeuser(state, ucred_getruid(ucred))) != 0)
1685 			goto return_rc;
1686 		break;
1687 	case ADT_USER:
1688 		if (state->as_have_user_data != ADT_HAVE_ALL) {
1689 			errno = EINVAL;
1690 			goto return_rc;
1691 		}
1692 		break;
1693 	default:
1694 		errno = EINVAL;
1695 		goto return_rc;
1696 	}
1697 	rc = 0;
1698 
1699 	state->as_ruid = ucred_getruid(ucred);
1700 	state->as_euid = ucred_geteuid(ucred);
1701 	state->as_rgid = ucred_getrgid(ucred);
1702 	state->as_egid = ucred_getegid(ucred);
1703 	state->as_pid = ucred_getpid(ucred);
1704 	state->as_label = adt_ucred_label(ucred);
1705 
1706 return_rc:
1707 	if (local_uc) {
1708 		ucred_free(ucred);
1709 	}
1710 	return (rc);
1711 }
1712 
1713 /*
1714  * adt_alloc_event() returns a pointer to allocated memory
1715  *
1716  */
1717 
1718 adt_event_data_t
1719 *adt_alloc_event(const adt_session_data_t *session_data, au_event_t event_id)
1720 {
1721 	struct adt_event_state	*event_state;
1722 	adt_internal_state_t	*session_state;
1723 	adt_event_data_t	*return_event = NULL;
1724 	/*
1725 	 * need to return a valid event pointer even if audit is
1726 	 * off, else the caller will end up either (1) keeping its
1727 	 * own flags for on/off or (2) writing to a NULL pointer.
1728 	 * If auditing is on, the session data must be valid; otherwise
1729 	 * we don't care.
1730 	 */
1731 	if (session_data != NULL) {
1732 		session_state = (adt_internal_state_t *)session_data;
1733 		assert(session_state->as_check == ADT_VALID);
1734 	}
1735 	event_state = calloc(1, sizeof (struct adt_event_state));
1736 	if (event_state == NULL)
1737 		goto return_ptr;
1738 
1739 	event_state->ae_check = ADT_VALID;
1740 
1741 	event_state->ae_event_id = event_id;
1742 	event_state->ae_session = (struct adt_internal_state *)session_data;
1743 
1744 	return_event = (adt_event_data_t *)&(event_state->ae_event_data);
1745 
1746 	/*
1747 	 * preload data so the adt_au_*() functions can detect un-supplied
1748 	 * values (0 and NULL are free via calloc()).
1749 	 */
1750 	adt_preload(event_id, return_event);
1751 
1752 return_ptr:
1753 	return (return_event);
1754 }
1755 
1756 /*
1757  * adt_getXlateTable -- look up translation table address for event id
1758  */
1759 
1760 static struct translation *
1761 adt_getXlateTable(au_event_t event_id)
1762 {
1763 	/* xlate_table is global in adt_xlate.c */
1764 	struct translation	**p_xlate = &xlate_table[0];
1765 	struct translation	*p_event;
1766 
1767 	while (*p_xlate != NULL) {
1768 		p_event = *p_xlate;
1769 		if (event_id == p_event->tx_external_event)
1770 			return (p_event);
1771 		p_xlate++;
1772 	}
1773 	return (NULL);
1774 }
1775 
1776 /*
1777  * adt_calcOffsets
1778  *
1779  * the call to this function is surrounded by a mutex.
1780  *
1781  * i walks down the table picking up next_token.  j walks again to
1782  * calculate the offset to the input data.  k points to the next
1783  * token's row.  Finally, l, is used to sum the values in the
1784  * datadef array.
1785  *
1786  * What's going on?  The entry array is in the order of the input
1787  * fields but the processing of array entries is in the order of
1788  * the output (see next_token).  Calculating the offset to the
1789  * "next" input can't be done in the outer loop (i) since i doesn't
1790  * point to the current entry and it can't be done with the k index
1791  * because it doesn't represent the order of input fields.
1792  *
1793  * While the resulting algorithm is n**2, it is only done once per
1794  * event type.
1795  */
1796 
1797 /*
1798  * adt_calcOffsets is only called once per event type, but it uses
1799  * the address alignment of memory allocated for that event as if it
1800  * were the same for all subsequently allocated memory.  This is
1801  * guaranteed by calloc/malloc.  Arrays take special handling since
1802  * what matters for figuring out the correct alignment is the size
1803  * of the array element.
1804  */
1805 
1806 static void
1807 adt_calcOffsets(struct entry *p_entry, int tablesize, void *p_data)
1808 {
1809 	int		i, j;
1810 	size_t		this_size, prev_size;
1811 	void		*struct_start = p_data;
1812 
1813 	for (i = 0; i < tablesize; i++) {
1814 		if (p_entry[i].en_type_def == NULL) {
1815 			p_entry[i].en_offset = 0;
1816 			continue;
1817 		}
1818 		prev_size = 0;
1819 		p_entry[i].en_offset = (char *)p_data - (char *)struct_start;
1820 
1821 		for (j = 0; j < p_entry[i].en_count_types; j++) {
1822 			if (p_entry[i].en_type_def[j].dd_datatype == ADT_MSG)
1823 				this_size = sizeof (enum adt_generic);
1824 			else
1825 				this_size =
1826 				    p_entry[i].en_type_def[j].dd_input_size;
1827 
1828 			/* adj for first entry */
1829 			if (prev_size == 0)
1830 				prev_size = this_size;
1831 
1832 			if (p_entry[i].en_type_def[j].dd_datatype ==
1833 			    ADT_UINT32ARRAY) {
1834 				p_data = (char *)adt_adjust_address(p_data,
1835 				    prev_size, sizeof (uint32_t)) +
1836 				    this_size - sizeof (uint32_t);
1837 
1838 				prev_size = sizeof (uint32_t);
1839 			} else {
1840 				p_data = adt_adjust_address(p_data, prev_size,
1841 				    this_size);
1842 				prev_size = this_size;
1843 			}
1844 		}
1845 	}
1846 }
1847 
1848 /*
1849  * adt_generate_event
1850  * generate event record from external struct.  The order is based on
1851  * the output tokens, allowing for the possibility that the input data
1852  * is in a different order.
1853  *
1854  */
1855 
1856 static void
1857 adt_generate_event(const adt_event_data_t *p_extdata,
1858     struct adt_event_state *p_event,
1859     struct translation *p_xlate)
1860 {
1861 	struct entry		*p_entry;
1862 	static mutex_t	lock = DEFAULTMUTEX;
1863 
1864 	p_entry = p_xlate->tx_first_entry;
1865 	assert(p_entry != NULL);
1866 
1867 	p_event->ae_internal_id = p_xlate->tx_internal_event;
1868 	adt_token_open(p_event);
1869 
1870 	/*
1871 	 * offsets are not pre-calculated; the initial offsets are all
1872 	 * 0; valid offsets are >= 0.  Offsets for no-input tokens such
1873 	 * as subject are set to -1 by adt_calcOffset()
1874 	 */
1875 	if (p_xlate->tx_offsetsCalculated == 0) {
1876 		(void) _mutex_lock(&lock);
1877 		p_xlate->tx_offsetsCalculated = 1;
1878 
1879 		adt_calcOffsets(p_xlate->tx_top_entry, p_xlate->tx_entries,
1880 		    (void *)p_extdata);
1881 		(void) _mutex_unlock(&lock);
1882 	}
1883 	while (p_entry != NULL) {
1884 		adt_generate_token(p_entry, (char *)p_extdata,
1885 		    p_event);
1886 
1887 		p_entry = p_entry->en_next_token;
1888 	}
1889 	adt_token_close(p_event);
1890 }
1891 
1892 /*
1893  * adt_put_event -- main event generation function.
1894  * The input "event" is the address of the struct containing
1895  * event-specific data.
1896  *
1897  * However if auditing is off or the session handle
1898  * is NULL, no attempt to write a record is made.
1899  */
1900 
1901 int
1902 adt_put_event(const adt_event_data_t *event, int status, int return_val)
1903 {
1904 	struct adt_event_state	*event_state;
1905 	struct translation	*xlate;
1906 	int			rc = 0;
1907 
1908 	if (event == NULL) {
1909 		errno = EINVAL;
1910 		rc = -1;
1911 		goto return_rc;
1912 	}
1913 	event_state = (struct adt_event_state *)event;
1914 
1915 	/* if audit off or this is a broken session, exit */
1916 	if (auditstate == AUC_DISABLED || (event_state->ae_session == NULL))
1917 		goto return_rc;
1918 
1919 	assert(event_state->ae_check == ADT_VALID);
1920 
1921 	event_state->ae_rc = status;
1922 	event_state->ae_type = return_val;
1923 
1924 	/* look up the event */
1925 
1926 	xlate = adt_getXlateTable(event_state->ae_event_id);
1927 
1928 	if (xlate == NULL) {
1929 		errno = EINVAL;
1930 		rc = -1;
1931 		goto return_rc;
1932 	}
1933 	DPRINTF(("got event %d\n", xlate->tx_internal_event));
1934 
1935 	if (adt_selected(event_state, xlate->tx_internal_event, status))
1936 		adt_generate_event(event, event_state, xlate);
1937 
1938 return_rc:
1939 	return (rc);
1940 }
1941 
1942 /*
1943  * adt_free_event -- invalidate and free
1944  */
1945 
1946 void
1947 adt_free_event(adt_event_data_t *event)
1948 {
1949 	struct adt_event_state	*event_state;
1950 
1951 	if (event == NULL)
1952 		return;
1953 
1954 	event_state = (struct adt_event_state *)event;
1955 
1956 	assert(event_state->ae_check == ADT_VALID);
1957 
1958 	event_state->ae_check = 0;
1959 
1960 	free(event_state);
1961 }
1962 
1963 /*
1964  * adt_is_selected -- helper to adt_selected(), below.
1965  *
1966  * "sorf" is "success or fail" status; au_preselect compares
1967  * that with success, fail, or both.
1968  */
1969 
1970 static int
1971 adt_is_selected(au_event_t e, au_mask_t *m, int sorf)
1972 {
1973 	int prs_sorf;
1974 
1975 	if (sorf == 0)
1976 		prs_sorf = AU_PRS_SUCCESS;
1977 	else
1978 		prs_sorf = AU_PRS_FAILURE;
1979 
1980 	return (au_preselect(e, m, prs_sorf, AU_PRS_REREAD));
1981 }
1982 
1983 /*
1984  * selected -- see if this event is preselected.
1985  *
1986  * if errors are encountered trying to check a preselection mask
1987  * or look up a user name, the event is selected.  Otherwise, the
1988  * preselection mask is used for the job.
1989  */
1990 
1991 static int
1992 adt_selected(struct adt_event_state *event, au_event_t actual_id, int status)
1993 {
1994 	adt_internal_state_t *sp;
1995 	au_mask_t	namask;
1996 
1997 	sp = event->ae_session;
1998 
1999 	if ((sp->as_have_user_data & ADT_HAVE_IDS) == 0) {
2000 		adt_write_syslog("No user data available", EINVAL);
2001 		return (1);	/* default is "selected" */
2002 	}
2003 
2004 	/* non-attributable? */
2005 	if ((sp->as_info.ai_auid == AU_NOAUDITID) ||
2006 	    (sp->as_info.ai_auid == ADT_NO_AUDIT)) {
2007 		if (auditon(A_GETKMASK, (caddr_t)&namask,
2008 		    sizeof (namask)) != 0) {
2009 			adt_write_syslog("auditon failure", errno);
2010 			return (1);
2011 		}
2012 		return (adt_is_selected(actual_id, &namask, status));
2013 	} else {
2014 		return (adt_is_selected(actual_id, &(sp->as_info.ai_mask),
2015 		    status));
2016 	}
2017 }
2018