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