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