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