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