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