xref: /freebsd/sys/kern/kern_prot.c (revision 4cd93df95e697942adf0ff038fc8f357cbb07cf9)
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 
40 /*
41  * System calls related to processes and protection
42  */
43 
44 #include <sys/cdefs.h>
45 #include "opt_inet.h"
46 #include "opt_inet6.h"
47 
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/abi_compat.h>
51 #include <sys/acct.h>
52 #include <sys/kdb.h>
53 #include <sys/kernel.h>
54 #include <sys/libkern.h>
55 #include <sys/lock.h>
56 #include <sys/loginclass.h>
57 #include <sys/malloc.h>
58 #include <sys/mutex.h>
59 #include <sys/ptrace.h>
60 #include <sys/refcount.h>
61 #include <sys/sx.h>
62 #include <sys/priv.h>
63 #include <sys/proc.h>
64 #ifdef COMPAT_43
65 #include <sys/sysent.h>
66 #endif
67 #include <sys/sysproto.h>
68 #include <sys/jail.h>
69 #include <sys/racct.h>
70 #include <sys/rctl.h>
71 #include <sys/resourcevar.h>
72 #include <sys/socket.h>
73 #include <sys/socketvar.h>
74 #include <sys/syscallsubr.h>
75 #include <sys/sysctl.h>
76 
77 #ifdef MAC
78 #include <security/mac/mac_syscalls.h>
79 #endif
80 
81 #include <vm/uma.h>
82 
83 #ifdef REGRESSION
84 FEATURE(regression,
85     "Kernel support for interfaces necessary for regression testing (SECURITY RISK!)");
86 #endif
87 
88 #include <security/audit/audit.h>
89 #include <security/mac/mac_framework.h>
90 
91 static MALLOC_DEFINE(M_CRED, "cred", "credentials");
92 
93 SYSCTL_NODE(_security, OID_AUTO, bsd, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
94     "BSD security policy");
95 
96 static void crfree_final(struct ucred *cr);
97 
98 static inline void
groups_check_positive_len(int ngrp)99 groups_check_positive_len(int ngrp)
100 {
101 	MPASS2(ngrp >= 0, "negative number of groups");
102 }
103 static inline void
groups_check_max_len(int ngrp)104 groups_check_max_len(int ngrp)
105 {
106 	MPASS2(ngrp <= ngroups_max, "too many supplementary groups");
107 }
108 
109 static void groups_normalize(int *ngrp, gid_t *groups);
110 static void crsetgroups_internal(struct ucred *cr, int ngrp,
111     const gid_t *groups);
112 
113 static int cr_canseeotheruids(struct ucred *u1, struct ucred *u2);
114 static int cr_canseeothergids(struct ucred *u1, struct ucred *u2);
115 static int cr_canseejailproc(struct ucred *u1, struct ucred *u2);
116 
117 #ifndef _SYS_SYSPROTO_H_
118 struct getpid_args {
119 	int	dummy;
120 };
121 #endif
122 /* ARGSUSED */
123 int
sys_getpid(struct thread * td,struct getpid_args * uap)124 sys_getpid(struct thread *td, struct getpid_args *uap)
125 {
126 	struct proc *p = td->td_proc;
127 
128 	td->td_retval[0] = p->p_pid;
129 #if defined(COMPAT_43)
130 	if (SV_PROC_FLAG(p, SV_AOUT))
131 		td->td_retval[1] = kern_getppid(td);
132 #endif
133 	return (0);
134 }
135 
136 #ifndef _SYS_SYSPROTO_H_
137 struct getppid_args {
138         int     dummy;
139 };
140 #endif
141 /* ARGSUSED */
142 int
sys_getppid(struct thread * td,struct getppid_args * uap)143 sys_getppid(struct thread *td, struct getppid_args *uap)
144 {
145 
146 	td->td_retval[0] = kern_getppid(td);
147 	return (0);
148 }
149 
150 int
kern_getppid(struct thread * td)151 kern_getppid(struct thread *td)
152 {
153 	struct proc *p = td->td_proc;
154 
155 	return (p->p_oppid);
156 }
157 
158 /*
159  * Get process group ID; note that POSIX getpgrp takes no parameter.
160  */
161 #ifndef _SYS_SYSPROTO_H_
162 struct getpgrp_args {
163         int     dummy;
164 };
165 #endif
166 int
sys_getpgrp(struct thread * td,struct getpgrp_args * uap)167 sys_getpgrp(struct thread *td, struct getpgrp_args *uap)
168 {
169 	struct proc *p = td->td_proc;
170 
171 	PROC_LOCK(p);
172 	td->td_retval[0] = p->p_pgrp->pg_id;
173 	PROC_UNLOCK(p);
174 	return (0);
175 }
176 
177 /* Get an arbitrary pid's process group id */
178 #ifndef _SYS_SYSPROTO_H_
179 struct getpgid_args {
180 	pid_t	pid;
181 };
182 #endif
183 int
sys_getpgid(struct thread * td,struct getpgid_args * uap)184 sys_getpgid(struct thread *td, struct getpgid_args *uap)
185 {
186 	struct proc *p;
187 	int error;
188 
189 	if (uap->pid == 0) {
190 		p = td->td_proc;
191 		PROC_LOCK(p);
192 	} else {
193 		p = pfind(uap->pid);
194 		if (p == NULL)
195 			return (ESRCH);
196 		error = p_cansee(td, p);
197 		if (error) {
198 			PROC_UNLOCK(p);
199 			return (error);
200 		}
201 	}
202 	td->td_retval[0] = p->p_pgrp->pg_id;
203 	PROC_UNLOCK(p);
204 	return (0);
205 }
206 
207 /*
208  * Get an arbitrary pid's session id.
209  */
210 #ifndef _SYS_SYSPROTO_H_
211 struct getsid_args {
212 	pid_t	pid;
213 };
214 #endif
215 int
sys_getsid(struct thread * td,struct getsid_args * uap)216 sys_getsid(struct thread *td, struct getsid_args *uap)
217 {
218 
219 	return (kern_getsid(td, uap->pid));
220 }
221 
222 int
kern_getsid(struct thread * td,pid_t pid)223 kern_getsid(struct thread *td, pid_t pid)
224 {
225 	struct proc *p;
226 	int error;
227 
228 	if (pid == 0) {
229 		p = td->td_proc;
230 		PROC_LOCK(p);
231 	} else {
232 		p = pfind(pid);
233 		if (p == NULL)
234 			return (ESRCH);
235 		error = p_cansee(td, p);
236 		if (error) {
237 			PROC_UNLOCK(p);
238 			return (error);
239 		}
240 	}
241 	td->td_retval[0] = p->p_session->s_sid;
242 	PROC_UNLOCK(p);
243 	return (0);
244 }
245 
246 #ifndef _SYS_SYSPROTO_H_
247 struct getuid_args {
248         int     dummy;
249 };
250 #endif
251 /* ARGSUSED */
252 int
sys_getuid(struct thread * td,struct getuid_args * uap)253 sys_getuid(struct thread *td, struct getuid_args *uap)
254 {
255 
256 	td->td_retval[0] = td->td_ucred->cr_ruid;
257 #if defined(COMPAT_43)
258 	td->td_retval[1] = td->td_ucred->cr_uid;
259 #endif
260 	return (0);
261 }
262 
263 #ifndef _SYS_SYSPROTO_H_
264 struct geteuid_args {
265         int     dummy;
266 };
267 #endif
268 /* ARGSUSED */
269 int
sys_geteuid(struct thread * td,struct geteuid_args * uap)270 sys_geteuid(struct thread *td, struct geteuid_args *uap)
271 {
272 
273 	td->td_retval[0] = td->td_ucred->cr_uid;
274 	return (0);
275 }
276 
277 #ifndef _SYS_SYSPROTO_H_
278 struct getgid_args {
279         int     dummy;
280 };
281 #endif
282 /* ARGSUSED */
283 int
sys_getgid(struct thread * td,struct getgid_args * uap)284 sys_getgid(struct thread *td, struct getgid_args *uap)
285 {
286 
287 	td->td_retval[0] = td->td_ucred->cr_rgid;
288 #if defined(COMPAT_43)
289 	td->td_retval[1] = td->td_ucred->cr_gid;
290 #endif
291 	return (0);
292 }
293 
294 #ifndef _SYS_SYSPROTO_H_
295 struct getegid_args {
296         int     dummy;
297 };
298 #endif
299 /* ARGSUSED */
300 int
sys_getegid(struct thread * td,struct getegid_args * uap)301 sys_getegid(struct thread *td, struct getegid_args *uap)
302 {
303 
304 	td->td_retval[0] = td->td_ucred->cr_gid;
305 	return (0);
306 }
307 
308 #ifdef COMPAT_FREEBSD14
309 int
freebsd14_getgroups(struct thread * td,struct freebsd14_getgroups_args * uap)310 freebsd14_getgroups(struct thread *td, struct freebsd14_getgroups_args *uap)
311 {
312 	struct ucred *cred;
313 	int ngrp, error;
314 
315 	cred = td->td_ucred;
316 
317 	/*
318 	 * For FreeBSD < 15.0, we account for the egid being placed at the
319 	 * beginning of the group list prior to all supplementary groups.
320 	 */
321 	ngrp = cred->cr_ngroups + 1;
322 	if (uap->gidsetsize == 0) {
323 		error = 0;
324 		goto out;
325 	} else if (uap->gidsetsize < ngrp) {
326 		return (EINVAL);
327 	}
328 
329 	error = copyout(&cred->cr_gid, uap->gidset, sizeof(gid_t));
330 	if (error == 0)
331 		error = copyout(cred->cr_groups, uap->gidset + 1,
332 		    (ngrp - 1) * sizeof(gid_t));
333 
334 out:
335 	td->td_retval[0] = ngrp;
336 	return (error);
337 
338 }
339 #endif	/* COMPAT_FREEBSD14 */
340 
341 #ifndef _SYS_SYSPROTO_H_
342 struct getgroups_args {
343 	int	gidsetsize;
344 	gid_t	*gidset;
345 };
346 #endif
347 int
sys_getgroups(struct thread * td,struct getgroups_args * uap)348 sys_getgroups(struct thread *td, struct getgroups_args *uap)
349 {
350 	struct ucred *cred;
351 	int ngrp, error;
352 
353 	cred = td->td_ucred;
354 
355 	ngrp = cred->cr_ngroups;
356 	if (uap->gidsetsize == 0) {
357 		error = 0;
358 		goto out;
359 	}
360 	if (uap->gidsetsize < ngrp)
361 		return (EINVAL);
362 
363 	error = copyout(cred->cr_groups, uap->gidset, ngrp * sizeof(gid_t));
364 out:
365 	td->td_retval[0] = ngrp;
366 	return (error);
367 }
368 
369 #ifndef _SYS_SYSPROTO_H_
370 struct setsid_args {
371         int     dummy;
372 };
373 #endif
374 /* ARGSUSED */
375 int
sys_setsid(struct thread * td,struct setsid_args * uap)376 sys_setsid(struct thread *td, struct setsid_args *uap)
377 {
378 	struct pgrp *pgrp;
379 	int error;
380 	struct proc *p = td->td_proc;
381 	struct pgrp *newpgrp;
382 	struct session *newsess;
383 
384 	pgrp = NULL;
385 
386 	newpgrp = uma_zalloc(pgrp_zone, M_WAITOK);
387 	newsess = malloc(sizeof(struct session), M_SESSION, M_WAITOK | M_ZERO);
388 
389 again:
390 	error = 0;
391 	sx_xlock(&proctree_lock);
392 
393 	if (p->p_pgid == p->p_pid || (pgrp = pgfind(p->p_pid)) != NULL) {
394 		if (pgrp != NULL)
395 			PGRP_UNLOCK(pgrp);
396 		error = EPERM;
397 	} else {
398 		error = enterpgrp(p, p->p_pid, newpgrp, newsess);
399 		if (error == ERESTART)
400 			goto again;
401 		MPASS(error == 0);
402 		td->td_retval[0] = p->p_pid;
403 		newpgrp = NULL;
404 		newsess = NULL;
405 	}
406 
407 	sx_xunlock(&proctree_lock);
408 
409 	uma_zfree(pgrp_zone, newpgrp);
410 	free(newsess, M_SESSION);
411 
412 	return (error);
413 }
414 
415 /*
416  * set process group (setpgid/old setpgrp)
417  *
418  * caller does setpgid(targpid, targpgid)
419  *
420  * pid must be caller or child of caller (ESRCH)
421  * if a child
422  *	pid must be in same session (EPERM)
423  *	pid can't have done an exec (EACCES)
424  * if pgid != pid
425  *	there must exist some pid in same session having pgid (EPERM)
426  * pid must not be session leader (EPERM)
427  */
428 #ifndef _SYS_SYSPROTO_H_
429 struct setpgid_args {
430 	int	pid;		/* target process id */
431 	int	pgid;		/* target pgrp id */
432 };
433 #endif
434 /* ARGSUSED */
435 int
sys_setpgid(struct thread * td,struct setpgid_args * uap)436 sys_setpgid(struct thread *td, struct setpgid_args *uap)
437 {
438 	struct proc *curp = td->td_proc;
439 	struct proc *targp;	/* target process */
440 	struct pgrp *pgrp;	/* target pgrp */
441 	int error;
442 	struct pgrp *newpgrp;
443 
444 	if (uap->pgid < 0)
445 		return (EINVAL);
446 
447 	newpgrp = uma_zalloc(pgrp_zone, M_WAITOK);
448 
449 again:
450 	error = 0;
451 
452 	sx_xlock(&proctree_lock);
453 	if (uap->pid != 0 && uap->pid != curp->p_pid) {
454 		if ((targp = pfind(uap->pid)) == NULL) {
455 			error = ESRCH;
456 			goto done;
457 		}
458 		if (!inferior(targp)) {
459 			PROC_UNLOCK(targp);
460 			error = ESRCH;
461 			goto done;
462 		}
463 		if ((error = p_cansee(td, targp))) {
464 			PROC_UNLOCK(targp);
465 			goto done;
466 		}
467 		if (targp->p_pgrp == NULL ||
468 		    targp->p_session != curp->p_session) {
469 			PROC_UNLOCK(targp);
470 			error = EPERM;
471 			goto done;
472 		}
473 		if (targp->p_flag & P_EXEC) {
474 			PROC_UNLOCK(targp);
475 			error = EACCES;
476 			goto done;
477 		}
478 		PROC_UNLOCK(targp);
479 	} else
480 		targp = curp;
481 	if (SESS_LEADER(targp)) {
482 		error = EPERM;
483 		goto done;
484 	}
485 	if (uap->pgid == 0)
486 		uap->pgid = targp->p_pid;
487 	if ((pgrp = pgfind(uap->pgid)) == NULL) {
488 		if (uap->pgid == targp->p_pid) {
489 			error = enterpgrp(targp, uap->pgid, newpgrp,
490 			    NULL);
491 			if (error == 0)
492 				newpgrp = NULL;
493 		} else
494 			error = EPERM;
495 	} else {
496 		if (pgrp == targp->p_pgrp) {
497 			PGRP_UNLOCK(pgrp);
498 			goto done;
499 		}
500 		if (pgrp->pg_id != targp->p_pid &&
501 		    pgrp->pg_session != curp->p_session) {
502 			PGRP_UNLOCK(pgrp);
503 			error = EPERM;
504 			goto done;
505 		}
506 		PGRP_UNLOCK(pgrp);
507 		error = enterthispgrp(targp, pgrp);
508 	}
509 done:
510 	KASSERT(error == 0 || newpgrp != NULL,
511 	    ("setpgid failed and newpgrp is NULL"));
512 	if (error == ERESTART)
513 		goto again;
514 	sx_xunlock(&proctree_lock);
515 	uma_zfree(pgrp_zone, newpgrp);
516 	return (error);
517 }
518 
519 static int
gidp_cmp(const void * p1,const void * p2)520 gidp_cmp(const void *p1, const void *p2)
521 {
522 	const gid_t g1 = *(const gid_t *)p1;
523 	const gid_t g2 = *(const gid_t *)p2;
524 
525 	return ((g1 > g2) - (g1 < g2));
526 }
527 
528 /*
529  * 'smallgroups' must be an (uninitialized) array of length CRED_SMALLGROUPS_NB.
530  * Always sets 'sc_supp_groups', either to a valid kernel-space groups array
531  * (which may or may not be 'smallgroups'), or NULL if SETCREDF_SUPP_GROUPS was
532  * not specified, or a buffer containing garbage on copyin() failure.  In the
533  * last two cases, 'sc_supp_groups_nb' is additionally set to 0 as a security
534  * measure.  'sc_supp_groups' must be freed (M_TEMP) if not equal to
535  * 'smallgroups' even on failure.
536  */
537 static int
kern_setcred_copyin_supp_groups(struct setcred * const wcred,const u_int flags,gid_t * const smallgroups)538 kern_setcred_copyin_supp_groups(struct setcred *const wcred,
539     const u_int flags, gid_t *const smallgroups)
540 {
541 	gid_t *groups;
542 	int error;
543 
544 	if ((flags & SETCREDF_SUPP_GROUPS) == 0) {
545 		wcred->sc_supp_groups_nb = 0;
546 		wcred->sc_supp_groups = NULL;
547 		return (0);
548 	}
549 
550 	/*
551 	 * Check the number of groups' limit right now in order to limit the
552 	 * amount of bytes to copy.
553 	 */
554 	if (wcred->sc_supp_groups_nb > ngroups_max)
555 		return (EINVAL);
556 
557 	groups = wcred->sc_supp_groups_nb <= CRED_SMALLGROUPS_NB ?
558 	    smallgroups : malloc(wcred->sc_supp_groups_nb * sizeof(gid_t),
559 	    M_TEMP, M_WAITOK);
560 
561 	error = copyin(wcred->sc_supp_groups, groups,
562 	    wcred->sc_supp_groups_nb * sizeof(gid_t));
563 	wcred->sc_supp_groups = groups;
564 	if (error != 0) {
565 		wcred->sc_supp_groups_nb = 0;
566 		return (error);
567 	}
568 
569 	return (0);
570 }
571 
572 int
user_setcred(struct thread * td,const u_int flags,struct setcred * const wcred)573 user_setcred(struct thread *td, const u_int flags, struct setcred *const wcred)
574 {
575 #ifdef MAC
576 	struct mac mac;
577 	/* Pointer to 'struct mac' or 'struct mac32'. */
578 	void *umac;
579 #endif
580 	gid_t smallgroups[CRED_SMALLGROUPS_NB];
581 	int error;
582 
583 	/*
584 	 * As the only point of this wrapper function is to copyin() from
585 	 * userland, we only interpret the data pieces we need to perform this
586 	 * operation and defer further sanity checks to kern_setcred(), except
587 	 * that we redundantly check here that no unknown flags have been
588 	 * passed.
589 	 */
590 	if ((flags & ~SETCREDF_MASK) != 0)
591 		return (EINVAL);
592 
593 #ifdef MAC
594 	umac = wcred->sc_label;
595 #endif
596 	/* Also done on !MAC as a defensive measure. */
597 	wcred->sc_label = NULL;
598 
599 	/*
600 	 * Copy supplementary groups as needed.  There is no specific
601 	 * alternative for 32-bit compatibility as 'gid_t' has the same size
602 	 * everywhere.
603 	 */
604 	error = kern_setcred_copyin_supp_groups(wcred, flags, smallgroups);
605 	if (error != 0)
606 		goto free_groups;
607 
608 #ifdef MAC
609 	if ((flags & SETCREDF_MAC_LABEL) != 0) {
610 		error = mac_label_copyin(umac, &mac, NULL);
611 		if (error != 0)
612 			goto free_groups;
613 		wcred->sc_label = &mac;
614 	}
615 #endif
616 
617 	error = kern_setcred(td, flags, wcred);
618 
619 #ifdef MAC
620 	if (wcred->sc_label != NULL)
621 		free_copied_label(wcred->sc_label);
622 #endif
623 
624 free_groups:
625 	if (wcred->sc_supp_groups != smallgroups)
626 		free(wcred->sc_supp_groups, M_TEMP);
627 
628 	return (error);
629 }
630 
631 #ifndef _SYS_SYSPROTO_H_
632 struct setcred_args {
633 	u_int			 flags;	/* Flags. */
634 	const struct setcred	*wcred;
635 	size_t			 size;	/* Passed 'setcred' structure length. */
636 };
637 #endif
638 /* ARGSUSED */
639 int
sys_setcred(struct thread * td,struct setcred_args * uap)640 sys_setcred(struct thread *td, struct setcred_args *uap)
641 {
642 	struct setcred wcred;
643 	int error;
644 
645 	if (uap->size != sizeof(wcred))
646 		return (EINVAL);
647 	error = copyin(uap->wcred, &wcred, sizeof(wcred));
648 	if (error != 0)
649 		return (error);
650 	return (user_setcred(td, uap->flags, &wcred));
651 }
652 
653 /*
654  * CAUTION: This function normalizes groups in 'wcred'.
655  */
656 int
kern_setcred(struct thread * const td,const u_int flags,struct setcred * const wcred)657 kern_setcred(struct thread *const td, const u_int flags,
658     struct setcred *const wcred)
659 {
660 	struct proc *const p = td->td_proc;
661 	struct ucred *new_cred, *old_cred, *to_free_cred = NULL;
662 	struct uidinfo *uip = NULL, *ruip = NULL;
663 #ifdef MAC
664 	void *mac_set_proc_data = NULL;
665 	bool proc_label_set = false;
666 #endif
667 	int error;
668 	bool cred_set = false;
669 
670 	/* Bail out on unrecognized flags. */
671 	if (flags & ~SETCREDF_MASK)
672 		return (EINVAL);
673 
674 	/*
675 	 * Part 1: We allocate and perform preparatory operations with no locks.
676 	 */
677 
678 	if ((flags & SETCREDF_SUPP_GROUPS) != 0 &&
679 	    wcred->sc_supp_groups_nb > ngroups_max)
680 			return (EINVAL);
681 
682 	if (flags & SETCREDF_MAC_LABEL) {
683 #ifdef MAC
684 		error = mac_set_proc_prepare(td, wcred->sc_label,
685 		    &mac_set_proc_data);
686 		if (error != 0)
687 			return (error);
688 #else
689 		return (ENOTSUP);
690 #endif
691 	}
692 
693 	if (flags & SETCREDF_UID) {
694 		AUDIT_ARG_EUID(wcred->sc_uid);
695 		uip = uifind(wcred->sc_uid);
696 	}
697 	if (flags & SETCREDF_RUID) {
698 		AUDIT_ARG_RUID(wcred->sc_ruid);
699 		ruip = uifind(wcred->sc_ruid);
700 	}
701 	if (flags & SETCREDF_SVUID)
702 		AUDIT_ARG_SUID(wcred->sc_svuid);
703 
704 	if (flags & SETCREDF_GID)
705 		AUDIT_ARG_EGID(wcred->sc_gid);
706 	if (flags & SETCREDF_RGID)
707 		AUDIT_ARG_RGID(wcred->sc_rgid);
708 	if (flags & SETCREDF_SVGID)
709 		AUDIT_ARG_SGID(wcred->sc_svgid);
710 	if (flags & SETCREDF_SUPP_GROUPS) {
711 		/*
712 		 * Output the raw supplementary groups array for better
713 		 * traceability.
714 		 */
715 		AUDIT_ARG_GROUPSET(wcred->sc_supp_groups,
716 		    wcred->sc_supp_groups_nb);
717 		groups_normalize(&wcred->sc_supp_groups_nb,
718 		    wcred->sc_supp_groups);
719 	}
720 
721 	/*
722 	 * We first completely build the new credentials and only then pass them
723 	 * to MAC along with the old ones so that modules can check whether the
724 	 * requested transition is allowed.
725 	 */
726 	new_cred = crget();
727 	to_free_cred = new_cred;
728 	if (flags & SETCREDF_SUPP_GROUPS)
729 		crextend(new_cred, wcred->sc_supp_groups_nb);
730 
731 #ifdef MAC
732 	mac_cred_setcred_enter();
733 #endif
734 
735 	/*
736 	 * Part 2: We grab the process lock as to have a stable view of its
737 	 * current credentials, and prepare a copy of them with the requested
738 	 * changes applied under that lock.
739 	 */
740 
741 	PROC_LOCK(p);
742 	old_cred = crcopysafe(p, new_cred);
743 
744 	/*
745 	 * Change user IDs.
746 	 */
747 	if (flags & SETCREDF_UID)
748 		change_euid(new_cred, uip);
749 	if (flags & SETCREDF_RUID)
750 		change_ruid(new_cred, ruip);
751 	if (flags & SETCREDF_SVUID)
752 		change_svuid(new_cred, wcred->sc_svuid);
753 
754 	/*
755 	 * Change groups.
756 	 */
757 	if (flags & SETCREDF_SUPP_GROUPS)
758 		crsetgroups_internal(new_cred, wcred->sc_supp_groups_nb,
759 		    wcred->sc_supp_groups);
760 	if (flags & SETCREDF_GID)
761 		change_egid(new_cred, wcred->sc_gid);
762 	if (flags & SETCREDF_RGID)
763 		change_rgid(new_cred, wcred->sc_rgid);
764 	if (flags & SETCREDF_SVGID)
765 		change_svgid(new_cred, wcred->sc_svgid);
766 
767 #ifdef MAC
768 	/*
769 	 * Change the MAC label.
770 	 */
771 	if (flags & SETCREDF_MAC_LABEL) {
772 		error = mac_set_proc_core(td, new_cred, mac_set_proc_data);
773 		if (error != 0)
774 			goto unlock_finish;
775 		proc_label_set = true;
776 	}
777 
778 	/*
779 	 * MAC security modules checks.
780 	 */
781 	error = mac_cred_check_setcred(flags, old_cred, new_cred);
782 	if (error != 0)
783 		goto unlock_finish;
784 #endif
785 	/*
786 	 * Privilege check.
787 	 */
788 	error = priv_check_cred(old_cred, PRIV_CRED_SETCRED);
789 	if (error != 0)
790 		goto unlock_finish;
791 
792 #ifdef RACCT
793 	/*
794 	 * Hold a reference to 'new_cred', as we need to call some functions on
795 	 * it after proc_set_cred_enforce_proc_lim().
796 	 */
797 	crhold(new_cred);
798 #endif
799 
800 	/* Set the new credentials. */
801 	cred_set = proc_set_cred_enforce_proc_lim(p, new_cred);
802 	if (cred_set) {
803 		setsugid(p);
804 #ifdef RACCT
805 		/* Adjust RACCT counters. */
806 		racct_proc_ucred_changed(p, old_cred, new_cred);
807 #endif
808 		to_free_cred = old_cred;
809 		MPASS(error == 0);
810 	} else {
811 #ifdef RACCT
812 		/* Matches the crhold() just before the containing 'if'. */
813 		crfree(new_cred);
814 #endif
815 		error = EAGAIN;
816 	}
817 
818 unlock_finish:
819 	PROC_UNLOCK(p);
820 
821 	/*
822 	 * Part 3: After releasing the process lock, we perform cleanups and
823 	 * finishing operations.
824 	 */
825 
826 #ifdef RACCT
827 	if (cred_set) {
828 #ifdef RCTL
829 		rctl_proc_ucred_changed(p, new_cred);
830 #endif
831 		/* Paired with the crhold() above. */
832 		crfree(new_cred);
833 	}
834 #endif
835 
836 #ifdef MAC
837 	if (mac_set_proc_data != NULL)
838 		mac_set_proc_finish(td, proc_label_set, mac_set_proc_data);
839 	mac_cred_setcred_exit();
840 #endif
841 	crfree(to_free_cred);
842 	if (uip != NULL)
843 		uifree(uip);
844 	if (ruip != NULL)
845 		uifree(ruip);
846 
847 	return (error);
848 }
849 
850 /*
851  * Use the clause in B.4.2.2 that allows setuid/setgid to be 4.2/4.3BSD
852  * compatible.  It says that setting the uid/gid to euid/egid is a special
853  * case of "appropriate privilege".  Once the rules are expanded out, this
854  * basically means that setuid(nnn) sets all three id's, in all permitted
855  * cases unless _POSIX_SAVED_IDS is enabled.  In that case, setuid(getuid())
856  * does not set the saved id - this is dangerous for traditional BSD
857  * programs.  For this reason, we *really* do not want to set
858  * _POSIX_SAVED_IDS and do not want to clear POSIX_APPENDIX_B_4_2_2.
859  */
860 #define POSIX_APPENDIX_B_4_2_2
861 
862 #ifndef _SYS_SYSPROTO_H_
863 struct setuid_args {
864 	uid_t	uid;
865 };
866 #endif
867 /* ARGSUSED */
868 int
sys_setuid(struct thread * td,struct setuid_args * uap)869 sys_setuid(struct thread *td, struct setuid_args *uap)
870 {
871 	struct proc *p = td->td_proc;
872 	struct ucred *newcred, *oldcred;
873 	uid_t uid;
874 	struct uidinfo *uip;
875 	int error;
876 
877 	uid = uap->uid;
878 	AUDIT_ARG_UID(uid);
879 	newcred = crget();
880 	uip = uifind(uid);
881 	PROC_LOCK(p);
882 	/*
883 	 * Copy credentials so other references do not see our changes.
884 	 */
885 	oldcred = crcopysafe(p, newcred);
886 
887 #ifdef MAC
888 	error = mac_cred_check_setuid(oldcred, uid);
889 	if (error)
890 		goto fail;
891 #endif
892 
893 	/*
894 	 * See if we have "permission" by POSIX 1003.1 rules.
895 	 *
896 	 * Note that setuid(geteuid()) is a special case of
897 	 * "appropriate privileges" in appendix B.4.2.2.  We need
898 	 * to use this clause to be compatible with traditional BSD
899 	 * semantics.  Basically, it means that "setuid(xx)" sets all
900 	 * three id's (assuming you have privs).
901 	 *
902 	 * Notes on the logic.  We do things in three steps.
903 	 * 1: We determine if the euid is going to change, and do EPERM
904 	 *    right away.  We unconditionally change the euid later if this
905 	 *    test is satisfied, simplifying that part of the logic.
906 	 * 2: We determine if the real and/or saved uids are going to
907 	 *    change.  Determined by compile options.
908 	 * 3: Change euid last. (after tests in #2 for "appropriate privs")
909 	 */
910 	if (uid != oldcred->cr_ruid &&		/* allow setuid(getuid()) */
911 #ifdef _POSIX_SAVED_IDS
912 	    uid != oldcred->cr_svuid &&		/* allow setuid(saved gid) */
913 #endif
914 #ifdef POSIX_APPENDIX_B_4_2_2	/* Use BSD-compat clause from B.4.2.2 */
915 	    uid != oldcred->cr_uid &&		/* allow setuid(geteuid()) */
916 #endif
917 	    (error = priv_check_cred(oldcred, PRIV_CRED_SETUID)) != 0)
918 		goto fail;
919 
920 #ifdef _POSIX_SAVED_IDS
921 	/*
922 	 * Do we have "appropriate privileges" (are we root or uid == euid)
923 	 * If so, we are changing the real uid and/or saved uid.
924 	 */
925 	if (
926 #ifdef POSIX_APPENDIX_B_4_2_2	/* Use the clause from B.4.2.2 */
927 	    uid == oldcred->cr_uid ||
928 #endif
929 	    /* We are using privs. */
930 	    priv_check_cred(oldcred, PRIV_CRED_SETUID) == 0)
931 #endif
932 	{
933 		/*
934 		 * Set the real uid.
935 		 */
936 		if (uid != oldcred->cr_ruid) {
937 			change_ruid(newcred, uip);
938 			setsugid(p);
939 		}
940 		/*
941 		 * Set saved uid
942 		 *
943 		 * XXX always set saved uid even if not _POSIX_SAVED_IDS, as
944 		 * the security of seteuid() depends on it.  B.4.2.2 says it
945 		 * is important that we should do this.
946 		 */
947 		if (uid != oldcred->cr_svuid) {
948 			change_svuid(newcred, uid);
949 			setsugid(p);
950 		}
951 	}
952 
953 	/*
954 	 * In all permitted cases, we are changing the euid.
955 	 */
956 	if (uid != oldcred->cr_uid) {
957 		change_euid(newcred, uip);
958 		setsugid(p);
959 	}
960 
961 #ifdef RACCT
962 	racct_proc_ucred_changed(p, oldcred, newcred);
963 #endif
964 #ifdef RCTL
965 	crhold(newcred);
966 #endif
967 	/*
968 	 * Takes over 'newcred''s reference, so 'newcred' must not be used
969 	 * besides this point except on RCTL where we took an additional
970 	 * reference above.
971 	 */
972 	proc_set_cred(p, newcred);
973 	PROC_UNLOCK(p);
974 #ifdef RCTL
975 	rctl_proc_ucred_changed(p, newcred);
976 	crfree(newcred);
977 #endif
978 	uifree(uip);
979 	crfree(oldcred);
980 	return (0);
981 
982 fail:
983 	PROC_UNLOCK(p);
984 	uifree(uip);
985 	crfree(newcred);
986 	return (error);
987 }
988 
989 #ifndef _SYS_SYSPROTO_H_
990 struct seteuid_args {
991 	uid_t	euid;
992 };
993 #endif
994 /* ARGSUSED */
995 int
sys_seteuid(struct thread * td,struct seteuid_args * uap)996 sys_seteuid(struct thread *td, struct seteuid_args *uap)
997 {
998 	struct proc *p = td->td_proc;
999 	struct ucred *newcred, *oldcred;
1000 	uid_t euid;
1001 	struct uidinfo *euip;
1002 	int error;
1003 
1004 	euid = uap->euid;
1005 	AUDIT_ARG_EUID(euid);
1006 	newcred = crget();
1007 	euip = uifind(euid);
1008 	PROC_LOCK(p);
1009 	/*
1010 	 * Copy credentials so other references do not see our changes.
1011 	 */
1012 	oldcred = crcopysafe(p, newcred);
1013 
1014 #ifdef MAC
1015 	error = mac_cred_check_seteuid(oldcred, euid);
1016 	if (error)
1017 		goto fail;
1018 #endif
1019 
1020 	if (euid != oldcred->cr_ruid &&		/* allow seteuid(getuid()) */
1021 	    euid != oldcred->cr_svuid &&	/* allow seteuid(saved uid) */
1022 	    (error = priv_check_cred(oldcred, PRIV_CRED_SETEUID)) != 0)
1023 		goto fail;
1024 
1025 	/*
1026 	 * Everything's okay, do it.
1027 	 */
1028 	if (oldcred->cr_uid != euid) {
1029 		change_euid(newcred, euip);
1030 		setsugid(p);
1031 	}
1032 	proc_set_cred(p, newcred);
1033 	PROC_UNLOCK(p);
1034 	uifree(euip);
1035 	crfree(oldcred);
1036 	return (0);
1037 
1038 fail:
1039 	PROC_UNLOCK(p);
1040 	uifree(euip);
1041 	crfree(newcred);
1042 	return (error);
1043 }
1044 
1045 #ifndef _SYS_SYSPROTO_H_
1046 struct setgid_args {
1047 	gid_t	gid;
1048 };
1049 #endif
1050 /* ARGSUSED */
1051 int
sys_setgid(struct thread * td,struct setgid_args * uap)1052 sys_setgid(struct thread *td, struct setgid_args *uap)
1053 {
1054 	struct proc *p = td->td_proc;
1055 	struct ucred *newcred, *oldcred;
1056 	gid_t gid;
1057 	int error;
1058 
1059 	gid = uap->gid;
1060 	AUDIT_ARG_GID(gid);
1061 	newcred = crget();
1062 	PROC_LOCK(p);
1063 	oldcred = crcopysafe(p, newcred);
1064 
1065 #ifdef MAC
1066 	error = mac_cred_check_setgid(oldcred, gid);
1067 	if (error)
1068 		goto fail;
1069 #endif
1070 
1071 	/*
1072 	 * See if we have "permission" by POSIX 1003.1 rules.
1073 	 *
1074 	 * Note that setgid(getegid()) is a special case of
1075 	 * "appropriate privileges" in appendix B.4.2.2.  We need
1076 	 * to use this clause to be compatible with traditional BSD
1077 	 * semantics.  Basically, it means that "setgid(xx)" sets all
1078 	 * three id's (assuming you have privs).
1079 	 *
1080 	 * For notes on the logic here, see setuid() above.
1081 	 */
1082 	if (gid != oldcred->cr_rgid &&		/* allow setgid(getgid()) */
1083 #ifdef _POSIX_SAVED_IDS
1084 	    gid != oldcred->cr_svgid &&		/* allow setgid(saved gid) */
1085 #endif
1086 #ifdef POSIX_APPENDIX_B_4_2_2	/* Use BSD-compat clause from B.4.2.2 */
1087 	    gid != oldcred->cr_gid && /* allow setgid(getegid()) */
1088 #endif
1089 	    (error = priv_check_cred(oldcred, PRIV_CRED_SETGID)) != 0)
1090 		goto fail;
1091 
1092 #ifdef _POSIX_SAVED_IDS
1093 	/*
1094 	 * Do we have "appropriate privileges" (are we root or gid == egid)
1095 	 * If so, we are changing the real uid and saved gid.
1096 	 */
1097 	if (
1098 #ifdef POSIX_APPENDIX_B_4_2_2	/* use the clause from B.4.2.2 */
1099 	    gid == oldcred->cr_gid ||
1100 #endif
1101 	    /* We are using privs. */
1102 	    priv_check_cred(oldcred, PRIV_CRED_SETGID) == 0)
1103 #endif
1104 	{
1105 		/*
1106 		 * Set real gid
1107 		 */
1108 		if (oldcred->cr_rgid != gid) {
1109 			change_rgid(newcred, gid);
1110 			setsugid(p);
1111 		}
1112 		/*
1113 		 * Set saved gid
1114 		 *
1115 		 * XXX always set saved gid even if not _POSIX_SAVED_IDS, as
1116 		 * the security of setegid() depends on it.  B.4.2.2 says it
1117 		 * is important that we should do this.
1118 		 */
1119 		if (oldcred->cr_svgid != gid) {
1120 			change_svgid(newcred, gid);
1121 			setsugid(p);
1122 		}
1123 	}
1124 	/*
1125 	 * In all cases permitted cases, we are changing the egid.
1126 	 * Copy credentials so other references do not see our changes.
1127 	 */
1128 	if (oldcred->cr_gid != gid) {
1129 		change_egid(newcred, gid);
1130 		setsugid(p);
1131 	}
1132 	proc_set_cred(p, newcred);
1133 	PROC_UNLOCK(p);
1134 	crfree(oldcred);
1135 	return (0);
1136 
1137 fail:
1138 	PROC_UNLOCK(p);
1139 	crfree(newcred);
1140 	return (error);
1141 }
1142 
1143 #ifndef _SYS_SYSPROTO_H_
1144 struct setegid_args {
1145 	gid_t	egid;
1146 };
1147 #endif
1148 /* ARGSUSED */
1149 int
sys_setegid(struct thread * td,struct setegid_args * uap)1150 sys_setegid(struct thread *td, struct setegid_args *uap)
1151 {
1152 	struct proc *p = td->td_proc;
1153 	struct ucred *newcred, *oldcred;
1154 	gid_t egid;
1155 	int error;
1156 
1157 	egid = uap->egid;
1158 	AUDIT_ARG_EGID(egid);
1159 	newcred = crget();
1160 	PROC_LOCK(p);
1161 	oldcred = crcopysafe(p, newcred);
1162 
1163 #ifdef MAC
1164 	error = mac_cred_check_setegid(oldcred, egid);
1165 	if (error)
1166 		goto fail;
1167 #endif
1168 
1169 	if (egid != oldcred->cr_rgid &&		/* allow setegid(getgid()) */
1170 	    egid != oldcred->cr_svgid &&	/* allow setegid(saved gid) */
1171 	    (error = priv_check_cred(oldcred, PRIV_CRED_SETEGID)) != 0)
1172 		goto fail;
1173 
1174 	if (oldcred->cr_gid != egid) {
1175 		change_egid(newcred, egid);
1176 		setsugid(p);
1177 	}
1178 	proc_set_cred(p, newcred);
1179 	PROC_UNLOCK(p);
1180 	crfree(oldcred);
1181 	return (0);
1182 
1183 fail:
1184 	PROC_UNLOCK(p);
1185 	crfree(newcred);
1186 	return (error);
1187 }
1188 
1189 #ifdef COMPAT_FREEBSD14
1190 int
freebsd14_setgroups(struct thread * td,struct freebsd14_setgroups_args * uap)1191 freebsd14_setgroups(struct thread *td, struct freebsd14_setgroups_args *uap)
1192 {
1193 	gid_t smallgroups[CRED_SMALLGROUPS_NB];
1194 	gid_t *groups;
1195 	int gidsetsize, error;
1196 
1197 	/*
1198 	 * Before FreeBSD 15.0, we allow one more group to be supplied to
1199 	 * account for the egid appearing before the supplementary groups.  This
1200 	 * may technically allow one more supplementary group for systems that
1201 	 * did use the default NGROUPS_MAX if we round it back up to 1024.
1202 	 */
1203 	gidsetsize = uap->gidsetsize;
1204 	if (gidsetsize > ngroups_max + 1 || gidsetsize < 0)
1205 		return (EINVAL);
1206 
1207 	if (gidsetsize > CRED_SMALLGROUPS_NB)
1208 		groups = malloc(gidsetsize * sizeof(gid_t), M_TEMP, M_WAITOK);
1209 	else
1210 		groups = smallgroups;
1211 
1212 	error = copyin(uap->gidset, groups, gidsetsize * sizeof(gid_t));
1213 	if (error == 0) {
1214 		int ngroups = gidsetsize > 0 ? gidsetsize - 1 /* egid */ : 0;
1215 
1216 		error = kern_setgroups(td, &ngroups, groups + 1);
1217 		if (error == 0 && gidsetsize > 0)
1218 			td->td_proc->p_ucred->cr_gid = groups[0];
1219 	}
1220 
1221 	if (groups != smallgroups)
1222 		free(groups, M_TEMP);
1223 	return (error);
1224 }
1225 #endif	/* COMPAT_FREEBSD14 */
1226 
1227 #ifndef _SYS_SYSPROTO_H_
1228 struct setgroups_args {
1229 	int	gidsetsize;
1230 	gid_t	*gidset;
1231 };
1232 #endif
1233 /* ARGSUSED */
1234 int
sys_setgroups(struct thread * td,struct setgroups_args * uap)1235 sys_setgroups(struct thread *td, struct setgroups_args *uap)
1236 {
1237 	gid_t smallgroups[CRED_SMALLGROUPS_NB];
1238 	gid_t *groups;
1239 	int gidsetsize, error;
1240 
1241 	/*
1242 	 * Sanity check size now to avoid passing too big a value to copyin(),
1243 	 * even if kern_setgroups() will do it again.
1244 	 *
1245 	 * Ideally, the 'gidsetsize' argument should have been a 'u_int' (and it
1246 	 * was, in this implementation, for a long time), but POSIX standardized
1247 	 * getgroups() to take an 'int' and it would be quite entrapping to have
1248 	 * setgroups() differ.
1249 	 */
1250 	gidsetsize = uap->gidsetsize;
1251 	if (gidsetsize > ngroups_max || gidsetsize < 0)
1252 		return (EINVAL);
1253 
1254 	if (gidsetsize > CRED_SMALLGROUPS_NB)
1255 		groups = malloc(gidsetsize * sizeof(gid_t), M_TEMP, M_WAITOK);
1256 	else
1257 		groups = smallgroups;
1258 
1259 	error = copyin(uap->gidset, groups, gidsetsize * sizeof(gid_t));
1260 	if (error == 0)
1261 		error = kern_setgroups(td, &gidsetsize, groups);
1262 
1263 	if (groups != smallgroups)
1264 		free(groups, M_TEMP);
1265 	return (error);
1266 }
1267 
1268 /*
1269  * CAUTION: This function normalizes 'groups', possibly also changing the value
1270  * of '*ngrpp' as a consequence.
1271  */
1272 int
kern_setgroups(struct thread * td,int * ngrpp,gid_t * groups)1273 kern_setgroups(struct thread *td, int *ngrpp, gid_t *groups)
1274 {
1275 	struct proc *p = td->td_proc;
1276 	struct ucred *newcred, *oldcred;
1277 	int ngrp, error;
1278 
1279 	ngrp = *ngrpp;
1280 	/* Sanity check size. */
1281 	if (ngrp < 0 || ngrp > ngroups_max)
1282 		return (EINVAL);
1283 
1284 	AUDIT_ARG_GROUPSET(groups, ngrp);
1285 
1286 	groups_normalize(&ngrp, groups);
1287 	*ngrpp = ngrp;
1288 
1289 	newcred = crget();
1290 	crextend(newcred, ngrp);
1291 	PROC_LOCK(p);
1292 	oldcred = crcopysafe(p, newcred);
1293 
1294 #ifdef MAC
1295 	/*
1296 	 * We pass NULL here explicitly if we don't have any supplementary
1297 	 * groups mostly for the sake of normalization, but also to avoid/detect
1298 	 * a situation where a MAC module has some assumption about the layout
1299 	 * of `groups` matching historical behavior.
1300 	 */
1301 	error = mac_cred_check_setgroups(oldcred, ngrp,
1302 	    ngrp == 0 ? NULL : groups);
1303 	if (error)
1304 		goto fail;
1305 #endif
1306 
1307 	error = priv_check_cred(oldcred, PRIV_CRED_SETGROUPS);
1308 	if (error)
1309 		goto fail;
1310 
1311 	crsetgroups_internal(newcred, ngrp, groups);
1312 	setsugid(p);
1313 	proc_set_cred(p, newcred);
1314 	PROC_UNLOCK(p);
1315 	crfree(oldcred);
1316 	return (0);
1317 
1318 fail:
1319 	PROC_UNLOCK(p);
1320 	crfree(newcred);
1321 	return (error);
1322 }
1323 
1324 #ifndef _SYS_SYSPROTO_H_
1325 struct setreuid_args {
1326 	uid_t	ruid;
1327 	uid_t	euid;
1328 };
1329 #endif
1330 /* ARGSUSED */
1331 int
sys_setreuid(struct thread * td,struct setreuid_args * uap)1332 sys_setreuid(struct thread *td, struct setreuid_args *uap)
1333 {
1334 	struct proc *p = td->td_proc;
1335 	struct ucred *newcred, *oldcred;
1336 	uid_t euid, ruid;
1337 	struct uidinfo *euip, *ruip;
1338 	int error;
1339 
1340 	euid = uap->euid;
1341 	ruid = uap->ruid;
1342 	AUDIT_ARG_EUID(euid);
1343 	AUDIT_ARG_RUID(ruid);
1344 	newcred = crget();
1345 	euip = uifind(euid);
1346 	ruip = uifind(ruid);
1347 	PROC_LOCK(p);
1348 	oldcred = crcopysafe(p, newcred);
1349 
1350 #ifdef MAC
1351 	error = mac_cred_check_setreuid(oldcred, ruid, euid);
1352 	if (error)
1353 		goto fail;
1354 #endif
1355 
1356 	if (((ruid != (uid_t)-1 && ruid != oldcred->cr_ruid &&
1357 	      ruid != oldcred->cr_svuid) ||
1358 	     (euid != (uid_t)-1 && euid != oldcred->cr_uid &&
1359 	      euid != oldcred->cr_ruid && euid != oldcred->cr_svuid)) &&
1360 	    (error = priv_check_cred(oldcred, PRIV_CRED_SETREUID)) != 0)
1361 		goto fail;
1362 
1363 	if (euid != (uid_t)-1 && oldcred->cr_uid != euid) {
1364 		change_euid(newcred, euip);
1365 		setsugid(p);
1366 	}
1367 	if (ruid != (uid_t)-1 && oldcred->cr_ruid != ruid) {
1368 		change_ruid(newcred, ruip);
1369 		setsugid(p);
1370 	}
1371 	if ((ruid != (uid_t)-1 || newcred->cr_uid != newcred->cr_ruid) &&
1372 	    newcred->cr_svuid != newcred->cr_uid) {
1373 		change_svuid(newcred, newcred->cr_uid);
1374 		setsugid(p);
1375 	}
1376 #ifdef RACCT
1377 	racct_proc_ucred_changed(p, oldcred, newcred);
1378 #endif
1379 #ifdef RCTL
1380 	crhold(newcred);
1381 #endif
1382 	/*
1383 	 * Takes over 'newcred''s reference, so 'newcred' must not be used
1384 	 * besides this point except on RCTL where we took an additional
1385 	 * reference above.
1386 	 */
1387 	proc_set_cred(p, newcred);
1388 	PROC_UNLOCK(p);
1389 #ifdef RCTL
1390 	rctl_proc_ucred_changed(p, newcred);
1391 	crfree(newcred);
1392 #endif
1393 	uifree(ruip);
1394 	uifree(euip);
1395 	crfree(oldcred);
1396 	return (0);
1397 
1398 fail:
1399 	PROC_UNLOCK(p);
1400 	uifree(ruip);
1401 	uifree(euip);
1402 	crfree(newcred);
1403 	return (error);
1404 }
1405 
1406 #ifndef _SYS_SYSPROTO_H_
1407 struct setregid_args {
1408 	gid_t	rgid;
1409 	gid_t	egid;
1410 };
1411 #endif
1412 /* ARGSUSED */
1413 int
sys_setregid(struct thread * td,struct setregid_args * uap)1414 sys_setregid(struct thread *td, struct setregid_args *uap)
1415 {
1416 	struct proc *p = td->td_proc;
1417 	struct ucred *newcred, *oldcred;
1418 	gid_t egid, rgid;
1419 	int error;
1420 
1421 	egid = uap->egid;
1422 	rgid = uap->rgid;
1423 	AUDIT_ARG_EGID(egid);
1424 	AUDIT_ARG_RGID(rgid);
1425 	newcred = crget();
1426 	PROC_LOCK(p);
1427 	oldcred = crcopysafe(p, newcred);
1428 
1429 #ifdef MAC
1430 	error = mac_cred_check_setregid(oldcred, rgid, egid);
1431 	if (error)
1432 		goto fail;
1433 #endif
1434 
1435 	if (((rgid != (gid_t)-1 && rgid != oldcred->cr_rgid &&
1436 	    rgid != oldcred->cr_svgid) ||
1437 	     (egid != (gid_t)-1 && egid != oldcred->cr_gid &&
1438 	     egid != oldcred->cr_rgid && egid != oldcred->cr_svgid)) &&
1439 	    (error = priv_check_cred(oldcred, PRIV_CRED_SETREGID)) != 0)
1440 		goto fail;
1441 
1442 	if (egid != (gid_t)-1 && oldcred->cr_gid != egid) {
1443 		change_egid(newcred, egid);
1444 		setsugid(p);
1445 	}
1446 	if (rgid != (gid_t)-1 && oldcred->cr_rgid != rgid) {
1447 		change_rgid(newcred, rgid);
1448 		setsugid(p);
1449 	}
1450 	if ((rgid != (gid_t)-1 || newcred->cr_gid != newcred->cr_rgid) &&
1451 	    newcred->cr_svgid != newcred->cr_gid) {
1452 		change_svgid(newcred, newcred->cr_gid);
1453 		setsugid(p);
1454 	}
1455 	proc_set_cred(p, newcred);
1456 	PROC_UNLOCK(p);
1457 	crfree(oldcred);
1458 	return (0);
1459 
1460 fail:
1461 	PROC_UNLOCK(p);
1462 	crfree(newcred);
1463 	return (error);
1464 }
1465 
1466 /*
1467  * setresuid(ruid, euid, suid) is like setreuid except control over the saved
1468  * uid is explicit.
1469  */
1470 #ifndef _SYS_SYSPROTO_H_
1471 struct setresuid_args {
1472 	uid_t	ruid;
1473 	uid_t	euid;
1474 	uid_t	suid;
1475 };
1476 #endif
1477 /* ARGSUSED */
1478 int
sys_setresuid(struct thread * td,struct setresuid_args * uap)1479 sys_setresuid(struct thread *td, struct setresuid_args *uap)
1480 {
1481 	struct proc *p = td->td_proc;
1482 	struct ucred *newcred, *oldcred;
1483 	uid_t euid, ruid, suid;
1484 	struct uidinfo *euip, *ruip;
1485 	int error;
1486 
1487 	euid = uap->euid;
1488 	ruid = uap->ruid;
1489 	suid = uap->suid;
1490 	AUDIT_ARG_EUID(euid);
1491 	AUDIT_ARG_RUID(ruid);
1492 	AUDIT_ARG_SUID(suid);
1493 	newcred = crget();
1494 	euip = uifind(euid);
1495 	ruip = uifind(ruid);
1496 	PROC_LOCK(p);
1497 	oldcred = crcopysafe(p, newcred);
1498 
1499 #ifdef MAC
1500 	error = mac_cred_check_setresuid(oldcred, ruid, euid, suid);
1501 	if (error)
1502 		goto fail;
1503 #endif
1504 
1505 	if (((ruid != (uid_t)-1 && ruid != oldcred->cr_ruid &&
1506 	     ruid != oldcred->cr_svuid &&
1507 	      ruid != oldcred->cr_uid) ||
1508 	     (euid != (uid_t)-1 && euid != oldcred->cr_ruid &&
1509 	    euid != oldcred->cr_svuid &&
1510 	      euid != oldcred->cr_uid) ||
1511 	     (suid != (uid_t)-1 && suid != oldcred->cr_ruid &&
1512 	    suid != oldcred->cr_svuid &&
1513 	      suid != oldcred->cr_uid)) &&
1514 	    (error = priv_check_cred(oldcred, PRIV_CRED_SETRESUID)) != 0)
1515 		goto fail;
1516 
1517 	if (euid != (uid_t)-1 && oldcred->cr_uid != euid) {
1518 		change_euid(newcred, euip);
1519 		setsugid(p);
1520 	}
1521 	if (ruid != (uid_t)-1 && oldcred->cr_ruid != ruid) {
1522 		change_ruid(newcred, ruip);
1523 		setsugid(p);
1524 	}
1525 	if (suid != (uid_t)-1 && oldcred->cr_svuid != suid) {
1526 		change_svuid(newcred, suid);
1527 		setsugid(p);
1528 	}
1529 #ifdef RACCT
1530 	racct_proc_ucred_changed(p, oldcred, newcred);
1531 #endif
1532 #ifdef RCTL
1533 	crhold(newcred);
1534 #endif
1535 	/*
1536 	 * Takes over 'newcred''s reference, so 'newcred' must not be used
1537 	 * besides this point except on RCTL where we took an additional
1538 	 * reference above.
1539 	 */
1540 	proc_set_cred(p, newcred);
1541 	PROC_UNLOCK(p);
1542 #ifdef RCTL
1543 	rctl_proc_ucred_changed(p, newcred);
1544 	crfree(newcred);
1545 #endif
1546 	uifree(ruip);
1547 	uifree(euip);
1548 	crfree(oldcred);
1549 	return (0);
1550 
1551 fail:
1552 	PROC_UNLOCK(p);
1553 	uifree(ruip);
1554 	uifree(euip);
1555 	crfree(newcred);
1556 	return (error);
1557 
1558 }
1559 
1560 /*
1561  * setresgid(rgid, egid, sgid) is like setregid except control over the saved
1562  * gid is explicit.
1563  */
1564 #ifndef _SYS_SYSPROTO_H_
1565 struct setresgid_args {
1566 	gid_t	rgid;
1567 	gid_t	egid;
1568 	gid_t	sgid;
1569 };
1570 #endif
1571 /* ARGSUSED */
1572 int
sys_setresgid(struct thread * td,struct setresgid_args * uap)1573 sys_setresgid(struct thread *td, struct setresgid_args *uap)
1574 {
1575 	struct proc *p = td->td_proc;
1576 	struct ucred *newcred, *oldcred;
1577 	gid_t egid, rgid, sgid;
1578 	int error;
1579 
1580 	egid = uap->egid;
1581 	rgid = uap->rgid;
1582 	sgid = uap->sgid;
1583 	AUDIT_ARG_EGID(egid);
1584 	AUDIT_ARG_RGID(rgid);
1585 	AUDIT_ARG_SGID(sgid);
1586 	newcred = crget();
1587 	PROC_LOCK(p);
1588 	oldcred = crcopysafe(p, newcred);
1589 
1590 #ifdef MAC
1591 	error = mac_cred_check_setresgid(oldcred, rgid, egid, sgid);
1592 	if (error)
1593 		goto fail;
1594 #endif
1595 
1596 	if (((rgid != (gid_t)-1 && rgid != oldcred->cr_rgid &&
1597 	      rgid != oldcred->cr_svgid &&
1598 	      rgid != oldcred->cr_gid) ||
1599 	     (egid != (gid_t)-1 && egid != oldcred->cr_rgid &&
1600 	      egid != oldcred->cr_svgid &&
1601 	      egid != oldcred->cr_gid) ||
1602 	     (sgid != (gid_t)-1 && sgid != oldcred->cr_rgid &&
1603 	      sgid != oldcred->cr_svgid &&
1604 	      sgid != oldcred->cr_gid)) &&
1605 	    (error = priv_check_cred(oldcred, PRIV_CRED_SETRESGID)) != 0)
1606 		goto fail;
1607 
1608 	if (egid != (gid_t)-1 && oldcred->cr_gid != egid) {
1609 		change_egid(newcred, egid);
1610 		setsugid(p);
1611 	}
1612 	if (rgid != (gid_t)-1 && oldcred->cr_rgid != rgid) {
1613 		change_rgid(newcred, rgid);
1614 		setsugid(p);
1615 	}
1616 	if (sgid != (gid_t)-1 && oldcred->cr_svgid != sgid) {
1617 		change_svgid(newcred, sgid);
1618 		setsugid(p);
1619 	}
1620 	proc_set_cred(p, newcred);
1621 	PROC_UNLOCK(p);
1622 	crfree(oldcred);
1623 	return (0);
1624 
1625 fail:
1626 	PROC_UNLOCK(p);
1627 	crfree(newcred);
1628 	return (error);
1629 }
1630 
1631 #ifndef _SYS_SYSPROTO_H_
1632 struct getresuid_args {
1633 	uid_t	*ruid;
1634 	uid_t	*euid;
1635 	uid_t	*suid;
1636 };
1637 #endif
1638 /* ARGSUSED */
1639 int
sys_getresuid(struct thread * td,struct getresuid_args * uap)1640 sys_getresuid(struct thread *td, struct getresuid_args *uap)
1641 {
1642 	struct ucred *cred;
1643 	int error1 = 0, error2 = 0, error3 = 0;
1644 
1645 	cred = td->td_ucred;
1646 	if (uap->ruid)
1647 		error1 = copyout(&cred->cr_ruid,
1648 		    uap->ruid, sizeof(cred->cr_ruid));
1649 	if (uap->euid)
1650 		error2 = copyout(&cred->cr_uid,
1651 		    uap->euid, sizeof(cred->cr_uid));
1652 	if (uap->suid)
1653 		error3 = copyout(&cred->cr_svuid,
1654 		    uap->suid, sizeof(cred->cr_svuid));
1655 	return (error1 ? error1 : error2 ? error2 : error3);
1656 }
1657 
1658 #ifndef _SYS_SYSPROTO_H_
1659 struct getresgid_args {
1660 	gid_t	*rgid;
1661 	gid_t	*egid;
1662 	gid_t	*sgid;
1663 };
1664 #endif
1665 /* ARGSUSED */
1666 int
sys_getresgid(struct thread * td,struct getresgid_args * uap)1667 sys_getresgid(struct thread *td, struct getresgid_args *uap)
1668 {
1669 	struct ucred *cred;
1670 	int error1 = 0, error2 = 0, error3 = 0;
1671 
1672 	cred = td->td_ucred;
1673 	if (uap->rgid)
1674 		error1 = copyout(&cred->cr_rgid,
1675 		    uap->rgid, sizeof(cred->cr_rgid));
1676 	if (uap->egid)
1677 		error2 = copyout(&cred->cr_gid,
1678 		    uap->egid, sizeof(cred->cr_gid));
1679 	if (uap->sgid)
1680 		error3 = copyout(&cred->cr_svgid,
1681 		    uap->sgid, sizeof(cred->cr_svgid));
1682 	return (error1 ? error1 : error2 ? error2 : error3);
1683 }
1684 
1685 #ifndef _SYS_SYSPROTO_H_
1686 struct issetugid_args {
1687 	int dummy;
1688 };
1689 #endif
1690 /* ARGSUSED */
1691 int
sys_issetugid(struct thread * td,struct issetugid_args * uap)1692 sys_issetugid(struct thread *td, struct issetugid_args *uap)
1693 {
1694 	struct proc *p = td->td_proc;
1695 
1696 	/*
1697 	 * Note: OpenBSD sets a P_SUGIDEXEC flag set at execve() time,
1698 	 * we use P_SUGID because we consider changing the owners as
1699 	 * "tainting" as well.
1700 	 * This is significant for procs that start as root and "become"
1701 	 * a user without an exec - programs cannot know *everything*
1702 	 * that libc *might* have put in their data segment.
1703 	 */
1704 	td->td_retval[0] = (p->p_flag & P_SUGID) ? 1 : 0;
1705 	return (0);
1706 }
1707 
1708 int
sys___setugid(struct thread * td,struct __setugid_args * uap)1709 sys___setugid(struct thread *td, struct __setugid_args *uap)
1710 {
1711 #ifdef REGRESSION
1712 	struct proc *p;
1713 
1714 	p = td->td_proc;
1715 	switch (uap->flag) {
1716 	case 0:
1717 		PROC_LOCK(p);
1718 		p->p_flag &= ~P_SUGID;
1719 		PROC_UNLOCK(p);
1720 		return (0);
1721 	case 1:
1722 		PROC_LOCK(p);
1723 		p->p_flag |= P_SUGID;
1724 		PROC_UNLOCK(p);
1725 		return (0);
1726 	default:
1727 		return (EINVAL);
1728 	}
1729 #else /* !REGRESSION */
1730 
1731 	return (ENOSYS);
1732 #endif /* REGRESSION */
1733 }
1734 
1735 #ifdef INVARIANTS
1736 static void
groups_check_normalized(int ngrp,const gid_t * groups)1737 groups_check_normalized(int ngrp, const gid_t *groups)
1738 {
1739 	gid_t prev_g;
1740 
1741 	groups_check_positive_len(ngrp);
1742 	groups_check_max_len(ngrp);
1743 
1744 	if (ngrp <= 1)
1745 		return;
1746 
1747 	prev_g = groups[0];
1748 	for (int i = 1; i < ngrp; ++i) {
1749 		const gid_t g = groups[i];
1750 
1751 		if (prev_g >= g)
1752 			panic("%s: groups[%d] (%u) >= groups[%d] (%u)",
1753 			    __func__, i - 1, prev_g, i, g);
1754 		prev_g = g;
1755 	}
1756 }
1757 #else
1758 #define groups_check_normalized(...)
1759 #endif
1760 
1761 /*
1762  * Returns whether gid designates a supplementary group in cred.
1763  */
1764 bool
group_is_supplementary(const gid_t gid,const struct ucred * const cred)1765 group_is_supplementary(const gid_t gid, const struct ucred *const cred)
1766 {
1767 
1768 	groups_check_normalized(cred->cr_ngroups, cred->cr_groups);
1769 
1770 	/*
1771 	 * Perform a binary search of the supplementary groups.  This is
1772 	 * possible because we sort the groups in crsetgroups().
1773 	 */
1774 	return (bsearch(&gid, cred->cr_groups, cred->cr_ngroups,
1775 	    sizeof(gid), gidp_cmp) != NULL);
1776 }
1777 
1778 /*
1779  * Check if gid is a member of the (effective) group set (i.e., effective and
1780  * supplementary groups).
1781  */
1782 bool
groupmember(gid_t gid,const struct ucred * cred)1783 groupmember(gid_t gid, const struct ucred *cred)
1784 {
1785 
1786 	groups_check_positive_len(cred->cr_ngroups);
1787 
1788 	if (gid == cred->cr_gid)
1789 		return (true);
1790 
1791 	return (group_is_supplementary(gid, cred));
1792 }
1793 
1794 /*
1795  * Check if gid is a member of the real group set (i.e., real and supplementary
1796  * groups).
1797  */
1798 bool
realgroupmember(gid_t gid,const struct ucred * cred)1799 realgroupmember(gid_t gid, const struct ucred *cred)
1800 {
1801 	groups_check_positive_len(cred->cr_ngroups);
1802 
1803 	if (gid == cred->cr_rgid)
1804 		return (true);
1805 
1806 	return (group_is_supplementary(gid, cred));
1807 }
1808 
1809 /*
1810  * Test the active securelevel against a given level.  securelevel_gt()
1811  * implements (securelevel > level).  securelevel_ge() implements
1812  * (securelevel >= level).  Note that the logic is inverted -- these
1813  * functions return EPERM on "success" and 0 on "failure".
1814  *
1815  * Due to care taken when setting the securelevel, we know that no jail will
1816  * be less secure that its parent (or the physical system), so it is sufficient
1817  * to test the current jail only.
1818  *
1819  * XXXRW: Possibly since this has to do with privilege, it should move to
1820  * kern_priv.c.
1821  */
1822 int
securelevel_gt(struct ucred * cr,int level)1823 securelevel_gt(struct ucred *cr, int level)
1824 {
1825 
1826 	return (cr->cr_prison->pr_securelevel > level ? EPERM : 0);
1827 }
1828 
1829 int
securelevel_ge(struct ucred * cr,int level)1830 securelevel_ge(struct ucred *cr, int level)
1831 {
1832 
1833 	return (cr->cr_prison->pr_securelevel >= level ? EPERM : 0);
1834 }
1835 
1836 /*
1837  * 'see_other_uids' determines whether or not visibility of processes
1838  * and sockets with credentials holding different real uids is possible
1839  * using a variety of system MIBs.
1840  * XXX: data declarations should be together near the beginning of the file.
1841  */
1842 static int	see_other_uids = 1;
1843 SYSCTL_INT(_security_bsd, OID_AUTO, see_other_uids, CTLFLAG_RW,
1844     &see_other_uids, 0,
1845     "Unprivileged processes may see subjects/objects with different real uid");
1846 
1847 /*-
1848  * Determine if u1 "can see" the subject specified by u2, according to the
1849  * 'see_other_uids' policy.
1850  * Returns: 0 for permitted, ESRCH otherwise
1851  * Locks: none
1852  * References: *u1 and *u2 must not change during the call
1853  *             u1 may equal u2, in which case only one reference is required
1854  */
1855 static int
cr_canseeotheruids(struct ucred * u1,struct ucred * u2)1856 cr_canseeotheruids(struct ucred *u1, struct ucred *u2)
1857 {
1858 
1859 	if (!see_other_uids && u1->cr_ruid != u2->cr_ruid) {
1860 		if (priv_check_cred(u1, PRIV_SEEOTHERUIDS) != 0)
1861 			return (ESRCH);
1862 	}
1863 	return (0);
1864 }
1865 
1866 /*
1867  * 'see_other_gids' determines whether or not visibility of processes
1868  * and sockets with credentials holding different real gids is possible
1869  * using a variety of system MIBs.
1870  * XXX: data declarations should be together near the beginning of the file.
1871  */
1872 static int	see_other_gids = 1;
1873 SYSCTL_INT(_security_bsd, OID_AUTO, see_other_gids, CTLFLAG_RW,
1874     &see_other_gids, 0,
1875     "Unprivileged processes may see subjects/objects with different real gid");
1876 
1877 /*
1878  * Determine if u1 can "see" the subject specified by u2, according to the
1879  * 'see_other_gids' policy.
1880  * Returns: 0 for permitted, ESRCH otherwise
1881  * Locks: none
1882  * References: *u1 and *u2 must not change during the call
1883  *             u1 may equal u2, in which case only one reference is required
1884  */
1885 static int
cr_canseeothergids(struct ucred * u1,struct ucred * u2)1886 cr_canseeothergids(struct ucred *u1, struct ucred *u2)
1887 {
1888 	if (see_other_gids)
1889 		return (0);
1890 
1891 	/* Restriction in force. */
1892 
1893 	if (realgroupmember(u1->cr_rgid, u2))
1894 		return (0);
1895 
1896 	for (int i = 0; i < u1->cr_ngroups; i++)
1897 		if (realgroupmember(u1->cr_groups[i], u2))
1898 			return (0);
1899 
1900 	if (priv_check_cred(u1, PRIV_SEEOTHERGIDS) == 0)
1901 		return (0);
1902 
1903 	return (ESRCH);
1904 }
1905 
1906 /*
1907  * 'see_jail_proc' determines whether or not visibility of processes and
1908  * sockets with credentials holding different jail ids is possible using a
1909  * variety of system MIBs.
1910  *
1911  * XXX: data declarations should be together near the beginning of the file.
1912  */
1913 
1914 static int	see_jail_proc = 1;
1915 SYSCTL_INT(_security_bsd, OID_AUTO, see_jail_proc, CTLFLAG_RW,
1916     &see_jail_proc, 0,
1917     "Unprivileged processes may see subjects/objects with different jail ids");
1918 
1919 /*-
1920  * Determine if u1 "can see" the subject specified by u2, according to the
1921  * 'see_jail_proc' policy.
1922  * Returns: 0 for permitted, ESRCH otherwise
1923  * Locks: none
1924  * References: *u1 and *u2 must not change during the call
1925  *             u1 may equal u2, in which case only one reference is required
1926  */
1927 static int
cr_canseejailproc(struct ucred * u1,struct ucred * u2)1928 cr_canseejailproc(struct ucred *u1, struct ucred *u2)
1929 {
1930 	if (see_jail_proc || /* Policy deactivated. */
1931 	    u1->cr_prison == u2->cr_prison || /* Same jail. */
1932 	    priv_check_cred(u1, PRIV_SEEJAILPROC) == 0) /* Privileged. */
1933 		return (0);
1934 
1935 	return (ESRCH);
1936 }
1937 
1938 /*
1939  * Determine if u1 can tamper with the subject specified by u2, if they are in
1940  * different jails and 'unprivileged_parent_tampering' jail policy allows it.
1941  *
1942  * May be called if u1 and u2 are in the same jail, but it is expected that the
1943  * caller has already done a prison_check() prior to calling it.
1944  *
1945  * Returns: 0 for permitted, EPERM otherwise
1946  */
1947 static int
cr_can_tamper_with_subjail(struct ucred * u1,struct ucred * u2,int priv)1948 cr_can_tamper_with_subjail(struct ucred *u1, struct ucred *u2, int priv)
1949 {
1950 
1951 	MPASS(prison_check(u1, u2) == 0);
1952 	if (u1->cr_prison == u2->cr_prison)
1953 		return (0);
1954 
1955 	if (priv_check_cred(u1, priv) == 0)
1956 		return (0);
1957 
1958 	/*
1959 	 * Jails do not maintain a distinct UID space, so process visibility is
1960 	 * all that would control an unprivileged process' ability to tamper
1961 	 * with a process in a subjail by default if we did not have the
1962 	 * allow.unprivileged_parent_tampering knob to restrict it by default.
1963 	 */
1964 	if (prison_allow(u2, PR_ALLOW_UNPRIV_PARENT_TAMPER))
1965 		return (0);
1966 
1967 	return (EPERM);
1968 }
1969 
1970 /*
1971  * Helper for cr_cansee*() functions to abide by system-wide security.bsd.see_*
1972  * policies.  Determines if u1 "can see" u2 according to these policies.
1973  * Returns: 0 for permitted, ESRCH otherwise
1974  */
1975 int
cr_bsd_visible(struct ucred * u1,struct ucred * u2)1976 cr_bsd_visible(struct ucred *u1, struct ucred *u2)
1977 {
1978 	int error;
1979 
1980 	error = cr_canseeotheruids(u1, u2);
1981 	if (error != 0)
1982 		return (error);
1983 	error = cr_canseeothergids(u1, u2);
1984 	if (error != 0)
1985 		return (error);
1986 	error = cr_canseejailproc(u1, u2);
1987 	if (error != 0)
1988 		return (error);
1989 	return (0);
1990 }
1991 
1992 /*-
1993  * Determine if u1 "can see" the subject specified by u2.
1994  * Returns: 0 for permitted, an errno value otherwise
1995  * Locks: none
1996  * References: *u1 and *u2 must not change during the call
1997  *             u1 may equal u2, in which case only one reference is required
1998  */
1999 int
cr_cansee(struct ucred * u1,struct ucred * u2)2000 cr_cansee(struct ucred *u1, struct ucred *u2)
2001 {
2002 	int error;
2003 
2004 	if ((error = prison_check(u1, u2)))
2005 		return (error);
2006 #ifdef MAC
2007 	if ((error = mac_cred_check_visible(u1, u2)))
2008 		return (error);
2009 #endif
2010 	if ((error = cr_bsd_visible(u1, u2)))
2011 		return (error);
2012 	return (0);
2013 }
2014 
2015 /*-
2016  * Determine if td "can see" the subject specified by p.
2017  * Returns: 0 for permitted, an errno value otherwise
2018  * Locks: Sufficient locks to protect p->p_ucred must be held.  td really
2019  *        should be curthread.
2020  * References: td and p must be valid for the lifetime of the call
2021  */
2022 int
p_cansee(struct thread * td,struct proc * p)2023 p_cansee(struct thread *td, struct proc *p)
2024 {
2025 	/* Wrap cr_cansee() for all functionality. */
2026 	KASSERT(td == curthread, ("%s: td not curthread", __func__));
2027 	PROC_LOCK_ASSERT(p, MA_OWNED);
2028 
2029 	if (td->td_proc == p)
2030 		return (0);
2031 	return (cr_cansee(td->td_ucred, p->p_ucred));
2032 }
2033 
2034 /*
2035  * 'conservative_signals' prevents the delivery of a broad class of
2036  * signals by unprivileged processes to processes that have changed their
2037  * credentials since the last invocation of execve().  This can prevent
2038  * the leakage of cached information or retained privileges as a result
2039  * of a common class of signal-related vulnerabilities.  However, this
2040  * may interfere with some applications that expect to be able to
2041  * deliver these signals to peer processes after having given up
2042  * privilege.
2043  */
2044 static int	conservative_signals = 1;
2045 SYSCTL_INT(_security_bsd, OID_AUTO, conservative_signals, CTLFLAG_RW,
2046     &conservative_signals, 0, "Unprivileged processes prevented from "
2047     "sending certain signals to processes whose credentials have changed");
2048 /*-
2049  * Determine whether cred may deliver the specified signal to proc.
2050  * Returns: 0 for permitted, an errno value otherwise.
2051  * Locks: A lock must be held for proc.
2052  * References: cred and proc must be valid for the lifetime of the call.
2053  */
2054 int
cr_cansignal(struct ucred * cred,struct proc * proc,int signum)2055 cr_cansignal(struct ucred *cred, struct proc *proc, int signum)
2056 {
2057 	int error;
2058 
2059 	PROC_LOCK_ASSERT(proc, MA_OWNED);
2060 	/*
2061 	 * Jail semantics limit the scope of signalling to proc in the
2062 	 * same jail as cred, if cred is in jail.
2063 	 */
2064 	error = prison_check(cred, proc->p_ucred);
2065 	if (error)
2066 		return (error);
2067 #ifdef MAC
2068 	if ((error = mac_proc_check_signal(cred, proc, signum)))
2069 		return (error);
2070 #endif
2071 	if ((error = cr_bsd_visible(cred, proc->p_ucred)))
2072 		return (error);
2073 
2074 	/*
2075 	 * UNIX signal semantics depend on the status of the P_SUGID
2076 	 * bit on the target process.  If the bit is set, then additional
2077 	 * restrictions are placed on the set of available signals.
2078 	 */
2079 	if (conservative_signals && (proc->p_flag & P_SUGID)) {
2080 		switch (signum) {
2081 		case 0:
2082 		case SIGKILL:
2083 		case SIGINT:
2084 		case SIGTERM:
2085 		case SIGALRM:
2086 		case SIGSTOP:
2087 		case SIGTTIN:
2088 		case SIGTTOU:
2089 		case SIGTSTP:
2090 		case SIGHUP:
2091 		case SIGUSR1:
2092 		case SIGUSR2:
2093 			/*
2094 			 * Generally, permit job and terminal control
2095 			 * signals.
2096 			 */
2097 			break;
2098 		default:
2099 			/* Not permitted without privilege. */
2100 			error = priv_check_cred(cred, PRIV_SIGNAL_SUGID);
2101 			if (error)
2102 				return (error);
2103 		}
2104 	}
2105 
2106 	/*
2107 	 * Generally, the target credential's ruid or svuid must match the
2108 	 * subject credential's ruid or euid.
2109 	 */
2110 	if (cred->cr_ruid != proc->p_ucred->cr_ruid &&
2111 	    cred->cr_ruid != proc->p_ucred->cr_svuid &&
2112 	    cred->cr_uid != proc->p_ucred->cr_ruid &&
2113 	    cred->cr_uid != proc->p_ucred->cr_svuid) {
2114 		error = priv_check_cred(cred, PRIV_SIGNAL_DIFFCRED);
2115 		if (error)
2116 			return (error);
2117 	}
2118 
2119 	/*
2120 	 * At this point, the target may be in a different jail than the
2121 	 * subject -- the subject must be in a parent jail to the target,
2122 	 * whether it is prison0 or a subordinate of prison0 that has
2123 	 * children.  Additional privileges are required to allow this, as
2124 	 * whether the creds are truly equivalent or not must be determined on
2125 	 * a case-by-case basis.
2126 	 */
2127 	error = cr_can_tamper_with_subjail(cred, proc->p_ucred,
2128 	    PRIV_SIGNAL_DIFFJAIL);
2129 	if (error)
2130 		return (error);
2131 
2132 	return (0);
2133 }
2134 
2135 /*-
2136  * Determine whether td may deliver the specified signal to p.
2137  * Returns: 0 for permitted, an errno value otherwise
2138  * Locks: Sufficient locks to protect various components of td and p
2139  *        must be held.  td must be curthread, and a lock must be
2140  *        held for p.
2141  * References: td and p must be valid for the lifetime of the call
2142  */
2143 int
p_cansignal(struct thread * td,struct proc * p,int signum)2144 p_cansignal(struct thread *td, struct proc *p, int signum)
2145 {
2146 
2147 	KASSERT(td == curthread, ("%s: td not curthread", __func__));
2148 	PROC_LOCK_ASSERT(p, MA_OWNED);
2149 	if (td->td_proc == p)
2150 		return (0);
2151 
2152 	/*
2153 	 * UNIX signalling semantics require that processes in the same
2154 	 * session always be able to deliver SIGCONT to one another,
2155 	 * overriding the remaining protections.
2156 	 */
2157 	/* XXX: This will require an additional lock of some sort. */
2158 	if (signum == SIGCONT && td->td_proc->p_session == p->p_session)
2159 		return (0);
2160 	/*
2161 	 * Some compat layers use SIGTHR and higher signals for
2162 	 * communication between different kernel threads of the same
2163 	 * process, so that they expect that it's always possible to
2164 	 * deliver them, even for suid applications where cr_cansignal() can
2165 	 * deny such ability for security consideration.  It should be
2166 	 * pretty safe to do since the only way to create two processes
2167 	 * with the same p_leader is via rfork(2).
2168 	 */
2169 	if (td->td_proc->p_leader != NULL && signum >= SIGTHR &&
2170 	    signum < SIGTHR + 4 && td->td_proc->p_leader == p->p_leader)
2171 		return (0);
2172 
2173 	return (cr_cansignal(td->td_ucred, p, signum));
2174 }
2175 
2176 /*-
2177  * Determine whether td may reschedule p.
2178  * Returns: 0 for permitted, an errno value otherwise
2179  * Locks: Sufficient locks to protect various components of td and p
2180  *        must be held.  td must be curthread, and a lock must
2181  *        be held for p.
2182  * References: td and p must be valid for the lifetime of the call
2183  */
2184 int
p_cansched(struct thread * td,struct proc * p)2185 p_cansched(struct thread *td, struct proc *p)
2186 {
2187 	int error;
2188 
2189 	KASSERT(td == curthread, ("%s: td not curthread", __func__));
2190 	PROC_LOCK_ASSERT(p, MA_OWNED);
2191 	if (td->td_proc == p)
2192 		return (0);
2193 	if ((error = prison_check(td->td_ucred, p->p_ucred)))
2194 		return (error);
2195 #ifdef MAC
2196 	if ((error = mac_proc_check_sched(td->td_ucred, p)))
2197 		return (error);
2198 #endif
2199 	if ((error = cr_bsd_visible(td->td_ucred, p->p_ucred)))
2200 		return (error);
2201 
2202 	if (td->td_ucred->cr_ruid != p->p_ucred->cr_ruid &&
2203 	    td->td_ucred->cr_uid != p->p_ucred->cr_ruid) {
2204 		error = priv_check(td, PRIV_SCHED_DIFFCRED);
2205 		if (error)
2206 			return (error);
2207 	}
2208 
2209 	error = cr_can_tamper_with_subjail(td->td_ucred, p->p_ucred,
2210 	    PRIV_SCHED_DIFFJAIL);
2211 	if (error)
2212 		return (error);
2213 
2214 	return (0);
2215 }
2216 
2217 /*
2218  * Handle getting or setting the prison's unprivileged_proc_debug
2219  * value.
2220  */
2221 static int
sysctl_unprivileged_proc_debug(SYSCTL_HANDLER_ARGS)2222 sysctl_unprivileged_proc_debug(SYSCTL_HANDLER_ARGS)
2223 {
2224 	int error, val;
2225 
2226 	val = prison_allow(req->td->td_ucred, PR_ALLOW_UNPRIV_DEBUG);
2227 	error = sysctl_handle_int(oidp, &val, 0, req);
2228 	if (error != 0 || req->newptr == NULL)
2229 		return (error);
2230 	if (val != 0 && val != 1)
2231 		return (EINVAL);
2232 	prison_set_allow(req->td->td_ucred, PR_ALLOW_UNPRIV_DEBUG, val);
2233 	return (0);
2234 }
2235 
2236 /*
2237  * The 'unprivileged_proc_debug' flag may be used to disable a variety of
2238  * unprivileged inter-process debugging services, including some procfs
2239  * functionality, ptrace(), and ktrace().  In the past, inter-process
2240  * debugging has been involved in a variety of security problems, and sites
2241  * not requiring the service might choose to disable it when hardening
2242  * systems.
2243  */
2244 SYSCTL_PROC(_security_bsd, OID_AUTO, unprivileged_proc_debug,
2245     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_PRISON | CTLFLAG_SECURE |
2246     CTLFLAG_MPSAFE, 0, 0, sysctl_unprivileged_proc_debug, "I",
2247     "Unprivileged processes may use process debugging facilities");
2248 
2249 /*
2250  * Return true if the object owner/group ids are subset of the active
2251  * credentials.
2252  */
2253 bool
cr_xids_subset(struct ucred * active_cred,struct ucred * obj_cred)2254 cr_xids_subset(struct ucred *active_cred, struct ucred *obj_cred)
2255 {
2256 	int i;
2257 	bool grpsubset, uidsubset;
2258 
2259 	/*
2260 	 * Is p's group set a subset of td's effective group set?  This
2261 	 * includes p's egid, group access list, rgid, and svgid.
2262 	 */
2263 	grpsubset = true;
2264 	for (i = 0; i < obj_cred->cr_ngroups; i++) {
2265 		if (!groupmember(obj_cred->cr_groups[i], active_cred)) {
2266 			grpsubset = false;
2267 			break;
2268 		}
2269 	}
2270 	grpsubset = grpsubset &&
2271 	    groupmember(obj_cred->cr_gid, active_cred) &&
2272 	    groupmember(obj_cred->cr_rgid, active_cred) &&
2273 	    groupmember(obj_cred->cr_svgid, active_cred);
2274 
2275 	/*
2276 	 * Are the uids present in obj_cred's credential equal to
2277 	 * active_cred's effective uid?  This includes obj_cred's
2278 	 * euid, svuid, and ruid.
2279 	 */
2280 	uidsubset = (active_cred->cr_uid == obj_cred->cr_uid &&
2281 	    active_cred->cr_uid == obj_cred->cr_svuid &&
2282 	    active_cred->cr_uid == obj_cred->cr_ruid);
2283 
2284 	return (uidsubset && grpsubset);
2285 }
2286 
2287 /*-
2288  * Determine whether td may debug p.
2289  * Returns: 0 for permitted, an errno value otherwise
2290  * Locks: Sufficient locks to protect various components of td and p
2291  *        must be held.  td must be curthread, and a lock must
2292  *        be held for p.
2293  * References: td and p must be valid for the lifetime of the call
2294  */
2295 int
p_candebug(struct thread * td,struct proc * p)2296 p_candebug(struct thread *td, struct proc *p)
2297 {
2298 	int error;
2299 
2300 	KASSERT(td == curthread, ("%s: td not curthread", __func__));
2301 	PROC_LOCK_ASSERT(p, MA_OWNED);
2302 	if (td->td_proc == p)
2303 		return (0);
2304 	if ((error = priv_check(td, PRIV_DEBUG_UNPRIV)))
2305 		return (error);
2306 	if ((error = prison_check(td->td_ucred, p->p_ucred)))
2307 		return (error);
2308 #ifdef MAC
2309 	if ((error = mac_proc_check_debug(td->td_ucred, p)))
2310 		return (error);
2311 #endif
2312 	if ((error = cr_bsd_visible(td->td_ucred, p->p_ucred)))
2313 		return (error);
2314 
2315 	/*
2316 	 * If p's gids aren't a subset, or the uids aren't a subset,
2317 	 * or the credential has changed, require appropriate privilege
2318 	 * for td to debug p.
2319 	 */
2320 	if (!cr_xids_subset(td->td_ucred, p->p_ucred)) {
2321 		error = priv_check(td, PRIV_DEBUG_DIFFCRED);
2322 		if (error)
2323 			return (error);
2324 	}
2325 
2326 	/*
2327 	 * Has the credential of the process changed since the last exec()?
2328 	 */
2329 	if ((p->p_flag & P_SUGID) != 0) {
2330 		error = priv_check(td, PRIV_DEBUG_SUGID);
2331 		if (error)
2332 			return (error);
2333 	}
2334 
2335 	error = cr_can_tamper_with_subjail(td->td_ucred, p->p_ucred,
2336 	    PRIV_DEBUG_DIFFJAIL);
2337 	if (error)
2338 		return (error);
2339 
2340 	/* Can't trace init when securelevel > 0. */
2341 	if (p == initproc) {
2342 		error = securelevel_gt(td->td_ucred, 0);
2343 		if (error)
2344 			return (error);
2345 	}
2346 
2347 	/*
2348 	 * Can't trace a process that's currently exec'ing.
2349 	 *
2350 	 * XXX: Note, this is not a security policy decision, it's a
2351 	 * basic correctness/functionality decision.  Therefore, this check
2352 	 * should be moved to the caller's of p_candebug().
2353 	 */
2354 	if ((p->p_flag & P_INEXEC) != 0)
2355 		return (EBUSY);
2356 
2357 	/* Denied explicitly */
2358 	if ((p->p_flag2 & P2_NOTRACE) != 0) {
2359 		error = priv_check(td, PRIV_DEBUG_DENIED);
2360 		if (error != 0)
2361 			return (error);
2362 	}
2363 
2364 	return (0);
2365 }
2366 
2367 /*-
2368  * Determine whether the subject represented by cred can "see" a socket.
2369  * Returns: 0 for permitted, ENOENT otherwise.
2370  */
2371 int
cr_canseesocket(struct ucred * cred,struct socket * so)2372 cr_canseesocket(struct ucred *cred, struct socket *so)
2373 {
2374 	int error;
2375 
2376 	error = prison_check(cred, so->so_cred);
2377 	if (error)
2378 		return (ENOENT);
2379 #ifdef MAC
2380 	error = mac_socket_check_visible(cred, so);
2381 	if (error)
2382 		return (error);
2383 #endif
2384 	if (cr_bsd_visible(cred, so->so_cred))
2385 		return (ENOENT);
2386 
2387 	return (0);
2388 }
2389 
2390 /*-
2391  * Determine whether td can wait for the exit of p.
2392  * Returns: 0 for permitted, an errno value otherwise
2393  * Locks: Sufficient locks to protect various components of td and p
2394  *        must be held.  td must be curthread, and a lock must
2395  *        be held for p.
2396  * References: td and p must be valid for the lifetime of the call
2397 
2398  */
2399 int
p_canwait(struct thread * td,struct proc * p)2400 p_canwait(struct thread *td, struct proc *p)
2401 {
2402 	int error;
2403 
2404 	KASSERT(td == curthread, ("%s: td not curthread", __func__));
2405 	PROC_LOCK_ASSERT(p, MA_OWNED);
2406 	if ((error = prison_check(td->td_ucred, p->p_ucred)))
2407 		return (error);
2408 #ifdef MAC
2409 	if ((error = mac_proc_check_wait(td->td_ucred, p)))
2410 		return (error);
2411 #endif
2412 #if 0
2413 	/* XXXMAC: This could have odd effects on some shells. */
2414 	if ((error = cr_bsd_visible(td->td_ucred, p->p_ucred)))
2415 		return (error);
2416 #endif
2417 
2418 	return (0);
2419 }
2420 
2421 /*
2422  * Credential management.
2423  *
2424  * struct ucred objects are rarely allocated but gain and lose references all
2425  * the time (e.g., on struct file alloc/dealloc) turning refcount updates into
2426  * a significant source of cache-line ping ponging. Common cases are worked
2427  * around by modifying thread-local counter instead if the cred to operate on
2428  * matches td_realucred.
2429  *
2430  * The counter is split into 2 parts:
2431  * - cr_users -- total count of all struct proc and struct thread objects
2432  *   which have given cred in p_ucred and td_ucred respectively
2433  * - cr_ref -- the actual ref count, only valid if cr_users == 0
2434  *
2435  * If users == 0 then cr_ref behaves similarly to refcount(9), in particular if
2436  * the count reaches 0 the object is freeable.
2437  * If users > 0 and curthread->td_realucred == cred, then updates are performed
2438  * against td_ucredref.
2439  * In other cases updates are performed against cr_ref.
2440  *
2441  * Changing td_realucred into something else decrements cr_users and transfers
2442  * accumulated updates.
2443  */
2444 struct ucred *
crcowget(struct ucred * cr)2445 crcowget(struct ucred *cr)
2446 {
2447 
2448 	mtx_lock(&cr->cr_mtx);
2449 	KASSERT(cr->cr_users > 0, ("%s: users %d not > 0 on cred %p",
2450 	    __func__, cr->cr_users, cr));
2451 	cr->cr_users++;
2452 	cr->cr_ref++;
2453 	mtx_unlock(&cr->cr_mtx);
2454 	return (cr);
2455 }
2456 
2457 static struct ucred *
crunuse(struct thread * td)2458 crunuse(struct thread *td)
2459 {
2460 	struct ucred *cr, *crold;
2461 
2462 	MPASS(td->td_realucred == td->td_ucred);
2463 	cr = td->td_realucred;
2464 	mtx_lock(&cr->cr_mtx);
2465 	cr->cr_ref += td->td_ucredref;
2466 	td->td_ucredref = 0;
2467 	KASSERT(cr->cr_users > 0, ("%s: users %d not > 0 on cred %p",
2468 	    __func__, cr->cr_users, cr));
2469 	cr->cr_users--;
2470 	if (cr->cr_users == 0) {
2471 		KASSERT(cr->cr_ref > 0, ("%s: ref %ld not > 0 on cred %p",
2472 		    __func__, cr->cr_ref, cr));
2473 		crold = cr;
2474 	} else {
2475 		cr->cr_ref--;
2476 		crold = NULL;
2477 	}
2478 	mtx_unlock(&cr->cr_mtx);
2479 	td->td_realucred = NULL;
2480 	return (crold);
2481 }
2482 
2483 static void
crunusebatch(struct ucred * cr,u_int users,long ref)2484 crunusebatch(struct ucred *cr, u_int users, long ref)
2485 {
2486 
2487 	KASSERT(users > 0, ("%s: passed users %d not > 0 ; cred %p",
2488 	    __func__, users, cr));
2489 	mtx_lock(&cr->cr_mtx);
2490 	KASSERT(cr->cr_users >= users, ("%s: users %d not > %d on cred %p",
2491 	    __func__, cr->cr_users, users, cr));
2492 	cr->cr_users -= users;
2493 	cr->cr_ref += ref;
2494 	cr->cr_ref -= users;
2495 	if (cr->cr_users > 0) {
2496 		mtx_unlock(&cr->cr_mtx);
2497 		return;
2498 	}
2499 	KASSERT(cr->cr_ref >= 0, ("%s: ref %ld not >= 0 on cred %p",
2500 	    __func__, cr->cr_ref, cr));
2501 	if (cr->cr_ref > 0) {
2502 		mtx_unlock(&cr->cr_mtx);
2503 		return;
2504 	}
2505 	crfree_final(cr);
2506 }
2507 
2508 void
crcowfree(struct thread * td)2509 crcowfree(struct thread *td)
2510 {
2511 	struct ucred *cr;
2512 
2513 	cr = crunuse(td);
2514 	if (cr != NULL)
2515 		crfree(cr);
2516 }
2517 
2518 struct ucred *
crcowsync(void)2519 crcowsync(void)
2520 {
2521 	struct thread *td;
2522 	struct proc *p;
2523 	struct ucred *crnew, *crold;
2524 
2525 	td = curthread;
2526 	p = td->td_proc;
2527 	PROC_LOCK_ASSERT(p, MA_OWNED);
2528 
2529 	MPASS(td->td_realucred == td->td_ucred);
2530 	if (td->td_realucred == p->p_ucred)
2531 		return (NULL);
2532 
2533 	crnew = crcowget(p->p_ucred);
2534 	crold = crunuse(td);
2535 	td->td_realucred = crnew;
2536 	td->td_ucred = td->td_realucred;
2537 	return (crold);
2538 }
2539 
2540 /*
2541  * Batching.
2542  */
2543 void
credbatch_add(struct credbatch * crb,struct thread * td)2544 credbatch_add(struct credbatch *crb, struct thread *td)
2545 {
2546 	struct ucred *cr;
2547 
2548 	MPASS(td->td_realucred != NULL);
2549 	MPASS(td->td_realucred == td->td_ucred);
2550 	MPASS(TD_GET_STATE(td) == TDS_INACTIVE);
2551 	cr = td->td_realucred;
2552 	KASSERT(cr->cr_users > 0, ("%s: users %d not > 0 on cred %p",
2553 	    __func__, cr->cr_users, cr));
2554 	if (crb->cred != cr) {
2555 		if (crb->users > 0) {
2556 			MPASS(crb->cred != NULL);
2557 			crunusebatch(crb->cred, crb->users, crb->ref);
2558 			crb->users = 0;
2559 			crb->ref = 0;
2560 		}
2561 	}
2562 	crb->cred = cr;
2563 	crb->users++;
2564 	crb->ref += td->td_ucredref;
2565 	td->td_ucredref = 0;
2566 	td->td_realucred = NULL;
2567 }
2568 
2569 void
credbatch_final(struct credbatch * crb)2570 credbatch_final(struct credbatch *crb)
2571 {
2572 
2573 	MPASS(crb->cred != NULL);
2574 	MPASS(crb->users > 0);
2575 	crunusebatch(crb->cred, crb->users, crb->ref);
2576 }
2577 
2578 /*
2579  * Allocate a zeroed cred structure.
2580  */
2581 struct ucred *
crget(void)2582 crget(void)
2583 {
2584 	struct ucred *cr;
2585 
2586 	cr = malloc(sizeof(*cr), M_CRED, M_WAITOK | M_ZERO);
2587 	mtx_init(&cr->cr_mtx, "cred", NULL, MTX_DEF);
2588 	cr->cr_ref = 1;
2589 #ifdef AUDIT
2590 	audit_cred_init(cr);
2591 #endif
2592 #ifdef MAC
2593 	mac_cred_init(cr);
2594 #endif
2595 	cr->cr_groups = cr->cr_smallgroups;
2596 	cr->cr_agroups = nitems(cr->cr_smallgroups);
2597 	return (cr);
2598 }
2599 
2600 /*
2601  * Claim another reference to a ucred structure.
2602  */
2603 struct ucred *
crhold(struct ucred * cr)2604 crhold(struct ucred *cr)
2605 {
2606 	struct thread *td;
2607 
2608 	td = curthread;
2609 	if (__predict_true(td->td_realucred == cr)) {
2610 		KASSERT(cr->cr_users > 0, ("%s: users %d not > 0 on cred %p",
2611 		    __func__, cr->cr_users, cr));
2612 		td->td_ucredref++;
2613 		return (cr);
2614 	}
2615 	mtx_lock(&cr->cr_mtx);
2616 	cr->cr_ref++;
2617 	mtx_unlock(&cr->cr_mtx);
2618 	return (cr);
2619 }
2620 
2621 /*
2622  * Free a cred structure.  Throws away space when ref count gets to 0.
2623  */
2624 void
crfree(struct ucred * cr)2625 crfree(struct ucred *cr)
2626 {
2627 	struct thread *td;
2628 
2629 	td = curthread;
2630 	if (__predict_true(td->td_realucred == cr)) {
2631 		KASSERT(cr->cr_users > 0, ("%s: users %d not > 0 on cred %p",
2632 		    __func__, cr->cr_users, cr));
2633 		td->td_ucredref--;
2634 		return;
2635 	}
2636 	mtx_lock(&cr->cr_mtx);
2637 	KASSERT(cr->cr_users >= 0, ("%s: users %d not >= 0 on cred %p",
2638 	    __func__, cr->cr_users, cr));
2639 	cr->cr_ref--;
2640 	if (cr->cr_users > 0) {
2641 		mtx_unlock(&cr->cr_mtx);
2642 		return;
2643 	}
2644 	KASSERT(cr->cr_ref >= 0, ("%s: ref %ld not >= 0 on cred %p",
2645 	    __func__, cr->cr_ref, cr));
2646 	if (cr->cr_ref > 0) {
2647 		mtx_unlock(&cr->cr_mtx);
2648 		return;
2649 	}
2650 	crfree_final(cr);
2651 }
2652 
2653 static void
crfree_final(struct ucred * cr)2654 crfree_final(struct ucred *cr)
2655 {
2656 
2657 	KASSERT(cr->cr_users == 0, ("%s: users %d not == 0 on cred %p",
2658 	    __func__, cr->cr_users, cr));
2659 	KASSERT(cr->cr_ref == 0, ("%s: ref %ld not == 0 on cred %p",
2660 	    __func__, cr->cr_ref, cr));
2661 
2662 	/*
2663 	 * Some callers of crget(), such as nfs_statfs(), allocate a temporary
2664 	 * credential, but don't allocate a uidinfo structure.
2665 	 */
2666 	if (cr->cr_uidinfo != NULL)
2667 		uifree(cr->cr_uidinfo);
2668 	if (cr->cr_ruidinfo != NULL)
2669 		uifree(cr->cr_ruidinfo);
2670 	if (cr->cr_prison != NULL)
2671 		prison_free(cr->cr_prison);
2672 	if (cr->cr_loginclass != NULL)
2673 		loginclass_free(cr->cr_loginclass);
2674 #ifdef AUDIT
2675 	audit_cred_destroy(cr);
2676 #endif
2677 #ifdef MAC
2678 	mac_cred_destroy(cr);
2679 #endif
2680 	mtx_destroy(&cr->cr_mtx);
2681 	if (cr->cr_groups != cr->cr_smallgroups)
2682 		free(cr->cr_groups, M_CRED);
2683 	free(cr, M_CRED);
2684 }
2685 
2686 /*
2687  * Copy a ucred's contents from a template.  Does not block.
2688  */
2689 void
crcopy(struct ucred * dest,struct ucred * src)2690 crcopy(struct ucred *dest, struct ucred *src)
2691 {
2692 
2693 	bcopy(&src->cr_startcopy, &dest->cr_startcopy,
2694 	    (unsigned)((caddr_t)&src->cr_endcopy -
2695 		(caddr_t)&src->cr_startcopy));
2696 	dest->cr_flags = src->cr_flags;
2697 	crsetgroups(dest, src->cr_ngroups, src->cr_groups);
2698 	uihold(dest->cr_uidinfo);
2699 	uihold(dest->cr_ruidinfo);
2700 	prison_hold(dest->cr_prison);
2701 	loginclass_hold(dest->cr_loginclass);
2702 #ifdef AUDIT
2703 	audit_cred_copy(src, dest);
2704 #endif
2705 #ifdef MAC
2706 	mac_cred_copy(src, dest);
2707 #endif
2708 }
2709 
2710 /*
2711  * Dup cred struct to a new held one.
2712  */
2713 struct ucred *
crdup(struct ucred * cr)2714 crdup(struct ucred *cr)
2715 {
2716 	struct ucred *newcr;
2717 
2718 	newcr = crget();
2719 	crcopy(newcr, cr);
2720 	return (newcr);
2721 }
2722 
2723 /*
2724  * Fill in a struct xucred based on a struct ucred.
2725  */
2726 void
cru2x(struct ucred * cr,struct xucred * xcr)2727 cru2x(struct ucred *cr, struct xucred *xcr)
2728 {
2729 	int ngroups;
2730 
2731 	bzero(xcr, sizeof(*xcr));
2732 	xcr->cr_version = XUCRED_VERSION;
2733 	xcr->cr_uid = cr->cr_uid;
2734 	xcr->cr_gid = cr->cr_gid;
2735 
2736 	/*
2737 	 * We use a union to alias cr_gid to cr_groups[0] in the xucred, so
2738 	 * this is kind of ugly; cr_ngroups still includes the egid for our
2739 	 * purposes to avoid bumping the xucred version.
2740 	 */
2741 	ngroups = MIN(cr->cr_ngroups + 1, nitems(xcr->cr_groups));
2742 	xcr->cr_ngroups = ngroups;
2743 	bcopy(cr->cr_groups, xcr->cr_sgroups,
2744 	    (ngroups - 1) * sizeof(*cr->cr_groups));
2745 }
2746 
2747 void
cru2xt(struct thread * td,struct xucred * xcr)2748 cru2xt(struct thread *td, struct xucred *xcr)
2749 {
2750 
2751 	cru2x(td->td_ucred, xcr);
2752 	xcr->cr_pid = td->td_proc->p_pid;
2753 }
2754 
2755 /*
2756  * Change process credentials.
2757  *
2758  * Callers are responsible for providing the reference for passed credentials
2759  * and for freeing old ones.  Calls chgproccnt() to correctly account the
2760  * current process to the proper real UID, if the latter has changed.  Returns
2761  * whether the operation was successful.  Failure can happen only on
2762  * 'enforce_proc_lim' being true and if no new process can be accounted to the
2763  * new real UID because of the current limit (see the inner comment for more
2764  * details) and the caller does not have privilege (PRIV_PROC_LIMIT) to override
2765  * that.  In this case, the reference to 'newcred' is not taken over.
2766  */
2767 static bool
_proc_set_cred(struct proc * p,struct ucred * newcred,bool enforce_proc_lim)2768 _proc_set_cred(struct proc *p, struct ucred *newcred, bool enforce_proc_lim)
2769 {
2770 	struct ucred *const oldcred = p->p_ucred;
2771 
2772 	MPASS(oldcred != NULL);
2773 	PROC_LOCK_ASSERT(p, MA_OWNED);
2774 
2775 	if (newcred->cr_ruidinfo != oldcred->cr_ruidinfo) {
2776 		/*
2777 		 * XXXOC: This check is flawed but nonetheless the best we can
2778 		 * currently do as we don't really track limits per UID contrary
2779 		 * to what we pretend in setrlimit(2).  Until this is reworked,
2780 		 * we just check here that the number of processes for our new
2781 		 * real UID doesn't exceed this process' process number limit
2782 		 * (which is meant to be associated with the current real UID).
2783 		 */
2784 		const int proccnt_changed = chgproccnt(newcred->cr_ruidinfo, 1,
2785 		    enforce_proc_lim ? lim_cur_proc(p, RLIMIT_NPROC) : 0);
2786 
2787 		if (!proccnt_changed) {
2788 			if (priv_check_cred(oldcred, PRIV_PROC_LIMIT) != 0)
2789 				return (false);
2790 			(void)chgproccnt(newcred->cr_ruidinfo, 1, 0);
2791 		}
2792 	}
2793 
2794 	mtx_lock(&oldcred->cr_mtx);
2795 	KASSERT(oldcred->cr_users > 0, ("%s: users %d not > 0 on cred %p",
2796 	    __func__, oldcred->cr_users, oldcred));
2797 	oldcred->cr_users--;
2798 	mtx_unlock(&oldcred->cr_mtx);
2799 	mtx_lock(&newcred->cr_mtx);
2800 	newcred->cr_users++;
2801 	mtx_unlock(&newcred->cr_mtx);
2802 	p->p_ucred = newcred;
2803 	PROC_UPDATE_COW(p);
2804 	if (newcred->cr_ruidinfo != oldcred->cr_ruidinfo)
2805 		(void)chgproccnt(oldcred->cr_ruidinfo, -1, 0);
2806 	return (true);
2807 }
2808 
2809 void
proc_set_cred(struct proc * p,struct ucred * newcred)2810 proc_set_cred(struct proc *p, struct ucred *newcred)
2811 {
2812 	bool success __diagused = _proc_set_cred(p, newcred, false);
2813 
2814 	MPASS(success);
2815 }
2816 
2817 bool
proc_set_cred_enforce_proc_lim(struct proc * p,struct ucred * newcred)2818 proc_set_cred_enforce_proc_lim(struct proc *p, struct ucred *newcred)
2819 {
2820 	return (_proc_set_cred(p, newcred, true));
2821 }
2822 
2823 void
proc_unset_cred(struct proc * p,bool decrement_proc_count)2824 proc_unset_cred(struct proc *p, bool decrement_proc_count)
2825 {
2826 	struct ucred *cr;
2827 
2828 	MPASS(p->p_state == PRS_ZOMBIE || p->p_state == PRS_NEW);
2829 	cr = p->p_ucred;
2830 	p->p_ucred = NULL;
2831 	KASSERT(cr->cr_users > 0, ("%s: users %d not > 0 on cred %p",
2832 	    __func__, cr->cr_users, cr));
2833 	mtx_lock(&cr->cr_mtx);
2834 	cr->cr_users--;
2835 	if (cr->cr_users == 0)
2836 		KASSERT(cr->cr_ref > 0, ("%s: ref %ld not > 0 on cred %p",
2837 		    __func__, cr->cr_ref, cr));
2838 	mtx_unlock(&cr->cr_mtx);
2839 	if (decrement_proc_count)
2840 		(void)chgproccnt(cr->cr_ruidinfo, -1, 0);
2841 	crfree(cr);
2842 }
2843 
2844 struct ucred *
crcopysafe(struct proc * p,struct ucred * cr)2845 crcopysafe(struct proc *p, struct ucred *cr)
2846 {
2847 	struct ucred *oldcred;
2848 	int groups;
2849 
2850 	PROC_LOCK_ASSERT(p, MA_OWNED);
2851 
2852 	oldcred = p->p_ucred;
2853 	while (cr->cr_agroups < oldcred->cr_ngroups) {
2854 		groups = oldcred->cr_ngroups;
2855 		PROC_UNLOCK(p);
2856 		crextend(cr, groups);
2857 		PROC_LOCK(p);
2858 		oldcred = p->p_ucred;
2859 	}
2860 	crcopy(cr, oldcred);
2861 
2862 	return (oldcred);
2863 }
2864 
2865 /*
2866  * Extend the passed-in credentials to hold n groups.
2867  *
2868  * Must not be called after groups have been set.
2869  */
2870 void
crextend(struct ucred * cr,int n)2871 crextend(struct ucred *cr, int n)
2872 {
2873 	size_t nbytes;
2874 
2875 	MPASS2(cr->cr_ref == 1, "'cr_ref' must be 1 (referenced, unshared)");
2876 	MPASS2((cr->cr_flags & CRED_FLAG_GROUPSET) == 0,
2877 	    "groups on 'cr' already set!");
2878 	groups_check_positive_len(n);
2879 	groups_check_max_len(n);
2880 
2881 	if (n <= cr->cr_agroups)
2882 		return;
2883 
2884 	nbytes = n * sizeof(gid_t);
2885 	if (nbytes < n)
2886 		panic("Too many groups (memory size overflow)! "
2887 		    "Computation of 'kern.ngroups' should have prevented this, "
2888 		    "please fix it. In the meantime, reduce 'kern.ngroups'.");
2889 
2890 	/*
2891 	 * We allocate a power of 2 larger than 'nbytes', except when that
2892 	 * exceeds PAGE_SIZE, in which case we allocate the right multiple of
2893 	 * pages.  We assume PAGE_SIZE is a power of 2 (the call to roundup2()
2894 	 * below) but do not need to for sizeof(gid_t).
2895 	 */
2896 	if (nbytes < PAGE_SIZE) {
2897 		if (!powerof2(nbytes))
2898 			/* fls*() return a bit index starting at 1. */
2899 			nbytes = 1 << flsl(nbytes);
2900 	} else
2901 		nbytes = roundup2(nbytes, PAGE_SIZE);
2902 
2903 	/* Free the old array. */
2904 	if (cr->cr_groups != cr->cr_smallgroups)
2905 		free(cr->cr_groups, M_CRED);
2906 
2907 	cr->cr_groups = malloc(nbytes, M_CRED, M_WAITOK | M_ZERO);
2908 	cr->cr_agroups = nbytes / sizeof(gid_t);
2909 }
2910 
2911 /*
2912  * Normalizes a set of groups to be applied to a 'struct ucred'.
2913  *
2914  * Normalization ensures that the supplementary groups are sorted in ascending
2915  * order and do not contain duplicates.  This allows group_is_supplementary() to
2916  * do a binary search.
2917  */
2918 static void
groups_normalize(int * ngrp,gid_t * groups)2919 groups_normalize(int *ngrp, gid_t *groups)
2920 {
2921 	gid_t prev_g;
2922 	int ins_idx;
2923 
2924 	groups_check_positive_len(*ngrp);
2925 	groups_check_max_len(*ngrp);
2926 
2927 	if (*ngrp <= 1)
2928 		return;
2929 
2930 	qsort(groups, *ngrp, sizeof(*groups), gidp_cmp);
2931 
2932 	/* Remove duplicates. */
2933 	prev_g = groups[0];
2934 	ins_idx = 1;
2935 	for (int i = ins_idx; i < *ngrp; ++i) {
2936 		const gid_t g = groups[i];
2937 
2938 		if (g != prev_g) {
2939 			if (i != ins_idx)
2940 				groups[ins_idx] = g;
2941 			++ins_idx;
2942 			prev_g = g;
2943 		}
2944 	}
2945 	*ngrp = ins_idx;
2946 
2947 	groups_check_normalized(*ngrp, groups);
2948 }
2949 
2950 /*
2951  * Internal function copying groups into a credential.
2952  *
2953  * 'ngrp' must be strictly positive.  Either the passed 'groups' array must have
2954  * been normalized in advance (see groups_normalize()), else it must be so
2955  * before the structure is to be used again.
2956  *
2957  * This function is suitable to be used under any lock (it doesn't take any lock
2958  * itself nor sleep, and in particular doesn't allocate memory).  crextend()
2959  * must have been called beforehand to ensure sufficient space is available.
2960  * See also crsetgroups(), which handles that.
2961  */
2962 static void
crsetgroups_internal(struct ucred * cr,int ngrp,const gid_t * groups)2963 crsetgroups_internal(struct ucred *cr, int ngrp, const gid_t *groups)
2964 {
2965 
2966 	MPASS2(cr->cr_ref == 1, "'cr_ref' must be 1 (referenced, unshared)");
2967 	MPASS2(cr->cr_agroups >= ngrp, "'cr_agroups' too small");
2968 	groups_check_positive_len(ngrp);
2969 
2970 	bcopy(groups, cr->cr_groups, ngrp * sizeof(gid_t));
2971 	cr->cr_ngroups = ngrp;
2972 	cr->cr_flags |= CRED_FLAG_GROUPSET;
2973 }
2974 
2975 /*
2976  * Copy groups in to a credential after expanding it if required.
2977  *
2978  * May sleep in order to allocate memory (except if, e.g., crextend() was called
2979  * before with 'ngrp' or greater).  Truncates the list to 'ngroups_max' if
2980  * it is too large.  Array 'groups' doesn't need to be sorted.  'ngrp' must be
2981  * positive.
2982  */
2983 void
crsetgroups(struct ucred * cr,int ngrp,const gid_t * groups)2984 crsetgroups(struct ucred *cr, int ngrp, const gid_t *groups)
2985 {
2986 
2987 	if (ngrp > ngroups_max)
2988 		ngrp = ngroups_max;
2989 	cr->cr_ngroups = 0;
2990 	if (ngrp == 0) {
2991 		cr->cr_flags |= CRED_FLAG_GROUPSET;
2992 		return;
2993 	}
2994 
2995 	/*
2996 	 * crextend() asserts that groups are not set, as it may allocate a new
2997 	 * backing storage without copying the content of the old one.  Since we
2998 	 * are going to install a completely new set anyway, signal that we
2999 	 * consider the old ones thrown away.
3000 	 */
3001 	cr->cr_flags &= ~CRED_FLAG_GROUPSET;
3002 
3003 	crextend(cr, ngrp);
3004 	crsetgroups_internal(cr, ngrp, groups);
3005 	groups_normalize(&cr->cr_ngroups, cr->cr_groups);
3006 }
3007 
3008 /*
3009  * Same as crsetgroups() but sets the effective GID as well.
3010  *
3011  * This function ensures that an effective GID is always present in credentials.
3012  * An empty array will only set the effective GID to 'default_egid', while
3013  * a non-empty array will peel off groups[0] to set as the effective GID and use
3014  * the remainder, if any, as supplementary groups.
3015  */
3016 void
crsetgroups_and_egid(struct ucred * cr,int ngrp,const gid_t * groups,const gid_t default_egid)3017 crsetgroups_and_egid(struct ucred *cr, int ngrp, const gid_t *groups,
3018     const gid_t default_egid)
3019 {
3020 	if (ngrp == 0) {
3021 		cr->cr_gid = default_egid;
3022 		cr->cr_ngroups = 0;
3023 		cr->cr_flags |= CRED_FLAG_GROUPSET;
3024 		return;
3025 	}
3026 
3027 	crsetgroups(cr, ngrp - 1, groups + 1);
3028 	cr->cr_gid = groups[0];
3029 }
3030 
3031 /*
3032  * Get login name, if available.
3033  */
3034 #ifndef _SYS_SYSPROTO_H_
3035 struct getlogin_args {
3036 	char	*namebuf;
3037 	u_int	namelen;
3038 };
3039 #endif
3040 /* ARGSUSED */
3041 int
sys_getlogin(struct thread * td,struct getlogin_args * uap)3042 sys_getlogin(struct thread *td, struct getlogin_args *uap)
3043 {
3044 	char login[MAXLOGNAME];
3045 	struct proc *p = td->td_proc;
3046 	size_t len;
3047 
3048 	if (uap->namelen > MAXLOGNAME)
3049 		uap->namelen = MAXLOGNAME;
3050 	PROC_LOCK(p);
3051 	SESS_LOCK(p->p_session);
3052 	len = strlcpy(login, p->p_session->s_login, uap->namelen) + 1;
3053 	SESS_UNLOCK(p->p_session);
3054 	PROC_UNLOCK(p);
3055 	if (len > uap->namelen)
3056 		return (ERANGE);
3057 	return (copyout(login, uap->namebuf, len));
3058 }
3059 
3060 /*
3061  * Set login name.
3062  */
3063 #ifndef _SYS_SYSPROTO_H_
3064 struct setlogin_args {
3065 	char	*namebuf;
3066 };
3067 #endif
3068 /* ARGSUSED */
3069 int
sys_setlogin(struct thread * td,struct setlogin_args * uap)3070 sys_setlogin(struct thread *td, struct setlogin_args *uap)
3071 {
3072 	struct proc *p = td->td_proc;
3073 	int error;
3074 	char logintmp[MAXLOGNAME];
3075 
3076 	CTASSERT(sizeof(p->p_session->s_login) >= sizeof(logintmp));
3077 
3078 	error = priv_check(td, PRIV_PROC_SETLOGIN);
3079 	if (error)
3080 		return (error);
3081 	error = copyinstr(uap->namebuf, logintmp, sizeof(logintmp), NULL);
3082 	if (error != 0) {
3083 		if (error == ENAMETOOLONG)
3084 			error = EINVAL;
3085 		return (error);
3086 	}
3087 	AUDIT_ARG_LOGIN(logintmp);
3088 	PROC_LOCK(p);
3089 	SESS_LOCK(p->p_session);
3090 	strcpy(p->p_session->s_login, logintmp);
3091 	SESS_UNLOCK(p->p_session);
3092 	PROC_UNLOCK(p);
3093 	return (0);
3094 }
3095 
3096 void
setsugid(struct proc * p)3097 setsugid(struct proc *p)
3098 {
3099 
3100 	PROC_LOCK_ASSERT(p, MA_OWNED);
3101 	p->p_flag |= P_SUGID;
3102 }
3103 
3104 /*-
3105  * Change a process's effective uid.
3106  * Side effects: newcred->cr_uid and newcred->cr_uidinfo will be modified.
3107  * References: newcred must be an exclusive credential reference for the
3108  *             duration of the call.
3109  */
3110 void
change_euid(struct ucred * newcred,struct uidinfo * euip)3111 change_euid(struct ucred *newcred, struct uidinfo *euip)
3112 {
3113 
3114 	newcred->cr_uid = euip->ui_uid;
3115 	uihold(euip);
3116 	uifree(newcred->cr_uidinfo);
3117 	newcred->cr_uidinfo = euip;
3118 }
3119 
3120 /*-
3121  * Change a process's effective gid.
3122  * Side effects: newcred->cr_gid will be modified.
3123  * References: newcred must be an exclusive credential reference for the
3124  *             duration of the call.
3125  */
3126 void
change_egid(struct ucred * newcred,gid_t egid)3127 change_egid(struct ucred *newcred, gid_t egid)
3128 {
3129 
3130 	newcred->cr_gid = egid;
3131 }
3132 
3133 /*-
3134  * Change a process's real uid.
3135  * Side effects: newcred->cr_ruid will be updated, newcred->cr_ruidinfo
3136  *               will be updated.
3137  * References: newcred must be an exclusive credential reference for the
3138  *             duration of the call.
3139  */
3140 void
change_ruid(struct ucred * newcred,struct uidinfo * ruip)3141 change_ruid(struct ucred *newcred, struct uidinfo *ruip)
3142 {
3143 
3144 	newcred->cr_ruid = ruip->ui_uid;
3145 	uihold(ruip);
3146 	uifree(newcred->cr_ruidinfo);
3147 	newcred->cr_ruidinfo = ruip;
3148 }
3149 
3150 /*-
3151  * Change a process's real gid.
3152  * Side effects: newcred->cr_rgid will be updated.
3153  * References: newcred must be an exclusive credential reference for the
3154  *             duration of the call.
3155  */
3156 void
change_rgid(struct ucred * newcred,gid_t rgid)3157 change_rgid(struct ucred *newcred, gid_t rgid)
3158 {
3159 
3160 	newcred->cr_rgid = rgid;
3161 }
3162 
3163 /*-
3164  * Change a process's saved uid.
3165  * Side effects: newcred->cr_svuid will be updated.
3166  * References: newcred must be an exclusive credential reference for the
3167  *             duration of the call.
3168  */
3169 void
change_svuid(struct ucred * newcred,uid_t svuid)3170 change_svuid(struct ucred *newcred, uid_t svuid)
3171 {
3172 
3173 	newcred->cr_svuid = svuid;
3174 }
3175 
3176 /*-
3177  * Change a process's saved gid.
3178  * Side effects: newcred->cr_svgid will be updated.
3179  * References: newcred must be an exclusive credential reference for the
3180  *             duration of the call.
3181  */
3182 void
change_svgid(struct ucred * newcred,gid_t svgid)3183 change_svgid(struct ucred *newcred, gid_t svgid)
3184 {
3185 
3186 	newcred->cr_svgid = svgid;
3187 }
3188 
3189 bool allow_ptrace = true;
3190 SYSCTL_BOOL(_security_bsd, OID_AUTO, allow_ptrace, CTLFLAG_RWTUN,
3191     &allow_ptrace, 0,
3192     "Deny ptrace(2) use by returning ENOSYS");
3193