xref: /titanic_41/usr/src/lib/libbsm/common/adt.c (revision 40cb5e5daa7b80bb70fcf8dadfb20f9281566331)
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 ((internal != NULL) &&
1282 	    ((adt_internal_state_t *)internal)->as_label != NULL) {
1283 		length = blabel_size();
1284 	}
1285 
1286 	*external = malloc(sizeof (adt_export_data_t) + length);
1287 
1288 	if (*external == NULL)
1289 		return (0);
1290 
1291 	if (internal == NULL) {
1292 		adt_internal_state_t	*dummy;
1293 
1294 		dummy = malloc(sizeof (adt_internal_state_t));
1295 		if (dummy == NULL)
1296 			goto return_length_free;
1297 
1298 		if (adt_init(dummy, 0)) { /* 0 == don't copy from proc */
1299 			free(dummy);
1300 			goto return_length_free;
1301 		}
1302 		length = adt_to_export_format(*external, dummy);
1303 		free(dummy);
1304 	} else {
1305 		length = adt_to_export_format(*external,
1306 		    (adt_internal_state_t *)internal);
1307 	}
1308 	return (length);
1309 
1310 return_length_free:
1311 	free(*external);
1312 	*external = NULL;
1313 	return (0);
1314 }
1315 
1316 static void
1317 adt_setto_unaudited(adt_internal_state_t *state)
1318 {
1319 	state->as_ruid = AU_NOAUDITID;
1320 	state->as_euid = AU_NOAUDITID;
1321 	state->as_rgid = AU_NOAUDITID;
1322 	state->as_egid = AU_NOAUDITID;
1323 	state->as_pid = (pid_t)-1;
1324 	state->as_label = NULL;
1325 
1326 	if (state->as_audit_enabled) {
1327 		state->as_info.ai_asid = 0;
1328 		state->as_info.ai_auid = AU_NOAUDITID;
1329 
1330 		(void) memset((void *)&(state->as_info.ai_termid), 0,
1331 		    sizeof (au_tid_addr_t));
1332 		state->as_info.ai_termid.at_type = AU_IPv4;
1333 
1334 		(void) memset((void *)&(state->as_info.ai_mask), 0,
1335 		    sizeof (au_mask_t));
1336 		state->as_have_user_data = 0;
1337 	}
1338 }
1339 
1340 /*
1341  * adt_init -- set session context by copying the audit characteristics
1342  * from the proc and picking up current uid/tid information.
1343  *
1344  * By default, an audit session is based on the process; the default
1345  * is overriden by adt_set_user()
1346  */
1347 
1348 static int
1349 adt_init(adt_internal_state_t *state, int use_proc_data)
1350 {
1351 
1352 	state->as_audit_enabled = (auditstate == AUC_DISABLED) ? 0 : 1;
1353 
1354 	if (use_proc_data) {
1355 		state->as_ruid = getuid();
1356 		state->as_euid = geteuid();
1357 		state->as_rgid = getgid();
1358 		state->as_egid = getegid();
1359 		state->as_pid = getpid();
1360 
1361 		if (state->as_audit_enabled) {
1362 			const au_tid64_addr_t	*tid;
1363 			const au_mask_t		*mask;
1364 			ucred_t			*ucred = ucred_get(P_MYID);
1365 
1366 			/*
1367 			 * Even if the ucred is NULL, the underlying
1368 			 * credential may have a valid terminal id; if the
1369 			 * terminal id is set, then that's good enough.  An
1370 			 * example of where this matters is failed login,
1371 			 * where rlogin/telnet sets the terminal id before
1372 			 * calling login; login does not load the credential
1373 			 * since auth failed.
1374 			 */
1375 			if (ucred == NULL) {
1376 				if (!adt_have_termid(
1377 				    &(state->as_info.ai_termid)))
1378 					return (-1);
1379 			} else {
1380 				mask = ucred_getamask(ucred);
1381 				if (mask != NULL) {
1382 					state->as_info.ai_mask = *mask;
1383 				} else {
1384 					ucred_free(ucred);
1385 					return (-1);
1386 				}
1387 				tid = ucred_getatid(ucred);
1388 				if (tid != NULL) {
1389 					adt_cpy_tid(&(state->as_info.ai_termid),
1390 					    tid);
1391 				} else {
1392 					ucred_free(ucred);
1393 					return (-1);
1394 				}
1395 				state->as_info.ai_asid = ucred_getasid(ucred);
1396 				state->as_info.ai_auid = ucred_getauid(ucred);
1397 				state->as_label = adt_ucred_label(ucred);
1398 				ucred_free(ucred);
1399 			}
1400 			state->as_have_user_data = ADT_HAVE_ALL;
1401 		}
1402 	} else {
1403 		adt_setto_unaudited(state);
1404 	}
1405 	state->as_session_model = ADT_SESSION_MODEL;	/* default */
1406 
1407 	if (state->as_audit_enabled &&
1408 	    auditon(A_GETPOLICY, (caddr_t)&(state->as_kernel_audit_policy),
1409 	    sizeof (state->as_kernel_audit_policy))) {
1410 		return (-1);  /* errno set by auditon */
1411 	}
1412 	state->as_check = ADT_VALID;
1413 	return (0);
1414 }
1415 
1416 /*
1417  * adt_set_proc
1418  *
1419  * Copy the current session state to the process.  If this function
1420  * is called, the model becomes a process model rather than a
1421  * session model.
1422  *
1423  * In the current implementation, the value state->as_have_user_data
1424  * must contain all of: ADT_HAVE_{AUID,MASK,TID,ASID}.  These are all set
1425  * by adt_set_user() when the ADT_SETTID or ADT_NEW flag is passed in.
1426  *
1427  */
1428 
1429 int
1430 adt_set_proc(const adt_session_data_t *session_data)
1431 {
1432 	int			rc;
1433 	adt_internal_state_t	*state;
1434 
1435 	if (auditstate == AUC_DISABLED || (session_data == NULL))
1436 		return (0);
1437 
1438 	state = (adt_internal_state_t *)session_data;
1439 
1440 	assert(state->as_check == ADT_VALID);
1441 
1442 	if ((state->as_have_user_data & (ADT_HAVE_ALL & ~ADT_HAVE_IDS)) !=
1443 	    (ADT_HAVE_ALL & ~ADT_HAVE_IDS)) {
1444 		errno = EINVAL;
1445 		goto return_err;
1446 	}
1447 
1448 	rc = setaudit_addr((auditinfo_addr_t *)&(state->as_info),
1449 	    sizeof (auditinfo_addr_t));
1450 
1451 	if (rc < 0)
1452 		goto return_err;	/* errno set by setaudit_addr() */
1453 
1454 	state->as_session_model = ADT_PROCESS_MODEL;
1455 
1456 	return (0);
1457 
1458 return_err:
1459 	adt_write_syslog("failed to set process audit characteristics", errno);
1460 	return (-1);
1461 }
1462 
1463 static int
1464 adt_newuser(adt_internal_state_t *state, uid_t ruid, au_tid_addr_t *termid)
1465 {
1466 	au_tid_addr_t	no_tid = {0, AU_IPv4, 0, 0, 0, 0};
1467 	au_mask_t	no_mask = {0, 0};
1468 
1469 	if (ruid == ADT_NO_AUDIT) {
1470 		state->as_info.ai_auid = AU_NOAUDITID;
1471 		state->as_info.ai_asid = 0;
1472 		state->as_info.ai_termid = no_tid;
1473 		state->as_info.ai_mask = no_mask;
1474 		return (0);
1475 	}
1476 	state->as_info.ai_auid = ruid;
1477 	state->as_info.ai_asid = adt_get_unique_id(ruid);
1478 	if (termid != NULL)
1479 		state->as_info.ai_termid = *termid;
1480 
1481 	if (adt_get_mask_from_user(ruid, &(state->as_info.ai_mask)))
1482 		return (-1);
1483 
1484 	return (0);
1485 }
1486 
1487 static int
1488 adt_changeuser(adt_internal_state_t *state, uid_t ruid)
1489 {
1490 	au_mask_t		mask;
1491 
1492 	if (!(state->as_have_user_data & ADT_HAVE_AUID))
1493 		state->as_info.ai_auid = ruid;
1494 	if (!(state->as_have_user_data & ADT_HAVE_ASID))
1495 		state->as_info.ai_asid = adt_get_unique_id(ruid);
1496 
1497 	if (ruid >= 0) {
1498 		if (adt_get_mask_from_user(ruid, &mask))
1499 			return (-1);
1500 
1501 		state->as_info.ai_mask.am_success |= mask.am_success;
1502 		state->as_info.ai_mask.am_failure |= mask.am_failure;
1503 	}
1504 	DPRINTF(("changed mask to %08X/%08X for ruid=%d\n",
1505 		state->as_info.ai_mask.am_success,
1506 		state->as_info.ai_mask.am_failure,
1507 		ruid));
1508 	return (0);
1509 }
1510 
1511 /*
1512  * adt_set_user -- see also adt_set_from_ucred()
1513  *
1514  * ADT_NO_ATTRIB is a valid uid/gid meaning "not known" or
1515  * "unattributed."  If ruid, change the model to session.
1516  *
1517  * ADT_NO_CHANGE is a valid uid/gid meaning "do not change this value"
1518  * only valid with ADT_UPDATE.
1519  *
1520  * ADT_NO_AUDIT is the external equivalent to AU_NOAUDITID -- there
1521  * isn't a good reason to call adt_set_user() with it unless you don't
1522  * have a good value yet and intend to replace it later; auid will be
1523  * AU_NOAUDITID.
1524  *
1525  * adt_set_user should be called even if auditing is not enabled
1526  * so that adt_export_session_data() will have useful stuff to
1527  * work with.
1528  *
1529  * See the note preceding adt_set_proc() about the use of ADT_HAVE_TID
1530  * and ADT_HAVE_ALL.
1531  */
1532 
1533 int
1534 adt_set_user(const adt_session_data_t *session_data, uid_t euid, gid_t egid,
1535     uid_t ruid, gid_t rgid, const adt_termid_t *termid,
1536     enum adt_user_context user_context)
1537 {
1538 	adt_internal_state_t	*state;
1539 	int			rc;
1540 
1541 	if (session_data == NULL) /* no session exists to audit */
1542 		return (0);
1543 
1544 	state = (adt_internal_state_t *)session_data;
1545 	assert(state->as_check == ADT_VALID);
1546 
1547 	switch (user_context) {
1548 	case ADT_NEW:
1549 		if (ruid == ADT_NO_CHANGE || euid == ADT_NO_CHANGE ||
1550 		    rgid == ADT_NO_CHANGE || egid == ADT_NO_CHANGE) {
1551 			errno = EINVAL;
1552 			return (-1);
1553 		}
1554 		if ((rc = adt_newuser(state, ruid,
1555 		    (au_tid_addr_t *)termid)) != 0)
1556 			return (rc);
1557 
1558 		state->as_have_user_data = ADT_HAVE_ALL;
1559 		break;
1560 	case ADT_UPDATE:
1561 		if (state->as_have_user_data != ADT_HAVE_ALL) {
1562 			errno = EINVAL;
1563 			return (-1);
1564 		}
1565 
1566 		if (ruid != ADT_NO_CHANGE)
1567 			if ((rc = adt_changeuser(state, ruid)) != 0)
1568 				return (rc);
1569 		break;
1570 	case ADT_USER:
1571 		if (state->as_have_user_data != ADT_HAVE_ALL) {
1572 			errno = EINVAL;
1573 			return (-1);
1574 		}
1575 		break;
1576 	case ADT_SETTID:
1577 		assert(termid != NULL);
1578 		state->as_info.ai_termid = *((au_tid_addr_t *)termid);
1579 		/* avoid fooling pam_setcred()... */
1580 		state->as_info.ai_auid = AU_NOAUDITID;
1581 		state->as_info.ai_asid = 0;
1582 		state->as_info.ai_mask.am_failure = 0;
1583 		state->as_info.ai_mask.am_success = 0;
1584 		state->as_have_user_data = ADT_HAVE_TID |
1585 		    ADT_HAVE_AUID | ADT_HAVE_ASID | ADT_HAVE_MASK;
1586 		return (0);
1587 	default:
1588 		errno = EINVAL;
1589 		return (-1);
1590 	}
1591 
1592 	if (ruid == ADT_NO_AUDIT) {
1593 		state->as_ruid = AU_NOAUDITID;
1594 		state->as_euid = AU_NOAUDITID;
1595 		state->as_rgid = AU_NOAUDITID;
1596 		state->as_egid = AU_NOAUDITID;
1597 	} else {
1598 		if (ruid != ADT_NO_CHANGE)
1599 			state->as_ruid = ruid;
1600 		if (euid != ADT_NO_CHANGE)
1601 			state->as_euid = euid;
1602 		if (rgid != ADT_NO_CHANGE)
1603 			state->as_rgid = rgid;
1604 		if (egid != ADT_NO_CHANGE)
1605 			state->as_egid = egid;
1606 	}
1607 
1608 	if (ruid == ADT_NO_ATTRIB) {
1609 		state->as_session_model = ADT_SESSION_MODEL;
1610 	}
1611 
1612 	return (0);
1613 }
1614 
1615 /*
1616  * adt_set_from_ucred()
1617  *
1618  * an alternate to adt_set_user that fills the same role but uses
1619  * a pointer to a ucred rather than a list of id's.  If the ucred
1620  * pointer is NULL, use the credential from the this process.
1621  *
1622  * A key difference is that for ADT_NEW, adt_set_from_ucred() does
1623  * not overwrite the asid and auid unless auid has not been set.
1624  * ADT_NEW differs from ADT_UPDATE in that it does not OR together
1625  * the incoming audit mask with the one that already exists.
1626  *
1627  * adt_set_from_ucred should be called even if auditing is not enabled
1628  * so that adt_export_session_data() will have useful stuff to
1629  * work with.
1630  */
1631 
1632 int
1633 adt_set_from_ucred(const adt_session_data_t *session_data, const ucred_t *uc,
1634     enum adt_user_context user_context)
1635 {
1636 	adt_internal_state_t	*state;
1637 	int			rc = -1;
1638 	const au_tid64_addr_t		*tid64;
1639 	au_tid_addr_t		termid, *tid;
1640 	ucred_t	*ucred = (ucred_t *)uc;
1641 	boolean_t	local_uc = B_FALSE;
1642 
1643 	if (session_data == NULL) /* no session exists to audit */
1644 		return (0);
1645 
1646 	state = (adt_internal_state_t *)session_data;
1647 	assert(state->as_check == ADT_VALID);
1648 
1649 	if (ucred == NULL) {
1650 		ucred = ucred_get(getpid());
1651 
1652 		if (ucred == NULL)
1653 			goto return_rc;
1654 		local_uc = B_TRUE;
1655 	}
1656 
1657 	switch (user_context) {
1658 	case ADT_NEW:
1659 		tid64 = ucred_getatid(ucred);
1660 		if (tid64 != NULL) {
1661 			adt_cpy_tid(&termid, tid64);
1662 			tid = &termid;
1663 		} else {
1664 			tid = NULL;
1665 		}
1666 		/* if unaudited, adt_newuser cleans up */
1667 		if (ucred_getauid(ucred) == AU_NOAUDITID) {
1668 			if ((rc = adt_newuser(state, ucred_getruid(ucred),
1669 			    tid)) != 0)
1670 				goto return_rc;
1671 		} else {
1672 			state->as_info.ai_auid = ucred_getauid(ucred);
1673 			state->as_info.ai_asid = ucred_getasid(ucred);
1674 			state->as_info.ai_mask = *ucred_getamask(ucred);
1675 			state->as_info.ai_termid = *tid;
1676 		}
1677 		state->as_have_user_data = ADT_HAVE_ALL;
1678 		break;
1679 	case ADT_UPDATE:
1680 		if (state->as_have_user_data != ADT_HAVE_ALL) {
1681 			errno = EINVAL;
1682 			goto return_rc;
1683 		}
1684 
1685 		if ((rc = adt_changeuser(state, ucred_getruid(ucred))) != 0)
1686 			goto return_rc;
1687 		break;
1688 	case ADT_USER:
1689 		if (state->as_have_user_data != ADT_HAVE_ALL) {
1690 			errno = EINVAL;
1691 			goto return_rc;
1692 		}
1693 		break;
1694 	default:
1695 		errno = EINVAL;
1696 		goto return_rc;
1697 	}
1698 	rc = 0;
1699 
1700 	state->as_ruid = ucred_getruid(ucred);
1701 	state->as_euid = ucred_geteuid(ucred);
1702 	state->as_rgid = ucred_getrgid(ucred);
1703 	state->as_egid = ucred_getegid(ucred);
1704 	state->as_pid = ucred_getpid(ucred);
1705 	state->as_label = adt_ucred_label(ucred);
1706 
1707 return_rc:
1708 	if (local_uc) {
1709 		ucred_free(ucred);
1710 	}
1711 	return (rc);
1712 }
1713 
1714 /*
1715  * adt_alloc_event() returns a pointer to allocated memory
1716  *
1717  */
1718 
1719 adt_event_data_t
1720 *adt_alloc_event(const adt_session_data_t *session_data, au_event_t event_id)
1721 {
1722 	struct adt_event_state	*event_state;
1723 	adt_internal_state_t	*session_state;
1724 	adt_event_data_t	*return_event = NULL;
1725 	/*
1726 	 * need to return a valid event pointer even if audit is
1727 	 * off, else the caller will end up either (1) keeping its
1728 	 * own flags for on/off or (2) writing to a NULL pointer.
1729 	 * If auditing is on, the session data must be valid; otherwise
1730 	 * we don't care.
1731 	 */
1732 	if (session_data != NULL) {
1733 		session_state = (adt_internal_state_t *)session_data;
1734 		assert(session_state->as_check == ADT_VALID);
1735 	}
1736 	event_state = calloc(1, sizeof (struct adt_event_state));
1737 	if (event_state == NULL)
1738 		goto return_ptr;
1739 
1740 	event_state->ae_check = ADT_VALID;
1741 
1742 	event_state->ae_event_id = event_id;
1743 	event_state->ae_session = (struct adt_internal_state *)session_data;
1744 
1745 	return_event = (adt_event_data_t *)&(event_state->ae_event_data);
1746 
1747 	/*
1748 	 * preload data so the adt_au_*() functions can detect un-supplied
1749 	 * values (0 and NULL are free via calloc()).
1750 	 */
1751 	adt_preload(event_id, return_event);
1752 
1753 return_ptr:
1754 	return (return_event);
1755 }
1756 
1757 /*
1758  * adt_getXlateTable -- look up translation table address for event id
1759  */
1760 
1761 static struct translation *
1762 adt_getXlateTable(au_event_t event_id)
1763 {
1764 	/* xlate_table is global in adt_xlate.c */
1765 	struct translation	**p_xlate = &xlate_table[0];
1766 	struct translation	*p_event;
1767 
1768 	while (*p_xlate != NULL) {
1769 		p_event = *p_xlate;
1770 		if (event_id == p_event->tx_external_event)
1771 			return (p_event);
1772 		p_xlate++;
1773 	}
1774 	return (NULL);
1775 }
1776 
1777 /*
1778  * adt_calcOffsets
1779  *
1780  * the call to this function is surrounded by a mutex.
1781  *
1782  * i walks down the table picking up next_token.  j walks again to
1783  * calculate the offset to the input data.  k points to the next
1784  * token's row.  Finally, l, is used to sum the values in the
1785  * datadef array.
1786  *
1787  * What's going on?  The entry array is in the order of the input
1788  * fields but the processing of array entries is in the order of
1789  * the output (see next_token).  Calculating the offset to the
1790  * "next" input can't be done in the outer loop (i) since i doesn't
1791  * point to the current entry and it can't be done with the k index
1792  * because it doesn't represent the order of input fields.
1793  *
1794  * While the resulting algorithm is n**2, it is only done once per
1795  * event type.
1796  */
1797 
1798 /*
1799  * adt_calcOffsets is only called once per event type, but it uses
1800  * the address alignment of memory allocated for that event as if it
1801  * were the same for all subsequently allocated memory.  This is
1802  * guaranteed by calloc/malloc.  Arrays take special handling since
1803  * what matters for figuring out the correct alignment is the size
1804  * of the array element.
1805  */
1806 
1807 static void
1808 adt_calcOffsets(struct entry *p_entry, int tablesize, void *p_data)
1809 {
1810 	int		i, j;
1811 	size_t		this_size, prev_size;
1812 	void		*struct_start = p_data;
1813 
1814 	for (i = 0; i < tablesize; i++) {
1815 		if (p_entry[i].en_type_def == NULL) {
1816 			p_entry[i].en_offset = 0;
1817 			continue;
1818 		}
1819 		prev_size = 0;
1820 		p_entry[i].en_offset = (char *)p_data - (char *)struct_start;
1821 
1822 		for (j = 0; j < p_entry[i].en_count_types; j++) {
1823 			if (p_entry[i].en_type_def[j].dd_datatype == ADT_MSG)
1824 				this_size = sizeof (enum adt_generic);
1825 			else
1826 				this_size =
1827 				    p_entry[i].en_type_def[j].dd_input_size;
1828 
1829 			/* adj for first entry */
1830 			if (prev_size == 0)
1831 				prev_size = this_size;
1832 
1833 			if (p_entry[i].en_type_def[j].dd_datatype ==
1834 			    ADT_UINT32ARRAY) {
1835 				p_data = (char *)adt_adjust_address(p_data,
1836 				    prev_size, sizeof (uint32_t)) +
1837 				    this_size - sizeof (uint32_t);
1838 
1839 				prev_size = sizeof (uint32_t);
1840 			} else {
1841 				p_data = adt_adjust_address(p_data, prev_size,
1842 				    this_size);
1843 				prev_size = this_size;
1844 			}
1845 		}
1846 	}
1847 }
1848 
1849 /*
1850  * adt_generate_event
1851  * generate event record from external struct.  The order is based on
1852  * the output tokens, allowing for the possibility that the input data
1853  * is in a different order.
1854  *
1855  */
1856 
1857 static void
1858 adt_generate_event(const adt_event_data_t *p_extdata,
1859     struct adt_event_state *p_event,
1860     struct translation *p_xlate)
1861 {
1862 	struct entry		*p_entry;
1863 	static mutex_t	lock = DEFAULTMUTEX;
1864 
1865 	p_entry = p_xlate->tx_first_entry;
1866 	assert(p_entry != NULL);
1867 
1868 	p_event->ae_internal_id = p_xlate->tx_internal_event;
1869 	adt_token_open(p_event);
1870 
1871 	/*
1872 	 * offsets are not pre-calculated; the initial offsets are all
1873 	 * 0; valid offsets are >= 0.  Offsets for no-input tokens such
1874 	 * as subject are set to -1 by adt_calcOffset()
1875 	 */
1876 	if (p_xlate->tx_offsetsCalculated == 0) {
1877 		(void) _mutex_lock(&lock);
1878 		p_xlate->tx_offsetsCalculated = 1;
1879 
1880 		adt_calcOffsets(p_xlate->tx_top_entry, p_xlate->tx_entries,
1881 		    (void *)p_extdata);
1882 		(void) _mutex_unlock(&lock);
1883 	}
1884 	while (p_entry != NULL) {
1885 		adt_generate_token(p_entry, (char *)p_extdata,
1886 		    p_event);
1887 
1888 		p_entry = p_entry->en_next_token;
1889 	}
1890 	adt_token_close(p_event);
1891 }
1892 
1893 /*
1894  * adt_put_event -- main event generation function.
1895  * The input "event" is the address of the struct containing
1896  * event-specific data.
1897  *
1898  * However if auditing is off or the session handle
1899  * is NULL, no attempt to write a record is made.
1900  */
1901 
1902 int
1903 adt_put_event(const adt_event_data_t *event, int status, int return_val)
1904 {
1905 	struct adt_event_state	*event_state;
1906 	struct translation	*xlate;
1907 	int			rc = 0;
1908 
1909 	if (event == NULL) {
1910 		errno = EINVAL;
1911 		rc = -1;
1912 		goto return_rc;
1913 	}
1914 	event_state = (struct adt_event_state *)event;
1915 
1916 	/* if audit off or this is a broken session, exit */
1917 	if (auditstate == AUC_DISABLED || (event_state->ae_session == NULL))
1918 		goto return_rc;
1919 
1920 	assert(event_state->ae_check == ADT_VALID);
1921 
1922 	event_state->ae_rc = status;
1923 	event_state->ae_type = return_val;
1924 
1925 	/* look up the event */
1926 
1927 	xlate = adt_getXlateTable(event_state->ae_event_id);
1928 
1929 	if (xlate == NULL) {
1930 		errno = EINVAL;
1931 		rc = -1;
1932 		goto return_rc;
1933 	}
1934 	DPRINTF(("got event %d\n", xlate->tx_internal_event));
1935 
1936 	if (adt_selected(event_state, xlate->tx_internal_event, status))
1937 		adt_generate_event(event, event_state, xlate);
1938 
1939 return_rc:
1940 	return (rc);
1941 }
1942 
1943 /*
1944  * adt_free_event -- invalidate and free
1945  */
1946 
1947 void
1948 adt_free_event(adt_event_data_t *event)
1949 {
1950 	struct adt_event_state	*event_state;
1951 
1952 	if (event == NULL)
1953 		return;
1954 
1955 	event_state = (struct adt_event_state *)event;
1956 
1957 	assert(event_state->ae_check == ADT_VALID);
1958 
1959 	event_state->ae_check = 0;
1960 
1961 	free(event_state);
1962 }
1963 
1964 /*
1965  * adt_is_selected -- helper to adt_selected(), below.
1966  *
1967  * "sorf" is "success or fail" status; au_preselect compares
1968  * that with success, fail, or both.
1969  */
1970 
1971 static int
1972 adt_is_selected(au_event_t e, au_mask_t *m, int sorf)
1973 {
1974 	int prs_sorf;
1975 
1976 	if (sorf == 0)
1977 		prs_sorf = AU_PRS_SUCCESS;
1978 	else
1979 		prs_sorf = AU_PRS_FAILURE;
1980 
1981 	return (au_preselect(e, m, prs_sorf, AU_PRS_REREAD));
1982 }
1983 
1984 /*
1985  * selected -- see if this event is preselected.
1986  *
1987  * if errors are encountered trying to check a preselection mask
1988  * or look up a user name, the event is selected.  Otherwise, the
1989  * preselection mask is used for the job.
1990  */
1991 
1992 static int
1993 adt_selected(struct adt_event_state *event, au_event_t actual_id, int status)
1994 {
1995 	adt_internal_state_t *sp;
1996 	au_mask_t	namask;
1997 
1998 	sp = event->ae_session;
1999 
2000 	if ((sp->as_have_user_data & ADT_HAVE_IDS) == 0) {
2001 		adt_write_syslog("No user data available", EINVAL);
2002 		return (1);	/* default is "selected" */
2003 	}
2004 
2005 	/* non-attributable? */
2006 	if ((sp->as_info.ai_auid == AU_NOAUDITID) ||
2007 	    (sp->as_info.ai_auid == ADT_NO_AUDIT)) {
2008 		if (auditon(A_GETKMASK, (caddr_t)&namask,
2009 		    sizeof (namask)) != 0) {
2010 			adt_write_syslog("auditon failure", errno);
2011 			return (1);
2012 		}
2013 		return (adt_is_selected(actual_id, &namask, status));
2014 	} else {
2015 		return (adt_is_selected(actual_id, &(sp->as_info.ai_mask),
2016 		    status));
2017 	}
2018 }
2019