xref: /freebsd/sys/kern/kern_prot.c (revision 911f0260390e18cf85f3dbf2c719b593efdc1e3c)
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  *
10  * All or some portions of this file are derived from material licensed
11  * to the University of California by American Telephone and Telegraph
12  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
13  * the permission of UNIX System Laboratories, Inc.
14  *
15  * Redistribution and use in source and binary forms, with or without
16  * modification, are permitted provided that the following conditions
17  * are met:
18  * 1. Redistributions of source code must retain the above copyright
19  *    notice, this list of conditions and the following disclaimer.
20  * 2. Redistributions in binary form must reproduce the above copyright
21  *    notice, this list of conditions and the following disclaimer in the
22  *    documentation and/or other materials provided with the distribution.
23  * 3. Neither the name of the University nor the names of its contributors
24  *    may be used to endorse or promote products derived from this software
25  *    without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37  * SUCH DAMAGE.
38  *
39  *	@(#)kern_prot.c	8.6 (Berkeley) 1/21/94
40  */
41 
42 /*
43  * System calls related to processes and protection
44  */
45 
46 #include <sys/cdefs.h>
47 __FBSDID("$FreeBSD$");
48 
49 #include "opt_inet.h"
50 #include "opt_inet6.h"
51 
52 #include <sys/param.h>
53 #include <sys/systm.h>
54 #include <sys/acct.h>
55 #include <sys/kdb.h>
56 #include <sys/kernel.h>
57 #include <sys/lock.h>
58 #include <sys/loginclass.h>
59 #include <sys/malloc.h>
60 #include <sys/mutex.h>
61 #include <sys/ptrace.h>
62 #include <sys/refcount.h>
63 #include <sys/sx.h>
64 #include <sys/priv.h>
65 #include <sys/proc.h>
66 #ifdef COMPAT_43
67 #include <sys/sysent.h>
68 #endif
69 #include <sys/sysproto.h>
70 #include <sys/jail.h>
71 #include <sys/racct.h>
72 #include <sys/rctl.h>
73 #include <sys/resourcevar.h>
74 #include <sys/socket.h>
75 #include <sys/socketvar.h>
76 #include <sys/syscallsubr.h>
77 #include <sys/sysctl.h>
78 
79 #ifdef REGRESSION
80 FEATURE(regression,
81     "Kernel support for interfaces necessary for regression testing (SECURITY RISK!)");
82 #endif
83 
84 #include <security/audit/audit.h>
85 #include <security/mac/mac_framework.h>
86 
87 static MALLOC_DEFINE(M_CRED, "cred", "credentials");
88 
89 SYSCTL_NODE(_security, OID_AUTO, bsd, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
90     "BSD security policy");
91 
92 static void crfree_final(struct ucred *cr);
93 static void crsetgroups_locked(struct ucred *cr, int ngrp,
94     gid_t *groups);
95 
96 #ifndef _SYS_SYSPROTO_H_
97 struct getpid_args {
98 	int	dummy;
99 };
100 #endif
101 /* ARGSUSED */
102 int
103 sys_getpid(struct thread *td, struct getpid_args *uap)
104 {
105 	struct proc *p = td->td_proc;
106 
107 	td->td_retval[0] = p->p_pid;
108 #if defined(COMPAT_43)
109 	if (SV_PROC_FLAG(p, SV_AOUT))
110 		td->td_retval[1] = kern_getppid(td);
111 #endif
112 	return (0);
113 }
114 
115 #ifndef _SYS_SYSPROTO_H_
116 struct getppid_args {
117         int     dummy;
118 };
119 #endif
120 /* ARGSUSED */
121 int
122 sys_getppid(struct thread *td, struct getppid_args *uap)
123 {
124 
125 	td->td_retval[0] = kern_getppid(td);
126 	return (0);
127 }
128 
129 int
130 kern_getppid(struct thread *td)
131 {
132 	struct proc *p = td->td_proc;
133 
134 	return (p->p_oppid);
135 }
136 
137 /*
138  * Get process group ID; note that POSIX getpgrp takes no parameter.
139  */
140 #ifndef _SYS_SYSPROTO_H_
141 struct getpgrp_args {
142         int     dummy;
143 };
144 #endif
145 int
146 sys_getpgrp(struct thread *td, struct getpgrp_args *uap)
147 {
148 	struct proc *p = td->td_proc;
149 
150 	PROC_LOCK(p);
151 	td->td_retval[0] = p->p_pgrp->pg_id;
152 	PROC_UNLOCK(p);
153 	return (0);
154 }
155 
156 /* Get an arbitrary pid's process group id */
157 #ifndef _SYS_SYSPROTO_H_
158 struct getpgid_args {
159 	pid_t	pid;
160 };
161 #endif
162 int
163 sys_getpgid(struct thread *td, struct getpgid_args *uap)
164 {
165 	struct proc *p;
166 	int error;
167 
168 	if (uap->pid == 0) {
169 		p = td->td_proc;
170 		PROC_LOCK(p);
171 	} else {
172 		p = pfind(uap->pid);
173 		if (p == NULL)
174 			return (ESRCH);
175 		error = p_cansee(td, p);
176 		if (error) {
177 			PROC_UNLOCK(p);
178 			return (error);
179 		}
180 	}
181 	td->td_retval[0] = p->p_pgrp->pg_id;
182 	PROC_UNLOCK(p);
183 	return (0);
184 }
185 
186 /*
187  * Get an arbitrary pid's session id.
188  */
189 #ifndef _SYS_SYSPROTO_H_
190 struct getsid_args {
191 	pid_t	pid;
192 };
193 #endif
194 int
195 sys_getsid(struct thread *td, struct getsid_args *uap)
196 {
197 
198 	return (kern_getsid(td, uap->pid));
199 }
200 
201 int
202 kern_getsid(struct thread *td, pid_t pid)
203 {
204 	struct proc *p;
205 	int error;
206 
207 	if (pid == 0) {
208 		p = td->td_proc;
209 		PROC_LOCK(p);
210 	} else {
211 		p = pfind(pid);
212 		if (p == NULL)
213 			return (ESRCH);
214 		error = p_cansee(td, p);
215 		if (error) {
216 			PROC_UNLOCK(p);
217 			return (error);
218 		}
219 	}
220 	td->td_retval[0] = p->p_session->s_sid;
221 	PROC_UNLOCK(p);
222 	return (0);
223 }
224 
225 #ifndef _SYS_SYSPROTO_H_
226 struct getuid_args {
227         int     dummy;
228 };
229 #endif
230 /* ARGSUSED */
231 int
232 sys_getuid(struct thread *td, struct getuid_args *uap)
233 {
234 
235 	td->td_retval[0] = td->td_ucred->cr_ruid;
236 #if defined(COMPAT_43)
237 	td->td_retval[1] = td->td_ucred->cr_uid;
238 #endif
239 	return (0);
240 }
241 
242 #ifndef _SYS_SYSPROTO_H_
243 struct geteuid_args {
244         int     dummy;
245 };
246 #endif
247 /* ARGSUSED */
248 int
249 sys_geteuid(struct thread *td, struct geteuid_args *uap)
250 {
251 
252 	td->td_retval[0] = td->td_ucred->cr_uid;
253 	return (0);
254 }
255 
256 #ifndef _SYS_SYSPROTO_H_
257 struct getgid_args {
258         int     dummy;
259 };
260 #endif
261 /* ARGSUSED */
262 int
263 sys_getgid(struct thread *td, struct getgid_args *uap)
264 {
265 
266 	td->td_retval[0] = td->td_ucred->cr_rgid;
267 #if defined(COMPAT_43)
268 	td->td_retval[1] = td->td_ucred->cr_groups[0];
269 #endif
270 	return (0);
271 }
272 
273 /*
274  * Get effective group ID.  The "egid" is groups[0], and could be obtained
275  * via getgroups.  This syscall exists because it is somewhat painful to do
276  * correctly in a library function.
277  */
278 #ifndef _SYS_SYSPROTO_H_
279 struct getegid_args {
280         int     dummy;
281 };
282 #endif
283 /* ARGSUSED */
284 int
285 sys_getegid(struct thread *td, struct getegid_args *uap)
286 {
287 
288 	td->td_retval[0] = td->td_ucred->cr_groups[0];
289 	return (0);
290 }
291 
292 #ifndef _SYS_SYSPROTO_H_
293 struct getgroups_args {
294 	int	gidsetsize;
295 	gid_t	*gidset;
296 };
297 #endif
298 int
299 sys_getgroups(struct thread *td, struct getgroups_args *uap)
300 {
301 	struct ucred *cred;
302 	int ngrp, error;
303 
304 	cred = td->td_ucred;
305 	ngrp = cred->cr_ngroups;
306 
307 	if (uap->gidsetsize == 0) {
308 		error = 0;
309 		goto out;
310 	}
311 	if (uap->gidsetsize < ngrp)
312 		return (EINVAL);
313 
314 	error = copyout(cred->cr_groups, uap->gidset, ngrp * sizeof(gid_t));
315 out:
316 	td->td_retval[0] = ngrp;
317 	return (error);
318 }
319 
320 #ifndef _SYS_SYSPROTO_H_
321 struct setsid_args {
322         int     dummy;
323 };
324 #endif
325 /* ARGSUSED */
326 int
327 sys_setsid(struct thread *td, struct setsid_args *uap)
328 {
329 	struct pgrp *pgrp;
330 	int error;
331 	struct proc *p = td->td_proc;
332 	struct pgrp *newpgrp;
333 	struct session *newsess;
334 
335 	pgrp = NULL;
336 
337 	newpgrp = uma_zalloc(pgrp_zone, M_WAITOK);
338 	newsess = malloc(sizeof(struct session), M_SESSION, M_WAITOK | M_ZERO);
339 
340 again:
341 	error = 0;
342 	sx_xlock(&proctree_lock);
343 
344 	if (p->p_pgid == p->p_pid || (pgrp = pgfind(p->p_pid)) != NULL) {
345 		if (pgrp != NULL)
346 			PGRP_UNLOCK(pgrp);
347 		error = EPERM;
348 	} else {
349 		error = enterpgrp(p, p->p_pid, newpgrp, newsess);
350 		if (error == ERESTART) {
351 			sx_xunlock(&proctree_lock);
352 			goto again;
353 		}
354 		MPASS(error == 0);
355 		td->td_retval[0] = p->p_pid;
356 		newpgrp = NULL;
357 		newsess = NULL;
358 	}
359 
360 	sx_xunlock(&proctree_lock);
361 
362 	uma_zfree(pgrp_zone, newpgrp);
363 	free(newsess, M_SESSION);
364 
365 	return (error);
366 }
367 
368 /*
369  * set process group (setpgid/old setpgrp)
370  *
371  * caller does setpgid(targpid, targpgid)
372  *
373  * pid must be caller or child of caller (ESRCH)
374  * if a child
375  *	pid must be in same session (EPERM)
376  *	pid can't have done an exec (EACCES)
377  * if pgid != pid
378  * 	there must exist some pid in same session having pgid (EPERM)
379  * pid must not be session leader (EPERM)
380  */
381 #ifndef _SYS_SYSPROTO_H_
382 struct setpgid_args {
383 	int	pid;		/* target process id */
384 	int	pgid;		/* target pgrp id */
385 };
386 #endif
387 /* ARGSUSED */
388 int
389 sys_setpgid(struct thread *td, struct setpgid_args *uap)
390 {
391 	struct proc *curp = td->td_proc;
392 	struct proc *targp;	/* target process */
393 	struct pgrp *pgrp;	/* target pgrp */
394 	int error;
395 	struct pgrp *newpgrp;
396 
397 	if (uap->pgid < 0)
398 		return (EINVAL);
399 
400 	newpgrp = uma_zalloc(pgrp_zone, M_WAITOK);
401 
402 again:
403 	error = 0;
404 
405 	sx_xlock(&proctree_lock);
406 	if (uap->pid != 0 && uap->pid != curp->p_pid) {
407 		if ((targp = pfind(uap->pid)) == NULL) {
408 			error = ESRCH;
409 			goto done;
410 		}
411 		if (!inferior(targp)) {
412 			PROC_UNLOCK(targp);
413 			error = ESRCH;
414 			goto done;
415 		}
416 		if ((error = p_cansee(td, targp))) {
417 			PROC_UNLOCK(targp);
418 			goto done;
419 		}
420 		if (targp->p_pgrp == NULL ||
421 		    targp->p_session != curp->p_session) {
422 			PROC_UNLOCK(targp);
423 			error = EPERM;
424 			goto done;
425 		}
426 		if (targp->p_flag & P_EXEC) {
427 			PROC_UNLOCK(targp);
428 			error = EACCES;
429 			goto done;
430 		}
431 		PROC_UNLOCK(targp);
432 	} else
433 		targp = curp;
434 	if (SESS_LEADER(targp)) {
435 		error = EPERM;
436 		goto done;
437 	}
438 	if (uap->pgid == 0)
439 		uap->pgid = targp->p_pid;
440 	if ((pgrp = pgfind(uap->pgid)) == NULL) {
441 		if (uap->pgid == targp->p_pid) {
442 			error = enterpgrp(targp, uap->pgid, newpgrp,
443 			    NULL);
444 			if (error == 0)
445 				newpgrp = NULL;
446 		} else
447 			error = EPERM;
448 	} else {
449 		if (pgrp == targp->p_pgrp) {
450 			PGRP_UNLOCK(pgrp);
451 			goto done;
452 		}
453 		if (pgrp->pg_id != targp->p_pid &&
454 		    pgrp->pg_session != curp->p_session) {
455 			PGRP_UNLOCK(pgrp);
456 			error = EPERM;
457 			goto done;
458 		}
459 		PGRP_UNLOCK(pgrp);
460 		error = enterthispgrp(targp, pgrp);
461 	}
462 done:
463 	sx_xunlock(&proctree_lock);
464 	KASSERT((error == 0) || (newpgrp != NULL),
465 	    ("setpgid failed and newpgrp is NULL"));
466 	if (error == ERESTART)
467 		goto again;
468 	uma_zfree(pgrp_zone, newpgrp);
469 	return (error);
470 }
471 
472 /*
473  * Use the clause in B.4.2.2 that allows setuid/setgid to be 4.2/4.3BSD
474  * compatible.  It says that setting the uid/gid to euid/egid is a special
475  * case of "appropriate privilege".  Once the rules are expanded out, this
476  * basically means that setuid(nnn) sets all three id's, in all permitted
477  * cases unless _POSIX_SAVED_IDS is enabled.  In that case, setuid(getuid())
478  * does not set the saved id - this is dangerous for traditional BSD
479  * programs.  For this reason, we *really* do not want to set
480  * _POSIX_SAVED_IDS and do not want to clear POSIX_APPENDIX_B_4_2_2.
481  */
482 #define POSIX_APPENDIX_B_4_2_2
483 
484 #ifndef _SYS_SYSPROTO_H_
485 struct setuid_args {
486 	uid_t	uid;
487 };
488 #endif
489 /* ARGSUSED */
490 int
491 sys_setuid(struct thread *td, struct setuid_args *uap)
492 {
493 	struct proc *p = td->td_proc;
494 	struct ucred *newcred, *oldcred;
495 	uid_t uid;
496 	struct uidinfo *uip;
497 	int error;
498 
499 	uid = uap->uid;
500 	AUDIT_ARG_UID(uid);
501 	newcred = crget();
502 	uip = uifind(uid);
503 	PROC_LOCK(p);
504 	/*
505 	 * Copy credentials so other references do not see our changes.
506 	 */
507 	oldcred = crcopysafe(p, newcred);
508 
509 #ifdef MAC
510 	error = mac_cred_check_setuid(oldcred, uid);
511 	if (error)
512 		goto fail;
513 #endif
514 
515 	/*
516 	 * See if we have "permission" by POSIX 1003.1 rules.
517 	 *
518 	 * Note that setuid(geteuid()) is a special case of
519 	 * "appropriate privileges" in appendix B.4.2.2.  We need
520 	 * to use this clause to be compatible with traditional BSD
521 	 * semantics.  Basically, it means that "setuid(xx)" sets all
522 	 * three id's (assuming you have privs).
523 	 *
524 	 * Notes on the logic.  We do things in three steps.
525 	 * 1: We determine if the euid is going to change, and do EPERM
526 	 *    right away.  We unconditionally change the euid later if this
527 	 *    test is satisfied, simplifying that part of the logic.
528 	 * 2: We determine if the real and/or saved uids are going to
529 	 *    change.  Determined by compile options.
530 	 * 3: Change euid last. (after tests in #2 for "appropriate privs")
531 	 */
532 	if (uid != oldcred->cr_ruid &&		/* allow setuid(getuid()) */
533 #ifdef _POSIX_SAVED_IDS
534 	    uid != oldcred->cr_svuid &&		/* allow setuid(saved gid) */
535 #endif
536 #ifdef POSIX_APPENDIX_B_4_2_2	/* Use BSD-compat clause from B.4.2.2 */
537 	    uid != oldcred->cr_uid &&		/* allow setuid(geteuid()) */
538 #endif
539 	    (error = priv_check_cred(oldcred, PRIV_CRED_SETUID)) != 0)
540 		goto fail;
541 
542 #ifdef _POSIX_SAVED_IDS
543 	/*
544 	 * Do we have "appropriate privileges" (are we root or uid == euid)
545 	 * If so, we are changing the real uid and/or saved uid.
546 	 */
547 	if (
548 #ifdef POSIX_APPENDIX_B_4_2_2	/* Use the clause from B.4.2.2 */
549 	    uid == oldcred->cr_uid ||
550 #endif
551 	    /* We are using privs. */
552 	    priv_check_cred(oldcred, PRIV_CRED_SETUID) == 0)
553 #endif
554 	{
555 		/*
556 		 * Set the real uid and transfer proc count to new user.
557 		 */
558 		if (uid != oldcred->cr_ruid) {
559 			change_ruid(newcred, uip);
560 			setsugid(p);
561 		}
562 		/*
563 		 * Set saved uid
564 		 *
565 		 * XXX always set saved uid even if not _POSIX_SAVED_IDS, as
566 		 * the security of seteuid() depends on it.  B.4.2.2 says it
567 		 * is important that we should do this.
568 		 */
569 		if (uid != oldcred->cr_svuid) {
570 			change_svuid(newcred, uid);
571 			setsugid(p);
572 		}
573 	}
574 
575 	/*
576 	 * In all permitted cases, we are changing the euid.
577 	 */
578 	if (uid != oldcred->cr_uid) {
579 		change_euid(newcred, uip);
580 		setsugid(p);
581 	}
582 	proc_set_cred(p, newcred);
583 #ifdef RACCT
584 	racct_proc_ucred_changed(p, oldcred, newcred);
585 	crhold(newcred);
586 #endif
587 	PROC_UNLOCK(p);
588 #ifdef RCTL
589 	rctl_proc_ucred_changed(p, newcred);
590 	crfree(newcred);
591 #endif
592 	uifree(uip);
593 	crfree(oldcred);
594 	return (0);
595 
596 fail:
597 	PROC_UNLOCK(p);
598 	uifree(uip);
599 	crfree(newcred);
600 	return (error);
601 }
602 
603 #ifndef _SYS_SYSPROTO_H_
604 struct seteuid_args {
605 	uid_t	euid;
606 };
607 #endif
608 /* ARGSUSED */
609 int
610 sys_seteuid(struct thread *td, struct seteuid_args *uap)
611 {
612 	struct proc *p = td->td_proc;
613 	struct ucred *newcred, *oldcred;
614 	uid_t euid;
615 	struct uidinfo *euip;
616 	int error;
617 
618 	euid = uap->euid;
619 	AUDIT_ARG_EUID(euid);
620 	newcred = crget();
621 	euip = uifind(euid);
622 	PROC_LOCK(p);
623 	/*
624 	 * Copy credentials so other references do not see our changes.
625 	 */
626 	oldcred = crcopysafe(p, newcred);
627 
628 #ifdef MAC
629 	error = mac_cred_check_seteuid(oldcred, euid);
630 	if (error)
631 		goto fail;
632 #endif
633 
634 	if (euid != oldcred->cr_ruid &&		/* allow seteuid(getuid()) */
635 	    euid != oldcred->cr_svuid &&	/* allow seteuid(saved uid) */
636 	    (error = priv_check_cred(oldcred, PRIV_CRED_SETEUID)) != 0)
637 		goto fail;
638 
639 	/*
640 	 * Everything's okay, do it.
641 	 */
642 	if (oldcred->cr_uid != euid) {
643 		change_euid(newcred, euip);
644 		setsugid(p);
645 	}
646 	proc_set_cred(p, newcred);
647 	PROC_UNLOCK(p);
648 	uifree(euip);
649 	crfree(oldcred);
650 	return (0);
651 
652 fail:
653 	PROC_UNLOCK(p);
654 	uifree(euip);
655 	crfree(newcred);
656 	return (error);
657 }
658 
659 #ifndef _SYS_SYSPROTO_H_
660 struct setgid_args {
661 	gid_t	gid;
662 };
663 #endif
664 /* ARGSUSED */
665 int
666 sys_setgid(struct thread *td, struct setgid_args *uap)
667 {
668 	struct proc *p = td->td_proc;
669 	struct ucred *newcred, *oldcred;
670 	gid_t gid;
671 	int error;
672 
673 	gid = uap->gid;
674 	AUDIT_ARG_GID(gid);
675 	newcred = crget();
676 	PROC_LOCK(p);
677 	oldcred = crcopysafe(p, newcred);
678 
679 #ifdef MAC
680 	error = mac_cred_check_setgid(oldcred, gid);
681 	if (error)
682 		goto fail;
683 #endif
684 
685 	/*
686 	 * See if we have "permission" by POSIX 1003.1 rules.
687 	 *
688 	 * Note that setgid(getegid()) is a special case of
689 	 * "appropriate privileges" in appendix B.4.2.2.  We need
690 	 * to use this clause to be compatible with traditional BSD
691 	 * semantics.  Basically, it means that "setgid(xx)" sets all
692 	 * three id's (assuming you have privs).
693 	 *
694 	 * For notes on the logic here, see setuid() above.
695 	 */
696 	if (gid != oldcred->cr_rgid &&		/* allow setgid(getgid()) */
697 #ifdef _POSIX_SAVED_IDS
698 	    gid != oldcred->cr_svgid &&		/* allow setgid(saved gid) */
699 #endif
700 #ifdef POSIX_APPENDIX_B_4_2_2	/* Use BSD-compat clause from B.4.2.2 */
701 	    gid != oldcred->cr_groups[0] && /* allow setgid(getegid()) */
702 #endif
703 	    (error = priv_check_cred(oldcred, PRIV_CRED_SETGID)) != 0)
704 		goto fail;
705 
706 #ifdef _POSIX_SAVED_IDS
707 	/*
708 	 * Do we have "appropriate privileges" (are we root or gid == egid)
709 	 * If so, we are changing the real uid and saved gid.
710 	 */
711 	if (
712 #ifdef POSIX_APPENDIX_B_4_2_2	/* use the clause from B.4.2.2 */
713 	    gid == oldcred->cr_groups[0] ||
714 #endif
715 	    /* We are using privs. */
716 	    priv_check_cred(oldcred, PRIV_CRED_SETGID) == 0)
717 #endif
718 	{
719 		/*
720 		 * Set real gid
721 		 */
722 		if (oldcred->cr_rgid != gid) {
723 			change_rgid(newcred, gid);
724 			setsugid(p);
725 		}
726 		/*
727 		 * Set saved gid
728 		 *
729 		 * XXX always set saved gid even if not _POSIX_SAVED_IDS, as
730 		 * the security of setegid() depends on it.  B.4.2.2 says it
731 		 * is important that we should do this.
732 		 */
733 		if (oldcred->cr_svgid != gid) {
734 			change_svgid(newcred, gid);
735 			setsugid(p);
736 		}
737 	}
738 	/*
739 	 * In all cases permitted cases, we are changing the egid.
740 	 * Copy credentials so other references do not see our changes.
741 	 */
742 	if (oldcred->cr_groups[0] != gid) {
743 		change_egid(newcred, gid);
744 		setsugid(p);
745 	}
746 	proc_set_cred(p, newcred);
747 	PROC_UNLOCK(p);
748 	crfree(oldcred);
749 	return (0);
750 
751 fail:
752 	PROC_UNLOCK(p);
753 	crfree(newcred);
754 	return (error);
755 }
756 
757 #ifndef _SYS_SYSPROTO_H_
758 struct setegid_args {
759 	gid_t	egid;
760 };
761 #endif
762 /* ARGSUSED */
763 int
764 sys_setegid(struct thread *td, struct setegid_args *uap)
765 {
766 	struct proc *p = td->td_proc;
767 	struct ucred *newcred, *oldcred;
768 	gid_t egid;
769 	int error;
770 
771 	egid = uap->egid;
772 	AUDIT_ARG_EGID(egid);
773 	newcred = crget();
774 	PROC_LOCK(p);
775 	oldcred = crcopysafe(p, newcred);
776 
777 #ifdef MAC
778 	error = mac_cred_check_setegid(oldcred, egid);
779 	if (error)
780 		goto fail;
781 #endif
782 
783 	if (egid != oldcred->cr_rgid &&		/* allow setegid(getgid()) */
784 	    egid != oldcred->cr_svgid &&	/* allow setegid(saved gid) */
785 	    (error = priv_check_cred(oldcred, PRIV_CRED_SETEGID)) != 0)
786 		goto fail;
787 
788 	if (oldcred->cr_groups[0] != egid) {
789 		change_egid(newcred, egid);
790 		setsugid(p);
791 	}
792 	proc_set_cred(p, newcred);
793 	PROC_UNLOCK(p);
794 	crfree(oldcred);
795 	return (0);
796 
797 fail:
798 	PROC_UNLOCK(p);
799 	crfree(newcred);
800 	return (error);
801 }
802 
803 #ifndef _SYS_SYSPROTO_H_
804 struct setgroups_args {
805 	int	gidsetsize;
806 	gid_t	*gidset;
807 };
808 #endif
809 /* ARGSUSED */
810 int
811 sys_setgroups(struct thread *td, struct setgroups_args *uap)
812 {
813 	gid_t smallgroups[XU_NGROUPS];
814 	gid_t *groups;
815 	int gidsetsize, error;
816 
817 	gidsetsize = uap->gidsetsize;
818 	if (gidsetsize > ngroups_max + 1 || gidsetsize < 0)
819 		return (EINVAL);
820 
821 	if (gidsetsize > XU_NGROUPS)
822 		groups = malloc(gidsetsize * sizeof(gid_t), M_TEMP, M_WAITOK);
823 	else
824 		groups = smallgroups;
825 
826 	error = copyin(uap->gidset, groups, gidsetsize * sizeof(gid_t));
827 	if (error == 0)
828 		error = kern_setgroups(td, gidsetsize, groups);
829 
830 	if (gidsetsize > XU_NGROUPS)
831 		free(groups, M_TEMP);
832 	return (error);
833 }
834 
835 int
836 kern_setgroups(struct thread *td, u_int ngrp, gid_t *groups)
837 {
838 	struct proc *p = td->td_proc;
839 	struct ucred *newcred, *oldcred;
840 	int error;
841 
842 	MPASS(ngrp <= ngroups_max + 1);
843 	AUDIT_ARG_GROUPSET(groups, ngrp);
844 	newcred = crget();
845 	crextend(newcred, ngrp);
846 	PROC_LOCK(p);
847 	oldcred = crcopysafe(p, newcred);
848 
849 #ifdef MAC
850 	error = mac_cred_check_setgroups(oldcred, ngrp, groups);
851 	if (error)
852 		goto fail;
853 #endif
854 
855 	error = priv_check_cred(oldcred, PRIV_CRED_SETGROUPS);
856 	if (error)
857 		goto fail;
858 
859 	if (ngrp == 0) {
860 		/*
861 		 * setgroups(0, NULL) is a legitimate way of clearing the
862 		 * groups vector on non-BSD systems (which generally do not
863 		 * have the egid in the groups[0]).  We risk security holes
864 		 * when running non-BSD software if we do not do the same.
865 		 */
866 		newcred->cr_ngroups = 1;
867 	} else {
868 		crsetgroups_locked(newcred, ngrp, groups);
869 	}
870 	setsugid(p);
871 	proc_set_cred(p, newcred);
872 	PROC_UNLOCK(p);
873 	crfree(oldcred);
874 	return (0);
875 
876 fail:
877 	PROC_UNLOCK(p);
878 	crfree(newcred);
879 	return (error);
880 }
881 
882 #ifndef _SYS_SYSPROTO_H_
883 struct setreuid_args {
884 	uid_t	ruid;
885 	uid_t	euid;
886 };
887 #endif
888 /* ARGSUSED */
889 int
890 sys_setreuid(struct thread *td, struct setreuid_args *uap)
891 {
892 	struct proc *p = td->td_proc;
893 	struct ucred *newcred, *oldcred;
894 	uid_t euid, ruid;
895 	struct uidinfo *euip, *ruip;
896 	int error;
897 
898 	euid = uap->euid;
899 	ruid = uap->ruid;
900 	AUDIT_ARG_EUID(euid);
901 	AUDIT_ARG_RUID(ruid);
902 	newcred = crget();
903 	euip = uifind(euid);
904 	ruip = uifind(ruid);
905 	PROC_LOCK(p);
906 	oldcred = crcopysafe(p, newcred);
907 
908 #ifdef MAC
909 	error = mac_cred_check_setreuid(oldcred, ruid, euid);
910 	if (error)
911 		goto fail;
912 #endif
913 
914 	if (((ruid != (uid_t)-1 && ruid != oldcred->cr_ruid &&
915 	      ruid != oldcred->cr_svuid) ||
916 	     (euid != (uid_t)-1 && euid != oldcred->cr_uid &&
917 	      euid != oldcred->cr_ruid && euid != oldcred->cr_svuid)) &&
918 	    (error = priv_check_cred(oldcred, PRIV_CRED_SETREUID)) != 0)
919 		goto fail;
920 
921 	if (euid != (uid_t)-1 && oldcred->cr_uid != euid) {
922 		change_euid(newcred, euip);
923 		setsugid(p);
924 	}
925 	if (ruid != (uid_t)-1 && oldcred->cr_ruid != ruid) {
926 		change_ruid(newcred, ruip);
927 		setsugid(p);
928 	}
929 	if ((ruid != (uid_t)-1 || newcred->cr_uid != newcred->cr_ruid) &&
930 	    newcred->cr_svuid != newcred->cr_uid) {
931 		change_svuid(newcred, newcred->cr_uid);
932 		setsugid(p);
933 	}
934 	proc_set_cred(p, newcred);
935 #ifdef RACCT
936 	racct_proc_ucred_changed(p, oldcred, newcred);
937 	crhold(newcred);
938 #endif
939 	PROC_UNLOCK(p);
940 #ifdef RCTL
941 	rctl_proc_ucred_changed(p, newcred);
942 	crfree(newcred);
943 #endif
944 	uifree(ruip);
945 	uifree(euip);
946 	crfree(oldcred);
947 	return (0);
948 
949 fail:
950 	PROC_UNLOCK(p);
951 	uifree(ruip);
952 	uifree(euip);
953 	crfree(newcred);
954 	return (error);
955 }
956 
957 #ifndef _SYS_SYSPROTO_H_
958 struct setregid_args {
959 	gid_t	rgid;
960 	gid_t	egid;
961 };
962 #endif
963 /* ARGSUSED */
964 int
965 sys_setregid(struct thread *td, struct setregid_args *uap)
966 {
967 	struct proc *p = td->td_proc;
968 	struct ucred *newcred, *oldcred;
969 	gid_t egid, rgid;
970 	int error;
971 
972 	egid = uap->egid;
973 	rgid = uap->rgid;
974 	AUDIT_ARG_EGID(egid);
975 	AUDIT_ARG_RGID(rgid);
976 	newcred = crget();
977 	PROC_LOCK(p);
978 	oldcred = crcopysafe(p, newcred);
979 
980 #ifdef MAC
981 	error = mac_cred_check_setregid(oldcred, rgid, egid);
982 	if (error)
983 		goto fail;
984 #endif
985 
986 	if (((rgid != (gid_t)-1 && rgid != oldcred->cr_rgid &&
987 	    rgid != oldcred->cr_svgid) ||
988 	     (egid != (gid_t)-1 && egid != oldcred->cr_groups[0] &&
989 	     egid != oldcred->cr_rgid && egid != oldcred->cr_svgid)) &&
990 	    (error = priv_check_cred(oldcred, PRIV_CRED_SETREGID)) != 0)
991 		goto fail;
992 
993 	if (egid != (gid_t)-1 && oldcred->cr_groups[0] != egid) {
994 		change_egid(newcred, egid);
995 		setsugid(p);
996 	}
997 	if (rgid != (gid_t)-1 && oldcred->cr_rgid != rgid) {
998 		change_rgid(newcred, rgid);
999 		setsugid(p);
1000 	}
1001 	if ((rgid != (gid_t)-1 || newcred->cr_groups[0] != newcred->cr_rgid) &&
1002 	    newcred->cr_svgid != newcred->cr_groups[0]) {
1003 		change_svgid(newcred, newcred->cr_groups[0]);
1004 		setsugid(p);
1005 	}
1006 	proc_set_cred(p, newcred);
1007 	PROC_UNLOCK(p);
1008 	crfree(oldcred);
1009 	return (0);
1010 
1011 fail:
1012 	PROC_UNLOCK(p);
1013 	crfree(newcred);
1014 	return (error);
1015 }
1016 
1017 /*
1018  * setresuid(ruid, euid, suid) is like setreuid except control over the saved
1019  * uid is explicit.
1020  */
1021 #ifndef _SYS_SYSPROTO_H_
1022 struct setresuid_args {
1023 	uid_t	ruid;
1024 	uid_t	euid;
1025 	uid_t	suid;
1026 };
1027 #endif
1028 /* ARGSUSED */
1029 int
1030 sys_setresuid(struct thread *td, struct setresuid_args *uap)
1031 {
1032 	struct proc *p = td->td_proc;
1033 	struct ucred *newcred, *oldcred;
1034 	uid_t euid, ruid, suid;
1035 	struct uidinfo *euip, *ruip;
1036 	int error;
1037 
1038 	euid = uap->euid;
1039 	ruid = uap->ruid;
1040 	suid = uap->suid;
1041 	AUDIT_ARG_EUID(euid);
1042 	AUDIT_ARG_RUID(ruid);
1043 	AUDIT_ARG_SUID(suid);
1044 	newcred = crget();
1045 	euip = uifind(euid);
1046 	ruip = uifind(ruid);
1047 	PROC_LOCK(p);
1048 	oldcred = crcopysafe(p, newcred);
1049 
1050 #ifdef MAC
1051 	error = mac_cred_check_setresuid(oldcred, ruid, euid, suid);
1052 	if (error)
1053 		goto fail;
1054 #endif
1055 
1056 	if (((ruid != (uid_t)-1 && ruid != oldcred->cr_ruid &&
1057 	     ruid != oldcred->cr_svuid &&
1058 	      ruid != oldcred->cr_uid) ||
1059 	     (euid != (uid_t)-1 && euid != oldcred->cr_ruid &&
1060 	    euid != oldcred->cr_svuid &&
1061 	      euid != oldcred->cr_uid) ||
1062 	     (suid != (uid_t)-1 && suid != oldcred->cr_ruid &&
1063 	    suid != oldcred->cr_svuid &&
1064 	      suid != oldcred->cr_uid)) &&
1065 	    (error = priv_check_cred(oldcred, PRIV_CRED_SETRESUID)) != 0)
1066 		goto fail;
1067 
1068 	if (euid != (uid_t)-1 && oldcred->cr_uid != euid) {
1069 		change_euid(newcred, euip);
1070 		setsugid(p);
1071 	}
1072 	if (ruid != (uid_t)-1 && oldcred->cr_ruid != ruid) {
1073 		change_ruid(newcred, ruip);
1074 		setsugid(p);
1075 	}
1076 	if (suid != (uid_t)-1 && oldcred->cr_svuid != suid) {
1077 		change_svuid(newcred, suid);
1078 		setsugid(p);
1079 	}
1080 	proc_set_cred(p, newcred);
1081 #ifdef RACCT
1082 	racct_proc_ucred_changed(p, oldcred, newcred);
1083 	crhold(newcred);
1084 #endif
1085 	PROC_UNLOCK(p);
1086 #ifdef RCTL
1087 	rctl_proc_ucred_changed(p, newcred);
1088 	crfree(newcred);
1089 #endif
1090 	uifree(ruip);
1091 	uifree(euip);
1092 	crfree(oldcred);
1093 	return (0);
1094 
1095 fail:
1096 	PROC_UNLOCK(p);
1097 	uifree(ruip);
1098 	uifree(euip);
1099 	crfree(newcred);
1100 	return (error);
1101 
1102 }
1103 
1104 /*
1105  * setresgid(rgid, egid, sgid) is like setregid except control over the saved
1106  * gid is explicit.
1107  */
1108 #ifndef _SYS_SYSPROTO_H_
1109 struct setresgid_args {
1110 	gid_t	rgid;
1111 	gid_t	egid;
1112 	gid_t	sgid;
1113 };
1114 #endif
1115 /* ARGSUSED */
1116 int
1117 sys_setresgid(struct thread *td, struct setresgid_args *uap)
1118 {
1119 	struct proc *p = td->td_proc;
1120 	struct ucred *newcred, *oldcred;
1121 	gid_t egid, rgid, sgid;
1122 	int error;
1123 
1124 	egid = uap->egid;
1125 	rgid = uap->rgid;
1126 	sgid = uap->sgid;
1127 	AUDIT_ARG_EGID(egid);
1128 	AUDIT_ARG_RGID(rgid);
1129 	AUDIT_ARG_SGID(sgid);
1130 	newcred = crget();
1131 	PROC_LOCK(p);
1132 	oldcred = crcopysafe(p, newcred);
1133 
1134 #ifdef MAC
1135 	error = mac_cred_check_setresgid(oldcred, rgid, egid, sgid);
1136 	if (error)
1137 		goto fail;
1138 #endif
1139 
1140 	if (((rgid != (gid_t)-1 && rgid != oldcred->cr_rgid &&
1141 	      rgid != oldcred->cr_svgid &&
1142 	      rgid != oldcred->cr_groups[0]) ||
1143 	     (egid != (gid_t)-1 && egid != oldcred->cr_rgid &&
1144 	      egid != oldcred->cr_svgid &&
1145 	      egid != oldcred->cr_groups[0]) ||
1146 	     (sgid != (gid_t)-1 && sgid != oldcred->cr_rgid &&
1147 	      sgid != oldcred->cr_svgid &&
1148 	      sgid != oldcred->cr_groups[0])) &&
1149 	    (error = priv_check_cred(oldcred, PRIV_CRED_SETRESGID)) != 0)
1150 		goto fail;
1151 
1152 	if (egid != (gid_t)-1 && oldcred->cr_groups[0] != egid) {
1153 		change_egid(newcred, egid);
1154 		setsugid(p);
1155 	}
1156 	if (rgid != (gid_t)-1 && oldcred->cr_rgid != rgid) {
1157 		change_rgid(newcred, rgid);
1158 		setsugid(p);
1159 	}
1160 	if (sgid != (gid_t)-1 && oldcred->cr_svgid != sgid) {
1161 		change_svgid(newcred, sgid);
1162 		setsugid(p);
1163 	}
1164 	proc_set_cred(p, newcred);
1165 	PROC_UNLOCK(p);
1166 	crfree(oldcred);
1167 	return (0);
1168 
1169 fail:
1170 	PROC_UNLOCK(p);
1171 	crfree(newcred);
1172 	return (error);
1173 }
1174 
1175 #ifndef _SYS_SYSPROTO_H_
1176 struct getresuid_args {
1177 	uid_t	*ruid;
1178 	uid_t	*euid;
1179 	uid_t	*suid;
1180 };
1181 #endif
1182 /* ARGSUSED */
1183 int
1184 sys_getresuid(struct thread *td, struct getresuid_args *uap)
1185 {
1186 	struct ucred *cred;
1187 	int error1 = 0, error2 = 0, error3 = 0;
1188 
1189 	cred = td->td_ucred;
1190 	if (uap->ruid)
1191 		error1 = copyout(&cred->cr_ruid,
1192 		    uap->ruid, sizeof(cred->cr_ruid));
1193 	if (uap->euid)
1194 		error2 = copyout(&cred->cr_uid,
1195 		    uap->euid, sizeof(cred->cr_uid));
1196 	if (uap->suid)
1197 		error3 = copyout(&cred->cr_svuid,
1198 		    uap->suid, sizeof(cred->cr_svuid));
1199 	return (error1 ? error1 : error2 ? error2 : error3);
1200 }
1201 
1202 #ifndef _SYS_SYSPROTO_H_
1203 struct getresgid_args {
1204 	gid_t	*rgid;
1205 	gid_t	*egid;
1206 	gid_t	*sgid;
1207 };
1208 #endif
1209 /* ARGSUSED */
1210 int
1211 sys_getresgid(struct thread *td, struct getresgid_args *uap)
1212 {
1213 	struct ucred *cred;
1214 	int error1 = 0, error2 = 0, error3 = 0;
1215 
1216 	cred = td->td_ucred;
1217 	if (uap->rgid)
1218 		error1 = copyout(&cred->cr_rgid,
1219 		    uap->rgid, sizeof(cred->cr_rgid));
1220 	if (uap->egid)
1221 		error2 = copyout(&cred->cr_groups[0],
1222 		    uap->egid, sizeof(cred->cr_groups[0]));
1223 	if (uap->sgid)
1224 		error3 = copyout(&cred->cr_svgid,
1225 		    uap->sgid, sizeof(cred->cr_svgid));
1226 	return (error1 ? error1 : error2 ? error2 : error3);
1227 }
1228 
1229 #ifndef _SYS_SYSPROTO_H_
1230 struct issetugid_args {
1231 	int dummy;
1232 };
1233 #endif
1234 /* ARGSUSED */
1235 int
1236 sys_issetugid(struct thread *td, struct issetugid_args *uap)
1237 {
1238 	struct proc *p = td->td_proc;
1239 
1240 	/*
1241 	 * Note: OpenBSD sets a P_SUGIDEXEC flag set at execve() time,
1242 	 * we use P_SUGID because we consider changing the owners as
1243 	 * "tainting" as well.
1244 	 * This is significant for procs that start as root and "become"
1245 	 * a user without an exec - programs cannot know *everything*
1246 	 * that libc *might* have put in their data segment.
1247 	 */
1248 	td->td_retval[0] = (p->p_flag & P_SUGID) ? 1 : 0;
1249 	return (0);
1250 }
1251 
1252 int
1253 sys___setugid(struct thread *td, struct __setugid_args *uap)
1254 {
1255 #ifdef REGRESSION
1256 	struct proc *p;
1257 
1258 	p = td->td_proc;
1259 	switch (uap->flag) {
1260 	case 0:
1261 		PROC_LOCK(p);
1262 		p->p_flag &= ~P_SUGID;
1263 		PROC_UNLOCK(p);
1264 		return (0);
1265 	case 1:
1266 		PROC_LOCK(p);
1267 		p->p_flag |= P_SUGID;
1268 		PROC_UNLOCK(p);
1269 		return (0);
1270 	default:
1271 		return (EINVAL);
1272 	}
1273 #else /* !REGRESSION */
1274 
1275 	return (ENOSYS);
1276 #endif /* REGRESSION */
1277 }
1278 
1279 /*
1280  * Check if gid is a member of the group set.
1281  */
1282 int
1283 groupmember(gid_t gid, struct ucred *cred)
1284 {
1285 	int l;
1286 	int h;
1287 	int m;
1288 
1289 	if (cred->cr_groups[0] == gid)
1290 		return(1);
1291 
1292 	/*
1293 	 * If gid was not our primary group, perform a binary search
1294 	 * of the supplemental groups.  This is possible because we
1295 	 * sort the groups in crsetgroups().
1296 	 */
1297 	l = 1;
1298 	h = cred->cr_ngroups;
1299 	while (l < h) {
1300 		m = l + ((h - l) / 2);
1301 		if (cred->cr_groups[m] < gid)
1302 			l = m + 1;
1303 		else
1304 			h = m;
1305 	}
1306 	if ((l < cred->cr_ngroups) && (cred->cr_groups[l] == gid))
1307 		return (1);
1308 
1309 	return (0);
1310 }
1311 
1312 /*
1313  * Test the active securelevel against a given level.  securelevel_gt()
1314  * implements (securelevel > level).  securelevel_ge() implements
1315  * (securelevel >= level).  Note that the logic is inverted -- these
1316  * functions return EPERM on "success" and 0 on "failure".
1317  *
1318  * Due to care taken when setting the securelevel, we know that no jail will
1319  * be less secure that its parent (or the physical system), so it is sufficient
1320  * to test the current jail only.
1321  *
1322  * XXXRW: Possibly since this has to do with privilege, it should move to
1323  * kern_priv.c.
1324  */
1325 int
1326 securelevel_gt(struct ucred *cr, int level)
1327 {
1328 
1329 	return (cr->cr_prison->pr_securelevel > level ? EPERM : 0);
1330 }
1331 
1332 int
1333 securelevel_ge(struct ucred *cr, int level)
1334 {
1335 
1336 	return (cr->cr_prison->pr_securelevel >= level ? EPERM : 0);
1337 }
1338 
1339 /*
1340  * 'see_other_uids' determines whether or not visibility of processes
1341  * and sockets with credentials holding different real uids is possible
1342  * using a variety of system MIBs.
1343  * XXX: data declarations should be together near the beginning of the file.
1344  */
1345 static int	see_other_uids = 1;
1346 SYSCTL_INT(_security_bsd, OID_AUTO, see_other_uids, CTLFLAG_RW,
1347     &see_other_uids, 0,
1348     "Unprivileged processes may see subjects/objects with different real uid");
1349 
1350 /*-
1351  * Determine if u1 "can see" the subject specified by u2, according to the
1352  * 'see_other_uids' policy.
1353  * Returns: 0 for permitted, ESRCH otherwise
1354  * Locks: none
1355  * References: *u1 and *u2 must not change during the call
1356  *             u1 may equal u2, in which case only one reference is required
1357  */
1358 int
1359 cr_canseeotheruids(struct ucred *u1, struct ucred *u2)
1360 {
1361 
1362 	if (!see_other_uids && u1->cr_ruid != u2->cr_ruid) {
1363 		if (priv_check_cred(u1, PRIV_SEEOTHERUIDS) != 0)
1364 			return (ESRCH);
1365 	}
1366 	return (0);
1367 }
1368 
1369 /*
1370  * 'see_other_gids' determines whether or not visibility of processes
1371  * and sockets with credentials holding different real gids is possible
1372  * using a variety of system MIBs.
1373  * XXX: data declarations should be together near the beginning of the file.
1374  */
1375 static int	see_other_gids = 1;
1376 SYSCTL_INT(_security_bsd, OID_AUTO, see_other_gids, CTLFLAG_RW,
1377     &see_other_gids, 0,
1378     "Unprivileged processes may see subjects/objects with different real gid");
1379 
1380 /*
1381  * Determine if u1 can "see" the subject specified by u2, according to the
1382  * 'see_other_gids' policy.
1383  * Returns: 0 for permitted, ESRCH otherwise
1384  * Locks: none
1385  * References: *u1 and *u2 must not change during the call
1386  *             u1 may equal u2, in which case only one reference is required
1387  */
1388 int
1389 cr_canseeothergids(struct ucred *u1, struct ucred *u2)
1390 {
1391 	int i, match;
1392 
1393 	if (!see_other_gids) {
1394 		match = 0;
1395 		for (i = 0; i < u1->cr_ngroups; i++) {
1396 			if (groupmember(u1->cr_groups[i], u2))
1397 				match = 1;
1398 			if (match)
1399 				break;
1400 		}
1401 		if (!match) {
1402 			if (priv_check_cred(u1, PRIV_SEEOTHERGIDS) != 0)
1403 				return (ESRCH);
1404 		}
1405 	}
1406 	return (0);
1407 }
1408 
1409 /*
1410  * 'see_jail_proc' determines whether or not visibility of processes and
1411  * sockets with credentials holding different jail ids is possible using a
1412  * variety of system MIBs.
1413  *
1414  * XXX: data declarations should be together near the beginning of the file.
1415  */
1416 
1417 static int	see_jail_proc = 1;
1418 SYSCTL_INT(_security_bsd, OID_AUTO, see_jail_proc, CTLFLAG_RW,
1419     &see_jail_proc, 0,
1420     "Unprivileged processes may see subjects/objects with different jail ids");
1421 
1422 /*-
1423  * Determine if u1 "can see" the subject specified by u2, according to the
1424  * 'see_jail_proc' policy.
1425  * Returns: 0 for permitted, ESRCH otherwise
1426  * Locks: none
1427  * References: *u1 and *u2 must not change during the call
1428  *             u1 may equal u2, in which case only one reference is required
1429  */
1430 int
1431 cr_canseejailproc(struct ucred *u1, struct ucred *u2)
1432 {
1433 	if (u1->cr_uid == 0)
1434 		return (0);
1435 	return (!see_jail_proc && u1->cr_prison != u2->cr_prison ? ESRCH : 0);
1436 }
1437 
1438 /*-
1439  * Determine if u1 "can see" the subject specified by u2.
1440  * Returns: 0 for permitted, an errno value otherwise
1441  * Locks: none
1442  * References: *u1 and *u2 must not change during the call
1443  *             u1 may equal u2, in which case only one reference is required
1444  */
1445 int
1446 cr_cansee(struct ucred *u1, struct ucred *u2)
1447 {
1448 	int error;
1449 
1450 	if ((error = prison_check(u1, u2)))
1451 		return (error);
1452 #ifdef MAC
1453 	if ((error = mac_cred_check_visible(u1, u2)))
1454 		return (error);
1455 #endif
1456 	if ((error = cr_canseeotheruids(u1, u2)))
1457 		return (error);
1458 	if ((error = cr_canseeothergids(u1, u2)))
1459 		return (error);
1460 	if ((error = cr_canseejailproc(u1, u2)))
1461 		return (error);
1462 	return (0);
1463 }
1464 
1465 /*-
1466  * Determine if td "can see" the subject specified by p.
1467  * Returns: 0 for permitted, an errno value otherwise
1468  * Locks: Sufficient locks to protect p->p_ucred must be held.  td really
1469  *        should be curthread.
1470  * References: td and p must be valid for the lifetime of the call
1471  */
1472 int
1473 p_cansee(struct thread *td, struct proc *p)
1474 {
1475 	/* Wrap cr_cansee() for all functionality. */
1476 	KASSERT(td == curthread, ("%s: td not curthread", __func__));
1477 	PROC_LOCK_ASSERT(p, MA_OWNED);
1478 
1479 	if (td->td_proc == p)
1480 		return (0);
1481 	return (cr_cansee(td->td_ucred, p->p_ucred));
1482 }
1483 
1484 /*
1485  * 'conservative_signals' prevents the delivery of a broad class of
1486  * signals by unprivileged processes to processes that have changed their
1487  * credentials since the last invocation of execve().  This can prevent
1488  * the leakage of cached information or retained privileges as a result
1489  * of a common class of signal-related vulnerabilities.  However, this
1490  * may interfere with some applications that expect to be able to
1491  * deliver these signals to peer processes after having given up
1492  * privilege.
1493  */
1494 static int	conservative_signals = 1;
1495 SYSCTL_INT(_security_bsd, OID_AUTO, conservative_signals, CTLFLAG_RW,
1496     &conservative_signals, 0, "Unprivileged processes prevented from "
1497     "sending certain signals to processes whose credentials have changed");
1498 /*-
1499  * Determine whether cred may deliver the specified signal to proc.
1500  * Returns: 0 for permitted, an errno value otherwise.
1501  * Locks: A lock must be held for proc.
1502  * References: cred and proc must be valid for the lifetime of the call.
1503  */
1504 int
1505 cr_cansignal(struct ucred *cred, struct proc *proc, int signum)
1506 {
1507 	int error;
1508 
1509 	PROC_LOCK_ASSERT(proc, MA_OWNED);
1510 	/*
1511 	 * Jail semantics limit the scope of signalling to proc in the
1512 	 * same jail as cred, if cred is in jail.
1513 	 */
1514 	error = prison_check(cred, proc->p_ucred);
1515 	if (error)
1516 		return (error);
1517 #ifdef MAC
1518 	if ((error = mac_proc_check_signal(cred, proc, signum)))
1519 		return (error);
1520 #endif
1521 	if ((error = cr_canseeotheruids(cred, proc->p_ucred)))
1522 		return (error);
1523 	if ((error = cr_canseeothergids(cred, proc->p_ucred)))
1524 		return (error);
1525 
1526 	/*
1527 	 * UNIX signal semantics depend on the status of the P_SUGID
1528 	 * bit on the target process.  If the bit is set, then additional
1529 	 * restrictions are placed on the set of available signals.
1530 	 */
1531 	if (conservative_signals && (proc->p_flag & P_SUGID)) {
1532 		switch (signum) {
1533 		case 0:
1534 		case SIGKILL:
1535 		case SIGINT:
1536 		case SIGTERM:
1537 		case SIGALRM:
1538 		case SIGSTOP:
1539 		case SIGTTIN:
1540 		case SIGTTOU:
1541 		case SIGTSTP:
1542 		case SIGHUP:
1543 		case SIGUSR1:
1544 		case SIGUSR2:
1545 			/*
1546 			 * Generally, permit job and terminal control
1547 			 * signals.
1548 			 */
1549 			break;
1550 		default:
1551 			/* Not permitted without privilege. */
1552 			error = priv_check_cred(cred, PRIV_SIGNAL_SUGID);
1553 			if (error)
1554 				return (error);
1555 		}
1556 	}
1557 
1558 	/*
1559 	 * Generally, the target credential's ruid or svuid must match the
1560 	 * subject credential's ruid or euid.
1561 	 */
1562 	if (cred->cr_ruid != proc->p_ucred->cr_ruid &&
1563 	    cred->cr_ruid != proc->p_ucred->cr_svuid &&
1564 	    cred->cr_uid != proc->p_ucred->cr_ruid &&
1565 	    cred->cr_uid != proc->p_ucred->cr_svuid) {
1566 		error = priv_check_cred(cred, PRIV_SIGNAL_DIFFCRED);
1567 		if (error)
1568 			return (error);
1569 	}
1570 
1571 	return (0);
1572 }
1573 
1574 /*-
1575  * Determine whether td may deliver the specified signal to p.
1576  * Returns: 0 for permitted, an errno value otherwise
1577  * Locks: Sufficient locks to protect various components of td and p
1578  *        must be held.  td must be curthread, and a lock must be
1579  *        held for p.
1580  * References: td and p must be valid for the lifetime of the call
1581  */
1582 int
1583 p_cansignal(struct thread *td, struct proc *p, int signum)
1584 {
1585 
1586 	KASSERT(td == curthread, ("%s: td not curthread", __func__));
1587 	PROC_LOCK_ASSERT(p, MA_OWNED);
1588 	if (td->td_proc == p)
1589 		return (0);
1590 
1591 	/*
1592 	 * UNIX signalling semantics require that processes in the same
1593 	 * session always be able to deliver SIGCONT to one another,
1594 	 * overriding the remaining protections.
1595 	 */
1596 	/* XXX: This will require an additional lock of some sort. */
1597 	if (signum == SIGCONT && td->td_proc->p_session == p->p_session)
1598 		return (0);
1599 	/*
1600 	 * Some compat layers use SIGTHR and higher signals for
1601 	 * communication between different kernel threads of the same
1602 	 * process, so that they expect that it's always possible to
1603 	 * deliver them, even for suid applications where cr_cansignal() can
1604 	 * deny such ability for security consideration.  It should be
1605 	 * pretty safe to do since the only way to create two processes
1606 	 * with the same p_leader is via rfork(2).
1607 	 */
1608 	if (td->td_proc->p_leader != NULL && signum >= SIGTHR &&
1609 	    signum < SIGTHR + 4 && td->td_proc->p_leader == p->p_leader)
1610 		return (0);
1611 
1612 	return (cr_cansignal(td->td_ucred, p, signum));
1613 }
1614 
1615 /*-
1616  * Determine whether td may reschedule p.
1617  * Returns: 0 for permitted, an errno value otherwise
1618  * Locks: Sufficient locks to protect various components of td and p
1619  *        must be held.  td must be curthread, and a lock must
1620  *        be held for p.
1621  * References: td and p must be valid for the lifetime of the call
1622  */
1623 int
1624 p_cansched(struct thread *td, struct proc *p)
1625 {
1626 	int error;
1627 
1628 	KASSERT(td == curthread, ("%s: td not curthread", __func__));
1629 	PROC_LOCK_ASSERT(p, MA_OWNED);
1630 	if (td->td_proc == p)
1631 		return (0);
1632 	if ((error = prison_check(td->td_ucred, p->p_ucred)))
1633 		return (error);
1634 #ifdef MAC
1635 	if ((error = mac_proc_check_sched(td->td_ucred, p)))
1636 		return (error);
1637 #endif
1638 	if ((error = cr_canseeotheruids(td->td_ucred, p->p_ucred)))
1639 		return (error);
1640 	if ((error = cr_canseeothergids(td->td_ucred, p->p_ucred)))
1641 		return (error);
1642 	if (td->td_ucred->cr_ruid != p->p_ucred->cr_ruid &&
1643 	    td->td_ucred->cr_uid != p->p_ucred->cr_ruid) {
1644 		error = priv_check(td, PRIV_SCHED_DIFFCRED);
1645 		if (error)
1646 			return (error);
1647 	}
1648 	return (0);
1649 }
1650 
1651 /*
1652  * Handle getting or setting the prison's unprivileged_proc_debug
1653  * value.
1654  */
1655 static int
1656 sysctl_unprivileged_proc_debug(SYSCTL_HANDLER_ARGS)
1657 {
1658 	int error, val;
1659 
1660 	val = prison_allow(req->td->td_ucred, PR_ALLOW_UNPRIV_DEBUG);
1661 	error = sysctl_handle_int(oidp, &val, 0, req);
1662 	if (error != 0 || req->newptr == NULL)
1663 		return (error);
1664 	if (val != 0 && val != 1)
1665 		return (EINVAL);
1666 	prison_set_allow(req->td->td_ucred, PR_ALLOW_UNPRIV_DEBUG, val);
1667 	return (0);
1668 }
1669 
1670 /*
1671  * The 'unprivileged_proc_debug' flag may be used to disable a variety of
1672  * unprivileged inter-process debugging services, including some procfs
1673  * functionality, ptrace(), and ktrace().  In the past, inter-process
1674  * debugging has been involved in a variety of security problems, and sites
1675  * not requiring the service might choose to disable it when hardening
1676  * systems.
1677  */
1678 SYSCTL_PROC(_security_bsd, OID_AUTO, unprivileged_proc_debug,
1679     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_PRISON | CTLFLAG_SECURE |
1680     CTLFLAG_MPSAFE, 0, 0, sysctl_unprivileged_proc_debug, "I",
1681     "Unprivileged processes may use process debugging facilities");
1682 
1683 /*-
1684  * Determine whether td may debug p.
1685  * Returns: 0 for permitted, an errno value otherwise
1686  * Locks: Sufficient locks to protect various components of td and p
1687  *        must be held.  td must be curthread, and a lock must
1688  *        be held for p.
1689  * References: td and p must be valid for the lifetime of the call
1690  */
1691 int
1692 p_candebug(struct thread *td, struct proc *p)
1693 {
1694 	int error, grpsubset, i, uidsubset;
1695 
1696 	KASSERT(td == curthread, ("%s: td not curthread", __func__));
1697 	PROC_LOCK_ASSERT(p, MA_OWNED);
1698 	if (td->td_proc == p)
1699 		return (0);
1700 	if ((error = priv_check(td, PRIV_DEBUG_UNPRIV)))
1701 		return (error);
1702 	if ((error = prison_check(td->td_ucred, p->p_ucred)))
1703 		return (error);
1704 #ifdef MAC
1705 	if ((error = mac_proc_check_debug(td->td_ucred, p)))
1706 		return (error);
1707 #endif
1708 	if ((error = cr_canseeotheruids(td->td_ucred, p->p_ucred)))
1709 		return (error);
1710 	if ((error = cr_canseeothergids(td->td_ucred, p->p_ucred)))
1711 		return (error);
1712 
1713 	/*
1714 	 * Is p's group set a subset of td's effective group set?  This
1715 	 * includes p's egid, group access list, rgid, and svgid.
1716 	 */
1717 	grpsubset = 1;
1718 	for (i = 0; i < p->p_ucred->cr_ngroups; i++) {
1719 		if (!groupmember(p->p_ucred->cr_groups[i], td->td_ucred)) {
1720 			grpsubset = 0;
1721 			break;
1722 		}
1723 	}
1724 	grpsubset = grpsubset &&
1725 	    groupmember(p->p_ucred->cr_rgid, td->td_ucred) &&
1726 	    groupmember(p->p_ucred->cr_svgid, td->td_ucred);
1727 
1728 	/*
1729 	 * Are the uids present in p's credential equal to td's
1730 	 * effective uid?  This includes p's euid, svuid, and ruid.
1731 	 */
1732 	uidsubset = (td->td_ucred->cr_uid == p->p_ucred->cr_uid &&
1733 	    td->td_ucred->cr_uid == p->p_ucred->cr_svuid &&
1734 	    td->td_ucred->cr_uid == p->p_ucred->cr_ruid);
1735 
1736 	/*
1737 	 * If p's gids aren't a subset, or the uids aren't a subset,
1738 	 * or the credential has changed, require appropriate privilege
1739 	 * for td to debug p.
1740 	 */
1741 	if (!grpsubset || !uidsubset) {
1742 		error = priv_check(td, PRIV_DEBUG_DIFFCRED);
1743 		if (error)
1744 			return (error);
1745 	}
1746 
1747 	/*
1748 	 * Has the credential of the process changed since the last exec()?
1749 	 */
1750 	if ((p->p_flag & P_SUGID) != 0) {
1751 		error = priv_check(td, PRIV_DEBUG_SUGID);
1752 		if (error)
1753 			return (error);
1754 	}
1755 
1756 	/* Can't trace init when securelevel > 0. */
1757 	if (p == initproc) {
1758 		error = securelevel_gt(td->td_ucred, 0);
1759 		if (error)
1760 			return (error);
1761 	}
1762 
1763 	/*
1764 	 * Can't trace a process that's currently exec'ing.
1765 	 *
1766 	 * XXX: Note, this is not a security policy decision, it's a
1767 	 * basic correctness/functionality decision.  Therefore, this check
1768 	 * should be moved to the caller's of p_candebug().
1769 	 */
1770 	if ((p->p_flag & P_INEXEC) != 0)
1771 		return (EBUSY);
1772 
1773 	/* Denied explicitly */
1774 	if ((p->p_flag2 & P2_NOTRACE) != 0) {
1775 		error = priv_check(td, PRIV_DEBUG_DENIED);
1776 		if (error != 0)
1777 			return (error);
1778 	}
1779 
1780 	return (0);
1781 }
1782 
1783 /*-
1784  * Determine whether the subject represented by cred can "see" a socket.
1785  * Returns: 0 for permitted, ENOENT otherwise.
1786  */
1787 int
1788 cr_canseesocket(struct ucred *cred, struct socket *so)
1789 {
1790 	int error;
1791 
1792 	error = prison_check(cred, so->so_cred);
1793 	if (error)
1794 		return (ENOENT);
1795 #ifdef MAC
1796 	error = mac_socket_check_visible(cred, so);
1797 	if (error)
1798 		return (error);
1799 #endif
1800 	if (cr_canseeotheruids(cred, so->so_cred))
1801 		return (ENOENT);
1802 	if (cr_canseeothergids(cred, so->so_cred))
1803 		return (ENOENT);
1804 
1805 	return (0);
1806 }
1807 
1808 /*-
1809  * Determine whether td can wait for the exit of p.
1810  * Returns: 0 for permitted, an errno value otherwise
1811  * Locks: Sufficient locks to protect various components of td and p
1812  *        must be held.  td must be curthread, and a lock must
1813  *        be held for p.
1814  * References: td and p must be valid for the lifetime of the call
1815 
1816  */
1817 int
1818 p_canwait(struct thread *td, struct proc *p)
1819 {
1820 	int error;
1821 
1822 	KASSERT(td == curthread, ("%s: td not curthread", __func__));
1823 	PROC_LOCK_ASSERT(p, MA_OWNED);
1824 	if ((error = prison_check(td->td_ucred, p->p_ucred)))
1825 		return (error);
1826 #ifdef MAC
1827 	if ((error = mac_proc_check_wait(td->td_ucred, p)))
1828 		return (error);
1829 #endif
1830 #if 0
1831 	/* XXXMAC: This could have odd effects on some shells. */
1832 	if ((error = cr_canseeotheruids(td->td_ucred, p->p_ucred)))
1833 		return (error);
1834 #endif
1835 
1836 	return (0);
1837 }
1838 
1839 /*
1840  * Credential management.
1841  *
1842  * struct ucred objects are rarely allocated but gain and lose references all
1843  * the time (e.g., on struct file alloc/dealloc) turning refcount updates into
1844  * a significant source of cache-line ping ponging. Common cases are worked
1845  * around by modifying thread-local counter instead if the cred to operate on
1846  * matches td_realucred.
1847  *
1848  * The counter is split into 2 parts:
1849  * - cr_users -- total count of all struct proc and struct thread objects
1850  *   which have given cred in p_ucred and td_ucred respectively
1851  * - cr_ref -- the actual ref count, only valid if cr_users == 0
1852  *
1853  * If users == 0 then cr_ref behaves similarly to refcount(9), in particular if
1854  * the count reaches 0 the object is freeable.
1855  * If users > 0 and curthread->td_realucred == cred, then updates are performed
1856  * against td_ucredref.
1857  * In other cases updates are performed against cr_ref.
1858  *
1859  * Changing td_realucred into something else decrements cr_users and transfers
1860  * accumulated updates.
1861  */
1862 struct ucred *
1863 crcowget(struct ucred *cr)
1864 {
1865 
1866 	mtx_lock(&cr->cr_mtx);
1867 	KASSERT(cr->cr_users > 0, ("%s: users %d not > 0 on cred %p",
1868 	    __func__, cr->cr_users, cr));
1869 	cr->cr_users++;
1870 	cr->cr_ref++;
1871 	mtx_unlock(&cr->cr_mtx);
1872 	return (cr);
1873 }
1874 
1875 static struct ucred *
1876 crunuse(struct thread *td)
1877 {
1878 	struct ucred *cr, *crold;
1879 
1880 	MPASS(td->td_realucred == td->td_ucred);
1881 	cr = td->td_realucred;
1882 	mtx_lock(&cr->cr_mtx);
1883 	cr->cr_ref += td->td_ucredref;
1884 	td->td_ucredref = 0;
1885 	KASSERT(cr->cr_users > 0, ("%s: users %d not > 0 on cred %p",
1886 	    __func__, cr->cr_users, cr));
1887 	cr->cr_users--;
1888 	if (cr->cr_users == 0) {
1889 		KASSERT(cr->cr_ref > 0, ("%s: ref %ld not > 0 on cred %p",
1890 		    __func__, cr->cr_ref, cr));
1891 		crold = cr;
1892 	} else {
1893 		cr->cr_ref--;
1894 		crold = NULL;
1895 	}
1896 	mtx_unlock(&cr->cr_mtx);
1897 	td->td_realucred = NULL;
1898 	return (crold);
1899 }
1900 
1901 static void
1902 crunusebatch(struct ucred *cr, int users, int ref)
1903 {
1904 
1905 	KASSERT(users > 0, ("%s: passed users %d not > 0 ; cred %p",
1906 	    __func__, users, cr));
1907 	mtx_lock(&cr->cr_mtx);
1908 	KASSERT(cr->cr_users >= users, ("%s: users %d not > %d on cred %p",
1909 	    __func__, cr->cr_users, users, cr));
1910 	cr->cr_users -= users;
1911 	cr->cr_ref += ref;
1912 	cr->cr_ref -= users;
1913 	if (cr->cr_users > 0) {
1914 		mtx_unlock(&cr->cr_mtx);
1915 		return;
1916 	}
1917 	KASSERT(cr->cr_ref >= 0, ("%s: ref %ld not >= 0 on cred %p",
1918 	    __func__, cr->cr_ref, cr));
1919 	if (cr->cr_ref > 0) {
1920 		mtx_unlock(&cr->cr_mtx);
1921 		return;
1922 	}
1923 	crfree_final(cr);
1924 }
1925 
1926 void
1927 crcowfree(struct thread *td)
1928 {
1929 	struct ucred *cr;
1930 
1931 	cr = crunuse(td);
1932 	if (cr != NULL)
1933 		crfree(cr);
1934 }
1935 
1936 struct ucred *
1937 crcowsync(void)
1938 {
1939 	struct thread *td;
1940 	struct proc *p;
1941 	struct ucred *crnew, *crold;
1942 
1943 	td = curthread;
1944 	p = td->td_proc;
1945 	PROC_LOCK_ASSERT(p, MA_OWNED);
1946 
1947 	MPASS(td->td_realucred == td->td_ucred);
1948 	if (td->td_realucred == p->p_ucred)
1949 		return (NULL);
1950 
1951 	crnew = crcowget(p->p_ucred);
1952 	crold = crunuse(td);
1953 	td->td_realucred = crnew;
1954 	td->td_ucred = td->td_realucred;
1955 	return (crold);
1956 }
1957 
1958 /*
1959  * Batching.
1960  */
1961 void
1962 credbatch_add(struct credbatch *crb, struct thread *td)
1963 {
1964 	struct ucred *cr;
1965 
1966 	MPASS(td->td_realucred != NULL);
1967 	MPASS(td->td_realucred == td->td_ucred);
1968 	MPASS(TD_GET_STATE(td) == TDS_INACTIVE);
1969 	cr = td->td_realucred;
1970 	KASSERT(cr->cr_users > 0, ("%s: users %d not > 0 on cred %p",
1971 	    __func__, cr->cr_users, cr));
1972 	if (crb->cred != cr) {
1973 		if (crb->users > 0) {
1974 			MPASS(crb->cred != NULL);
1975 			crunusebatch(crb->cred, crb->users, crb->ref);
1976 			crb->users = 0;
1977 			crb->ref = 0;
1978 		}
1979 	}
1980 	crb->cred = cr;
1981 	crb->users++;
1982 	crb->ref += td->td_ucredref;
1983 	td->td_ucredref = 0;
1984 	td->td_realucred = NULL;
1985 }
1986 
1987 void
1988 credbatch_final(struct credbatch *crb)
1989 {
1990 
1991 	MPASS(crb->cred != NULL);
1992 	MPASS(crb->users > 0);
1993 	crunusebatch(crb->cred, crb->users, crb->ref);
1994 }
1995 
1996 /*
1997  * Allocate a zeroed cred structure.
1998  */
1999 struct ucred *
2000 crget(void)
2001 {
2002 	struct ucred *cr;
2003 
2004 	cr = malloc(sizeof(*cr), M_CRED, M_WAITOK | M_ZERO);
2005 	mtx_init(&cr->cr_mtx, "cred", NULL, MTX_DEF);
2006 	cr->cr_ref = 1;
2007 #ifdef AUDIT
2008 	audit_cred_init(cr);
2009 #endif
2010 #ifdef MAC
2011 	mac_cred_init(cr);
2012 #endif
2013 	cr->cr_groups = cr->cr_smallgroups;
2014 	cr->cr_agroups =
2015 	    sizeof(cr->cr_smallgroups) / sizeof(cr->cr_smallgroups[0]);
2016 	return (cr);
2017 }
2018 
2019 /*
2020  * Claim another reference to a ucred structure.
2021  */
2022 struct ucred *
2023 crhold(struct ucred *cr)
2024 {
2025 	struct thread *td;
2026 
2027 	td = curthread;
2028 	if (__predict_true(td->td_realucred == cr)) {
2029 		KASSERT(cr->cr_users > 0, ("%s: users %d not > 0 on cred %p",
2030 		    __func__, cr->cr_users, cr));
2031 		td->td_ucredref++;
2032 		return (cr);
2033 	}
2034 	mtx_lock(&cr->cr_mtx);
2035 	cr->cr_ref++;
2036 	mtx_unlock(&cr->cr_mtx);
2037 	return (cr);
2038 }
2039 
2040 /*
2041  * Free a cred structure.  Throws away space when ref count gets to 0.
2042  */
2043 void
2044 crfree(struct ucred *cr)
2045 {
2046 	struct thread *td;
2047 
2048 	td = curthread;
2049 	if (__predict_true(td->td_realucred == cr)) {
2050 		KASSERT(cr->cr_users > 0, ("%s: users %d not > 0 on cred %p",
2051 		    __func__, cr->cr_users, cr));
2052 		td->td_ucredref--;
2053 		return;
2054 	}
2055 	mtx_lock(&cr->cr_mtx);
2056 	KASSERT(cr->cr_users >= 0, ("%s: users %d not >= 0 on cred %p",
2057 	    __func__, cr->cr_users, cr));
2058 	cr->cr_ref--;
2059 	if (cr->cr_users > 0) {
2060 		mtx_unlock(&cr->cr_mtx);
2061 		return;
2062 	}
2063 	KASSERT(cr->cr_ref >= 0, ("%s: ref %ld not >= 0 on cred %p",
2064 	    __func__, cr->cr_ref, cr));
2065 	if (cr->cr_ref > 0) {
2066 		mtx_unlock(&cr->cr_mtx);
2067 		return;
2068 	}
2069 	crfree_final(cr);
2070 }
2071 
2072 static void
2073 crfree_final(struct ucred *cr)
2074 {
2075 
2076 	KASSERT(cr->cr_users == 0, ("%s: users %d not == 0 on cred %p",
2077 	    __func__, cr->cr_users, cr));
2078 	KASSERT(cr->cr_ref == 0, ("%s: ref %ld not == 0 on cred %p",
2079 	    __func__, cr->cr_ref, cr));
2080 
2081 	/*
2082 	 * Some callers of crget(), such as nfs_statfs(), allocate a temporary
2083 	 * credential, but don't allocate a uidinfo structure.
2084 	 */
2085 	if (cr->cr_uidinfo != NULL)
2086 		uifree(cr->cr_uidinfo);
2087 	if (cr->cr_ruidinfo != NULL)
2088 		uifree(cr->cr_ruidinfo);
2089 	if (cr->cr_prison != NULL)
2090 		prison_free(cr->cr_prison);
2091 	if (cr->cr_loginclass != NULL)
2092 		loginclass_free(cr->cr_loginclass);
2093 #ifdef AUDIT
2094 	audit_cred_destroy(cr);
2095 #endif
2096 #ifdef MAC
2097 	mac_cred_destroy(cr);
2098 #endif
2099 	mtx_destroy(&cr->cr_mtx);
2100 	if (cr->cr_groups != cr->cr_smallgroups)
2101 		free(cr->cr_groups, M_CRED);
2102 	free(cr, M_CRED);
2103 }
2104 
2105 /*
2106  * Copy a ucred's contents from a template.  Does not block.
2107  */
2108 void
2109 crcopy(struct ucred *dest, struct ucred *src)
2110 {
2111 
2112 	KASSERT(dest->cr_ref == 1, ("crcopy of shared ucred"));
2113 	bcopy(&src->cr_startcopy, &dest->cr_startcopy,
2114 	    (unsigned)((caddr_t)&src->cr_endcopy -
2115 		(caddr_t)&src->cr_startcopy));
2116 	dest->cr_flags = src->cr_flags;
2117 	crsetgroups(dest, src->cr_ngroups, src->cr_groups);
2118 	uihold(dest->cr_uidinfo);
2119 	uihold(dest->cr_ruidinfo);
2120 	prison_hold(dest->cr_prison);
2121 	loginclass_hold(dest->cr_loginclass);
2122 #ifdef AUDIT
2123 	audit_cred_copy(src, dest);
2124 #endif
2125 #ifdef MAC
2126 	mac_cred_copy(src, dest);
2127 #endif
2128 }
2129 
2130 /*
2131  * Dup cred struct to a new held one.
2132  */
2133 struct ucred *
2134 crdup(struct ucred *cr)
2135 {
2136 	struct ucred *newcr;
2137 
2138 	newcr = crget();
2139 	crcopy(newcr, cr);
2140 	return (newcr);
2141 }
2142 
2143 /*
2144  * Fill in a struct xucred based on a struct ucred.
2145  */
2146 void
2147 cru2x(struct ucred *cr, struct xucred *xcr)
2148 {
2149 	int ngroups;
2150 
2151 	bzero(xcr, sizeof(*xcr));
2152 	xcr->cr_version = XUCRED_VERSION;
2153 	xcr->cr_uid = cr->cr_uid;
2154 
2155 	ngroups = MIN(cr->cr_ngroups, XU_NGROUPS);
2156 	xcr->cr_ngroups = ngroups;
2157 	bcopy(cr->cr_groups, xcr->cr_groups,
2158 	    ngroups * sizeof(*cr->cr_groups));
2159 }
2160 
2161 void
2162 cru2xt(struct thread *td, struct xucred *xcr)
2163 {
2164 
2165 	cru2x(td->td_ucred, xcr);
2166 	xcr->cr_pid = td->td_proc->p_pid;
2167 }
2168 
2169 /*
2170  * Set initial process credentials.
2171  * Callers are responsible for providing the reference for provided credentials.
2172  */
2173 void
2174 proc_set_cred_init(struct proc *p, struct ucred *newcred)
2175 {
2176 
2177 	p->p_ucred = crcowget(newcred);
2178 }
2179 
2180 /*
2181  * Change process credentials.
2182  * Callers are responsible for providing the reference for passed credentials
2183  * and for freeing old ones.
2184  *
2185  * Process has to be locked except when it does not have credentials (as it
2186  * should not be visible just yet) or when newcred is NULL (as this can be
2187  * only used when the process is about to be freed, at which point it should
2188  * not be visible anymore).
2189  */
2190 void
2191 proc_set_cred(struct proc *p, struct ucred *newcred)
2192 {
2193 	struct ucred *cr;
2194 
2195 	cr = p->p_ucred;
2196 	MPASS(cr != NULL);
2197 	PROC_LOCK_ASSERT(p, MA_OWNED);
2198 	KASSERT(newcred->cr_users == 0, ("%s: users %d not 0 on cred %p",
2199 	    __func__, newcred->cr_users, newcred));
2200 	mtx_lock(&cr->cr_mtx);
2201 	KASSERT(cr->cr_users > 0, ("%s: users %d not > 0 on cred %p",
2202 	    __func__, cr->cr_users, cr));
2203 	cr->cr_users--;
2204 	mtx_unlock(&cr->cr_mtx);
2205 	p->p_ucred = newcred;
2206 	newcred->cr_users = 1;
2207 	PROC_UPDATE_COW(p);
2208 }
2209 
2210 void
2211 proc_unset_cred(struct proc *p)
2212 {
2213 	struct ucred *cr;
2214 
2215 	MPASS(p->p_state == PRS_ZOMBIE || p->p_state == PRS_NEW);
2216 	cr = p->p_ucred;
2217 	p->p_ucred = NULL;
2218 	KASSERT(cr->cr_users > 0, ("%s: users %d not > 0 on cred %p",
2219 	    __func__, cr->cr_users, cr));
2220 	mtx_lock(&cr->cr_mtx);
2221 	cr->cr_users--;
2222 	if (cr->cr_users == 0)
2223 		KASSERT(cr->cr_ref > 0, ("%s: ref %ld not > 0 on cred %p",
2224 		    __func__, cr->cr_ref, cr));
2225 	mtx_unlock(&cr->cr_mtx);
2226 	crfree(cr);
2227 }
2228 
2229 struct ucred *
2230 crcopysafe(struct proc *p, struct ucred *cr)
2231 {
2232 	struct ucred *oldcred;
2233 	int groups;
2234 
2235 	PROC_LOCK_ASSERT(p, MA_OWNED);
2236 
2237 	oldcred = p->p_ucred;
2238 	while (cr->cr_agroups < oldcred->cr_agroups) {
2239 		groups = oldcred->cr_agroups;
2240 		PROC_UNLOCK(p);
2241 		crextend(cr, groups);
2242 		PROC_LOCK(p);
2243 		oldcred = p->p_ucred;
2244 	}
2245 	crcopy(cr, oldcred);
2246 
2247 	return (oldcred);
2248 }
2249 
2250 /*
2251  * Extend the passed in credential to hold n items.
2252  */
2253 void
2254 crextend(struct ucred *cr, int n)
2255 {
2256 	int cnt;
2257 
2258 	/* Truncate? */
2259 	if (n <= cr->cr_agroups)
2260 		return;
2261 
2262 	/*
2263 	 * We extend by 2 each time since we're using a power of two
2264 	 * allocator until we need enough groups to fill a page.
2265 	 * Once we're allocating multiple pages, only allocate as many
2266 	 * as we actually need.  The case of processes needing a
2267 	 * non-power of two number of pages seems more likely than
2268 	 * a real world process that adds thousands of groups one at a
2269 	 * time.
2270 	 */
2271 	if ( n < PAGE_SIZE / sizeof(gid_t) ) {
2272 		if (cr->cr_agroups == 0)
2273 			cnt = MAX(1, MINALLOCSIZE / sizeof(gid_t));
2274 		else
2275 			cnt = cr->cr_agroups * 2;
2276 
2277 		while (cnt < n)
2278 			cnt *= 2;
2279 	} else
2280 		cnt = roundup2(n, PAGE_SIZE / sizeof(gid_t));
2281 
2282 	/* Free the old array. */
2283 	if (cr->cr_groups != cr->cr_smallgroups)
2284 		free(cr->cr_groups, M_CRED);
2285 
2286 	cr->cr_groups = malloc(cnt * sizeof(gid_t), M_CRED, M_WAITOK | M_ZERO);
2287 	cr->cr_agroups = cnt;
2288 }
2289 
2290 /*
2291  * Copy groups in to a credential, preserving any necessary invariants.
2292  * Currently this includes the sorting of all supplemental gids.
2293  * crextend() must have been called before hand to ensure sufficient
2294  * space is available.
2295  */
2296 static void
2297 crsetgroups_locked(struct ucred *cr, int ngrp, gid_t *groups)
2298 {
2299 	int i;
2300 	int j;
2301 	gid_t g;
2302 
2303 	KASSERT(cr->cr_agroups >= ngrp, ("cr_ngroups is too small"));
2304 
2305 	bcopy(groups, cr->cr_groups, ngrp * sizeof(gid_t));
2306 	cr->cr_ngroups = ngrp;
2307 
2308 	/*
2309 	 * Sort all groups except cr_groups[0] to allow groupmember to
2310 	 * perform a binary search.
2311 	 *
2312 	 * XXX: If large numbers of groups become common this should
2313 	 * be replaced with shell sort like linux uses or possibly
2314 	 * heap sort.
2315 	 */
2316 	for (i = 2; i < ngrp; i++) {
2317 		g = cr->cr_groups[i];
2318 		for (j = i-1; j >= 1 && g < cr->cr_groups[j]; j--)
2319 			cr->cr_groups[j + 1] = cr->cr_groups[j];
2320 		cr->cr_groups[j + 1] = g;
2321 	}
2322 }
2323 
2324 /*
2325  * Copy groups in to a credential after expanding it if required.
2326  * Truncate the list to (ngroups_max + 1) if it is too large.
2327  */
2328 void
2329 crsetgroups(struct ucred *cr, int ngrp, gid_t *groups)
2330 {
2331 
2332 	if (ngrp > ngroups_max + 1)
2333 		ngrp = ngroups_max + 1;
2334 
2335 	crextend(cr, ngrp);
2336 	crsetgroups_locked(cr, ngrp, groups);
2337 }
2338 
2339 /*
2340  * Get login name, if available.
2341  */
2342 #ifndef _SYS_SYSPROTO_H_
2343 struct getlogin_args {
2344 	char	*namebuf;
2345 	u_int	namelen;
2346 };
2347 #endif
2348 /* ARGSUSED */
2349 int
2350 sys_getlogin(struct thread *td, struct getlogin_args *uap)
2351 {
2352 	char login[MAXLOGNAME];
2353 	struct proc *p = td->td_proc;
2354 	size_t len;
2355 
2356 	if (uap->namelen > MAXLOGNAME)
2357 		uap->namelen = MAXLOGNAME;
2358 	PROC_LOCK(p);
2359 	SESS_LOCK(p->p_session);
2360 	len = strlcpy(login, p->p_session->s_login, uap->namelen) + 1;
2361 	SESS_UNLOCK(p->p_session);
2362 	PROC_UNLOCK(p);
2363 	if (len > uap->namelen)
2364 		return (ERANGE);
2365 	return (copyout(login, uap->namebuf, len));
2366 }
2367 
2368 /*
2369  * Set login name.
2370  */
2371 #ifndef _SYS_SYSPROTO_H_
2372 struct setlogin_args {
2373 	char	*namebuf;
2374 };
2375 #endif
2376 /* ARGSUSED */
2377 int
2378 sys_setlogin(struct thread *td, struct setlogin_args *uap)
2379 {
2380 	struct proc *p = td->td_proc;
2381 	int error;
2382 	char logintmp[MAXLOGNAME];
2383 
2384 	CTASSERT(sizeof(p->p_session->s_login) >= sizeof(logintmp));
2385 
2386 	error = priv_check(td, PRIV_PROC_SETLOGIN);
2387 	if (error)
2388 		return (error);
2389 	error = copyinstr(uap->namebuf, logintmp, sizeof(logintmp), NULL);
2390 	if (error != 0) {
2391 		if (error == ENAMETOOLONG)
2392 			error = EINVAL;
2393 		return (error);
2394 	}
2395 	AUDIT_ARG_LOGIN(logintmp);
2396 	PROC_LOCK(p);
2397 	SESS_LOCK(p->p_session);
2398 	strcpy(p->p_session->s_login, logintmp);
2399 	SESS_UNLOCK(p->p_session);
2400 	PROC_UNLOCK(p);
2401 	return (0);
2402 }
2403 
2404 void
2405 setsugid(struct proc *p)
2406 {
2407 
2408 	PROC_LOCK_ASSERT(p, MA_OWNED);
2409 	p->p_flag |= P_SUGID;
2410 }
2411 
2412 /*-
2413  * Change a process's effective uid.
2414  * Side effects: newcred->cr_uid and newcred->cr_uidinfo will be modified.
2415  * References: newcred must be an exclusive credential reference for the
2416  *             duration of the call.
2417  */
2418 void
2419 change_euid(struct ucred *newcred, struct uidinfo *euip)
2420 {
2421 
2422 	newcred->cr_uid = euip->ui_uid;
2423 	uihold(euip);
2424 	uifree(newcred->cr_uidinfo);
2425 	newcred->cr_uidinfo = euip;
2426 }
2427 
2428 /*-
2429  * Change a process's effective gid.
2430  * Side effects: newcred->cr_gid will be modified.
2431  * References: newcred must be an exclusive credential reference for the
2432  *             duration of the call.
2433  */
2434 void
2435 change_egid(struct ucred *newcred, gid_t egid)
2436 {
2437 
2438 	newcred->cr_groups[0] = egid;
2439 }
2440 
2441 /*-
2442  * Change a process's real uid.
2443  * Side effects: newcred->cr_ruid will be updated, newcred->cr_ruidinfo
2444  *               will be updated, and the old and new cr_ruidinfo proc
2445  *               counts will be updated.
2446  * References: newcred must be an exclusive credential reference for the
2447  *             duration of the call.
2448  */
2449 void
2450 change_ruid(struct ucred *newcred, struct uidinfo *ruip)
2451 {
2452 
2453 	(void)chgproccnt(newcred->cr_ruidinfo, -1, 0);
2454 	newcred->cr_ruid = ruip->ui_uid;
2455 	uihold(ruip);
2456 	uifree(newcred->cr_ruidinfo);
2457 	newcred->cr_ruidinfo = ruip;
2458 	(void)chgproccnt(newcred->cr_ruidinfo, 1, 0);
2459 }
2460 
2461 /*-
2462  * Change a process's real gid.
2463  * Side effects: newcred->cr_rgid will be updated.
2464  * References: newcred must be an exclusive credential reference for the
2465  *             duration of the call.
2466  */
2467 void
2468 change_rgid(struct ucred *newcred, gid_t rgid)
2469 {
2470 
2471 	newcred->cr_rgid = rgid;
2472 }
2473 
2474 /*-
2475  * Change a process's saved uid.
2476  * Side effects: newcred->cr_svuid will be updated.
2477  * References: newcred must be an exclusive credential reference for the
2478  *             duration of the call.
2479  */
2480 void
2481 change_svuid(struct ucred *newcred, uid_t svuid)
2482 {
2483 
2484 	newcred->cr_svuid = svuid;
2485 }
2486 
2487 /*-
2488  * Change a process's saved gid.
2489  * Side effects: newcred->cr_svgid will be updated.
2490  * References: newcred must be an exclusive credential reference for the
2491  *             duration of the call.
2492  */
2493 void
2494 change_svgid(struct ucred *newcred, gid_t svgid)
2495 {
2496 
2497 	newcred->cr_svgid = svgid;
2498 }
2499 
2500 bool allow_ptrace = true;
2501 SYSCTL_BOOL(_security_bsd, OID_AUTO, allow_ptrace, CTLFLAG_RWTUN,
2502     &allow_ptrace, 0,
2503     "Deny ptrace(2) use by returning ENOSYS");
2504