xref: /freebsd/sys/kern/kern_prot.c (revision e17f5b1d)
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  * Credential management.
1845  *
1846  * struct ucred objects are rarely allocated but gain and lose references all
1847  * the time (e.g., on struct file alloc/dealloc) turning refcount updates into
1848  * a significant source of cache-line ping ponging. Common cases are worked
1849  * around by modifying thread-local counter instead if the cred to operate on
1850  * matches td_realucred.
1851  *
1852  * The counter is split into 2 parts:
1853  * - cr_users -- total count of all struct proc and struct thread objects
1854  *   which have given cred in p_ucred and td_ucred respectively
1855  * - cr_ref -- the actual ref count, only valid if cr_users == 0
1856  *
1857  * If users == 0 then cr_ref behaves similarly to refcount(9), in particular if
1858  * the count reaches 0 the object is freeable.
1859  * If users > 0 and curthread->td_realucred == cred, then updates are performed
1860  * against td_ucredref.
1861  * In other cases updates are performed against cr_ref.
1862  *
1863  * Changing td_realucred into something else decrements cr_users and transfers
1864  * accumulated updates.
1865  */
1866 struct ucred *
1867 crcowget(struct ucred *cr)
1868 {
1869 
1870 	mtx_lock(&cr->cr_mtx);
1871 	KASSERT(cr->cr_users > 0, ("%s: users %d not > 0 on cred %p",
1872 	    __func__, cr->cr_users, cr));
1873 	cr->cr_users++;
1874 	cr->cr_ref++;
1875 	mtx_unlock(&cr->cr_mtx);
1876 	return (cr);
1877 }
1878 
1879 static struct ucred *
1880 crunuse(struct thread *td)
1881 {
1882 	struct ucred *cr, *crold;
1883 
1884 	cr = td->td_ucred;
1885 	mtx_lock(&cr->cr_mtx);
1886 	cr->cr_ref += td->td_ucredref;
1887 	td->td_ucredref = 0;
1888 	KASSERT(cr->cr_users > 0, ("%s: users %d not > 0 on cred %p",
1889 	    __func__, cr->cr_users, cr));
1890 	cr->cr_users--;
1891 	if (cr->cr_users == 0) {
1892 		KASSERT(cr->cr_ref > 0, ("%s: ref %d not > 0 on cred %p",
1893 		    __func__, cr->cr_ref, cr));
1894 		crold = cr;
1895 	} else {
1896 		cr->cr_ref--;
1897 		crold = NULL;
1898 	}
1899 	mtx_unlock(&cr->cr_mtx);
1900 	return (crold);
1901 }
1902 
1903 void
1904 crcowfree(struct thread *td)
1905 {
1906 	struct ucred *cr;
1907 
1908 	cr = crunuse(td);
1909 	if (cr != NULL)
1910 		crfree(cr);
1911 }
1912 
1913 struct ucred *
1914 crcowsync(void)
1915 {
1916 	struct thread *td;
1917 	struct proc *p;
1918 	struct ucred *crnew, *crold;
1919 
1920 	td = curthread;
1921 	p = td->td_proc;
1922 	PROC_LOCK_ASSERT(p, MA_OWNED);
1923 
1924 	MPASS(td->td_realucred == td->td_ucred);
1925 	if (td->td_realucred == p->p_ucred)
1926 		return (NULL);
1927 
1928 	crnew = crcowget(p->p_ucred);
1929 	crold = crunuse(td);
1930 	td->td_realucred = crnew;
1931 	td->td_ucred = td->td_realucred;
1932 	return (crold);
1933 }
1934 
1935 /*
1936  * Allocate a zeroed cred structure.
1937  */
1938 struct ucred *
1939 crget(void)
1940 {
1941 	struct ucred *cr;
1942 
1943 	cr = malloc(sizeof(*cr), M_CRED, M_WAITOK | M_ZERO);
1944 	mtx_init(&cr->cr_mtx, "cred", NULL, MTX_DEF);
1945 	cr->cr_ref = 1;
1946 #ifdef AUDIT
1947 	audit_cred_init(cr);
1948 #endif
1949 #ifdef MAC
1950 	mac_cred_init(cr);
1951 #endif
1952 	cr->cr_groups = cr->cr_smallgroups;
1953 	cr->cr_agroups =
1954 	    sizeof(cr->cr_smallgroups) / sizeof(cr->cr_smallgroups[0]);
1955 	return (cr);
1956 }
1957 
1958 /*
1959  * Claim another reference to a ucred structure.
1960  */
1961 struct ucred *
1962 crhold(struct ucred *cr)
1963 {
1964 	struct thread *td;
1965 
1966 	td = curthread;
1967 	if (__predict_true(td->td_realucred == cr)) {
1968 		KASSERT(cr->cr_users > 0, ("%s: users %d not > 0 on cred %p",
1969 		    __func__, cr->cr_users, cr));
1970 		td->td_ucredref++;
1971 		return (cr);
1972 	}
1973 	mtx_lock(&cr->cr_mtx);
1974 	cr->cr_ref++;
1975 	mtx_unlock(&cr->cr_mtx);
1976 	return (cr);
1977 }
1978 
1979 /*
1980  * Free a cred structure.  Throws away space when ref count gets to 0.
1981  */
1982 void
1983 crfree(struct ucred *cr)
1984 {
1985 	struct thread *td;
1986 
1987 	td = curthread;
1988 	if (__predict_true(td->td_realucred == cr)) {
1989 		KASSERT(cr->cr_users > 0, ("%s: users %d not > 0 on cred %p",
1990 		    __func__, cr->cr_users, cr));
1991 		td->td_ucredref--;
1992 		return;
1993 	}
1994 	mtx_lock(&cr->cr_mtx);
1995 	KASSERT(cr->cr_users >= 0, ("%s: users %d not >= 0 on cred %p",
1996 	    __func__, cr->cr_users, cr));
1997 	cr->cr_ref--;
1998 	if (cr->cr_users > 0) {
1999 		mtx_unlock(&cr->cr_mtx);
2000 		return;
2001 	}
2002 	KASSERT(cr->cr_ref >= 0, ("%s: ref %d not >= 0 on cred %p",
2003 	    __func__, cr->cr_ref, cr));
2004 	if (cr->cr_ref > 0) {
2005 		mtx_unlock(&cr->cr_mtx);
2006 		return;
2007 	}
2008 	/*
2009 	 * Some callers of crget(), such as nfs_statfs(), allocate a temporary
2010 	 * credential, but don't allocate a uidinfo structure.
2011 	 */
2012 	if (cr->cr_uidinfo != NULL)
2013 		uifree(cr->cr_uidinfo);
2014 	if (cr->cr_ruidinfo != NULL)
2015 		uifree(cr->cr_ruidinfo);
2016 	if (cr->cr_prison != NULL)
2017 		prison_free(cr->cr_prison);
2018 	if (cr->cr_loginclass != NULL)
2019 		loginclass_free(cr->cr_loginclass);
2020 #ifdef AUDIT
2021 	audit_cred_destroy(cr);
2022 #endif
2023 #ifdef MAC
2024 	mac_cred_destroy(cr);
2025 #endif
2026 	mtx_destroy(&cr->cr_mtx);
2027 	if (cr->cr_groups != cr->cr_smallgroups)
2028 		free(cr->cr_groups, M_CRED);
2029 	free(cr, M_CRED);
2030 }
2031 
2032 /*
2033  * Copy a ucred's contents from a template.  Does not block.
2034  */
2035 void
2036 crcopy(struct ucred *dest, struct ucred *src)
2037 {
2038 
2039 	KASSERT(dest->cr_ref == 1, ("crcopy of shared ucred"));
2040 	bcopy(&src->cr_startcopy, &dest->cr_startcopy,
2041 	    (unsigned)((caddr_t)&src->cr_endcopy -
2042 		(caddr_t)&src->cr_startcopy));
2043 	crsetgroups(dest, src->cr_ngroups, src->cr_groups);
2044 	uihold(dest->cr_uidinfo);
2045 	uihold(dest->cr_ruidinfo);
2046 	prison_hold(dest->cr_prison);
2047 	loginclass_hold(dest->cr_loginclass);
2048 #ifdef AUDIT
2049 	audit_cred_copy(src, dest);
2050 #endif
2051 #ifdef MAC
2052 	mac_cred_copy(src, dest);
2053 #endif
2054 }
2055 
2056 /*
2057  * Dup cred struct to a new held one.
2058  */
2059 struct ucred *
2060 crdup(struct ucred *cr)
2061 {
2062 	struct ucred *newcr;
2063 
2064 	newcr = crget();
2065 	crcopy(newcr, cr);
2066 	return (newcr);
2067 }
2068 
2069 /*
2070  * Fill in a struct xucred based on a struct ucred.
2071  */
2072 void
2073 cru2x(struct ucred *cr, struct xucred *xcr)
2074 {
2075 	int ngroups;
2076 
2077 	bzero(xcr, sizeof(*xcr));
2078 	xcr->cr_version = XUCRED_VERSION;
2079 	xcr->cr_uid = cr->cr_uid;
2080 
2081 	ngroups = MIN(cr->cr_ngroups, XU_NGROUPS);
2082 	xcr->cr_ngroups = ngroups;
2083 	bcopy(cr->cr_groups, xcr->cr_groups,
2084 	    ngroups * sizeof(*cr->cr_groups));
2085 }
2086 
2087 void
2088 cru2xt(struct thread *td, struct xucred *xcr)
2089 {
2090 
2091 	cru2x(td->td_ucred, xcr);
2092 	xcr->cr_pid = td->td_proc->p_pid;
2093 }
2094 
2095 /*
2096  * Set initial process credentials.
2097  * Callers are responsible for providing the reference for provided credentials.
2098  */
2099 void
2100 proc_set_cred_init(struct proc *p, struct ucred *newcred)
2101 {
2102 
2103 	p->p_ucred = crcowget(newcred);
2104 }
2105 
2106 /*
2107  * Change process credentials.
2108  * Callers are responsible for providing the reference for passed credentials
2109  * and for freeing old ones.
2110  *
2111  * Process has to be locked except when it does not have credentials (as it
2112  * should not be visible just yet) or when newcred is NULL (as this can be
2113  * only used when the process is about to be freed, at which point it should
2114  * not be visible anymore).
2115  */
2116 void
2117 proc_set_cred(struct proc *p, struct ucred *newcred)
2118 {
2119 	struct ucred *cr;
2120 
2121 	cr = p->p_ucred;
2122 	MPASS(cr != NULL);
2123 	PROC_LOCK_ASSERT(p, MA_OWNED);
2124 	KASSERT(newcred->cr_users == 0, ("%s: users %d not 0 on cred %p",
2125 	    __func__, newcred->cr_users, newcred));
2126 	mtx_lock(&cr->cr_mtx);
2127 	KASSERT(cr->cr_users > 0, ("%s: users %d not > 0 on cred %p",
2128 	    __func__, cr->cr_users, cr));
2129 	cr->cr_users--;
2130 	mtx_unlock(&cr->cr_mtx);
2131 	p->p_ucred = newcred;
2132 	newcred->cr_users = 1;
2133 	PROC_UPDATE_COW(p);
2134 }
2135 
2136 void
2137 proc_unset_cred(struct proc *p)
2138 {
2139 	struct ucred *cr;
2140 
2141 	MPASS(p->p_state == PRS_ZOMBIE || p->p_state == PRS_NEW);
2142 	cr = p->p_ucred;
2143 	p->p_ucred = NULL;
2144 	KASSERT(cr->cr_users > 0, ("%s: users %d not > 0 on cred %p",
2145 	    __func__, cr->cr_users, cr));
2146 	mtx_lock(&cr->cr_mtx);
2147 	cr->cr_users--;
2148 	if (cr->cr_users == 0)
2149 		KASSERT(cr->cr_ref > 0, ("%s: ref %d not > 0 on cred %p",
2150 		    __func__, cr->cr_ref, cr));
2151 	mtx_unlock(&cr->cr_mtx);
2152 	crfree(cr);
2153 }
2154 
2155 struct ucred *
2156 crcopysafe(struct proc *p, struct ucred *cr)
2157 {
2158 	struct ucred *oldcred;
2159 	int groups;
2160 
2161 	PROC_LOCK_ASSERT(p, MA_OWNED);
2162 
2163 	oldcred = p->p_ucred;
2164 	while (cr->cr_agroups < oldcred->cr_agroups) {
2165 		groups = oldcred->cr_agroups;
2166 		PROC_UNLOCK(p);
2167 		crextend(cr, groups);
2168 		PROC_LOCK(p);
2169 		oldcred = p->p_ucred;
2170 	}
2171 	crcopy(cr, oldcred);
2172 
2173 	return (oldcred);
2174 }
2175 
2176 /*
2177  * Extend the passed in credential to hold n items.
2178  */
2179 void
2180 crextend(struct ucred *cr, int n)
2181 {
2182 	int cnt;
2183 
2184 	/* Truncate? */
2185 	if (n <= cr->cr_agroups)
2186 		return;
2187 
2188 	/*
2189 	 * We extend by 2 each time since we're using a power of two
2190 	 * allocator until we need enough groups to fill a page.
2191 	 * Once we're allocating multiple pages, only allocate as many
2192 	 * as we actually need.  The case of processes needing a
2193 	 * non-power of two number of pages seems more likely than
2194 	 * a real world process that adds thousands of groups one at a
2195 	 * time.
2196 	 */
2197 	if ( n < PAGE_SIZE / sizeof(gid_t) ) {
2198 		if (cr->cr_agroups == 0)
2199 			cnt = MAX(1, MINALLOCSIZE / sizeof(gid_t));
2200 		else
2201 			cnt = cr->cr_agroups * 2;
2202 
2203 		while (cnt < n)
2204 			cnt *= 2;
2205 	} else
2206 		cnt = roundup2(n, PAGE_SIZE / sizeof(gid_t));
2207 
2208 	/* Free the old array. */
2209 	if (cr->cr_groups != cr->cr_smallgroups)
2210 		free(cr->cr_groups, M_CRED);
2211 
2212 	cr->cr_groups = malloc(cnt * sizeof(gid_t), M_CRED, M_WAITOK | M_ZERO);
2213 	cr->cr_agroups = cnt;
2214 }
2215 
2216 /*
2217  * Copy groups in to a credential, preserving any necessary invariants.
2218  * Currently this includes the sorting of all supplemental gids.
2219  * crextend() must have been called before hand to ensure sufficient
2220  * space is available.
2221  */
2222 static void
2223 crsetgroups_locked(struct ucred *cr, int ngrp, gid_t *groups)
2224 {
2225 	int i;
2226 	int j;
2227 	gid_t g;
2228 
2229 	KASSERT(cr->cr_agroups >= ngrp, ("cr_ngroups is too small"));
2230 
2231 	bcopy(groups, cr->cr_groups, ngrp * sizeof(gid_t));
2232 	cr->cr_ngroups = ngrp;
2233 
2234 	/*
2235 	 * Sort all groups except cr_groups[0] to allow groupmember to
2236 	 * perform a binary search.
2237 	 *
2238 	 * XXX: If large numbers of groups become common this should
2239 	 * be replaced with shell sort like linux uses or possibly
2240 	 * heap sort.
2241 	 */
2242 	for (i = 2; i < ngrp; i++) {
2243 		g = cr->cr_groups[i];
2244 		for (j = i-1; j >= 1 && g < cr->cr_groups[j]; j--)
2245 			cr->cr_groups[j + 1] = cr->cr_groups[j];
2246 		cr->cr_groups[j + 1] = g;
2247 	}
2248 }
2249 
2250 /*
2251  * Copy groups in to a credential after expanding it if required.
2252  * Truncate the list to (ngroups_max + 1) if it is too large.
2253  */
2254 void
2255 crsetgroups(struct ucred *cr, int ngrp, gid_t *groups)
2256 {
2257 
2258 	if (ngrp > ngroups_max + 1)
2259 		ngrp = ngroups_max + 1;
2260 
2261 	crextend(cr, ngrp);
2262 	crsetgroups_locked(cr, ngrp, groups);
2263 }
2264 
2265 /*
2266  * Get login name, if available.
2267  */
2268 #ifndef _SYS_SYSPROTO_H_
2269 struct getlogin_args {
2270 	char	*namebuf;
2271 	u_int	namelen;
2272 };
2273 #endif
2274 /* ARGSUSED */
2275 int
2276 sys_getlogin(struct thread *td, struct getlogin_args *uap)
2277 {
2278 	char login[MAXLOGNAME];
2279 	struct proc *p = td->td_proc;
2280 	size_t len;
2281 
2282 	if (uap->namelen > MAXLOGNAME)
2283 		uap->namelen = MAXLOGNAME;
2284 	PROC_LOCK(p);
2285 	SESS_LOCK(p->p_session);
2286 	len = strlcpy(login, p->p_session->s_login, uap->namelen) + 1;
2287 	SESS_UNLOCK(p->p_session);
2288 	PROC_UNLOCK(p);
2289 	if (len > uap->namelen)
2290 		return (ERANGE);
2291 	return (copyout(login, uap->namebuf, len));
2292 }
2293 
2294 /*
2295  * Set login name.
2296  */
2297 #ifndef _SYS_SYSPROTO_H_
2298 struct setlogin_args {
2299 	char	*namebuf;
2300 };
2301 #endif
2302 /* ARGSUSED */
2303 int
2304 sys_setlogin(struct thread *td, struct setlogin_args *uap)
2305 {
2306 	struct proc *p = td->td_proc;
2307 	int error;
2308 	char logintmp[MAXLOGNAME];
2309 
2310 	CTASSERT(sizeof(p->p_session->s_login) >= sizeof(logintmp));
2311 
2312 	error = priv_check(td, PRIV_PROC_SETLOGIN);
2313 	if (error)
2314 		return (error);
2315 	error = copyinstr(uap->namebuf, logintmp, sizeof(logintmp), NULL);
2316 	if (error != 0) {
2317 		if (error == ENAMETOOLONG)
2318 			error = EINVAL;
2319 		return (error);
2320 	}
2321 	AUDIT_ARG_LOGIN(logintmp);
2322 	PROC_LOCK(p);
2323 	SESS_LOCK(p->p_session);
2324 	strcpy(p->p_session->s_login, logintmp);
2325 	SESS_UNLOCK(p->p_session);
2326 	PROC_UNLOCK(p);
2327 	return (0);
2328 }
2329 
2330 void
2331 setsugid(struct proc *p)
2332 {
2333 
2334 	PROC_LOCK_ASSERT(p, MA_OWNED);
2335 	p->p_flag |= P_SUGID;
2336 }
2337 
2338 /*-
2339  * Change a process's effective uid.
2340  * Side effects: newcred->cr_uid and newcred->cr_uidinfo will be modified.
2341  * References: newcred must be an exclusive credential reference for the
2342  *             duration of the call.
2343  */
2344 void
2345 change_euid(struct ucred *newcred, struct uidinfo *euip)
2346 {
2347 
2348 	newcred->cr_uid = euip->ui_uid;
2349 	uihold(euip);
2350 	uifree(newcred->cr_uidinfo);
2351 	newcred->cr_uidinfo = euip;
2352 }
2353 
2354 /*-
2355  * Change a process's effective gid.
2356  * Side effects: newcred->cr_gid will be modified.
2357  * References: newcred must be an exclusive credential reference for the
2358  *             duration of the call.
2359  */
2360 void
2361 change_egid(struct ucred *newcred, gid_t egid)
2362 {
2363 
2364 	newcred->cr_groups[0] = egid;
2365 }
2366 
2367 /*-
2368  * Change a process's real uid.
2369  * Side effects: newcred->cr_ruid will be updated, newcred->cr_ruidinfo
2370  *               will be updated, and the old and new cr_ruidinfo proc
2371  *               counts will be updated.
2372  * References: newcred must be an exclusive credential reference for the
2373  *             duration of the call.
2374  */
2375 void
2376 change_ruid(struct ucred *newcred, struct uidinfo *ruip)
2377 {
2378 
2379 	(void)chgproccnt(newcred->cr_ruidinfo, -1, 0);
2380 	newcred->cr_ruid = ruip->ui_uid;
2381 	uihold(ruip);
2382 	uifree(newcred->cr_ruidinfo);
2383 	newcred->cr_ruidinfo = ruip;
2384 	(void)chgproccnt(newcred->cr_ruidinfo, 1, 0);
2385 }
2386 
2387 /*-
2388  * Change a process's real gid.
2389  * Side effects: newcred->cr_rgid will be updated.
2390  * References: newcred must be an exclusive credential reference for the
2391  *             duration of the call.
2392  */
2393 void
2394 change_rgid(struct ucred *newcred, gid_t rgid)
2395 {
2396 
2397 	newcred->cr_rgid = rgid;
2398 }
2399 
2400 /*-
2401  * Change a process's saved uid.
2402  * Side effects: newcred->cr_svuid will be updated.
2403  * References: newcred must be an exclusive credential reference for the
2404  *             duration of the call.
2405  */
2406 void
2407 change_svuid(struct ucred *newcred, uid_t svuid)
2408 {
2409 
2410 	newcred->cr_svuid = svuid;
2411 }
2412 
2413 /*-
2414  * Change a process's saved gid.
2415  * Side effects: newcred->cr_svgid will be updated.
2416  * References: newcred must be an exclusive credential reference for the
2417  *             duration of the call.
2418  */
2419 void
2420 change_svgid(struct ucred *newcred, gid_t svgid)
2421 {
2422 
2423 	newcred->cr_svgid = svgid;
2424 }
2425