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