xref: /freebsd/sys/kern/kern_prot.c (revision e40d60838c9a0ebe5e5fb0e3cb00e7b08dd8c959)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1989, 1990, 1991, 1993
5  *	The Regents of the University of California.
6  * (c) UNIX System Laboratories, Inc.
7  * Copyright (c) 2000-2001 Robert N. M. Watson.
8  * All rights reserved.
9  * Copyright (c) 2024-2025 The FreeBSD Foundation
10  *
11  * Portions of this software were developed by Olivier Certner
12  * <olce@FreeBSD.org> at Kumacom SARL under sponsorship from the FreeBSD
13  * Foundation.
14  *
15  * All or some portions of this file are derived from material licensed
16  * to the University of California by American Telephone and Telegraph
17  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
18  * the permission of UNIX System Laboratories, Inc.
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions
22  * are met:
23  * 1. Redistributions of source code must retain the above copyright
24  *    notice, this list of conditions and the following disclaimer.
25  * 2. Redistributions in binary form must reproduce the above copyright
26  *    notice, this list of conditions and the following disclaimer in the
27  *    documentation and/or other materials provided with the distribution.
28  * 3. Neither the name of the University nor the names of its contributors
29  *    may be used to endorse or promote products derived from this software
30  *    without specific prior written permission.
31  *
32  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
33  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
34  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
35  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
36  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
37  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
38  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
39  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
40  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
41  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
42  * SUCH DAMAGE.
43  */
44 
45 /*
46  * System calls related to processes and protection
47  */
48 
49 #include "opt_inet.h"
50 #include "opt_inet6.h"
51 
52 #include <sys/systm.h>
53 #include <sys/abi_compat.h>
54 #include <sys/acct.h>
55 #include <sys/capsicum.h>
56 #include <sys/imgact.h>
57 #include <sys/kdb.h>
58 #include <sys/kernel.h>
59 #include <sys/libkern.h>
60 #include <sys/lock.h>
61 #include <sys/loginclass.h>
62 #include <sys/malloc.h>
63 #include <sys/mutex.h>
64 #include <sys/ptrace.h>
65 #include <sys/refcount.h>
66 #include <sys/sx.h>
67 #include <sys/priv.h>
68 #include <sys/proc.h>
69 #ifdef COMPAT_43
70 #include <sys/sysent.h>
71 #endif
72 #include <sys/sysproto.h>
73 #include <sys/jail.h>
74 #include <sys/racct.h>
75 #include <sys/rctl.h>
76 #include <sys/resourcevar.h>
77 #include <sys/socket.h>
78 #include <sys/socketvar.h>
79 #include <sys/syscallsubr.h>
80 #include <sys/sysctl.h>
81 
82 #ifdef MAC
83 #include <security/mac/mac_syscalls.h>
84 #endif
85 
86 #include <vm/uma.h>
87 
88 #ifdef REGRESSION
89 FEATURE(regression,
90     "Kernel support for interfaces necessary for regression testing (SECURITY RISK!)");
91 #endif
92 
93 #include <security/audit/audit.h>
94 #include <security/mac/mac_framework.h>
95 
96 static MALLOC_DEFINE(M_CRED, "cred", "credentials");
97 
98 SYSCTL_NODE(_security, OID_AUTO, bsd, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
99     "BSD security policy");
100 
101 static void crfree_final(struct ucred *cr);
102 
103 static inline void
104 groups_check_positive_len(int ngrp)
105 {
106 	MPASS2(ngrp >= 0, "negative number of groups");
107 }
108 static inline void
109 groups_check_max_len(int ngrp)
110 {
111 	MPASS2(ngrp <= ngroups_max, "too many supplementary groups");
112 }
113 
114 static void groups_normalize(int *ngrp, gid_t *groups);
115 static void crsetgroups_internal(struct ucred *cr, int ngrp,
116     const gid_t *groups);
117 
118 static int cr_canseeotheruids(struct ucred *u1, struct ucred *u2);
119 static int cr_canseeothergids(struct ucred *u1, struct ucred *u2);
120 static int cr_canseejailproc(struct ucred *u1, struct ucred *u2);
121 
122 #ifndef _SYS_SYSPROTO_H_
123 struct getpid_args {
124 	int	dummy;
125 };
126 #endif
127 /* ARGSUSED */
128 int
129 sys_getpid(struct thread *td, struct getpid_args *uap)
130 {
131 	struct proc *p = td->td_proc;
132 
133 	td->td_retval[0] = p->p_pid;
134 #if defined(COMPAT_43)
135 	if (SV_PROC_FLAG(p, SV_AOUT))
136 		td->td_retval[1] = kern_getppid(td);
137 #endif
138 	return (0);
139 }
140 
141 #ifndef _SYS_SYSPROTO_H_
142 struct getppid_args {
143         int     dummy;
144 };
145 #endif
146 /* ARGSUSED */
147 int
148 sys_getppid(struct thread *td, struct getppid_args *uap)
149 {
150 
151 	td->td_retval[0] = kern_getppid(td);
152 	return (0);
153 }
154 
155 int
156 kern_getppid(struct thread *td)
157 {
158 	struct proc *p = td->td_proc;
159 
160 	return (p->p_oppid);
161 }
162 
163 /*
164  * Get process group ID; note that POSIX getpgrp takes no parameter.
165  */
166 #ifndef _SYS_SYSPROTO_H_
167 struct getpgrp_args {
168         int     dummy;
169 };
170 #endif
171 int
172 sys_getpgrp(struct thread *td, struct getpgrp_args *uap)
173 {
174 	struct proc *p = td->td_proc;
175 
176 	PROC_LOCK(p);
177 	td->td_retval[0] = p->p_pgrp->pg_id;
178 	PROC_UNLOCK(p);
179 	return (0);
180 }
181 
182 /* Get an arbitrary pid's process group id */
183 #ifndef _SYS_SYSPROTO_H_
184 struct getpgid_args {
185 	pid_t	pid;
186 };
187 #endif
188 int
189 sys_getpgid(struct thread *td, struct getpgid_args *uap)
190 {
191 	struct proc *p;
192 	int error;
193 
194 	if (uap->pid == 0) {
195 		p = td->td_proc;
196 		PROC_LOCK(p);
197 	} else {
198 		p = pfind_any(uap->pid);
199 		if (p == NULL)
200 			return (ESRCH);
201 		error = p_cansee(td, p);
202 		if (error) {
203 			PROC_UNLOCK(p);
204 			return (error);
205 		}
206 	}
207 	td->td_retval[0] = p->p_pgrp->pg_id;
208 	PROC_UNLOCK(p);
209 	return (0);
210 }
211 
212 /*
213  * Get an arbitrary pid's session id.
214  */
215 #ifndef _SYS_SYSPROTO_H_
216 struct getsid_args {
217 	pid_t	pid;
218 };
219 #endif
220 int
221 sys_getsid(struct thread *td, struct getsid_args *uap)
222 {
223 
224 	return (kern_getsid(td, uap->pid));
225 }
226 
227 int
228 kern_getsid(struct thread *td, pid_t pid)
229 {
230 	struct proc *p;
231 	int error;
232 
233 	error = 0;
234 	if (pid == 0) {
235 		p = td->td_proc;
236 		PROC_LOCK(p);
237 	} else {
238 		p = pfind_any(pid);
239 		if (p == NULL)
240 			return (ESRCH);
241 		error = p_cansee(td, p);
242 		if (error) {
243 			PROC_UNLOCK(p);
244 			return (error);
245 		}
246 	}
247 	if (p->p_session != NULL)
248 		td->td_retval[0] = p->p_session->s_sid;
249 	else
250 		error = EINVAL;
251 	PROC_UNLOCK(p);
252 	return (error);
253 }
254 
255 #ifndef _SYS_SYSPROTO_H_
256 struct getuid_args {
257         int     dummy;
258 };
259 #endif
260 /* ARGSUSED */
261 int
262 sys_getuid(struct thread *td, struct getuid_args *uap)
263 {
264 
265 	td->td_retval[0] = td->td_ucred->cr_ruid;
266 #if defined(COMPAT_43)
267 	td->td_retval[1] = td->td_ucred->cr_uid;
268 #endif
269 	return (0);
270 }
271 
272 #ifndef _SYS_SYSPROTO_H_
273 struct geteuid_args {
274         int     dummy;
275 };
276 #endif
277 /* ARGSUSED */
278 int
279 sys_geteuid(struct thread *td, struct geteuid_args *uap)
280 {
281 
282 	td->td_retval[0] = td->td_ucred->cr_uid;
283 	return (0);
284 }
285 
286 #ifndef _SYS_SYSPROTO_H_
287 struct getgid_args {
288         int     dummy;
289 };
290 #endif
291 /* ARGSUSED */
292 int
293 sys_getgid(struct thread *td, struct getgid_args *uap)
294 {
295 
296 	td->td_retval[0] = td->td_ucred->cr_rgid;
297 #if defined(COMPAT_43)
298 	td->td_retval[1] = td->td_ucred->cr_gid;
299 #endif
300 	return (0);
301 }
302 
303 #ifndef _SYS_SYSPROTO_H_
304 struct getegid_args {
305         int     dummy;
306 };
307 #endif
308 /* ARGSUSED */
309 int
310 sys_getegid(struct thread *td, struct getegid_args *uap)
311 {
312 
313 	td->td_retval[0] = td->td_ucred->cr_gid;
314 	return (0);
315 }
316 
317 #ifdef COMPAT_FREEBSD14
318 int
319 freebsd14_getgroups(struct thread *td, struct freebsd14_getgroups_args *uap)
320 {
321 	struct ucred *cred;
322 	int ngrp, error;
323 
324 	cred = td->td_ucred;
325 
326 	/*
327 	 * For FreeBSD < 15.0, we account for the egid being placed at the
328 	 * beginning of the group list prior to all supplementary groups.
329 	 */
330 	ngrp = cred->cr_ngroups + 1;
331 	if (uap->gidsetsize == 0) {
332 		error = 0;
333 		goto out;
334 	} else if (uap->gidsetsize < ngrp) {
335 		return (EINVAL);
336 	}
337 
338 	error = copyout(&cred->cr_gid, uap->gidset, sizeof(gid_t));
339 	if (error == 0)
340 		error = copyout(cred->cr_groups, uap->gidset + 1,
341 		    (ngrp - 1) * sizeof(gid_t));
342 
343 out:
344 	td->td_retval[0] = ngrp;
345 	return (error);
346 
347 }
348 #endif	/* COMPAT_FREEBSD14 */
349 
350 #ifndef _SYS_SYSPROTO_H_
351 struct getgroups_args {
352 	int	gidsetsize;
353 	gid_t	*gidset;
354 };
355 #endif
356 int
357 sys_getgroups(struct thread *td, struct getgroups_args *uap)
358 {
359 	struct ucred *cred;
360 	int ngrp, error;
361 
362 	cred = td->td_ucred;
363 
364 	ngrp = cred->cr_ngroups;
365 	if (uap->gidsetsize == 0) {
366 		error = 0;
367 		goto out;
368 	}
369 	if (uap->gidsetsize < ngrp)
370 		return (EINVAL);
371 
372 	error = copyout(cred->cr_groups, uap->gidset, ngrp * sizeof(gid_t));
373 out:
374 	td->td_retval[0] = ngrp;
375 	return (error);
376 }
377 
378 #ifndef _SYS_SYSPROTO_H_
379 struct setsid_args {
380         int     dummy;
381 };
382 #endif
383 /* ARGSUSED */
384 int
385 sys_setsid(struct thread *td, struct setsid_args *uap)
386 {
387 	struct pgrp *pgrp;
388 	int error;
389 	struct proc *p = td->td_proc;
390 	struct pgrp *newpgrp;
391 	struct session *newsess;
392 
393 	pgrp = NULL;
394 
395 	newpgrp = uma_zalloc(pgrp_zone, M_WAITOK);
396 	newsess = malloc(sizeof(struct session), M_SESSION, M_WAITOK | M_ZERO);
397 
398 again:
399 	error = 0;
400 	sx_xlock(&proctree_lock);
401 
402 	if (p->p_pgid == p->p_pid || (pgrp = pgfind(p->p_pid)) != NULL) {
403 		if (pgrp != NULL)
404 			PGRP_UNLOCK(pgrp);
405 		error = EPERM;
406 	} else {
407 		error = enterpgrp(p, p->p_pid, newpgrp, newsess);
408 		if (error == ERESTART)
409 			goto again;
410 		MPASS(error == 0);
411 		td->td_retval[0] = p->p_pid;
412 		newpgrp = NULL;
413 		newsess = NULL;
414 	}
415 
416 	sx_xunlock(&proctree_lock);
417 
418 	uma_zfree(pgrp_zone, newpgrp);
419 	free(newsess, M_SESSION);
420 
421 	return (error);
422 }
423 
424 /*
425  * set process group (setpgid/old setpgrp)
426  *
427  * caller does setpgid(targpid, targpgid)
428  *
429  * pid must be caller or child of caller (ESRCH)
430  * if a child
431  *	pid must be in same session (EPERM)
432  *	pid can't have done an exec (EACCES)
433  * if pgid != pid
434  *	there must exist some pid in same session having pgid (EPERM)
435  * pid must not be session leader (EPERM)
436  */
437 #ifndef _SYS_SYSPROTO_H_
438 struct setpgid_args {
439 	int	pid;		/* target process id */
440 	int	pgid;		/* target pgrp id */
441 };
442 #endif
443 /* ARGSUSED */
444 int
445 sys_setpgid(struct thread *td, struct setpgid_args *uap)
446 {
447 	struct proc *curp = td->td_proc;
448 	struct proc *targp;	/* target process */
449 	struct pgrp *pgrp;	/* target pgrp */
450 	int error;
451 	struct pgrp *newpgrp;
452 
453 	if (uap->pgid < 0)
454 		return (EINVAL);
455 
456 	newpgrp = uma_zalloc(pgrp_zone, M_WAITOK);
457 
458 again:
459 	error = 0;
460 
461 	sx_xlock(&proctree_lock);
462 	if (uap->pid != 0 && uap->pid != curp->p_pid) {
463 		if ((targp = pfind(uap->pid)) == NULL) {
464 			error = ESRCH;
465 			goto done;
466 		}
467 		if (!inferior(targp)) {
468 			PROC_UNLOCK(targp);
469 			error = ESRCH;
470 			goto done;
471 		}
472 		if ((error = p_cansee(td, targp))) {
473 			PROC_UNLOCK(targp);
474 			goto done;
475 		}
476 		if (targp->p_pgrp == NULL ||
477 		    targp->p_session != curp->p_session) {
478 			PROC_UNLOCK(targp);
479 			error = EPERM;
480 			goto done;
481 		}
482 		if (targp->p_flag & P_EXEC) {
483 			PROC_UNLOCK(targp);
484 			error = EACCES;
485 			goto done;
486 		}
487 		PROC_UNLOCK(targp);
488 	} else
489 		targp = curp;
490 	if (SESS_LEADER(targp)) {
491 		error = EPERM;
492 		goto done;
493 	}
494 	if (uap->pgid == 0)
495 		uap->pgid = targp->p_pid;
496 	if ((pgrp = pgfind(uap->pgid)) == NULL) {
497 		if (uap->pgid == targp->p_pid) {
498 			error = enterpgrp(targp, uap->pgid, newpgrp,
499 			    NULL);
500 			if (error == 0)
501 				newpgrp = NULL;
502 		} else
503 			error = EPERM;
504 	} else {
505 		if (pgrp == targp->p_pgrp) {
506 			PGRP_UNLOCK(pgrp);
507 			goto done;
508 		}
509 		if (pgrp->pg_id != targp->p_pid &&
510 		    pgrp->pg_session != curp->p_session) {
511 			PGRP_UNLOCK(pgrp);
512 			error = EPERM;
513 			goto done;
514 		}
515 		PGRP_UNLOCK(pgrp);
516 		error = enterthispgrp(targp, pgrp);
517 	}
518 done:
519 	KASSERT(error == 0 || newpgrp != NULL,
520 	    ("setpgid failed and newpgrp is NULL"));
521 	if (error == ERESTART)
522 		goto again;
523 	sx_xunlock(&proctree_lock);
524 	uma_zfree(pgrp_zone, newpgrp);
525 	return (error);
526 }
527 
528 static int
529 gidp_cmp(const void *p1, const void *p2)
530 {
531 	const gid_t g1 = *(const gid_t *)p1;
532 	const gid_t g2 = *(const gid_t *)p2;
533 
534 	return ((g1 > g2) - (g1 < g2));
535 }
536 
537 /*
538  * 'smallgroups' must be an (uninitialized) array of length CRED_SMALLGROUPS_NB.
539  * Always sets 'sc_supp_groups', either to a valid kernel-space groups array
540  * (which may or may not be 'smallgroups'), or NULL if SETCREDF_SUPP_GROUPS was
541  * not specified or there are too many groups, or a buffer containing garbage on
542  * copyin() failure.  In the last two cases, 'sc_supp_groups_nb' is additionally
543  * set to 0 as a security measure.  'sc_supp_groups' must be freed (M_TEMP) if
544  * not equal to 'smallgroups' even on failure.
545  */
546 static int
547 user_setcred_copyin_supp_groups(struct setcred *const wcred,
548     const u_int flags, gid_t *const smallgroups)
549 {
550 	gid_t *groups;
551 	int error;
552 
553 	if ((flags & SETCREDF_SUPP_GROUPS) == 0) {
554 		error = 0;
555 		goto reset_groups_exit;
556 	}
557 
558 	/*
559 	 * Check the number of groups' limit right now in order to limit the
560 	 * amount of bytes to copy.
561 	 */
562 	if (wcred->sc_supp_groups_nb > ngroups_max) {
563 		error = EINVAL;
564 		goto reset_groups_exit;
565 	}
566 
567 	groups = wcred->sc_supp_groups_nb <= CRED_SMALLGROUPS_NB ?
568 	    smallgroups : malloc(wcred->sc_supp_groups_nb * sizeof(gid_t),
569 	    M_TEMP, M_WAITOK);
570 	error = copyin(wcred->sc_supp_groups, groups,
571 	    wcred->sc_supp_groups_nb * sizeof(gid_t));
572 	wcred->sc_supp_groups = groups;
573 
574 	if (error != 0) {
575 		wcred->sc_supp_groups_nb = 0;
576 		/*
577 		 * 'sc_supp_groups' must be freed by caller if not
578 		 * 'smallgroups'.
579 		 */
580 		return (error);
581 	}
582 
583 	return (0);
584 
585 reset_groups_exit:
586 	wcred->sc_supp_groups_nb = 0;
587 	wcred->sc_supp_groups = NULL;
588 	return (error);
589 }
590 
591 int
592 user_setcred(struct thread *td, const u_int flags, struct setcred *const wcred)
593 {
594 #ifdef MAC
595 	struct mac mac;
596 	/* Pointer to 'struct mac' or 'struct mac32'. */
597 	void *umac;
598 #endif
599 	gid_t smallgroups[CRED_SMALLGROUPS_NB];
600 	int error;
601 
602 	/*
603 	 * As the only point of this wrapper function is to copyin() from
604 	 * userland, we only interpret the data pieces we need to perform this
605 	 * operation and defer further sanity checks to kern_setcred(), except
606 	 * that we redundantly check here that no unknown flags have been
607 	 * passed.
608 	 */
609 	if ((flags & ~SETCREDF_MASK) != 0)
610 		return (EINVAL);
611 
612 #ifdef MAC
613 	umac = wcred->sc_label;
614 #endif
615 	/* Also done on !MAC as a defensive measure. */
616 	wcred->sc_label = NULL;
617 
618 	/*
619 	 * Copy supplementary groups as needed.  There is no specific
620 	 * alternative for 32-bit compatibility as 'gid_t' has the same size
621 	 * everywhere.
622 	 */
623 	error = user_setcred_copyin_supp_groups(wcred, flags, smallgroups);
624 	if (error != 0)
625 		goto free_groups;
626 
627 #ifdef MAC
628 	if ((flags & SETCREDF_MAC_LABEL) != 0) {
629 		error = mac_label_copyin(umac, &mac, NULL);
630 		if (error != 0)
631 			goto free_groups;
632 		wcred->sc_label = &mac;
633 	}
634 #endif
635 
636 	error = kern_setcred(td, flags, wcred);
637 
638 #ifdef MAC
639 	if (wcred->sc_label != NULL)
640 		free_copied_label(wcred->sc_label);
641 #endif
642 
643 free_groups:
644 	if (wcred->sc_supp_groups != smallgroups)
645 		free(wcred->sc_supp_groups, M_TEMP);
646 
647 	return (error);
648 }
649 
650 #ifndef _SYS_SYSPROTO_H_
651 struct setcred_args {
652 	u_int			 flags;	/* Flags. */
653 	const struct setcred	*wcred;
654 	size_t			 size;	/* Passed 'setcred' structure length. */
655 };
656 #endif
657 /* ARGSUSED */
658 int
659 sys_setcred(struct thread *td, struct setcred_args *uap)
660 {
661 	struct setcred wcred;
662 	int error;
663 
664 	if (uap->size != sizeof(wcred))
665 		return (EINVAL);
666 	error = copyin(uap->wcred, &wcred, sizeof(wcred));
667 	if (error != 0)
668 		return (error);
669 	return (user_setcred(td, uap->flags, &wcred));
670 }
671 
672 /*
673  * CAUTION: This function normalizes groups in 'wcred'.
674  */
675 int
676 kern_setcred(struct thread *const td, const u_int flags,
677     struct setcred *const wcred)
678 {
679 	struct proc *const p = td->td_proc;
680 	struct ucred *new_cred, *old_cred, *to_free_cred = NULL;
681 	struct uidinfo *uip = NULL, *ruip = NULL;
682 #ifdef MAC
683 	void *mac_set_proc_data = NULL;
684 	bool proc_label_set = false;
685 #endif
686 	int error;
687 	bool cred_set = false;
688 
689 	/* Bail out on unrecognized flags. */
690 	if (flags & ~SETCREDF_MASK)
691 		return (EINVAL);
692 
693 	/*
694 	 * Part 1: We allocate and perform preparatory operations with no locks.
695 	 */
696 
697 	if ((flags & SETCREDF_SUPP_GROUPS) != 0 &&
698 	    wcred->sc_supp_groups_nb > ngroups_max)
699 			return (EINVAL);
700 
701 	if (flags & SETCREDF_MAC_LABEL) {
702 #ifdef MAC
703 		error = mac_set_proc_prepare(td, wcred->sc_label,
704 		    &mac_set_proc_data);
705 		if (error != 0)
706 			return (error);
707 #else
708 		return (ENOTSUP);
709 #endif
710 	}
711 
712 	if (flags & SETCREDF_UID) {
713 		AUDIT_ARG_EUID(wcred->sc_uid);
714 		uip = uifind(wcred->sc_uid);
715 	}
716 	if (flags & SETCREDF_RUID) {
717 		AUDIT_ARG_RUID(wcred->sc_ruid);
718 		ruip = uifind(wcred->sc_ruid);
719 	}
720 	if (flags & SETCREDF_SVUID)
721 		AUDIT_ARG_SUID(wcred->sc_svuid);
722 
723 	if (flags & SETCREDF_GID)
724 		AUDIT_ARG_EGID(wcred->sc_gid);
725 	if (flags & SETCREDF_RGID)
726 		AUDIT_ARG_RGID(wcred->sc_rgid);
727 	if (flags & SETCREDF_SVGID)
728 		AUDIT_ARG_SGID(wcred->sc_svgid);
729 	if (flags & SETCREDF_SUPP_GROUPS) {
730 		/*
731 		 * Output the raw supplementary groups array for better
732 		 * traceability.
733 		 */
734 		AUDIT_ARG_GROUPSET(wcred->sc_supp_groups,
735 		    wcred->sc_supp_groups_nb);
736 		groups_normalize(&wcred->sc_supp_groups_nb,
737 		    wcred->sc_supp_groups);
738 	}
739 
740 	/*
741 	 * We first completely build the new credentials and only then pass them
742 	 * to MAC along with the old ones so that modules can check whether the
743 	 * requested transition is allowed.
744 	 */
745 	new_cred = crget();
746 	to_free_cred = new_cred;
747 	if (flags & SETCREDF_SUPP_GROUPS)
748 		crextend(new_cred, wcred->sc_supp_groups_nb);
749 
750 #ifdef MAC
751 	mac_cred_setcred_enter();
752 #endif
753 
754 	/*
755 	 * Part 2: We grab the process lock as to have a stable view of its
756 	 * current credentials, and prepare a copy of them with the requested
757 	 * changes applied under that lock.
758 	 */
759 
760 	PROC_LOCK(p);
761 	old_cred = crcopysafe(p, new_cred);
762 
763 	/*
764 	 * Change user IDs.
765 	 */
766 	if (flags & SETCREDF_UID)
767 		change_euid(new_cred, uip);
768 	if (flags & SETCREDF_RUID)
769 		change_ruid(new_cred, ruip);
770 	if (flags & SETCREDF_SVUID)
771 		change_svuid(new_cred, wcred->sc_svuid);
772 
773 	/*
774 	 * Change groups.
775 	 */
776 	if (flags & SETCREDF_SUPP_GROUPS)
777 		crsetgroups_internal(new_cred, wcred->sc_supp_groups_nb,
778 		    wcred->sc_supp_groups);
779 	if (flags & SETCREDF_GID)
780 		change_egid(new_cred, wcred->sc_gid);
781 	if (flags & SETCREDF_RGID)
782 		change_rgid(new_cred, wcred->sc_rgid);
783 	if (flags & SETCREDF_SVGID)
784 		change_svgid(new_cred, wcred->sc_svgid);
785 
786 #ifdef MAC
787 	/*
788 	 * Change the MAC label.
789 	 */
790 	if (flags & SETCREDF_MAC_LABEL) {
791 		error = mac_set_proc_core(td, new_cred, mac_set_proc_data);
792 		if (error != 0)
793 			goto unlock_finish;
794 		proc_label_set = true;
795 	}
796 
797 	/*
798 	 * MAC security modules checks.
799 	 */
800 	error = mac_cred_check_setcred(flags, old_cred, new_cred);
801 	if (error != 0)
802 		goto unlock_finish;
803 #endif
804 	/*
805 	 * Privilege check.
806 	 */
807 	error = priv_check_cred(old_cred, PRIV_CRED_SETCRED);
808 	if (error != 0)
809 		goto unlock_finish;
810 
811 #ifdef RACCT
812 	/*
813 	 * Hold a reference to 'new_cred', as we need to call some functions on
814 	 * it after proc_set_cred_enforce_proc_lim().
815 	 */
816 	crhold(new_cred);
817 #endif
818 
819 	/* Set the new credentials. */
820 	cred_set = proc_set_cred_enforce_proc_lim(p, new_cred);
821 	if (cred_set) {
822 		setsugid(p);
823 #ifdef RACCT
824 		/* Adjust RACCT counters. */
825 		racct_proc_ucred_changed(p, old_cred, new_cred);
826 #endif
827 		to_free_cred = old_cred;
828 		MPASS(error == 0);
829 	} else {
830 #ifdef RACCT
831 		/* Matches the crhold() just before the containing 'if'. */
832 		crfree(new_cred);
833 #endif
834 		error = EAGAIN;
835 	}
836 
837 unlock_finish:
838 	PROC_UNLOCK(p);
839 
840 	/*
841 	 * Part 3: After releasing the process lock, we perform cleanups and
842 	 * finishing operations.
843 	 */
844 
845 #ifdef RACCT
846 	if (cred_set) {
847 #ifdef RCTL
848 		rctl_proc_ucred_changed(p, new_cred);
849 #endif
850 		/* Paired with the crhold() above. */
851 		crfree(new_cred);
852 	}
853 #endif
854 
855 #ifdef MAC
856 	if (mac_set_proc_data != NULL)
857 		mac_set_proc_finish(td, proc_label_set, mac_set_proc_data);
858 	mac_cred_setcred_exit();
859 #endif
860 	crfree(to_free_cred);
861 	if (uip != NULL)
862 		uifree(uip);
863 	if (ruip != NULL)
864 		uifree(ruip);
865 
866 	return (error);
867 }
868 
869 /*
870  * Use the clause in B.4.2.2 that allows setuid/setgid to be 4.2/4.3BSD
871  * compatible.  It says that setting the uid/gid to euid/egid is a special
872  * case of "appropriate privilege".  Once the rules are expanded out, this
873  * basically means that setuid(nnn) sets all three id's, in all permitted
874  * cases unless _POSIX_SAVED_IDS is enabled.  In that case, setuid(getuid())
875  * does not set the saved id - this is dangerous for traditional BSD
876  * programs.  For this reason, we *really* do not want to set
877  * _POSIX_SAVED_IDS and do not want to clear POSIX_APPENDIX_B_4_2_2.
878  */
879 #define POSIX_APPENDIX_B_4_2_2
880 
881 #ifndef _SYS_SYSPROTO_H_
882 struct setuid_args {
883 	uid_t	uid;
884 };
885 #endif
886 /* ARGSUSED */
887 int
888 sys_setuid(struct thread *td, struct setuid_args *uap)
889 {
890 	struct proc *p = td->td_proc;
891 	struct ucred *newcred, *oldcred;
892 	uid_t uid;
893 	struct uidinfo *uip;
894 	int error;
895 
896 	uid = uap->uid;
897 	AUDIT_ARG_UID(uid);
898 	newcred = crget();
899 	uip = uifind(uid);
900 	PROC_LOCK(p);
901 	/*
902 	 * Copy credentials so other references do not see our changes.
903 	 */
904 	oldcred = crcopysafe(p, newcred);
905 
906 #ifdef MAC
907 	error = mac_cred_check_setuid(oldcred, uid);
908 	if (error)
909 		goto fail;
910 #endif
911 
912 	/*
913 	 * See if we have "permission" by POSIX 1003.1 rules.
914 	 *
915 	 * Note that setuid(geteuid()) is a special case of
916 	 * "appropriate privileges" in appendix B.4.2.2.  We need
917 	 * to use this clause to be compatible with traditional BSD
918 	 * semantics.  Basically, it means that "setuid(xx)" sets all
919 	 * three id's (assuming you have privs).
920 	 *
921 	 * Notes on the logic.  We do things in three steps.
922 	 * 1: We determine if the euid is going to change, and do EPERM
923 	 *    right away.  We unconditionally change the euid later if this
924 	 *    test is satisfied, simplifying that part of the logic.
925 	 * 2: We determine if the real and/or saved uids are going to
926 	 *    change.  Determined by compile options.
927 	 * 3: Change euid last. (after tests in #2 for "appropriate privs")
928 	 */
929 	if (uid != oldcred->cr_ruid &&		/* allow setuid(getuid()) */
930 #ifdef _POSIX_SAVED_IDS
931 	    uid != oldcred->cr_svuid &&		/* allow setuid(saved gid) */
932 #endif
933 #ifdef POSIX_APPENDIX_B_4_2_2	/* Use BSD-compat clause from B.4.2.2 */
934 	    uid != oldcred->cr_uid &&		/* allow setuid(geteuid()) */
935 #endif
936 	    (error = priv_check_cred(oldcred, PRIV_CRED_SETUID)) != 0)
937 		goto fail;
938 
939 #ifdef _POSIX_SAVED_IDS
940 	/*
941 	 * Do we have "appropriate privileges" (are we root or uid == euid)
942 	 * If so, we are changing the real uid and/or saved uid.
943 	 */
944 	if (
945 #ifdef POSIX_APPENDIX_B_4_2_2	/* Use the clause from B.4.2.2 */
946 	    uid == oldcred->cr_uid ||
947 #endif
948 	    /* We are using privs. */
949 	    priv_check_cred(oldcred, PRIV_CRED_SETUID) == 0)
950 #endif
951 	{
952 		/*
953 		 * Set the real uid.
954 		 */
955 		if (uid != oldcred->cr_ruid) {
956 			change_ruid(newcred, uip);
957 			setsugid(p);
958 		}
959 		/*
960 		 * Set saved uid
961 		 *
962 		 * XXX always set saved uid even if not _POSIX_SAVED_IDS, as
963 		 * the security of seteuid() depends on it.  B.4.2.2 says it
964 		 * is important that we should do this.
965 		 */
966 		if (uid != oldcred->cr_svuid) {
967 			change_svuid(newcred, uid);
968 			setsugid(p);
969 		}
970 	}
971 
972 	/*
973 	 * In all permitted cases, we are changing the euid.
974 	 */
975 	if (uid != oldcred->cr_uid) {
976 		change_euid(newcred, uip);
977 		setsugid(p);
978 	}
979 
980 #ifdef RACCT
981 	racct_proc_ucred_changed(p, oldcred, newcred);
982 #endif
983 #ifdef RCTL
984 	crhold(newcred);
985 #endif
986 	/*
987 	 * Takes over 'newcred''s reference, so 'newcred' must not be used
988 	 * besides this point except on RCTL where we took an additional
989 	 * reference above.
990 	 */
991 	proc_set_cred(p, newcred);
992 	PROC_UNLOCK(p);
993 #ifdef RCTL
994 	rctl_proc_ucred_changed(p, newcred);
995 	crfree(newcred);
996 #endif
997 	uifree(uip);
998 	crfree(oldcred);
999 	return (0);
1000 
1001 fail:
1002 	PROC_UNLOCK(p);
1003 	uifree(uip);
1004 	crfree(newcred);
1005 	return (error);
1006 }
1007 
1008 #ifndef _SYS_SYSPROTO_H_
1009 struct seteuid_args {
1010 	uid_t	euid;
1011 };
1012 #endif
1013 /* ARGSUSED */
1014 int
1015 sys_seteuid(struct thread *td, struct seteuid_args *uap)
1016 {
1017 	struct proc *p = td->td_proc;
1018 	struct ucred *newcred, *oldcred;
1019 	uid_t euid;
1020 	struct uidinfo *euip;
1021 	int error;
1022 
1023 	euid = uap->euid;
1024 	AUDIT_ARG_EUID(euid);
1025 	newcred = crget();
1026 	euip = uifind(euid);
1027 	PROC_LOCK(p);
1028 	execve_block_pass(td);
1029 
1030 	/*
1031 	 * Copy credentials so other references do not see our changes.
1032 	 */
1033 	oldcred = crcopysafe(p, newcred);
1034 
1035 #ifdef MAC
1036 	error = mac_cred_check_seteuid(oldcred, euid);
1037 	if (error)
1038 		goto fail;
1039 #endif
1040 
1041 	if (euid != oldcred->cr_ruid &&		/* allow seteuid(getuid()) */
1042 	    euid != oldcred->cr_svuid &&	/* allow seteuid(saved uid) */
1043 	    (error = priv_check_cred(oldcred, PRIV_CRED_SETEUID)) != 0)
1044 		goto fail;
1045 
1046 	/*
1047 	 * Everything's okay, do it.
1048 	 */
1049 	if (oldcred->cr_uid != euid) {
1050 		change_euid(newcred, euip);
1051 		setsugid(p);
1052 	}
1053 	proc_set_cred(p, newcred);
1054 	PROC_UNLOCK(p);
1055 	uifree(euip);
1056 	crfree(oldcred);
1057 	return (0);
1058 
1059 fail:
1060 	PROC_UNLOCK(p);
1061 	uifree(euip);
1062 	crfree(newcred);
1063 	return (error);
1064 }
1065 
1066 #ifndef _SYS_SYSPROTO_H_
1067 struct setgid_args {
1068 	gid_t	gid;
1069 };
1070 #endif
1071 /* ARGSUSED */
1072 int
1073 sys_setgid(struct thread *td, struct setgid_args *uap)
1074 {
1075 	struct proc *p = td->td_proc;
1076 	struct ucred *newcred, *oldcred;
1077 	gid_t gid;
1078 	int error;
1079 
1080 	gid = uap->gid;
1081 	AUDIT_ARG_GID(gid);
1082 	newcred = crget();
1083 	PROC_LOCK(p);
1084 	execve_block_pass(td);
1085 	oldcred = crcopysafe(p, newcred);
1086 
1087 #ifdef MAC
1088 	error = mac_cred_check_setgid(oldcred, gid);
1089 	if (error)
1090 		goto fail;
1091 #endif
1092 
1093 	/*
1094 	 * See if we have "permission" by POSIX 1003.1 rules.
1095 	 *
1096 	 * Note that setgid(getegid()) is a special case of
1097 	 * "appropriate privileges" in appendix B.4.2.2.  We need
1098 	 * to use this clause to be compatible with traditional BSD
1099 	 * semantics.  Basically, it means that "setgid(xx)" sets all
1100 	 * three id's (assuming you have privs).
1101 	 *
1102 	 * For notes on the logic here, see setuid() above.
1103 	 */
1104 	if (gid != oldcred->cr_rgid &&		/* allow setgid(getgid()) */
1105 #ifdef _POSIX_SAVED_IDS
1106 	    gid != oldcred->cr_svgid &&		/* allow setgid(saved gid) */
1107 #endif
1108 #ifdef POSIX_APPENDIX_B_4_2_2	/* Use BSD-compat clause from B.4.2.2 */
1109 	    gid != oldcred->cr_gid && /* allow setgid(getegid()) */
1110 #endif
1111 	    (error = priv_check_cred(oldcred, PRIV_CRED_SETGID)) != 0)
1112 		goto fail;
1113 
1114 #ifdef _POSIX_SAVED_IDS
1115 	/*
1116 	 * Do we have "appropriate privileges" (are we root or gid == egid)
1117 	 * If so, we are changing the real uid and saved gid.
1118 	 */
1119 	if (
1120 #ifdef POSIX_APPENDIX_B_4_2_2	/* use the clause from B.4.2.2 */
1121 	    gid == oldcred->cr_gid ||
1122 #endif
1123 	    /* We are using privs. */
1124 	    priv_check_cred(oldcred, PRIV_CRED_SETGID) == 0)
1125 #endif
1126 	{
1127 		/*
1128 		 * Set real gid
1129 		 */
1130 		if (oldcred->cr_rgid != gid) {
1131 			change_rgid(newcred, gid);
1132 			setsugid(p);
1133 		}
1134 		/*
1135 		 * Set saved gid
1136 		 *
1137 		 * XXX always set saved gid even if not _POSIX_SAVED_IDS, as
1138 		 * the security of setegid() depends on it.  B.4.2.2 says it
1139 		 * is important that we should do this.
1140 		 */
1141 		if (oldcred->cr_svgid != gid) {
1142 			change_svgid(newcred, gid);
1143 			setsugid(p);
1144 		}
1145 	}
1146 	/*
1147 	 * In all cases permitted cases, we are changing the egid.
1148 	 * Copy credentials so other references do not see our changes.
1149 	 */
1150 	if (oldcred->cr_gid != gid) {
1151 		change_egid(newcred, gid);
1152 		setsugid(p);
1153 	}
1154 	proc_set_cred(p, newcred);
1155 	PROC_UNLOCK(p);
1156 	crfree(oldcred);
1157 	return (0);
1158 
1159 fail:
1160 	PROC_UNLOCK(p);
1161 	crfree(newcred);
1162 	return (error);
1163 }
1164 
1165 #ifndef _SYS_SYSPROTO_H_
1166 struct setegid_args {
1167 	gid_t	egid;
1168 };
1169 #endif
1170 /* ARGSUSED */
1171 int
1172 sys_setegid(struct thread *td, struct setegid_args *uap)
1173 {
1174 	struct proc *p = td->td_proc;
1175 	struct ucred *newcred, *oldcred;
1176 	gid_t egid;
1177 	int error;
1178 
1179 	egid = uap->egid;
1180 	AUDIT_ARG_EGID(egid);
1181 	newcred = crget();
1182 	PROC_LOCK(p);
1183 	execve_block_pass(td);
1184 	oldcred = crcopysafe(p, newcred);
1185 
1186 #ifdef MAC
1187 	error = mac_cred_check_setegid(oldcred, egid);
1188 	if (error)
1189 		goto fail;
1190 #endif
1191 
1192 	if (egid != oldcred->cr_rgid &&		/* allow setegid(getgid()) */
1193 	    egid != oldcred->cr_svgid &&	/* allow setegid(saved gid) */
1194 	    (error = priv_check_cred(oldcred, PRIV_CRED_SETEGID)) != 0)
1195 		goto fail;
1196 
1197 	if (oldcred->cr_gid != egid) {
1198 		change_egid(newcred, egid);
1199 		setsugid(p);
1200 	}
1201 	proc_set_cred(p, newcred);
1202 	PROC_UNLOCK(p);
1203 	crfree(oldcred);
1204 	return (0);
1205 
1206 fail:
1207 	PROC_UNLOCK(p);
1208 	crfree(newcred);
1209 	return (error);
1210 }
1211 
1212 #ifdef COMPAT_FREEBSD14
1213 int
1214 freebsd14_setgroups(struct thread *td, struct freebsd14_setgroups_args *uap)
1215 {
1216 	gid_t smallgroups[CRED_SMALLGROUPS_NB];
1217 	gid_t *groups;
1218 	int gidsetsize, error;
1219 
1220 	/*
1221 	 * Before FreeBSD 15.0, we allow one more group to be supplied to
1222 	 * account for the egid appearing before the supplementary groups.
1223 	 */
1224 	gidsetsize = uap->gidsetsize;
1225 	if (gidsetsize > ngroups_max + 1 || gidsetsize < 0)
1226 		return (EINVAL);
1227 
1228 	if (gidsetsize > CRED_SMALLGROUPS_NB)
1229 		groups = malloc(gidsetsize * sizeof(gid_t), M_TEMP, M_WAITOK);
1230 	else
1231 		groups = smallgroups;
1232 
1233 	error = copyin(uap->gidset, groups, gidsetsize * sizeof(gid_t));
1234 	if (error == 0)
1235 		error = kern_setgroups(td, &gidsetsize, groups, true);
1236 
1237 	if (groups != smallgroups)
1238 		free(groups, M_TEMP);
1239 	return (error);
1240 }
1241 #endif	/* COMPAT_FREEBSD14 */
1242 
1243 #ifndef _SYS_SYSPROTO_H_
1244 struct setgroups_args {
1245 	int	gidsetsize;
1246 	gid_t	*gidset;
1247 };
1248 #endif
1249 /* ARGSUSED */
1250 int
1251 sys_setgroups(struct thread *td, struct setgroups_args *uap)
1252 {
1253 	gid_t smallgroups[CRED_SMALLGROUPS_NB];
1254 	gid_t *groups;
1255 	int gidsetsize, error;
1256 
1257 	/*
1258 	 * Sanity check size now to avoid passing too big a value to copyin(),
1259 	 * even if kern_setgroups() will do it again.
1260 	 *
1261 	 * Ideally, the 'gidsetsize' argument should have been a 'u_int' (and it
1262 	 * was, in this implementation, for a long time), but POSIX standardized
1263 	 * getgroups() to take an 'int' and it would be quite entrapping to have
1264 	 * setgroups() differ.
1265 	 */
1266 	gidsetsize = uap->gidsetsize;
1267 	if (gidsetsize > ngroups_max || gidsetsize < 0)
1268 		return (EINVAL);
1269 
1270 	if (gidsetsize > CRED_SMALLGROUPS_NB)
1271 		groups = malloc(gidsetsize * sizeof(gid_t), M_TEMP, M_WAITOK);
1272 	else
1273 		groups = smallgroups;
1274 
1275 	error = copyin(uap->gidset, groups, gidsetsize * sizeof(gid_t));
1276 	if (error == 0)
1277 		error = kern_setgroups(td, &gidsetsize, groups, false);
1278 
1279 	if (groups != smallgroups)
1280 		free(groups, M_TEMP);
1281 	return (error);
1282 }
1283 
1284 /*
1285  * 'includes_egid' indicates that the first element of groups[] (if any) is the
1286  * desired effective GID and that only the other elements will be used to set
1287  * the supplementary groups.  If true, and groups[] is empty, the effective GID
1288  * is left unchanged and all supplementary groups deleted (see setgroups(2)).
1289  *
1290  * CAUTION: This function normalizes 'groups' (only the supplementary groups on
1291  * 'includes_egid') and may need to update the value of '*ngrpp' as
1292  * a consequence.
1293  */
1294 int
1295 kern_setgroups(struct thread *td, int *ngrpp, gid_t *groups, bool includes_egid)
1296 {
1297 	struct proc *p = td->td_proc;
1298 	struct ucred *newcred, *oldcred;
1299 	gid_t egid;
1300 	int ngrp, error;
1301 
1302 	ngrp = *ngrpp;
1303 	/* Sanity check size. */
1304 	if (ngrp < 0 || ngrp > (includes_egid ? ngroups_max + 1 : ngroups_max))
1305 		return (EINVAL);
1306 
1307 	if (includes_egid) {
1308 		if (ngrp > 0) {
1309 			egid = groups[0];
1310 			groups++;
1311 			ngrp--;
1312 		} else
1313 			includes_egid = false;
1314 	}
1315 
1316 	AUDIT_ARG_GROUPSET(groups, ngrp);
1317 	if (includes_egid)
1318 		AUDIT_ARG_EGID(egid);
1319 
1320 	groups_normalize(&ngrp, groups);
1321 	*ngrpp = includes_egid ? ngrp + 1 : ngrp;
1322 
1323 	newcred = crget();
1324 	crextend(newcred, ngrp);
1325 	PROC_LOCK(p);
1326 	execve_block_pass(td);
1327 	oldcred = crcopysafe(p, newcred);
1328 
1329 #ifdef MAC
1330 	/*
1331 	 * We pass NULL here explicitly if we don't have any supplementary
1332 	 * groups mostly for the sake of normalization, but also to avoid/detect
1333 	 * a situation where a MAC module has some assumption about the layout
1334 	 * of `groups` matching historical behavior.
1335 	 */
1336 	error = mac_cred_check_setgroups(oldcred, ngrp,
1337 	    ngrp == 0 ? NULL : groups);
1338 	if (error != 0)
1339 		goto fail;
1340 
1341 	if (includes_egid) {
1342 		error = mac_cred_check_setegid(oldcred, egid);
1343 		if (error != 0)
1344 			goto fail;
1345 	}
1346 #endif
1347 
1348 	error = priv_check_cred(oldcred, PRIV_CRED_SETGROUPS);
1349 	if (error != 0)
1350 		goto fail;
1351 
1352 	if (includes_egid) {
1353 		error = priv_check_cred(oldcred, PRIV_CRED_SETEGID);
1354 		if (error != 0)
1355 			goto fail;
1356 	}
1357 
1358 	crsetgroups_internal(newcred, ngrp, groups);
1359 	if (includes_egid)
1360 		change_egid(newcred, egid);
1361 	setsugid(p);
1362 	proc_set_cred(p, newcred);
1363 	PROC_UNLOCK(p);
1364 	crfree(oldcred);
1365 	return (0);
1366 
1367 fail:
1368 	PROC_UNLOCK(p);
1369 	crfree(newcred);
1370 	return (error);
1371 }
1372 
1373 #ifndef _SYS_SYSPROTO_H_
1374 struct setreuid_args {
1375 	uid_t	ruid;
1376 	uid_t	euid;
1377 };
1378 #endif
1379 /* ARGSUSED */
1380 int
1381 sys_setreuid(struct thread *td, struct setreuid_args *uap)
1382 {
1383 	struct proc *p = td->td_proc;
1384 	struct ucred *newcred, *oldcred;
1385 	uid_t euid, ruid;
1386 	struct uidinfo *euip, *ruip;
1387 	int error;
1388 
1389 	euid = uap->euid;
1390 	ruid = uap->ruid;
1391 	AUDIT_ARG_EUID(euid);
1392 	AUDIT_ARG_RUID(ruid);
1393 	newcred = crget();
1394 	euip = uifind(euid);
1395 	ruip = uifind(ruid);
1396 	PROC_LOCK(p);
1397 	execve_block_pass(td);
1398 	oldcred = crcopysafe(p, newcred);
1399 
1400 #ifdef MAC
1401 	error = mac_cred_check_setreuid(oldcred, ruid, euid);
1402 	if (error)
1403 		goto fail;
1404 #endif
1405 
1406 	if (((ruid != (uid_t)-1 && ruid != oldcred->cr_ruid &&
1407 	      ruid != oldcred->cr_svuid) ||
1408 	     (euid != (uid_t)-1 && euid != oldcred->cr_uid &&
1409 	      euid != oldcred->cr_ruid && euid != oldcred->cr_svuid)) &&
1410 	    (error = priv_check_cred(oldcred, PRIV_CRED_SETREUID)) != 0)
1411 		goto fail;
1412 
1413 	if (euid != (uid_t)-1 && oldcred->cr_uid != euid) {
1414 		change_euid(newcred, euip);
1415 		setsugid(p);
1416 	}
1417 	if (ruid != (uid_t)-1 && oldcred->cr_ruid != ruid) {
1418 		change_ruid(newcred, ruip);
1419 		setsugid(p);
1420 	}
1421 	if ((ruid != (uid_t)-1 || newcred->cr_uid != newcred->cr_ruid) &&
1422 	    newcred->cr_svuid != newcred->cr_uid) {
1423 		change_svuid(newcred, newcred->cr_uid);
1424 		setsugid(p);
1425 	}
1426 #ifdef RACCT
1427 	racct_proc_ucred_changed(p, oldcred, newcred);
1428 #endif
1429 #ifdef RCTL
1430 	crhold(newcred);
1431 #endif
1432 	/*
1433 	 * Takes over 'newcred''s reference, so 'newcred' must not be used
1434 	 * besides this point except on RCTL where we took an additional
1435 	 * reference above.
1436 	 */
1437 	proc_set_cred(p, newcred);
1438 	PROC_UNLOCK(p);
1439 #ifdef RCTL
1440 	rctl_proc_ucred_changed(p, newcred);
1441 	crfree(newcred);
1442 #endif
1443 	uifree(ruip);
1444 	uifree(euip);
1445 	crfree(oldcred);
1446 	return (0);
1447 
1448 fail:
1449 	PROC_UNLOCK(p);
1450 	uifree(ruip);
1451 	uifree(euip);
1452 	crfree(newcred);
1453 	return (error);
1454 }
1455 
1456 #ifndef _SYS_SYSPROTO_H_
1457 struct setregid_args {
1458 	gid_t	rgid;
1459 	gid_t	egid;
1460 };
1461 #endif
1462 /* ARGSUSED */
1463 int
1464 sys_setregid(struct thread *td, struct setregid_args *uap)
1465 {
1466 	struct proc *p = td->td_proc;
1467 	struct ucred *newcred, *oldcred;
1468 	gid_t egid, rgid;
1469 	int error;
1470 
1471 	egid = uap->egid;
1472 	rgid = uap->rgid;
1473 	AUDIT_ARG_EGID(egid);
1474 	AUDIT_ARG_RGID(rgid);
1475 	newcred = crget();
1476 	PROC_LOCK(p);
1477 	execve_block_pass(td);
1478 	oldcred = crcopysafe(p, newcred);
1479 
1480 #ifdef MAC
1481 	error = mac_cred_check_setregid(oldcred, rgid, egid);
1482 	if (error)
1483 		goto fail;
1484 #endif
1485 
1486 	if (((rgid != (gid_t)-1 && rgid != oldcred->cr_rgid &&
1487 	    rgid != oldcred->cr_svgid) ||
1488 	     (egid != (gid_t)-1 && egid != oldcred->cr_gid &&
1489 	     egid != oldcred->cr_rgid && egid != oldcred->cr_svgid)) &&
1490 	    (error = priv_check_cred(oldcred, PRIV_CRED_SETREGID)) != 0)
1491 		goto fail;
1492 
1493 	if (egid != (gid_t)-1 && oldcred->cr_gid != egid) {
1494 		change_egid(newcred, egid);
1495 		setsugid(p);
1496 	}
1497 	if (rgid != (gid_t)-1 && oldcred->cr_rgid != rgid) {
1498 		change_rgid(newcred, rgid);
1499 		setsugid(p);
1500 	}
1501 	if ((rgid != (gid_t)-1 || newcred->cr_gid != newcred->cr_rgid) &&
1502 	    newcred->cr_svgid != newcred->cr_gid) {
1503 		change_svgid(newcred, newcred->cr_gid);
1504 		setsugid(p);
1505 	}
1506 	proc_set_cred(p, newcred);
1507 	PROC_UNLOCK(p);
1508 	crfree(oldcred);
1509 	return (0);
1510 
1511 fail:
1512 	PROC_UNLOCK(p);
1513 	crfree(newcred);
1514 	return (error);
1515 }
1516 
1517 /*
1518  * setresuid(ruid, euid, suid) is like setreuid except control over the saved
1519  * uid is explicit.
1520  */
1521 #ifndef _SYS_SYSPROTO_H_
1522 struct setresuid_args {
1523 	uid_t	ruid;
1524 	uid_t	euid;
1525 	uid_t	suid;
1526 };
1527 #endif
1528 /* ARGSUSED */
1529 int
1530 sys_setresuid(struct thread *td, struct setresuid_args *uap)
1531 {
1532 	struct proc *p = td->td_proc;
1533 	struct ucred *newcred, *oldcred;
1534 	uid_t euid, ruid, suid;
1535 	struct uidinfo *euip, *ruip;
1536 	int error;
1537 
1538 	euid = uap->euid;
1539 	ruid = uap->ruid;
1540 	suid = uap->suid;
1541 	AUDIT_ARG_EUID(euid);
1542 	AUDIT_ARG_RUID(ruid);
1543 	AUDIT_ARG_SUID(suid);
1544 	newcred = crget();
1545 	euip = uifind(euid);
1546 	ruip = uifind(ruid);
1547 	PROC_LOCK(p);
1548 	execve_block_pass(td);
1549 	oldcred = crcopysafe(p, newcred);
1550 
1551 #ifdef MAC
1552 	error = mac_cred_check_setresuid(oldcred, ruid, euid, suid);
1553 	if (error)
1554 		goto fail;
1555 #endif
1556 
1557 	if (((ruid != (uid_t)-1 && ruid != oldcred->cr_ruid &&
1558 	     ruid != oldcred->cr_svuid &&
1559 	      ruid != oldcred->cr_uid) ||
1560 	     (euid != (uid_t)-1 && euid != oldcred->cr_ruid &&
1561 	    euid != oldcred->cr_svuid &&
1562 	      euid != oldcred->cr_uid) ||
1563 	     (suid != (uid_t)-1 && suid != oldcred->cr_ruid &&
1564 	    suid != oldcred->cr_svuid &&
1565 	      suid != oldcred->cr_uid)) &&
1566 	    (error = priv_check_cred(oldcred, PRIV_CRED_SETRESUID)) != 0)
1567 		goto fail;
1568 
1569 	if (euid != (uid_t)-1 && oldcred->cr_uid != euid) {
1570 		change_euid(newcred, euip);
1571 		setsugid(p);
1572 	}
1573 	if (ruid != (uid_t)-1 && oldcred->cr_ruid != ruid) {
1574 		change_ruid(newcred, ruip);
1575 		setsugid(p);
1576 	}
1577 	if (suid != (uid_t)-1 && oldcred->cr_svuid != suid) {
1578 		change_svuid(newcred, suid);
1579 		setsugid(p);
1580 	}
1581 #ifdef RACCT
1582 	racct_proc_ucred_changed(p, oldcred, newcred);
1583 #endif
1584 #ifdef RCTL
1585 	crhold(newcred);
1586 #endif
1587 	/*
1588 	 * Takes over 'newcred''s reference, so 'newcred' must not be used
1589 	 * besides this point except on RCTL where we took an additional
1590 	 * reference above.
1591 	 */
1592 	proc_set_cred(p, newcred);
1593 	PROC_UNLOCK(p);
1594 #ifdef RCTL
1595 	rctl_proc_ucred_changed(p, newcred);
1596 	crfree(newcred);
1597 #endif
1598 	uifree(ruip);
1599 	uifree(euip);
1600 	crfree(oldcred);
1601 	return (0);
1602 
1603 fail:
1604 	PROC_UNLOCK(p);
1605 	uifree(ruip);
1606 	uifree(euip);
1607 	crfree(newcred);
1608 	return (error);
1609 
1610 }
1611 
1612 /*
1613  * setresgid(rgid, egid, sgid) is like setregid except control over the saved
1614  * gid is explicit.
1615  */
1616 #ifndef _SYS_SYSPROTO_H_
1617 struct setresgid_args {
1618 	gid_t	rgid;
1619 	gid_t	egid;
1620 	gid_t	sgid;
1621 };
1622 #endif
1623 /* ARGSUSED */
1624 int
1625 sys_setresgid(struct thread *td, struct setresgid_args *uap)
1626 {
1627 	struct proc *p = td->td_proc;
1628 	struct ucred *newcred, *oldcred;
1629 	gid_t egid, rgid, sgid;
1630 	int error;
1631 
1632 	egid = uap->egid;
1633 	rgid = uap->rgid;
1634 	sgid = uap->sgid;
1635 	AUDIT_ARG_EGID(egid);
1636 	AUDIT_ARG_RGID(rgid);
1637 	AUDIT_ARG_SGID(sgid);
1638 	newcred = crget();
1639 	PROC_LOCK(p);
1640 	execve_block_pass(td);
1641 	oldcred = crcopysafe(p, newcred);
1642 
1643 #ifdef MAC
1644 	error = mac_cred_check_setresgid(oldcred, rgid, egid, sgid);
1645 	if (error)
1646 		goto fail;
1647 #endif
1648 
1649 	if (((rgid != (gid_t)-1 && rgid != oldcred->cr_rgid &&
1650 	      rgid != oldcred->cr_svgid &&
1651 	      rgid != oldcred->cr_gid) ||
1652 	     (egid != (gid_t)-1 && egid != oldcred->cr_rgid &&
1653 	      egid != oldcred->cr_svgid &&
1654 	      egid != oldcred->cr_gid) ||
1655 	     (sgid != (gid_t)-1 && sgid != oldcred->cr_rgid &&
1656 	      sgid != oldcred->cr_svgid &&
1657 	      sgid != oldcred->cr_gid)) &&
1658 	    (error = priv_check_cred(oldcred, PRIV_CRED_SETRESGID)) != 0)
1659 		goto fail;
1660 
1661 	if (egid != (gid_t)-1 && oldcred->cr_gid != egid) {
1662 		change_egid(newcred, egid);
1663 		setsugid(p);
1664 	}
1665 	if (rgid != (gid_t)-1 && oldcred->cr_rgid != rgid) {
1666 		change_rgid(newcred, rgid);
1667 		setsugid(p);
1668 	}
1669 	if (sgid != (gid_t)-1 && oldcred->cr_svgid != sgid) {
1670 		change_svgid(newcred, sgid);
1671 		setsugid(p);
1672 	}
1673 	proc_set_cred(p, newcred);
1674 	PROC_UNLOCK(p);
1675 	crfree(oldcred);
1676 	return (0);
1677 
1678 fail:
1679 	PROC_UNLOCK(p);
1680 	crfree(newcred);
1681 	return (error);
1682 }
1683 
1684 #ifndef _SYS_SYSPROTO_H_
1685 struct getresuid_args {
1686 	uid_t	*ruid;
1687 	uid_t	*euid;
1688 	uid_t	*suid;
1689 };
1690 #endif
1691 /* ARGSUSED */
1692 int
1693 sys_getresuid(struct thread *td, struct getresuid_args *uap)
1694 {
1695 	struct ucred *cred;
1696 	int error1 = 0, error2 = 0, error3 = 0;
1697 
1698 	cred = td->td_ucred;
1699 	if (uap->ruid)
1700 		error1 = copyout(&cred->cr_ruid,
1701 		    uap->ruid, sizeof(cred->cr_ruid));
1702 	if (uap->euid)
1703 		error2 = copyout(&cred->cr_uid,
1704 		    uap->euid, sizeof(cred->cr_uid));
1705 	if (uap->suid)
1706 		error3 = copyout(&cred->cr_svuid,
1707 		    uap->suid, sizeof(cred->cr_svuid));
1708 	return (error1 ? error1 : error2 ? error2 : error3);
1709 }
1710 
1711 #ifndef _SYS_SYSPROTO_H_
1712 struct getresgid_args {
1713 	gid_t	*rgid;
1714 	gid_t	*egid;
1715 	gid_t	*sgid;
1716 };
1717 #endif
1718 /* ARGSUSED */
1719 int
1720 sys_getresgid(struct thread *td, struct getresgid_args *uap)
1721 {
1722 	struct ucred *cred;
1723 	int error1 = 0, error2 = 0, error3 = 0;
1724 
1725 	cred = td->td_ucred;
1726 	if (uap->rgid)
1727 		error1 = copyout(&cred->cr_rgid,
1728 		    uap->rgid, sizeof(cred->cr_rgid));
1729 	if (uap->egid)
1730 		error2 = copyout(&cred->cr_gid,
1731 		    uap->egid, sizeof(cred->cr_gid));
1732 	if (uap->sgid)
1733 		error3 = copyout(&cred->cr_svgid,
1734 		    uap->sgid, sizeof(cred->cr_svgid));
1735 	return (error1 ? error1 : error2 ? error2 : error3);
1736 }
1737 
1738 #ifndef _SYS_SYSPROTO_H_
1739 struct issetugid_args {
1740 	int dummy;
1741 };
1742 #endif
1743 /* ARGSUSED */
1744 int
1745 sys_issetugid(struct thread *td, struct issetugid_args *uap)
1746 {
1747 	struct proc *p = td->td_proc;
1748 
1749 	/*
1750 	 * Note: OpenBSD sets a P_SUGIDEXEC flag set at execve() time,
1751 	 * we use P_SUGID because we consider changing the owners as
1752 	 * "tainting" as well.
1753 	 * This is significant for procs that start as root and "become"
1754 	 * a user without an exec - programs cannot know *everything*
1755 	 * that libc *might* have put in their data segment.
1756 	 */
1757 	td->td_retval[0] = (p->p_flag & P_SUGID) ? 1 : 0;
1758 	return (0);
1759 }
1760 
1761 int
1762 sys___setugid(struct thread *td, struct __setugid_args *uap)
1763 {
1764 #ifdef REGRESSION
1765 	struct proc *p;
1766 
1767 	p = td->td_proc;
1768 	switch (uap->flag) {
1769 	case 0:
1770 		PROC_LOCK(p);
1771 		p->p_flag &= ~P_SUGID;
1772 		PROC_UNLOCK(p);
1773 		return (0);
1774 	case 1:
1775 		PROC_LOCK(p);
1776 		p->p_flag |= P_SUGID;
1777 		PROC_UNLOCK(p);
1778 		return (0);
1779 	default:
1780 		return (EINVAL);
1781 	}
1782 #else /* !REGRESSION */
1783 
1784 	return (ENOSYS);
1785 #endif /* REGRESSION */
1786 }
1787 
1788 #ifdef INVARIANTS
1789 static void
1790 groups_check_normalized(int ngrp, const gid_t *groups)
1791 {
1792 	gid_t prev_g;
1793 
1794 	groups_check_positive_len(ngrp);
1795 	groups_check_max_len(ngrp);
1796 
1797 	if (ngrp <= 1)
1798 		return;
1799 
1800 	prev_g = groups[0];
1801 	for (int i = 1; i < ngrp; ++i) {
1802 		const gid_t g = groups[i];
1803 
1804 		if (prev_g >= g)
1805 			panic("%s: groups[%d] (%u) >= groups[%d] (%u)",
1806 			    __func__, i - 1, prev_g, i, g);
1807 		prev_g = g;
1808 	}
1809 }
1810 #else
1811 #define groups_check_normalized(...)
1812 #endif
1813 
1814 /*
1815  * Returns whether gid designates a supplementary group in cred.
1816  */
1817 bool
1818 group_is_supplementary(const gid_t gid, const struct ucred *const cred)
1819 {
1820 
1821 	groups_check_normalized(cred->cr_ngroups, cred->cr_groups);
1822 
1823 	/*
1824 	 * Perform a binary search of the supplementary groups.  This is
1825 	 * possible because we sort the groups in crsetgroups().
1826 	 */
1827 	return (bsearch(&gid, cred->cr_groups, cred->cr_ngroups,
1828 	    sizeof(gid), gidp_cmp) != NULL);
1829 }
1830 
1831 /*
1832  * Check if gid is a member of the (effective) group set (i.e., effective and
1833  * supplementary groups).
1834  */
1835 bool
1836 groupmember(gid_t gid, const struct ucred *cred)
1837 {
1838 
1839 	groups_check_positive_len(cred->cr_ngroups);
1840 
1841 	if (gid == cred->cr_gid)
1842 		return (true);
1843 
1844 	return (group_is_supplementary(gid, cred));
1845 }
1846 
1847 /*
1848  * Check if gid is a member of the real group set (i.e., real and supplementary
1849  * groups).
1850  */
1851 bool
1852 realgroupmember(gid_t gid, const struct ucred *cred)
1853 {
1854 	groups_check_positive_len(cred->cr_ngroups);
1855 
1856 	if (gid == cred->cr_rgid)
1857 		return (true);
1858 
1859 	return (group_is_supplementary(gid, cred));
1860 }
1861 
1862 /*
1863  * Test the active securelevel against a given level.  securelevel_gt()
1864  * implements (securelevel > level).  securelevel_ge() implements
1865  * (securelevel >= level).  Note that the logic is inverted -- these
1866  * functions return EPERM on "success" and 0 on "failure".
1867  *
1868  * Due to care taken when setting the securelevel, we know that no jail will
1869  * be less secure that its parent (or the physical system), so it is sufficient
1870  * to test the current jail only.
1871  *
1872  * XXXRW: Possibly since this has to do with privilege, it should move to
1873  * kern_priv.c.
1874  */
1875 int
1876 securelevel_gt(struct ucred *cr, int level)
1877 {
1878 
1879 	return (cr->cr_prison->pr_securelevel > level ? EPERM : 0);
1880 }
1881 
1882 int
1883 securelevel_ge(struct ucred *cr, int level)
1884 {
1885 
1886 	return (cr->cr_prison->pr_securelevel >= level ? EPERM : 0);
1887 }
1888 
1889 /*
1890  * 'see_other_uids' determines whether or not visibility of processes
1891  * and sockets with credentials holding different real uids is possible
1892  * using a variety of system MIBs.
1893  * XXX: data declarations should be together near the beginning of the file.
1894  */
1895 static int	see_other_uids = 1;
1896 SYSCTL_INT(_security_bsd, OID_AUTO, see_other_uids, CTLFLAG_RW,
1897     &see_other_uids, 0,
1898     "Unprivileged processes may see subjects/objects with different real uid");
1899 
1900 /*-
1901  * Determine if u1 "can see" the subject specified by u2, according to the
1902  * 'see_other_uids' policy.
1903  * Returns: 0 for permitted, ESRCH otherwise
1904  * Locks: none
1905  * References: *u1 and *u2 must not change during the call
1906  *             u1 may equal u2, in which case only one reference is required
1907  */
1908 static int
1909 cr_canseeotheruids(struct ucred *u1, struct ucred *u2)
1910 {
1911 
1912 	if (!see_other_uids && u1->cr_ruid != u2->cr_ruid) {
1913 		if (priv_check_cred(u1, PRIV_SEEOTHERUIDS) != 0)
1914 			return (ESRCH);
1915 	}
1916 	return (0);
1917 }
1918 
1919 /*
1920  * 'see_other_gids' determines whether or not visibility of processes
1921  * and sockets with credentials holding different real gids is possible
1922  * using a variety of system MIBs.
1923  * XXX: data declarations should be together near the beginning of the file.
1924  */
1925 static int	see_other_gids = 1;
1926 SYSCTL_INT(_security_bsd, OID_AUTO, see_other_gids, CTLFLAG_RW,
1927     &see_other_gids, 0,
1928     "Unprivileged processes may see subjects/objects with different real gid");
1929 
1930 /*
1931  * Determine if u1 can "see" the subject specified by u2, according to the
1932  * 'see_other_gids' policy.
1933  * Returns: 0 for permitted, ESRCH otherwise
1934  * Locks: none
1935  * References: *u1 and *u2 must not change during the call
1936  *             u1 may equal u2, in which case only one reference is required
1937  */
1938 static int
1939 cr_canseeothergids(struct ucred *u1, struct ucred *u2)
1940 {
1941 	if (see_other_gids)
1942 		return (0);
1943 
1944 	/* Restriction in force. */
1945 
1946 	if (realgroupmember(u1->cr_rgid, u2))
1947 		return (0);
1948 
1949 	for (int i = 0; i < u1->cr_ngroups; i++)
1950 		if (realgroupmember(u1->cr_groups[i], u2))
1951 			return (0);
1952 
1953 	if (priv_check_cred(u1, PRIV_SEEOTHERGIDS) == 0)
1954 		return (0);
1955 
1956 	return (ESRCH);
1957 }
1958 
1959 /*
1960  * 'see_jail_proc' determines whether or not visibility of processes and
1961  * sockets with credentials holding different jail ids is possible using a
1962  * variety of system MIBs.
1963  *
1964  * XXX: data declarations should be together near the beginning of the file.
1965  */
1966 
1967 static int	see_jail_proc = 1;
1968 SYSCTL_INT(_security_bsd, OID_AUTO, see_jail_proc, CTLFLAG_RW,
1969     &see_jail_proc, 0,
1970     "Unprivileged processes may see subjects/objects with different jail ids");
1971 
1972 /*-
1973  * Determine if u1 "can see" the subject specified by u2, according to the
1974  * 'see_jail_proc' policy.
1975  * Returns: 0 for permitted, ESRCH otherwise
1976  * Locks: none
1977  * References: *u1 and *u2 must not change during the call
1978  *             u1 may equal u2, in which case only one reference is required
1979  */
1980 static int
1981 cr_canseejailproc(struct ucred *u1, struct ucred *u2)
1982 {
1983 	if (see_jail_proc || /* Policy deactivated. */
1984 	    u1->cr_prison == u2->cr_prison || /* Same jail. */
1985 	    priv_check_cred(u1, PRIV_SEEJAILPROC) == 0) /* Privileged. */
1986 		return (0);
1987 
1988 	return (ESRCH);
1989 }
1990 
1991 /*
1992  * Determine if u1 can tamper with the subject specified by u2, if they are in
1993  * different jails and 'unprivileged_parent_tampering' jail policy allows it.
1994  *
1995  * May be called if u1 and u2 are in the same jail, but it is expected that the
1996  * caller has already done a prison_check() prior to calling it.
1997  *
1998  * Returns: 0 for permitted, EPERM otherwise
1999  */
2000 static int
2001 cr_can_tamper_with_subjail(struct ucred *u1, struct ucred *u2, int priv)
2002 {
2003 
2004 	MPASS(prison_check(u1, u2) == 0);
2005 	if (u1->cr_prison == u2->cr_prison)
2006 		return (0);
2007 
2008 	if (priv_check_cred(u1, priv) == 0)
2009 		return (0);
2010 
2011 	/*
2012 	 * Jails do not maintain a distinct UID space, so process visibility is
2013 	 * all that would control an unprivileged process' ability to tamper
2014 	 * with a process in a subjail by default if we did not have the
2015 	 * allow.unprivileged_parent_tampering knob to restrict it by default.
2016 	 */
2017 	if (prison_allow(u2, PR_ALLOW_UNPRIV_PARENT_TAMPER))
2018 		return (0);
2019 
2020 	return (EPERM);
2021 }
2022 
2023 /*
2024  * Helper for cr_cansee*() functions to abide by system-wide security.bsd.see_*
2025  * policies.  Determines if u1 "can see" u2 according to these policies.
2026  * Returns: 0 for permitted, ESRCH otherwise
2027  */
2028 int
2029 cr_bsd_visible(struct ucred *u1, struct ucred *u2)
2030 {
2031 	int error;
2032 
2033 	error = cr_canseeotheruids(u1, u2);
2034 	if (error != 0)
2035 		return (error);
2036 	error = cr_canseeothergids(u1, u2);
2037 	if (error != 0)
2038 		return (error);
2039 	error = cr_canseejailproc(u1, u2);
2040 	if (error != 0)
2041 		return (error);
2042 	return (0);
2043 }
2044 
2045 /*-
2046  * Determine if u1 "can see" the subject specified by u2.
2047  * Returns: 0 for permitted, an errno value otherwise
2048  * Locks: none
2049  * References: *u1 and *u2 must not change during the call
2050  *             u1 may equal u2, in which case only one reference is required
2051  */
2052 int
2053 cr_cansee(struct ucred *u1, struct ucred *u2)
2054 {
2055 	int error;
2056 
2057 	if ((error = prison_check(u1, u2)))
2058 		return (error);
2059 #ifdef MAC
2060 	if ((error = mac_cred_check_visible(u1, u2)))
2061 		return (error);
2062 #endif
2063 	if ((error = cr_bsd_visible(u1, u2)))
2064 		return (error);
2065 	return (0);
2066 }
2067 
2068 /*-
2069  * Determine if td "can see" the subject specified by p.
2070  * Returns: 0 for permitted, an errno value otherwise
2071  * Locks: Sufficient locks to protect p->p_ucred must be held.  td really
2072  *        should be curthread.
2073  * References: td and p must be valid for the lifetime of the call
2074  */
2075 int
2076 p_cansee(struct thread *td, struct proc *p)
2077 {
2078 	/* Wrap cr_cansee() for all functionality. */
2079 	KASSERT(td == curthread, ("%s: td not curthread", __func__));
2080 	PROC_LOCK_ASSERT(p, MA_OWNED);
2081 
2082 	if (td->td_proc == p)
2083 		return (0);
2084 	return (cr_cansee(td->td_ucred, p->p_ucred));
2085 }
2086 
2087 /*
2088  * 'conservative_signals' prevents the delivery of a broad class of
2089  * signals by unprivileged processes to processes that have changed their
2090  * credentials since the last invocation of execve().  This can prevent
2091  * the leakage of cached information or retained privileges as a result
2092  * of a common class of signal-related vulnerabilities.  However, this
2093  * may interfere with some applications that expect to be able to
2094  * deliver these signals to peer processes after having given up
2095  * privilege.
2096  */
2097 static int	conservative_signals = 1;
2098 SYSCTL_INT(_security_bsd, OID_AUTO, conservative_signals, CTLFLAG_RW,
2099     &conservative_signals, 0, "Unprivileged processes prevented from "
2100     "sending certain signals to processes whose credentials have changed");
2101 /*-
2102  * Determine whether cred may deliver the specified signal to proc.
2103  * Returns: 0 for permitted, an errno value otherwise.
2104  * Locks: A lock must be held for proc.
2105  * References: cred and proc must be valid for the lifetime of the call.
2106  */
2107 int
2108 cr_cansignal(struct ucred *cred, struct proc *proc, int signum)
2109 {
2110 	int error;
2111 
2112 	PROC_LOCK_ASSERT(proc, MA_OWNED);
2113 	/*
2114 	 * Jail semantics limit the scope of signalling to proc in the
2115 	 * same jail as cred, if cred is in jail.
2116 	 */
2117 	error = prison_check(cred, proc->p_ucred);
2118 	if (error)
2119 		return (error);
2120 #ifdef MAC
2121 	if ((error = mac_proc_check_signal(cred, proc, signum)))
2122 		return (error);
2123 #endif
2124 	if ((error = cr_bsd_visible(cred, proc->p_ucred)))
2125 		return (error);
2126 
2127 	/*
2128 	 * UNIX signal semantics depend on the status of the P_SUGID
2129 	 * bit on the target process.  If the bit is set, then additional
2130 	 * restrictions are placed on the set of available signals.
2131 	 */
2132 	if (conservative_signals && (proc->p_flag & P_SUGID)) {
2133 		switch (signum) {
2134 		case 0:
2135 		case SIGKILL:
2136 		case SIGINT:
2137 		case SIGTERM:
2138 		case SIGALRM:
2139 		case SIGSTOP:
2140 		case SIGTTIN:
2141 		case SIGTTOU:
2142 		case SIGTSTP:
2143 		case SIGHUP:
2144 		case SIGUSR1:
2145 		case SIGUSR2:
2146 			/*
2147 			 * Generally, permit job and terminal control
2148 			 * signals.
2149 			 */
2150 			break;
2151 		default:
2152 			/* Not permitted without privilege. */
2153 			error = priv_check_cred(cred, PRIV_SIGNAL_SUGID);
2154 			if (error)
2155 				return (error);
2156 		}
2157 	}
2158 
2159 	/*
2160 	 * Generally, the target credential's ruid or svuid must match the
2161 	 * subject credential's ruid or euid.
2162 	 */
2163 	if (cred->cr_ruid != proc->p_ucred->cr_ruid &&
2164 	    cred->cr_ruid != proc->p_ucred->cr_svuid &&
2165 	    cred->cr_uid != proc->p_ucred->cr_ruid &&
2166 	    cred->cr_uid != proc->p_ucred->cr_svuid) {
2167 		error = priv_check_cred(cred, PRIV_SIGNAL_DIFFCRED);
2168 		if (error)
2169 			return (error);
2170 	}
2171 
2172 	/*
2173 	 * At this point, the target may be in a different jail than the
2174 	 * subject -- the subject must be in a parent jail to the target,
2175 	 * whether it is prison0 or a subordinate of prison0 that has
2176 	 * children.  Additional privileges are required to allow this, as
2177 	 * whether the creds are truly equivalent or not must be determined on
2178 	 * a case-by-case basis.
2179 	 */
2180 	error = cr_can_tamper_with_subjail(cred, proc->p_ucred,
2181 	    PRIV_SIGNAL_DIFFJAIL);
2182 	if (error)
2183 		return (error);
2184 
2185 	return (0);
2186 }
2187 
2188 /*-
2189  * Determine whether td may deliver the specified signal to p.
2190  * Returns: 0 for permitted, an errno value otherwise
2191  * Locks: Sufficient locks to protect various components of td and p
2192  *        must be held.  td must be curthread, and a lock must be
2193  *        held for p.
2194  * References: td and p must be valid for the lifetime of the call
2195  */
2196 int
2197 p_cansignal(struct thread *td, struct proc *p, int signum)
2198 {
2199 
2200 	KASSERT(td == curthread, ("%s: td not curthread", __func__));
2201 	PROC_LOCK_ASSERT(p, MA_OWNED);
2202 	if (td->td_proc == p)
2203 		return (0);
2204 
2205 	/*
2206 	 * UNIX signalling semantics require that processes in the same
2207 	 * session always be able to deliver SIGCONT to one another,
2208 	 * overriding the remaining protections.
2209 	 */
2210 	/* XXX: This will require an additional lock of some sort. */
2211 	if (signum == SIGCONT && td->td_proc->p_session == p->p_session)
2212 		return (0);
2213 	/*
2214 	 * Some compat layers use SIGTHR and higher signals for
2215 	 * communication between different kernel threads of the same
2216 	 * process, so that they expect that it's always possible to
2217 	 * deliver them, even for suid applications where cr_cansignal() can
2218 	 * deny such ability for security consideration.  It should be
2219 	 * pretty safe to do since the only way to create two processes
2220 	 * with the same p_leader is via rfork(2).
2221 	 */
2222 	if (td->td_proc->p_leader != NULL && signum >= SIGTHR &&
2223 	    signum < SIGTHR + 4 && td->td_proc->p_leader == p->p_leader)
2224 		return (0);
2225 
2226 	return (cr_cansignal(td->td_ucred, p, signum));
2227 }
2228 
2229 /*-
2230  * Determine whether td may reschedule p.
2231  * Returns: 0 for permitted, an errno value otherwise
2232  * Locks: Sufficient locks to protect various components of td and p
2233  *        must be held.  td must be curthread, and a lock must
2234  *        be held for p.
2235  * References: td and p must be valid for the lifetime of the call
2236  */
2237 int
2238 p_cansched(struct thread *td, struct proc *p)
2239 {
2240 	int error;
2241 
2242 	KASSERT(td == curthread, ("%s: td not curthread", __func__));
2243 	PROC_LOCK_ASSERT(p, MA_OWNED);
2244 	if (td->td_proc == p)
2245 		return (0);
2246 	if ((error = prison_check(td->td_ucred, p->p_ucred)))
2247 		return (error);
2248 #ifdef MAC
2249 	if ((error = mac_proc_check_sched(td->td_ucred, p)))
2250 		return (error);
2251 #endif
2252 	if ((error = cr_bsd_visible(td->td_ucred, p->p_ucred)))
2253 		return (error);
2254 
2255 	if (td->td_ucred->cr_ruid != p->p_ucred->cr_ruid &&
2256 	    td->td_ucred->cr_uid != p->p_ucred->cr_ruid) {
2257 		error = priv_check(td, PRIV_SCHED_DIFFCRED);
2258 		if (error)
2259 			return (error);
2260 	}
2261 
2262 	error = cr_can_tamper_with_subjail(td->td_ucred, p->p_ucred,
2263 	    PRIV_SCHED_DIFFJAIL);
2264 	if (error)
2265 		return (error);
2266 
2267 	return (0);
2268 }
2269 
2270 /*
2271  * Handle getting or setting the prison's unprivileged_proc_debug
2272  * value.
2273  */
2274 static int
2275 sysctl_unprivileged_proc_debug(SYSCTL_HANDLER_ARGS)
2276 {
2277 	int error, val;
2278 
2279 	val = prison_allow(req->td->td_ucred, PR_ALLOW_UNPRIV_DEBUG);
2280 	error = sysctl_handle_int(oidp, &val, 0, req);
2281 	if (error != 0 || req->newptr == NULL)
2282 		return (error);
2283 	if (val != 0 && val != 1)
2284 		return (EINVAL);
2285 	prison_set_allow(req->td->td_ucred, PR_ALLOW_UNPRIV_DEBUG, val);
2286 	return (0);
2287 }
2288 
2289 /*
2290  * The 'unprivileged_proc_debug' flag may be used to disable a variety of
2291  * unprivileged inter-process debugging services, including some procfs
2292  * functionality, ptrace(), and ktrace().  In the past, inter-process
2293  * debugging has been involved in a variety of security problems, and sites
2294  * not requiring the service might choose to disable it when hardening
2295  * systems.
2296  */
2297 SYSCTL_PROC(_security_bsd, OID_AUTO, unprivileged_proc_debug,
2298     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_PRISON | CTLFLAG_SECURE |
2299     CTLFLAG_MPSAFE, 0, 0, sysctl_unprivileged_proc_debug, "I",
2300     "Unprivileged processes may use process debugging facilities");
2301 
2302 /*
2303  * Return true if the object owner/group ids are subset of the active
2304  * credentials.
2305  */
2306 bool
2307 cr_xids_subset(struct ucred *active_cred, struct ucred *obj_cred)
2308 {
2309 	int i;
2310 	bool grpsubset, uidsubset;
2311 
2312 	/*
2313 	 * Is p's group set a subset of td's effective group set?  This
2314 	 * includes p's egid, group access list, rgid, and svgid.
2315 	 */
2316 	grpsubset = true;
2317 	for (i = 0; i < obj_cred->cr_ngroups; i++) {
2318 		if (!groupmember(obj_cred->cr_groups[i], active_cred)) {
2319 			grpsubset = false;
2320 			break;
2321 		}
2322 	}
2323 	grpsubset = grpsubset &&
2324 	    groupmember(obj_cred->cr_gid, active_cred) &&
2325 	    groupmember(obj_cred->cr_rgid, active_cred) &&
2326 	    groupmember(obj_cred->cr_svgid, active_cred);
2327 
2328 	/*
2329 	 * Are the uids present in obj_cred's credential equal to
2330 	 * active_cred's effective uid?  This includes obj_cred's
2331 	 * euid, svuid, and ruid.
2332 	 */
2333 	uidsubset = (active_cred->cr_uid == obj_cred->cr_uid &&
2334 	    active_cred->cr_uid == obj_cred->cr_svuid &&
2335 	    active_cred->cr_uid == obj_cred->cr_ruid);
2336 
2337 	return (uidsubset && grpsubset);
2338 }
2339 
2340 /*
2341  * Determine whether the td thread allowed to do pdopenpid(2) on the
2342  * process p.  The permissions are scoped to the PIDs namespace and
2343  * processes hierarchy, and do not imply permissions to perform
2344  * operations on the resulting process descriptor, e.g. pdkill(2) and
2345  * other.
2346  */
2347 int
2348 p_canopen(struct thread *td, struct proc *p)
2349 {
2350 #ifdef INVARIANTS
2351 	if (IN_CAPABILITY_MODE(td))
2352 		sx_assert(&proctree_lock, SX_LOCKED);
2353 #endif
2354 
2355 	/*
2356 	 * Allow implicit parent in cap mode: either real parent or
2357 	 * debugger can open pid.
2358 	 */
2359 	if (!IN_CAPABILITY_MODE(td) || (allow_ptrace_in_cap_mode &&
2360 	    (td->td_proc == p->p_pptr || p->p_oppid == td->td_proc->p_pid)))
2361 		return (0);
2362 	return (ECAPMODE);
2363 }
2364 
2365 /*-
2366  * Determine whether td may debug p.
2367  * Returns: 0 for permitted, an errno value otherwise
2368  * Locks: Sufficient locks to protect various components of td and p
2369  *        must be held.  td must be curthread, and a lock must
2370  *        be held for p.
2371  * References: td and p must be valid for the lifetime of the call
2372  */
2373 int
2374 p_candebug(struct thread *td, struct proc *p)
2375 {
2376 	int error;
2377 
2378 	KASSERT(td == curthread, ("%s: td not curthread", __func__));
2379 	PROC_LOCK_ASSERT(p, MA_OWNED);
2380 	if (td->td_proc == p)
2381 		return (0);
2382 	if ((error = priv_check(td, PRIV_DEBUG_UNPRIV)))
2383 		return (error);
2384 	if ((error = prison_check(td->td_ucred, p->p_ucred)))
2385 		return (error);
2386 #ifdef MAC
2387 	if ((error = mac_proc_check_debug(td->td_ucred, p)))
2388 		return (error);
2389 #endif
2390 	if ((error = cr_bsd_visible(td->td_ucred, p->p_ucred)))
2391 		return (error);
2392 
2393 	/*
2394 	 * If p's gids aren't a subset, or the uids aren't a subset,
2395 	 * or the credential has changed, require appropriate privilege
2396 	 * for td to debug p.
2397 	 */
2398 	if (!cr_xids_subset(td->td_ucred, p->p_ucred)) {
2399 		error = priv_check(td, PRIV_DEBUG_DIFFCRED);
2400 		if (error)
2401 			return (error);
2402 	}
2403 
2404 	/*
2405 	 * Has the credential of the process changed since the last exec()?
2406 	 */
2407 	if ((p->p_flag & P_SUGID) != 0) {
2408 		error = priv_check(td, PRIV_DEBUG_SUGID);
2409 		if (error)
2410 			return (error);
2411 	}
2412 
2413 	error = cr_can_tamper_with_subjail(td->td_ucred, p->p_ucred,
2414 	    PRIV_DEBUG_DIFFJAIL);
2415 	if (error)
2416 		return (error);
2417 
2418 	/* Can't trace init when securelevel > 0. */
2419 	if (p == initproc) {
2420 		error = securelevel_gt(td->td_ucred, 0);
2421 		if (error)
2422 			return (error);
2423 	}
2424 
2425 	/*
2426 	 * Can't trace a process that's currently exec'ing.  Otherwise
2427 	 * the process vmspace might change, and the target might be
2428 	 * loading a setugid image.  The execve_block(9) and
2429 	 * proc_vmspace_ref(9) allow to get the stable credentials and
2430 	 * vmspace reference.
2431 	 */
2432 	if ((p->p_flag & P_INEXEC) != 0)
2433 		return (EBUSY);
2434 
2435 	/* Denied explicitly */
2436 	if ((p->p_flag2 & P2_NOTRACE) != 0) {
2437 		error = priv_check(td, PRIV_DEBUG_DENIED);
2438 		if (error != 0)
2439 			return (error);
2440 	}
2441 
2442 	return (0);
2443 }
2444 
2445 /*-
2446  * Determine whether the subject represented by cred can "see" a socket.
2447  * Returns: 0 for permitted, ENOENT otherwise.
2448  */
2449 int
2450 cr_canseesocket(struct ucred *cred, struct socket *so)
2451 {
2452 	int error;
2453 
2454 	error = prison_check(cred, so->so_cred);
2455 	if (error)
2456 		return (ENOENT);
2457 #ifdef MAC
2458 	error = mac_socket_check_visible(cred, so);
2459 	if (error)
2460 		return (error);
2461 #endif
2462 	if (cr_bsd_visible(cred, so->so_cred))
2463 		return (ENOENT);
2464 
2465 	return (0);
2466 }
2467 
2468 /*-
2469  * Determine whether td can wait for the exit of p.
2470  * Returns: 0 for permitted, an errno value otherwise
2471  * Locks: Sufficient locks to protect various components of td and p
2472  *        must be held.  td must be curthread, and a lock must
2473  *        be held for p.
2474  * References: td and p must be valid for the lifetime of the call
2475 
2476  */
2477 int
2478 p_canwait(struct thread *td, struct proc *p)
2479 {
2480 	int error;
2481 
2482 	KASSERT(td == curthread, ("%s: td not curthread", __func__));
2483 	PROC_LOCK_ASSERT(p, MA_OWNED);
2484 	if ((error = prison_check(td->td_ucred, p->p_ucred)))
2485 		return (error);
2486 #ifdef MAC
2487 	if ((error = mac_proc_check_wait(td->td_ucred, p)))
2488 		return (error);
2489 #endif
2490 #if 0
2491 	/* XXXMAC: This could have odd effects on some shells. */
2492 	if ((error = cr_bsd_visible(td->td_ucred, p->p_ucred)))
2493 		return (error);
2494 #endif
2495 
2496 	return (0);
2497 }
2498 
2499 /*
2500  * Credential management.
2501  *
2502  * struct ucred objects are rarely allocated but gain and lose references all
2503  * the time (e.g., on struct file alloc/dealloc) turning refcount updates into
2504  * a significant source of cache-line ping ponging. Common cases are worked
2505  * around by modifying thread-local counter instead if the cred to operate on
2506  * matches td_realucred.
2507  *
2508  * The counter is split into 2 parts:
2509  * - cr_users -- total count of all struct proc and struct thread objects
2510  *   which have given cred in p_ucred and td_ucred respectively
2511  * - cr_ref -- the actual ref count, only valid if cr_users == 0
2512  *
2513  * If users == 0 then cr_ref behaves similarly to refcount(9), in particular if
2514  * the count reaches 0 the object is freeable.
2515  * If users > 0 and curthread->td_realucred == cred, then updates are performed
2516  * against td_ucredref.
2517  * In other cases updates are performed against cr_ref.
2518  *
2519  * Changing td_realucred into something else decrements cr_users and transfers
2520  * accumulated updates.
2521  */
2522 struct ucred *
2523 crcowget(struct ucred *cr)
2524 {
2525 
2526 	mtx_lock(&cr->cr_mtx);
2527 	KASSERT(cr->cr_users > 0, ("%s: users %d not > 0 on cred %p",
2528 	    __func__, cr->cr_users, cr));
2529 	cr->cr_users++;
2530 	cr->cr_ref++;
2531 	mtx_unlock(&cr->cr_mtx);
2532 	return (cr);
2533 }
2534 
2535 static struct ucred *
2536 crunuse(struct thread *td)
2537 {
2538 	struct ucred *cr, *crold;
2539 
2540 	MPASS(td->td_realucred == td->td_ucred);
2541 	cr = td->td_realucred;
2542 	mtx_lock(&cr->cr_mtx);
2543 	cr->cr_ref += td->td_ucredref;
2544 	td->td_ucredref = 0;
2545 	KASSERT(cr->cr_users > 0, ("%s: users %d not > 0 on cred %p",
2546 	    __func__, cr->cr_users, cr));
2547 	cr->cr_users--;
2548 	if (cr->cr_users == 0) {
2549 		KASSERT(cr->cr_ref > 0, ("%s: ref %ld not > 0 on cred %p",
2550 		    __func__, cr->cr_ref, cr));
2551 		crold = cr;
2552 	} else {
2553 		cr->cr_ref--;
2554 		crold = NULL;
2555 	}
2556 	mtx_unlock(&cr->cr_mtx);
2557 	td->td_realucred = NULL;
2558 	return (crold);
2559 }
2560 
2561 static void
2562 crunusebatch(struct ucred *cr, u_int users, long ref)
2563 {
2564 
2565 	KASSERT(users > 0, ("%s: passed users %d not > 0 ; cred %p",
2566 	    __func__, users, cr));
2567 	mtx_lock(&cr->cr_mtx);
2568 	KASSERT(cr->cr_users >= users, ("%s: users %d not > %d on cred %p",
2569 	    __func__, cr->cr_users, users, cr));
2570 	cr->cr_users -= users;
2571 	cr->cr_ref += ref;
2572 	cr->cr_ref -= users;
2573 	if (cr->cr_users > 0) {
2574 		mtx_unlock(&cr->cr_mtx);
2575 		return;
2576 	}
2577 	KASSERT(cr->cr_ref >= 0, ("%s: ref %ld not >= 0 on cred %p",
2578 	    __func__, cr->cr_ref, cr));
2579 	if (cr->cr_ref > 0) {
2580 		mtx_unlock(&cr->cr_mtx);
2581 		return;
2582 	}
2583 	crfree_final(cr);
2584 }
2585 
2586 void
2587 crcowfree(struct thread *td)
2588 {
2589 	struct ucred *cr;
2590 
2591 	cr = crunuse(td);
2592 	if (cr != NULL)
2593 		crfree(cr);
2594 }
2595 
2596 struct ucred *
2597 crcowsync(void)
2598 {
2599 	struct thread *td;
2600 	struct proc *p;
2601 	struct ucred *crnew, *crold;
2602 
2603 	td = curthread;
2604 	p = td->td_proc;
2605 	PROC_LOCK_ASSERT(p, MA_OWNED);
2606 
2607 	MPASS(td->td_realucred == td->td_ucred);
2608 	if (td->td_realucred == p->p_ucred)
2609 		return (NULL);
2610 
2611 	crnew = crcowget(p->p_ucred);
2612 	crold = crunuse(td);
2613 	td->td_realucred = crnew;
2614 	td->td_ucred = td->td_realucred;
2615 	return (crold);
2616 }
2617 
2618 /*
2619  * Batching.
2620  */
2621 void
2622 credbatch_add(struct credbatch *crb, struct thread *td)
2623 {
2624 	struct ucred *cr;
2625 
2626 	MPASS(td->td_realucred != NULL);
2627 	MPASS(td->td_realucred == td->td_ucred);
2628 	MPASS(TD_GET_STATE(td) == TDS_INACTIVE);
2629 	cr = td->td_realucred;
2630 	KASSERT(cr->cr_users > 0, ("%s: users %d not > 0 on cred %p",
2631 	    __func__, cr->cr_users, cr));
2632 	if (crb->cred != cr) {
2633 		if (crb->users > 0) {
2634 			MPASS(crb->cred != NULL);
2635 			crunusebatch(crb->cred, crb->users, crb->ref);
2636 			crb->users = 0;
2637 			crb->ref = 0;
2638 		}
2639 	}
2640 	crb->cred = cr;
2641 	crb->users++;
2642 	crb->ref += td->td_ucredref;
2643 	td->td_ucredref = 0;
2644 	td->td_realucred = NULL;
2645 }
2646 
2647 void
2648 credbatch_final(struct credbatch *crb)
2649 {
2650 
2651 	MPASS(crb->cred != NULL);
2652 	MPASS(crb->users > 0);
2653 	crunusebatch(crb->cred, crb->users, crb->ref);
2654 }
2655 
2656 /*
2657  * Allocate a zeroed cred structure.
2658  */
2659 struct ucred *
2660 crget(void)
2661 {
2662 	struct ucred *cr;
2663 
2664 	cr = malloc(sizeof(*cr), M_CRED, M_WAITOK | M_ZERO);
2665 	mtx_init(&cr->cr_mtx, "cred", NULL, MTX_DEF);
2666 	cr->cr_ref = 1;
2667 #ifdef AUDIT
2668 	audit_cred_init(cr);
2669 #endif
2670 #ifdef MAC
2671 	mac_cred_init(cr);
2672 #endif
2673 	cr->cr_groups = cr->cr_smallgroups;
2674 	cr->cr_agroups = nitems(cr->cr_smallgroups);
2675 	return (cr);
2676 }
2677 
2678 /*
2679  * Claim another reference to a ucred structure.
2680  */
2681 struct ucred *
2682 crhold(struct ucred *cr)
2683 {
2684 	struct thread *td;
2685 
2686 	td = curthread;
2687 	if (__predict_true(td->td_realucred == cr)) {
2688 		KASSERT(cr->cr_users > 0, ("%s: users %d not > 0 on cred %p",
2689 		    __func__, cr->cr_users, cr));
2690 		td->td_ucredref++;
2691 		return (cr);
2692 	}
2693 	mtx_lock(&cr->cr_mtx);
2694 	cr->cr_ref++;
2695 	mtx_unlock(&cr->cr_mtx);
2696 	return (cr);
2697 }
2698 
2699 /*
2700  * Free a cred structure.  Throws away space when ref count gets to 0.
2701  */
2702 void
2703 crfree(struct ucred *cr)
2704 {
2705 	struct thread *td;
2706 
2707 	td = curthread;
2708 	if (__predict_true(td->td_realucred == cr)) {
2709 		KASSERT(cr->cr_users > 0, ("%s: users %d not > 0 on cred %p",
2710 		    __func__, cr->cr_users, cr));
2711 		td->td_ucredref--;
2712 		return;
2713 	}
2714 	mtx_lock(&cr->cr_mtx);
2715 	KASSERT(cr->cr_users >= 0, ("%s: users %d not >= 0 on cred %p",
2716 	    __func__, cr->cr_users, cr));
2717 	cr->cr_ref--;
2718 	if (cr->cr_users > 0) {
2719 		mtx_unlock(&cr->cr_mtx);
2720 		return;
2721 	}
2722 	KASSERT(cr->cr_ref >= 0, ("%s: ref %ld not >= 0 on cred %p",
2723 	    __func__, cr->cr_ref, cr));
2724 	if (cr->cr_ref > 0) {
2725 		mtx_unlock(&cr->cr_mtx);
2726 		return;
2727 	}
2728 	crfree_final(cr);
2729 }
2730 
2731 static void
2732 crfree_final(struct ucred *cr)
2733 {
2734 
2735 	KASSERT(cr->cr_users == 0, ("%s: users %d not == 0 on cred %p",
2736 	    __func__, cr->cr_users, cr));
2737 	KASSERT(cr->cr_ref == 0, ("%s: ref %ld not == 0 on cred %p",
2738 	    __func__, cr->cr_ref, cr));
2739 
2740 	/*
2741 	 * Some callers of crget(), such as nfs_statfs(), allocate a temporary
2742 	 * credential, but don't allocate a uidinfo structure.
2743 	 */
2744 	if (cr->cr_uidinfo != NULL)
2745 		uifree(cr->cr_uidinfo);
2746 	if (cr->cr_ruidinfo != NULL)
2747 		uifree(cr->cr_ruidinfo);
2748 	if (cr->cr_prison != NULL)
2749 		prison_free(cr->cr_prison);
2750 	if (cr->cr_loginclass != NULL)
2751 		loginclass_free(cr->cr_loginclass);
2752 #ifdef AUDIT
2753 	audit_cred_destroy(cr);
2754 #endif
2755 #ifdef MAC
2756 	mac_cred_destroy(cr);
2757 #endif
2758 	mtx_destroy(&cr->cr_mtx);
2759 	if (cr->cr_groups != cr->cr_smallgroups)
2760 		free(cr->cr_groups, M_CRED);
2761 	free(cr, M_CRED);
2762 }
2763 
2764 /*
2765  * Copy a ucred's contents from a template.  Does not block.
2766  */
2767 void
2768 crcopy(struct ucred *dest, struct ucred *src)
2769 {
2770 
2771 	bcopy(&src->cr_startcopy, &dest->cr_startcopy,
2772 	    (unsigned)((caddr_t)&src->cr_endcopy -
2773 		(caddr_t)&src->cr_startcopy));
2774 	dest->cr_flags = src->cr_flags;
2775 	crsetgroups(dest, src->cr_ngroups, src->cr_groups);
2776 	uihold(dest->cr_uidinfo);
2777 	uihold(dest->cr_ruidinfo);
2778 	prison_hold(dest->cr_prison);
2779 	loginclass_hold(dest->cr_loginclass);
2780 #ifdef AUDIT
2781 	audit_cred_copy(src, dest);
2782 #endif
2783 #ifdef MAC
2784 	mac_cred_copy(src, dest);
2785 #endif
2786 }
2787 
2788 /*
2789  * Dup cred struct to a new held one.
2790  */
2791 struct ucred *
2792 crdup(struct ucred *cr)
2793 {
2794 	struct ucred *newcr;
2795 
2796 	newcr = crget();
2797 	crcopy(newcr, cr);
2798 	return (newcr);
2799 }
2800 
2801 /*
2802  * Fill in a struct xucred based on a struct ucred.
2803  */
2804 void
2805 cru2x(struct ucred *cr, struct xucred *xcr)
2806 {
2807 	int ngroups;
2808 
2809 	bzero(xcr, sizeof(*xcr));
2810 	xcr->cr_version = XUCRED_VERSION;
2811 	xcr->cr_uid = cr->cr_uid;
2812 	xcr->cr_gid = cr->cr_gid;
2813 
2814 	/*
2815 	 * We use a union to alias cr_gid to cr_groups[0] in the xucred, so
2816 	 * this is kind of ugly; cr_ngroups still includes the egid for our
2817 	 * purposes to avoid bumping the xucred version.
2818 	 */
2819 	ngroups = MIN(cr->cr_ngroups + 1, nitems(xcr->cr_groups));
2820 	xcr->cr_ngroups = ngroups;
2821 	bcopy(cr->cr_groups, xcr->cr_sgroups,
2822 	    (ngroups - 1) * sizeof(*cr->cr_groups));
2823 }
2824 
2825 void
2826 cru2xt(struct thread *td, struct xucred *xcr)
2827 {
2828 
2829 	cru2x(td->td_ucred, xcr);
2830 	xcr->cr_pid = td->td_proc->p_pid;
2831 }
2832 
2833 /*
2834  * Change process credentials.
2835  *
2836  * Callers are responsible for providing the reference for passed credentials
2837  * and for freeing old ones.  Calls chgproccnt() to correctly account the
2838  * current process to the proper real UID, if the latter has changed.  Returns
2839  * whether the operation was successful.  Failure can happen only on
2840  * 'enforce_proc_lim' being true and if no new process can be accounted to the
2841  * new real UID because of the current limit (see the inner comment for more
2842  * details) and the caller does not have privilege (PRIV_PROC_LIMIT) to override
2843  * that.  In this case, the reference to 'newcred' is not taken over.
2844  */
2845 static bool
2846 _proc_set_cred(struct proc *p, struct ucred *newcred, bool enforce_proc_lim)
2847 {
2848 	struct ucred *const oldcred = p->p_ucred;
2849 
2850 	MPASS(oldcred != NULL);
2851 	PROC_LOCK_ASSERT(p, MA_OWNED);
2852 
2853 	if (newcred->cr_ruidinfo != oldcred->cr_ruidinfo) {
2854 		/*
2855 		 * XXXOC: This check is flawed but nonetheless the best we can
2856 		 * currently do as we don't really track limits per UID contrary
2857 		 * to what we pretend in setrlimit(2).  Until this is reworked,
2858 		 * we just check here that the number of processes for our new
2859 		 * real UID doesn't exceed this process' process number limit
2860 		 * (which is meant to be associated with the current real UID).
2861 		 */
2862 		const int proccnt_changed = chgproccnt(newcred->cr_ruidinfo, 1,
2863 		    enforce_proc_lim ? lim_cur_proc(p, RLIMIT_NPROC) : 0);
2864 
2865 		if (!proccnt_changed) {
2866 			if (priv_check_cred(oldcred, PRIV_PROC_LIMIT) != 0)
2867 				return (false);
2868 			(void)chgproccnt(newcred->cr_ruidinfo, 1, 0);
2869 		}
2870 	}
2871 
2872 	mtx_lock(&oldcred->cr_mtx);
2873 	KASSERT(oldcred->cr_users > 0, ("%s: users %d not > 0 on cred %p",
2874 	    __func__, oldcred->cr_users, oldcred));
2875 	oldcred->cr_users--;
2876 	mtx_unlock(&oldcred->cr_mtx);
2877 	mtx_lock(&newcred->cr_mtx);
2878 	newcred->cr_users++;
2879 	mtx_unlock(&newcred->cr_mtx);
2880 	p->p_ucred = newcred;
2881 	PROC_UPDATE_COW(p);
2882 	if (newcred->cr_ruidinfo != oldcred->cr_ruidinfo)
2883 		(void)chgproccnt(oldcred->cr_ruidinfo, -1, 0);
2884 	return (true);
2885 }
2886 
2887 void
2888 proc_set_cred(struct proc *p, struct ucred *newcred)
2889 {
2890 	bool success __diagused = _proc_set_cred(p, newcred, false);
2891 
2892 	MPASS(success);
2893 }
2894 
2895 bool
2896 proc_set_cred_enforce_proc_lim(struct proc *p, struct ucred *newcred)
2897 {
2898 	return (_proc_set_cred(p, newcred, true));
2899 }
2900 
2901 void
2902 proc_unset_cred(struct proc *p, bool decrement_proc_count)
2903 {
2904 	struct ucred *cr;
2905 
2906 	MPASS(p->p_state == PRS_ZOMBIE || p->p_state == PRS_NEW);
2907 	cr = p->p_ucred;
2908 	p->p_ucred = NULL;
2909 	KASSERT(cr->cr_users > 0, ("%s: users %d not > 0 on cred %p",
2910 	    __func__, cr->cr_users, cr));
2911 	mtx_lock(&cr->cr_mtx);
2912 	cr->cr_users--;
2913 	if (cr->cr_users == 0)
2914 		KASSERT(cr->cr_ref > 0, ("%s: ref %ld not > 0 on cred %p",
2915 		    __func__, cr->cr_ref, cr));
2916 	mtx_unlock(&cr->cr_mtx);
2917 	if (decrement_proc_count)
2918 		(void)chgproccnt(cr->cr_ruidinfo, -1, 0);
2919 	crfree(cr);
2920 }
2921 
2922 struct ucred *
2923 crcopysafe(struct proc *p, struct ucred *cr)
2924 {
2925 	struct ucred *oldcred;
2926 	int groups;
2927 
2928 	PROC_LOCK_ASSERT(p, MA_OWNED);
2929 
2930 	oldcred = p->p_ucred;
2931 	while (cr->cr_agroups < oldcred->cr_ngroups) {
2932 		groups = oldcred->cr_ngroups;
2933 		PROC_UNLOCK(p);
2934 		crextend(cr, groups);
2935 		PROC_LOCK(p);
2936 		oldcred = p->p_ucred;
2937 	}
2938 	crcopy(cr, oldcred);
2939 
2940 	return (oldcred);
2941 }
2942 
2943 /*
2944  * Extend the passed-in credentials to hold n groups.
2945  *
2946  * Must not be called after groups have been set.
2947  */
2948 void
2949 crextend(struct ucred *cr, int n)
2950 {
2951 	size_t nbytes;
2952 
2953 	MPASS2(cr->cr_ref == 1, "'cr_ref' must be 1 (referenced, unshared)");
2954 	MPASS2((cr->cr_flags & CRED_FLAG_GROUPSET) == 0,
2955 	    "groups on 'cr' already set!");
2956 	groups_check_positive_len(n);
2957 	groups_check_max_len(n);
2958 
2959 	if (n <= cr->cr_agroups)
2960 		return;
2961 
2962 	nbytes = n * sizeof(gid_t);
2963 	if (nbytes < n)
2964 		panic("Too many groups (memory size overflow)! "
2965 		    "Computation of 'kern.ngroups' should have prevented this, "
2966 		    "please fix it. In the meantime, reduce 'kern.ngroups'.");
2967 
2968 	/*
2969 	 * We allocate a power of 2 larger than 'nbytes', except when that
2970 	 * exceeds PAGE_SIZE, in which case we allocate the right multiple of
2971 	 * pages.  We assume PAGE_SIZE is a power of 2 (the call to roundup2()
2972 	 * below) but do not need to for sizeof(gid_t).
2973 	 */
2974 	if (nbytes < PAGE_SIZE) {
2975 		if (!powerof2(nbytes))
2976 			/* fls*() return a bit index starting at 1. */
2977 			nbytes = 1 << flsl(nbytes);
2978 	} else
2979 		nbytes = roundup2(nbytes, PAGE_SIZE);
2980 
2981 	/* Free the old array. */
2982 	if (cr->cr_groups != cr->cr_smallgroups)
2983 		free(cr->cr_groups, M_CRED);
2984 
2985 	cr->cr_groups = malloc(nbytes, M_CRED, M_WAITOK | M_ZERO);
2986 	cr->cr_agroups = nbytes / sizeof(gid_t);
2987 }
2988 
2989 /*
2990  * Normalizes a set of groups to be applied to a 'struct ucred'.
2991  *
2992  * Normalization ensures that the supplementary groups are sorted in ascending
2993  * order and do not contain duplicates.  This allows group_is_supplementary() to
2994  * do a binary search.
2995  */
2996 static void
2997 groups_normalize(int *ngrp, gid_t *groups)
2998 {
2999 	gid_t prev_g;
3000 	int ins_idx;
3001 
3002 	groups_check_positive_len(*ngrp);
3003 	groups_check_max_len(*ngrp);
3004 
3005 	if (*ngrp <= 1)
3006 		return;
3007 
3008 	qsort(groups, *ngrp, sizeof(*groups), gidp_cmp);
3009 
3010 	/* Remove duplicates. */
3011 	prev_g = groups[0];
3012 	ins_idx = 1;
3013 	for (int i = ins_idx; i < *ngrp; ++i) {
3014 		const gid_t g = groups[i];
3015 
3016 		if (g != prev_g) {
3017 			if (i != ins_idx)
3018 				groups[ins_idx] = g;
3019 			++ins_idx;
3020 			prev_g = g;
3021 		}
3022 	}
3023 	*ngrp = ins_idx;
3024 
3025 	groups_check_normalized(*ngrp, groups);
3026 }
3027 
3028 /*
3029  * Internal function copying groups into a credential.
3030  *
3031  * 'ngrp' must be strictly positive.  Either the passed 'groups' array must have
3032  * been normalized in advance (see groups_normalize()), else it must be so
3033  * before the structure is to be used again.
3034  *
3035  * This function is suitable to be used under any lock (it doesn't take any lock
3036  * itself nor sleep, and in particular doesn't allocate memory).  crextend()
3037  * must have been called beforehand to ensure sufficient space is available.
3038  * See also crsetgroups(), which handles that.
3039  */
3040 static void
3041 crsetgroups_internal(struct ucred *cr, int ngrp, const gid_t *groups)
3042 {
3043 
3044 	MPASS2(cr->cr_ref == 1, "'cr_ref' must be 1 (referenced, unshared)");
3045 	MPASS2(cr->cr_agroups >= ngrp, "'cr_agroups' too small");
3046 	groups_check_positive_len(ngrp);
3047 
3048 	bcopy(groups, cr->cr_groups, ngrp * sizeof(gid_t));
3049 	cr->cr_ngroups = ngrp;
3050 	cr->cr_flags |= CRED_FLAG_GROUPSET;
3051 }
3052 
3053 /*
3054  * Copy groups in to a credential after expanding it if required.
3055  *
3056  * May sleep in order to allocate memory (except if, e.g., crextend() was called
3057  * before with 'ngrp' or greater).  Truncates the list to 'ngroups_max' if
3058  * it is too large.  Array 'groups' doesn't need to be sorted.  'ngrp' must be
3059  * positive.
3060  */
3061 void
3062 crsetgroups(struct ucred *cr, int ngrp, const gid_t *groups)
3063 {
3064 
3065 	if (ngrp > ngroups_max)
3066 		ngrp = ngroups_max;
3067 	cr->cr_ngroups = 0;
3068 	if (ngrp == 0) {
3069 		cr->cr_flags |= CRED_FLAG_GROUPSET;
3070 		return;
3071 	}
3072 
3073 	/*
3074 	 * crextend() asserts that groups are not set, as it may allocate a new
3075 	 * backing storage without copying the content of the old one.  Since we
3076 	 * are going to install a completely new set anyway, signal that we
3077 	 * consider the old ones thrown away.
3078 	 */
3079 	cr->cr_flags &= ~CRED_FLAG_GROUPSET;
3080 
3081 	crextend(cr, ngrp);
3082 	crsetgroups_internal(cr, ngrp, groups);
3083 	groups_normalize(&cr->cr_ngroups, cr->cr_groups);
3084 }
3085 
3086 /*
3087  * Same as crsetgroups() but sets the effective GID as well.
3088  *
3089  * This function ensures that an effective GID is always present in credentials.
3090  * An empty array will only set the effective GID to 'default_egid', while
3091  * a non-empty array will peel off groups[0] to set as the effective GID and use
3092  * the remainder, if any, as supplementary groups.
3093  */
3094 void
3095 crsetgroups_and_egid(struct ucred *cr, int ngrp, const gid_t *groups,
3096     const gid_t default_egid)
3097 {
3098 	if (ngrp == 0) {
3099 		cr->cr_gid = default_egid;
3100 		cr->cr_ngroups = 0;
3101 		cr->cr_flags |= CRED_FLAG_GROUPSET;
3102 		return;
3103 	}
3104 
3105 	crsetgroups(cr, ngrp - 1, groups + 1);
3106 	cr->cr_gid = groups[0];
3107 }
3108 
3109 /*
3110  * Get login name, if available.
3111  */
3112 #ifndef _SYS_SYSPROTO_H_
3113 struct getlogin_args {
3114 	char	*namebuf;
3115 	u_int	namelen;
3116 };
3117 #endif
3118 /* ARGSUSED */
3119 int
3120 sys_getlogin(struct thread *td, struct getlogin_args *uap)
3121 {
3122 	char login[MAXLOGNAME];
3123 	struct proc *p = td->td_proc;
3124 	size_t len;
3125 
3126 	if (uap->namelen > MAXLOGNAME)
3127 		uap->namelen = MAXLOGNAME;
3128 	PROC_LOCK(p);
3129 	SESS_LOCK(p->p_session);
3130 	len = strlcpy(login, p->p_session->s_login, uap->namelen) + 1;
3131 	SESS_UNLOCK(p->p_session);
3132 	PROC_UNLOCK(p);
3133 	if (len > uap->namelen)
3134 		return (ERANGE);
3135 	return (copyout(login, uap->namebuf, len));
3136 }
3137 
3138 /*
3139  * Set login name.
3140  */
3141 #ifndef _SYS_SYSPROTO_H_
3142 struct setlogin_args {
3143 	char	*namebuf;
3144 };
3145 #endif
3146 /* ARGSUSED */
3147 int
3148 sys_setlogin(struct thread *td, struct setlogin_args *uap)
3149 {
3150 	struct proc *p = td->td_proc;
3151 	int error;
3152 	char logintmp[MAXLOGNAME];
3153 
3154 	CTASSERT(sizeof(p->p_session->s_login) >= sizeof(logintmp));
3155 
3156 	error = priv_check(td, PRIV_PROC_SETLOGIN);
3157 	if (error)
3158 		return (error);
3159 	error = copyinstr(uap->namebuf, logintmp, sizeof(logintmp), NULL);
3160 	if (error != 0) {
3161 		if (error == ENAMETOOLONG)
3162 			error = EINVAL;
3163 		return (error);
3164 	}
3165 	AUDIT_ARG_LOGIN(logintmp);
3166 	PROC_LOCK(p);
3167 	SESS_LOCK(p->p_session);
3168 	strcpy(p->p_session->s_login, logintmp);
3169 	SESS_UNLOCK(p->p_session);
3170 	PROC_UNLOCK(p);
3171 	return (0);
3172 }
3173 
3174 void
3175 setsugid(struct proc *p)
3176 {
3177 
3178 	PROC_LOCK_ASSERT(p, MA_OWNED);
3179 	p->p_flag |= P_SUGID;
3180 }
3181 
3182 /*-
3183  * Change a process's effective uid.
3184  * Side effects: newcred->cr_uid and newcred->cr_uidinfo will be modified.
3185  * References: newcred must be an exclusive credential reference for the
3186  *             duration of the call.
3187  */
3188 void
3189 change_euid(struct ucred *newcred, struct uidinfo *euip)
3190 {
3191 
3192 	newcred->cr_uid = euip->ui_uid;
3193 	uihold(euip);
3194 	uifree(newcred->cr_uidinfo);
3195 	newcred->cr_uidinfo = euip;
3196 }
3197 
3198 /*-
3199  * Change a process's effective gid.
3200  * Side effects: newcred->cr_gid will be modified.
3201  * References: newcred must be an exclusive credential reference for the
3202  *             duration of the call.
3203  */
3204 void
3205 change_egid(struct ucred *newcred, gid_t egid)
3206 {
3207 
3208 	newcred->cr_gid = egid;
3209 }
3210 
3211 /*-
3212  * Change a process's real uid.
3213  * Side effects: newcred->cr_ruid will be updated, newcred->cr_ruidinfo
3214  *               will be updated.
3215  * References: newcred must be an exclusive credential reference for the
3216  *             duration of the call.
3217  */
3218 void
3219 change_ruid(struct ucred *newcred, struct uidinfo *ruip)
3220 {
3221 
3222 	newcred->cr_ruid = ruip->ui_uid;
3223 	uihold(ruip);
3224 	uifree(newcred->cr_ruidinfo);
3225 	newcred->cr_ruidinfo = ruip;
3226 }
3227 
3228 /*-
3229  * Change a process's real gid.
3230  * Side effects: newcred->cr_rgid will be updated.
3231  * References: newcred must be an exclusive credential reference for the
3232  *             duration of the call.
3233  */
3234 void
3235 change_rgid(struct ucred *newcred, gid_t rgid)
3236 {
3237 
3238 	newcred->cr_rgid = rgid;
3239 }
3240 
3241 /*-
3242  * Change a process's saved uid.
3243  * Side effects: newcred->cr_svuid will be updated.
3244  * References: newcred must be an exclusive credential reference for the
3245  *             duration of the call.
3246  */
3247 void
3248 change_svuid(struct ucred *newcred, uid_t svuid)
3249 {
3250 
3251 	newcred->cr_svuid = svuid;
3252 }
3253 
3254 /*-
3255  * Change a process's saved gid.
3256  * Side effects: newcred->cr_svgid will be updated.
3257  * References: newcred must be an exclusive credential reference for the
3258  *             duration of the call.
3259  */
3260 void
3261 change_svgid(struct ucred *newcred, gid_t svgid)
3262 {
3263 
3264 	newcred->cr_svgid = svgid;
3265 }
3266 
3267 bool allow_ptrace = true;
3268 SYSCTL_BOOL(_security_bsd, OID_AUTO, allow_ptrace, CTLFLAG_RWTUN,
3269     &allow_ptrace, 0,
3270     "Deny ptrace(2) use by returning ENOSYS");
3271