Back to home page

LXR

 
 

    


0001 /* Common capabilities, needed by capability.o.
0002  *
0003  *  This program is free software; you can redistribute it and/or modify
0004  *  it under the terms of the GNU General Public License as published by
0005  *  the Free Software Foundation; either version 2 of the License, or
0006  *  (at your option) any later version.
0007  *
0008  */
0009 
0010 #include <linux/capability.h>
0011 #include <linux/audit.h>
0012 #include <linux/module.h>
0013 #include <linux/init.h>
0014 #include <linux/kernel.h>
0015 #include <linux/lsm_hooks.h>
0016 #include <linux/file.h>
0017 #include <linux/mm.h>
0018 #include <linux/mman.h>
0019 #include <linux/pagemap.h>
0020 #include <linux/swap.h>
0021 #include <linux/skbuff.h>
0022 #include <linux/netlink.h>
0023 #include <linux/ptrace.h>
0024 #include <linux/xattr.h>
0025 #include <linux/hugetlb.h>
0026 #include <linux/mount.h>
0027 #include <linux/sched.h>
0028 #include <linux/prctl.h>
0029 #include <linux/securebits.h>
0030 #include <linux/user_namespace.h>
0031 #include <linux/binfmts.h>
0032 #include <linux/personality.h>
0033 
0034 /*
0035  * If a non-root user executes a setuid-root binary in
0036  * !secure(SECURE_NOROOT) mode, then we raise capabilities.
0037  * However if fE is also set, then the intent is for only
0038  * the file capabilities to be applied, and the setuid-root
0039  * bit is left on either to change the uid (plausible) or
0040  * to get full privilege on a kernel without file capabilities
0041  * support.  So in that case we do not raise capabilities.
0042  *
0043  * Warn if that happens, once per boot.
0044  */
0045 static void warn_setuid_and_fcaps_mixed(const char *fname)
0046 {
0047     static int warned;
0048     if (!warned) {
0049         printk(KERN_INFO "warning: `%s' has both setuid-root and"
0050             " effective capabilities. Therefore not raising all"
0051             " capabilities.\n", fname);
0052         warned = 1;
0053     }
0054 }
0055 
0056 /**
0057  * cap_capable - Determine whether a task has a particular effective capability
0058  * @cred: The credentials to use
0059  * @ns:  The user namespace in which we need the capability
0060  * @cap: The capability to check for
0061  * @audit: Whether to write an audit message or not
0062  *
0063  * Determine whether the nominated task has the specified capability amongst
0064  * its effective set, returning 0 if it does, -ve if it does not.
0065  *
0066  * NOTE WELL: cap_has_capability() cannot be used like the kernel's capable()
0067  * and has_capability() functions.  That is, it has the reverse semantics:
0068  * cap_has_capability() returns 0 when a task has a capability, but the
0069  * kernel's capable() and has_capability() returns 1 for this case.
0070  */
0071 int cap_capable(const struct cred *cred, struct user_namespace *targ_ns,
0072         int cap, int audit)
0073 {
0074     struct user_namespace *ns = targ_ns;
0075 
0076     /* See if cred has the capability in the target user namespace
0077      * by examining the target user namespace and all of the target
0078      * user namespace's parents.
0079      */
0080     for (;;) {
0081         /* Do we have the necessary capabilities? */
0082         if (ns == cred->user_ns)
0083             return cap_raised(cred->cap_effective, cap) ? 0 : -EPERM;
0084 
0085         /* Have we tried all of the parent namespaces? */
0086         if (ns == &init_user_ns)
0087             return -EPERM;
0088 
0089         /* 
0090          * The owner of the user namespace in the parent of the
0091          * user namespace has all caps.
0092          */
0093         if ((ns->parent == cred->user_ns) && uid_eq(ns->owner, cred->euid))
0094             return 0;
0095 
0096         /*
0097          * If you have a capability in a parent user ns, then you have
0098          * it over all children user namespaces as well.
0099          */
0100         ns = ns->parent;
0101     }
0102 
0103     /* We never get here */
0104 }
0105 
0106 /**
0107  * cap_settime - Determine whether the current process may set the system clock
0108  * @ts: The time to set
0109  * @tz: The timezone to set
0110  *
0111  * Determine whether the current process may set the system clock and timezone
0112  * information, returning 0 if permission granted, -ve if denied.
0113  */
0114 int cap_settime(const struct timespec64 *ts, const struct timezone *tz)
0115 {
0116     if (!capable(CAP_SYS_TIME))
0117         return -EPERM;
0118     return 0;
0119 }
0120 
0121 /**
0122  * cap_ptrace_access_check - Determine whether the current process may access
0123  *             another
0124  * @child: The process to be accessed
0125  * @mode: The mode of attachment.
0126  *
0127  * If we are in the same or an ancestor user_ns and have all the target
0128  * task's capabilities, then ptrace access is allowed.
0129  * If we have the ptrace capability to the target user_ns, then ptrace
0130  * access is allowed.
0131  * Else denied.
0132  *
0133  * Determine whether a process may access another, returning 0 if permission
0134  * granted, -ve if denied.
0135  */
0136 int cap_ptrace_access_check(struct task_struct *child, unsigned int mode)
0137 {
0138     int ret = 0;
0139     const struct cred *cred, *child_cred;
0140     const kernel_cap_t *caller_caps;
0141 
0142     rcu_read_lock();
0143     cred = current_cred();
0144     child_cred = __task_cred(child);
0145     if (mode & PTRACE_MODE_FSCREDS)
0146         caller_caps = &cred->cap_effective;
0147     else
0148         caller_caps = &cred->cap_permitted;
0149     if (cred->user_ns == child_cred->user_ns &&
0150         cap_issubset(child_cred->cap_permitted, *caller_caps))
0151         goto out;
0152     if (ns_capable(child_cred->user_ns, CAP_SYS_PTRACE))
0153         goto out;
0154     ret = -EPERM;
0155 out:
0156     rcu_read_unlock();
0157     return ret;
0158 }
0159 
0160 /**
0161  * cap_ptrace_traceme - Determine whether another process may trace the current
0162  * @parent: The task proposed to be the tracer
0163  *
0164  * If parent is in the same or an ancestor user_ns and has all current's
0165  * capabilities, then ptrace access is allowed.
0166  * If parent has the ptrace capability to current's user_ns, then ptrace
0167  * access is allowed.
0168  * Else denied.
0169  *
0170  * Determine whether the nominated task is permitted to trace the current
0171  * process, returning 0 if permission is granted, -ve if denied.
0172  */
0173 int cap_ptrace_traceme(struct task_struct *parent)
0174 {
0175     int ret = 0;
0176     const struct cred *cred, *child_cred;
0177 
0178     rcu_read_lock();
0179     cred = __task_cred(parent);
0180     child_cred = current_cred();
0181     if (cred->user_ns == child_cred->user_ns &&
0182         cap_issubset(child_cred->cap_permitted, cred->cap_permitted))
0183         goto out;
0184     if (has_ns_capability(parent, child_cred->user_ns, CAP_SYS_PTRACE))
0185         goto out;
0186     ret = -EPERM;
0187 out:
0188     rcu_read_unlock();
0189     return ret;
0190 }
0191 
0192 /**
0193  * cap_capget - Retrieve a task's capability sets
0194  * @target: The task from which to retrieve the capability sets
0195  * @effective: The place to record the effective set
0196  * @inheritable: The place to record the inheritable set
0197  * @permitted: The place to record the permitted set
0198  *
0199  * This function retrieves the capabilities of the nominated task and returns
0200  * them to the caller.
0201  */
0202 int cap_capget(struct task_struct *target, kernel_cap_t *effective,
0203            kernel_cap_t *inheritable, kernel_cap_t *permitted)
0204 {
0205     const struct cred *cred;
0206 
0207     /* Derived from kernel/capability.c:sys_capget. */
0208     rcu_read_lock();
0209     cred = __task_cred(target);
0210     *effective   = cred->cap_effective;
0211     *inheritable = cred->cap_inheritable;
0212     *permitted   = cred->cap_permitted;
0213     rcu_read_unlock();
0214     return 0;
0215 }
0216 
0217 /*
0218  * Determine whether the inheritable capabilities are limited to the old
0219  * permitted set.  Returns 1 if they are limited, 0 if they are not.
0220  */
0221 static inline int cap_inh_is_capped(void)
0222 {
0223 
0224     /* they are so limited unless the current task has the CAP_SETPCAP
0225      * capability
0226      */
0227     if (cap_capable(current_cred(), current_cred()->user_ns,
0228             CAP_SETPCAP, SECURITY_CAP_AUDIT) == 0)
0229         return 0;
0230     return 1;
0231 }
0232 
0233 /**
0234  * cap_capset - Validate and apply proposed changes to current's capabilities
0235  * @new: The proposed new credentials; alterations should be made here
0236  * @old: The current task's current credentials
0237  * @effective: A pointer to the proposed new effective capabilities set
0238  * @inheritable: A pointer to the proposed new inheritable capabilities set
0239  * @permitted: A pointer to the proposed new permitted capabilities set
0240  *
0241  * This function validates and applies a proposed mass change to the current
0242  * process's capability sets.  The changes are made to the proposed new
0243  * credentials, and assuming no error, will be committed by the caller of LSM.
0244  */
0245 int cap_capset(struct cred *new,
0246            const struct cred *old,
0247            const kernel_cap_t *effective,
0248            const kernel_cap_t *inheritable,
0249            const kernel_cap_t *permitted)
0250 {
0251     if (cap_inh_is_capped() &&
0252         !cap_issubset(*inheritable,
0253               cap_combine(old->cap_inheritable,
0254                       old->cap_permitted)))
0255         /* incapable of using this inheritable set */
0256         return -EPERM;
0257 
0258     if (!cap_issubset(*inheritable,
0259               cap_combine(old->cap_inheritable,
0260                       old->cap_bset)))
0261         /* no new pI capabilities outside bounding set */
0262         return -EPERM;
0263 
0264     /* verify restrictions on target's new Permitted set */
0265     if (!cap_issubset(*permitted, old->cap_permitted))
0266         return -EPERM;
0267 
0268     /* verify the _new_Effective_ is a subset of the _new_Permitted_ */
0269     if (!cap_issubset(*effective, *permitted))
0270         return -EPERM;
0271 
0272     new->cap_effective   = *effective;
0273     new->cap_inheritable = *inheritable;
0274     new->cap_permitted   = *permitted;
0275 
0276     /*
0277      * Mask off ambient bits that are no longer both permitted and
0278      * inheritable.
0279      */
0280     new->cap_ambient = cap_intersect(new->cap_ambient,
0281                      cap_intersect(*permitted,
0282                                *inheritable));
0283     if (WARN_ON(!cap_ambient_invariant_ok(new)))
0284         return -EINVAL;
0285     return 0;
0286 }
0287 
0288 /*
0289  * Clear proposed capability sets for execve().
0290  */
0291 static inline void bprm_clear_caps(struct linux_binprm *bprm)
0292 {
0293     cap_clear(bprm->cred->cap_permitted);
0294     bprm->cap_effective = false;
0295 }
0296 
0297 /**
0298  * cap_inode_need_killpriv - Determine if inode change affects privileges
0299  * @dentry: The inode/dentry in being changed with change marked ATTR_KILL_PRIV
0300  *
0301  * Determine if an inode having a change applied that's marked ATTR_KILL_PRIV
0302  * affects the security markings on that inode, and if it is, should
0303  * inode_killpriv() be invoked or the change rejected?
0304  *
0305  * Returns 0 if granted; +ve if granted, but inode_killpriv() is required; and
0306  * -ve to deny the change.
0307  */
0308 int cap_inode_need_killpriv(struct dentry *dentry)
0309 {
0310     struct inode *inode = d_backing_inode(dentry);
0311     int error;
0312 
0313     error = __vfs_getxattr(dentry, inode, XATTR_NAME_CAPS, NULL, 0);
0314     return error > 0;
0315 }
0316 
0317 /**
0318  * cap_inode_killpriv - Erase the security markings on an inode
0319  * @dentry: The inode/dentry to alter
0320  *
0321  * Erase the privilege-enhancing security markings on an inode.
0322  *
0323  * Returns 0 if successful, -ve on error.
0324  */
0325 int cap_inode_killpriv(struct dentry *dentry)
0326 {
0327     int error;
0328 
0329     error = __vfs_removexattr(dentry, XATTR_NAME_CAPS);
0330     if (error == -EOPNOTSUPP)
0331         error = 0;
0332     return error;
0333 }
0334 
0335 /*
0336  * Calculate the new process capability sets from the capability sets attached
0337  * to a file.
0338  */
0339 static inline int bprm_caps_from_vfs_caps(struct cpu_vfs_cap_data *caps,
0340                       struct linux_binprm *bprm,
0341                       bool *effective,
0342                       bool *has_cap)
0343 {
0344     struct cred *new = bprm->cred;
0345     unsigned i;
0346     int ret = 0;
0347 
0348     if (caps->magic_etc & VFS_CAP_FLAGS_EFFECTIVE)
0349         *effective = true;
0350 
0351     if (caps->magic_etc & VFS_CAP_REVISION_MASK)
0352         *has_cap = true;
0353 
0354     CAP_FOR_EACH_U32(i) {
0355         __u32 permitted = caps->permitted.cap[i];
0356         __u32 inheritable = caps->inheritable.cap[i];
0357 
0358         /*
0359          * pP' = (X & fP) | (pI & fI)
0360          * The addition of pA' is handled later.
0361          */
0362         new->cap_permitted.cap[i] =
0363             (new->cap_bset.cap[i] & permitted) |
0364             (new->cap_inheritable.cap[i] & inheritable);
0365 
0366         if (permitted & ~new->cap_permitted.cap[i])
0367             /* insufficient to execute correctly */
0368             ret = -EPERM;
0369     }
0370 
0371     /*
0372      * For legacy apps, with no internal support for recognizing they
0373      * do not have enough capabilities, we return an error if they are
0374      * missing some "forced" (aka file-permitted) capabilities.
0375      */
0376     return *effective ? ret : 0;
0377 }
0378 
0379 /*
0380  * Extract the on-exec-apply capability sets for an executable file.
0381  */
0382 int get_vfs_caps_from_disk(const struct dentry *dentry, struct cpu_vfs_cap_data *cpu_caps)
0383 {
0384     struct inode *inode = d_backing_inode(dentry);
0385     __u32 magic_etc;
0386     unsigned tocopy, i;
0387     int size;
0388     struct vfs_cap_data caps;
0389 
0390     memset(cpu_caps, 0, sizeof(struct cpu_vfs_cap_data));
0391 
0392     if (!inode)
0393         return -ENODATA;
0394 
0395     size = __vfs_getxattr((struct dentry *)dentry, inode,
0396                   XATTR_NAME_CAPS, &caps, XATTR_CAPS_SZ);
0397     if (size == -ENODATA || size == -EOPNOTSUPP)
0398         /* no data, that's ok */
0399         return -ENODATA;
0400     if (size < 0)
0401         return size;
0402 
0403     if (size < sizeof(magic_etc))
0404         return -EINVAL;
0405 
0406     cpu_caps->magic_etc = magic_etc = le32_to_cpu(caps.magic_etc);
0407 
0408     switch (magic_etc & VFS_CAP_REVISION_MASK) {
0409     case VFS_CAP_REVISION_1:
0410         if (size != XATTR_CAPS_SZ_1)
0411             return -EINVAL;
0412         tocopy = VFS_CAP_U32_1;
0413         break;
0414     case VFS_CAP_REVISION_2:
0415         if (size != XATTR_CAPS_SZ_2)
0416             return -EINVAL;
0417         tocopy = VFS_CAP_U32_2;
0418         break;
0419     default:
0420         return -EINVAL;
0421     }
0422 
0423     CAP_FOR_EACH_U32(i) {
0424         if (i >= tocopy)
0425             break;
0426         cpu_caps->permitted.cap[i] = le32_to_cpu(caps.data[i].permitted);
0427         cpu_caps->inheritable.cap[i] = le32_to_cpu(caps.data[i].inheritable);
0428     }
0429 
0430     cpu_caps->permitted.cap[CAP_LAST_U32] &= CAP_LAST_U32_VALID_MASK;
0431     cpu_caps->inheritable.cap[CAP_LAST_U32] &= CAP_LAST_U32_VALID_MASK;
0432 
0433     return 0;
0434 }
0435 
0436 /*
0437  * Attempt to get the on-exec apply capability sets for an executable file from
0438  * its xattrs and, if present, apply them to the proposed credentials being
0439  * constructed by execve().
0440  */
0441 static int get_file_caps(struct linux_binprm *bprm, bool *effective, bool *has_cap)
0442 {
0443     int rc = 0;
0444     struct cpu_vfs_cap_data vcaps;
0445 
0446     bprm_clear_caps(bprm);
0447 
0448     if (!file_caps_enabled)
0449         return 0;
0450 
0451     if (!mnt_may_suid(bprm->file->f_path.mnt))
0452         return 0;
0453 
0454     /*
0455      * This check is redundant with mnt_may_suid() but is kept to make
0456      * explicit that capability bits are limited to s_user_ns and its
0457      * descendants.
0458      */
0459     if (!current_in_userns(bprm->file->f_path.mnt->mnt_sb->s_user_ns))
0460         return 0;
0461 
0462     rc = get_vfs_caps_from_disk(bprm->file->f_path.dentry, &vcaps);
0463     if (rc < 0) {
0464         if (rc == -EINVAL)
0465             printk(KERN_NOTICE "%s: get_vfs_caps_from_disk returned %d for %s\n",
0466                 __func__, rc, bprm->filename);
0467         else if (rc == -ENODATA)
0468             rc = 0;
0469         goto out;
0470     }
0471 
0472     rc = bprm_caps_from_vfs_caps(&vcaps, bprm, effective, has_cap);
0473     if (rc == -EINVAL)
0474         printk(KERN_NOTICE "%s: cap_from_disk returned %d for %s\n",
0475                __func__, rc, bprm->filename);
0476 
0477 out:
0478     if (rc)
0479         bprm_clear_caps(bprm);
0480 
0481     return rc;
0482 }
0483 
0484 /**
0485  * cap_bprm_set_creds - Set up the proposed credentials for execve().
0486  * @bprm: The execution parameters, including the proposed creds
0487  *
0488  * Set up the proposed credentials for a new execution context being
0489  * constructed by execve().  The proposed creds in @bprm->cred is altered,
0490  * which won't take effect immediately.  Returns 0 if successful, -ve on error.
0491  */
0492 int cap_bprm_set_creds(struct linux_binprm *bprm)
0493 {
0494     const struct cred *old = current_cred();
0495     struct cred *new = bprm->cred;
0496     bool effective, has_cap = false, is_setid;
0497     int ret;
0498     kuid_t root_uid;
0499 
0500     if (WARN_ON(!cap_ambient_invariant_ok(old)))
0501         return -EPERM;
0502 
0503     effective = false;
0504     ret = get_file_caps(bprm, &effective, &has_cap);
0505     if (ret < 0)
0506         return ret;
0507 
0508     root_uid = make_kuid(new->user_ns, 0);
0509 
0510     if (!issecure(SECURE_NOROOT)) {
0511         /*
0512          * If the legacy file capability is set, then don't set privs
0513          * for a setuid root binary run by a non-root user.  Do set it
0514          * for a root user just to cause least surprise to an admin.
0515          */
0516         if (has_cap && !uid_eq(new->uid, root_uid) && uid_eq(new->euid, root_uid)) {
0517             warn_setuid_and_fcaps_mixed(bprm->filename);
0518             goto skip;
0519         }
0520         /*
0521          * To support inheritance of root-permissions and suid-root
0522          * executables under compatibility mode, we override the
0523          * capability sets for the file.
0524          *
0525          * If only the real uid is 0, we do not set the effective bit.
0526          */
0527         if (uid_eq(new->euid, root_uid) || uid_eq(new->uid, root_uid)) {
0528             /* pP' = (cap_bset & ~0) | (pI & ~0) */
0529             new->cap_permitted = cap_combine(old->cap_bset,
0530                              old->cap_inheritable);
0531         }
0532         if (uid_eq(new->euid, root_uid))
0533             effective = true;
0534     }
0535 skip:
0536 
0537     /* if we have fs caps, clear dangerous personality flags */
0538     if (!cap_issubset(new->cap_permitted, old->cap_permitted))
0539         bprm->per_clear |= PER_CLEAR_ON_SETID;
0540 
0541 
0542     /* Don't let someone trace a set[ug]id/setpcap binary with the revised
0543      * credentials unless they have the appropriate permit.
0544      *
0545      * In addition, if NO_NEW_PRIVS, then ensure we get no new privs.
0546      */
0547     is_setid = !uid_eq(new->euid, old->uid) || !gid_eq(new->egid, old->gid);
0548 
0549     if ((is_setid ||
0550          !cap_issubset(new->cap_permitted, old->cap_permitted)) &&
0551         bprm->unsafe & ~LSM_UNSAFE_PTRACE_CAP) {
0552         /* downgrade; they get no more than they had, and maybe less */
0553         if (!capable(CAP_SETUID) ||
0554             (bprm->unsafe & LSM_UNSAFE_NO_NEW_PRIVS)) {
0555             new->euid = new->uid;
0556             new->egid = new->gid;
0557         }
0558         new->cap_permitted = cap_intersect(new->cap_permitted,
0559                            old->cap_permitted);
0560     }
0561 
0562     new->suid = new->fsuid = new->euid;
0563     new->sgid = new->fsgid = new->egid;
0564 
0565     /* File caps or setid cancels ambient. */
0566     if (has_cap || is_setid)
0567         cap_clear(new->cap_ambient);
0568 
0569     /*
0570      * Now that we've computed pA', update pP' to give:
0571      *   pP' = (X & fP) | (pI & fI) | pA'
0572      */
0573     new->cap_permitted = cap_combine(new->cap_permitted, new->cap_ambient);
0574 
0575     /*
0576      * Set pE' = (fE ? pP' : pA').  Because pA' is zero if fE is set,
0577      * this is the same as pE' = (fE ? pP' : 0) | pA'.
0578      */
0579     if (effective)
0580         new->cap_effective = new->cap_permitted;
0581     else
0582         new->cap_effective = new->cap_ambient;
0583 
0584     if (WARN_ON(!cap_ambient_invariant_ok(new)))
0585         return -EPERM;
0586 
0587     bprm->cap_effective = effective;
0588 
0589     /*
0590      * Audit candidate if current->cap_effective is set
0591      *
0592      * We do not bother to audit if 3 things are true:
0593      *   1) cap_effective has all caps
0594      *   2) we are root
0595      *   3) root is supposed to have all caps (SECURE_NOROOT)
0596      * Since this is just a normal root execing a process.
0597      *
0598      * Number 1 above might fail if you don't have a full bset, but I think
0599      * that is interesting information to audit.
0600      */
0601     if (!cap_issubset(new->cap_effective, new->cap_ambient)) {
0602         if (!cap_issubset(CAP_FULL_SET, new->cap_effective) ||
0603             !uid_eq(new->euid, root_uid) || !uid_eq(new->uid, root_uid) ||
0604             issecure(SECURE_NOROOT)) {
0605             ret = audit_log_bprm_fcaps(bprm, new, old);
0606             if (ret < 0)
0607                 return ret;
0608         }
0609     }
0610 
0611     new->securebits &= ~issecure_mask(SECURE_KEEP_CAPS);
0612 
0613     if (WARN_ON(!cap_ambient_invariant_ok(new)))
0614         return -EPERM;
0615 
0616     return 0;
0617 }
0618 
0619 /**
0620  * cap_bprm_secureexec - Determine whether a secure execution is required
0621  * @bprm: The execution parameters
0622  *
0623  * Determine whether a secure execution is required, return 1 if it is, and 0
0624  * if it is not.
0625  *
0626  * The credentials have been committed by this point, and so are no longer
0627  * available through @bprm->cred.
0628  */
0629 int cap_bprm_secureexec(struct linux_binprm *bprm)
0630 {
0631     const struct cred *cred = current_cred();
0632     kuid_t root_uid = make_kuid(cred->user_ns, 0);
0633 
0634     if (!uid_eq(cred->uid, root_uid)) {
0635         if (bprm->cap_effective)
0636             return 1;
0637         if (!cap_issubset(cred->cap_permitted, cred->cap_ambient))
0638             return 1;
0639     }
0640 
0641     return (!uid_eq(cred->euid, cred->uid) ||
0642         !gid_eq(cred->egid, cred->gid));
0643 }
0644 
0645 /**
0646  * cap_inode_setxattr - Determine whether an xattr may be altered
0647  * @dentry: The inode/dentry being altered
0648  * @name: The name of the xattr to be changed
0649  * @value: The value that the xattr will be changed to
0650  * @size: The size of value
0651  * @flags: The replacement flag
0652  *
0653  * Determine whether an xattr may be altered or set on an inode, returning 0 if
0654  * permission is granted, -ve if denied.
0655  *
0656  * This is used to make sure security xattrs don't get updated or set by those
0657  * who aren't privileged to do so.
0658  */
0659 int cap_inode_setxattr(struct dentry *dentry, const char *name,
0660                const void *value, size_t size, int flags)
0661 {
0662     if (!strcmp(name, XATTR_NAME_CAPS)) {
0663         if (!capable(CAP_SETFCAP))
0664             return -EPERM;
0665         return 0;
0666     }
0667 
0668     if (!strncmp(name, XATTR_SECURITY_PREFIX,
0669              sizeof(XATTR_SECURITY_PREFIX) - 1) &&
0670         !capable(CAP_SYS_ADMIN))
0671         return -EPERM;
0672     return 0;
0673 }
0674 
0675 /**
0676  * cap_inode_removexattr - Determine whether an xattr may be removed
0677  * @dentry: The inode/dentry being altered
0678  * @name: The name of the xattr to be changed
0679  *
0680  * Determine whether an xattr may be removed from an inode, returning 0 if
0681  * permission is granted, -ve if denied.
0682  *
0683  * This is used to make sure security xattrs don't get removed by those who
0684  * aren't privileged to remove them.
0685  */
0686 int cap_inode_removexattr(struct dentry *dentry, const char *name)
0687 {
0688     if (!strcmp(name, XATTR_NAME_CAPS)) {
0689         if (!capable(CAP_SETFCAP))
0690             return -EPERM;
0691         return 0;
0692     }
0693 
0694     if (!strncmp(name, XATTR_SECURITY_PREFIX,
0695              sizeof(XATTR_SECURITY_PREFIX) - 1) &&
0696         !capable(CAP_SYS_ADMIN))
0697         return -EPERM;
0698     return 0;
0699 }
0700 
0701 /*
0702  * cap_emulate_setxuid() fixes the effective / permitted capabilities of
0703  * a process after a call to setuid, setreuid, or setresuid.
0704  *
0705  *  1) When set*uiding _from_ one of {r,e,s}uid == 0 _to_ all of
0706  *  {r,e,s}uid != 0, the permitted and effective capabilities are
0707  *  cleared.
0708  *
0709  *  2) When set*uiding _from_ euid == 0 _to_ euid != 0, the effective
0710  *  capabilities of the process are cleared.
0711  *
0712  *  3) When set*uiding _from_ euid != 0 _to_ euid == 0, the effective
0713  *  capabilities are set to the permitted capabilities.
0714  *
0715  *  fsuid is handled elsewhere. fsuid == 0 and {r,e,s}uid!= 0 should
0716  *  never happen.
0717  *
0718  *  -astor
0719  *
0720  * cevans - New behaviour, Oct '99
0721  * A process may, via prctl(), elect to keep its capabilities when it
0722  * calls setuid() and switches away from uid==0. Both permitted and
0723  * effective sets will be retained.
0724  * Without this change, it was impossible for a daemon to drop only some
0725  * of its privilege. The call to setuid(!=0) would drop all privileges!
0726  * Keeping uid 0 is not an option because uid 0 owns too many vital
0727  * files..
0728  * Thanks to Olaf Kirch and Peter Benie for spotting this.
0729  */
0730 static inline void cap_emulate_setxuid(struct cred *new, const struct cred *old)
0731 {
0732     kuid_t root_uid = make_kuid(old->user_ns, 0);
0733 
0734     if ((uid_eq(old->uid, root_uid) ||
0735          uid_eq(old->euid, root_uid) ||
0736          uid_eq(old->suid, root_uid)) &&
0737         (!uid_eq(new->uid, root_uid) &&
0738          !uid_eq(new->euid, root_uid) &&
0739          !uid_eq(new->suid, root_uid))) {
0740         if (!issecure(SECURE_KEEP_CAPS)) {
0741             cap_clear(new->cap_permitted);
0742             cap_clear(new->cap_effective);
0743         }
0744 
0745         /*
0746          * Pre-ambient programs expect setresuid to nonroot followed
0747          * by exec to drop capabilities.  We should make sure that
0748          * this remains the case.
0749          */
0750         cap_clear(new->cap_ambient);
0751     }
0752     if (uid_eq(old->euid, root_uid) && !uid_eq(new->euid, root_uid))
0753         cap_clear(new->cap_effective);
0754     if (!uid_eq(old->euid, root_uid) && uid_eq(new->euid, root_uid))
0755         new->cap_effective = new->cap_permitted;
0756 }
0757 
0758 /**
0759  * cap_task_fix_setuid - Fix up the results of setuid() call
0760  * @new: The proposed credentials
0761  * @old: The current task's current credentials
0762  * @flags: Indications of what has changed
0763  *
0764  * Fix up the results of setuid() call before the credential changes are
0765  * actually applied, returning 0 to grant the changes, -ve to deny them.
0766  */
0767 int cap_task_fix_setuid(struct cred *new, const struct cred *old, int flags)
0768 {
0769     switch (flags) {
0770     case LSM_SETID_RE:
0771     case LSM_SETID_ID:
0772     case LSM_SETID_RES:
0773         /* juggle the capabilities to follow [RES]UID changes unless
0774          * otherwise suppressed */
0775         if (!issecure(SECURE_NO_SETUID_FIXUP))
0776             cap_emulate_setxuid(new, old);
0777         break;
0778 
0779     case LSM_SETID_FS:
0780         /* juggle the capabilties to follow FSUID changes, unless
0781          * otherwise suppressed
0782          *
0783          * FIXME - is fsuser used for all CAP_FS_MASK capabilities?
0784          *          if not, we might be a bit too harsh here.
0785          */
0786         if (!issecure(SECURE_NO_SETUID_FIXUP)) {
0787             kuid_t root_uid = make_kuid(old->user_ns, 0);
0788             if (uid_eq(old->fsuid, root_uid) && !uid_eq(new->fsuid, root_uid))
0789                 new->cap_effective =
0790                     cap_drop_fs_set(new->cap_effective);
0791 
0792             if (!uid_eq(old->fsuid, root_uid) && uid_eq(new->fsuid, root_uid))
0793                 new->cap_effective =
0794                     cap_raise_fs_set(new->cap_effective,
0795                              new->cap_permitted);
0796         }
0797         break;
0798 
0799     default:
0800         return -EINVAL;
0801     }
0802 
0803     return 0;
0804 }
0805 
0806 /*
0807  * Rationale: code calling task_setscheduler, task_setioprio, and
0808  * task_setnice, assumes that
0809  *   . if capable(cap_sys_nice), then those actions should be allowed
0810  *   . if not capable(cap_sys_nice), but acting on your own processes,
0811  *      then those actions should be allowed
0812  * This is insufficient now since you can call code without suid, but
0813  * yet with increased caps.
0814  * So we check for increased caps on the target process.
0815  */
0816 static int cap_safe_nice(struct task_struct *p)
0817 {
0818     int is_subset, ret = 0;
0819 
0820     rcu_read_lock();
0821     is_subset = cap_issubset(__task_cred(p)->cap_permitted,
0822                  current_cred()->cap_permitted);
0823     if (!is_subset && !ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE))
0824         ret = -EPERM;
0825     rcu_read_unlock();
0826 
0827     return ret;
0828 }
0829 
0830 /**
0831  * cap_task_setscheduler - Detemine if scheduler policy change is permitted
0832  * @p: The task to affect
0833  *
0834  * Detemine if the requested scheduler policy change is permitted for the
0835  * specified task, returning 0 if permission is granted, -ve if denied.
0836  */
0837 int cap_task_setscheduler(struct task_struct *p)
0838 {
0839     return cap_safe_nice(p);
0840 }
0841 
0842 /**
0843  * cap_task_ioprio - Detemine if I/O priority change is permitted
0844  * @p: The task to affect
0845  * @ioprio: The I/O priority to set
0846  *
0847  * Detemine if the requested I/O priority change is permitted for the specified
0848  * task, returning 0 if permission is granted, -ve if denied.
0849  */
0850 int cap_task_setioprio(struct task_struct *p, int ioprio)
0851 {
0852     return cap_safe_nice(p);
0853 }
0854 
0855 /**
0856  * cap_task_ioprio - Detemine if task priority change is permitted
0857  * @p: The task to affect
0858  * @nice: The nice value to set
0859  *
0860  * Detemine if the requested task priority change is permitted for the
0861  * specified task, returning 0 if permission is granted, -ve if denied.
0862  */
0863 int cap_task_setnice(struct task_struct *p, int nice)
0864 {
0865     return cap_safe_nice(p);
0866 }
0867 
0868 /*
0869  * Implement PR_CAPBSET_DROP.  Attempt to remove the specified capability from
0870  * the current task's bounding set.  Returns 0 on success, -ve on error.
0871  */
0872 static int cap_prctl_drop(unsigned long cap)
0873 {
0874     struct cred *new;
0875 
0876     if (!ns_capable(current_user_ns(), CAP_SETPCAP))
0877         return -EPERM;
0878     if (!cap_valid(cap))
0879         return -EINVAL;
0880 
0881     new = prepare_creds();
0882     if (!new)
0883         return -ENOMEM;
0884     cap_lower(new->cap_bset, cap);
0885     return commit_creds(new);
0886 }
0887 
0888 /**
0889  * cap_task_prctl - Implement process control functions for this security module
0890  * @option: The process control function requested
0891  * @arg2, @arg3, @arg4, @arg5: The argument data for this function
0892  *
0893  * Allow process control functions (sys_prctl()) to alter capabilities; may
0894  * also deny access to other functions not otherwise implemented here.
0895  *
0896  * Returns 0 or +ve on success, -ENOSYS if this function is not implemented
0897  * here, other -ve on error.  If -ENOSYS is returned, sys_prctl() and other LSM
0898  * modules will consider performing the function.
0899  */
0900 int cap_task_prctl(int option, unsigned long arg2, unsigned long arg3,
0901            unsigned long arg4, unsigned long arg5)
0902 {
0903     const struct cred *old = current_cred();
0904     struct cred *new;
0905 
0906     switch (option) {
0907     case PR_CAPBSET_READ:
0908         if (!cap_valid(arg2))
0909             return -EINVAL;
0910         return !!cap_raised(old->cap_bset, arg2);
0911 
0912     case PR_CAPBSET_DROP:
0913         return cap_prctl_drop(arg2);
0914 
0915     /*
0916      * The next four prctl's remain to assist with transitioning a
0917      * system from legacy UID=0 based privilege (when filesystem
0918      * capabilities are not in use) to a system using filesystem
0919      * capabilities only - as the POSIX.1e draft intended.
0920      *
0921      * Note:
0922      *
0923      *  PR_SET_SECUREBITS =
0924      *      issecure_mask(SECURE_KEEP_CAPS_LOCKED)
0925      *    | issecure_mask(SECURE_NOROOT)
0926      *    | issecure_mask(SECURE_NOROOT_LOCKED)
0927      *    | issecure_mask(SECURE_NO_SETUID_FIXUP)
0928      *    | issecure_mask(SECURE_NO_SETUID_FIXUP_LOCKED)
0929      *
0930      * will ensure that the current process and all of its
0931      * children will be locked into a pure
0932      * capability-based-privilege environment.
0933      */
0934     case PR_SET_SECUREBITS:
0935         if ((((old->securebits & SECURE_ALL_LOCKS) >> 1)
0936              & (old->securebits ^ arg2))            /*[1]*/
0937             || ((old->securebits & SECURE_ALL_LOCKS & ~arg2))   /*[2]*/
0938             || (arg2 & ~(SECURE_ALL_LOCKS | SECURE_ALL_BITS))   /*[3]*/
0939             || (cap_capable(current_cred(),
0940                     current_cred()->user_ns, CAP_SETPCAP,
0941                     SECURITY_CAP_AUDIT) != 0)       /*[4]*/
0942             /*
0943              * [1] no changing of bits that are locked
0944              * [2] no unlocking of locks
0945              * [3] no setting of unsupported bits
0946              * [4] doing anything requires privilege (go read about
0947              *     the "sendmail capabilities bug")
0948              */
0949             )
0950             /* cannot change a locked bit */
0951             return -EPERM;
0952 
0953         new = prepare_creds();
0954         if (!new)
0955             return -ENOMEM;
0956         new->securebits = arg2;
0957         return commit_creds(new);
0958 
0959     case PR_GET_SECUREBITS:
0960         return old->securebits;
0961 
0962     case PR_GET_KEEPCAPS:
0963         return !!issecure(SECURE_KEEP_CAPS);
0964 
0965     case PR_SET_KEEPCAPS:
0966         if (arg2 > 1) /* Note, we rely on arg2 being unsigned here */
0967             return -EINVAL;
0968         if (issecure(SECURE_KEEP_CAPS_LOCKED))
0969             return -EPERM;
0970 
0971         new = prepare_creds();
0972         if (!new)
0973             return -ENOMEM;
0974         if (arg2)
0975             new->securebits |= issecure_mask(SECURE_KEEP_CAPS);
0976         else
0977             new->securebits &= ~issecure_mask(SECURE_KEEP_CAPS);
0978         return commit_creds(new);
0979 
0980     case PR_CAP_AMBIENT:
0981         if (arg2 == PR_CAP_AMBIENT_CLEAR_ALL) {
0982             if (arg3 | arg4 | arg5)
0983                 return -EINVAL;
0984 
0985             new = prepare_creds();
0986             if (!new)
0987                 return -ENOMEM;
0988             cap_clear(new->cap_ambient);
0989             return commit_creds(new);
0990         }
0991 
0992         if (((!cap_valid(arg3)) | arg4 | arg5))
0993             return -EINVAL;
0994 
0995         if (arg2 == PR_CAP_AMBIENT_IS_SET) {
0996             return !!cap_raised(current_cred()->cap_ambient, arg3);
0997         } else if (arg2 != PR_CAP_AMBIENT_RAISE &&
0998                arg2 != PR_CAP_AMBIENT_LOWER) {
0999             return -EINVAL;
1000         } else {
1001             if (arg2 == PR_CAP_AMBIENT_RAISE &&
1002                 (!cap_raised(current_cred()->cap_permitted, arg3) ||
1003                  !cap_raised(current_cred()->cap_inheritable,
1004                      arg3) ||
1005                  issecure(SECURE_NO_CAP_AMBIENT_RAISE)))
1006                 return -EPERM;
1007 
1008             new = prepare_creds();
1009             if (!new)
1010                 return -ENOMEM;
1011             if (arg2 == PR_CAP_AMBIENT_RAISE)
1012                 cap_raise(new->cap_ambient, arg3);
1013             else
1014                 cap_lower(new->cap_ambient, arg3);
1015             return commit_creds(new);
1016         }
1017 
1018     default:
1019         /* No functionality available - continue with default */
1020         return -ENOSYS;
1021     }
1022 }
1023 
1024 /**
1025  * cap_vm_enough_memory - Determine whether a new virtual mapping is permitted
1026  * @mm: The VM space in which the new mapping is to be made
1027  * @pages: The size of the mapping
1028  *
1029  * Determine whether the allocation of a new virtual mapping by the current
1030  * task is permitted, returning 1 if permission is granted, 0 if not.
1031  */
1032 int cap_vm_enough_memory(struct mm_struct *mm, long pages)
1033 {
1034     int cap_sys_admin = 0;
1035 
1036     if (cap_capable(current_cred(), &init_user_ns, CAP_SYS_ADMIN,
1037             SECURITY_CAP_NOAUDIT) == 0)
1038         cap_sys_admin = 1;
1039     return cap_sys_admin;
1040 }
1041 
1042 /*
1043  * cap_mmap_addr - check if able to map given addr
1044  * @addr: address attempting to be mapped
1045  *
1046  * If the process is attempting to map memory below dac_mmap_min_addr they need
1047  * CAP_SYS_RAWIO.  The other parameters to this function are unused by the
1048  * capability security module.  Returns 0 if this mapping should be allowed
1049  * -EPERM if not.
1050  */
1051 int cap_mmap_addr(unsigned long addr)
1052 {
1053     int ret = 0;
1054 
1055     if (addr < dac_mmap_min_addr) {
1056         ret = cap_capable(current_cred(), &init_user_ns, CAP_SYS_RAWIO,
1057                   SECURITY_CAP_AUDIT);
1058         /* set PF_SUPERPRIV if it turns out we allow the low mmap */
1059         if (ret == 0)
1060             current->flags |= PF_SUPERPRIV;
1061     }
1062     return ret;
1063 }
1064 
1065 int cap_mmap_file(struct file *file, unsigned long reqprot,
1066           unsigned long prot, unsigned long flags)
1067 {
1068     return 0;
1069 }
1070 
1071 #ifdef CONFIG_SECURITY
1072 
1073 struct security_hook_list capability_hooks[] = {
1074     LSM_HOOK_INIT(capable, cap_capable),
1075     LSM_HOOK_INIT(settime, cap_settime),
1076     LSM_HOOK_INIT(ptrace_access_check, cap_ptrace_access_check),
1077     LSM_HOOK_INIT(ptrace_traceme, cap_ptrace_traceme),
1078     LSM_HOOK_INIT(capget, cap_capget),
1079     LSM_HOOK_INIT(capset, cap_capset),
1080     LSM_HOOK_INIT(bprm_set_creds, cap_bprm_set_creds),
1081     LSM_HOOK_INIT(bprm_secureexec, cap_bprm_secureexec),
1082     LSM_HOOK_INIT(inode_need_killpriv, cap_inode_need_killpriv),
1083     LSM_HOOK_INIT(inode_killpriv, cap_inode_killpriv),
1084     LSM_HOOK_INIT(mmap_addr, cap_mmap_addr),
1085     LSM_HOOK_INIT(mmap_file, cap_mmap_file),
1086     LSM_HOOK_INIT(task_fix_setuid, cap_task_fix_setuid),
1087     LSM_HOOK_INIT(task_prctl, cap_task_prctl),
1088     LSM_HOOK_INIT(task_setscheduler, cap_task_setscheduler),
1089     LSM_HOOK_INIT(task_setioprio, cap_task_setioprio),
1090     LSM_HOOK_INIT(task_setnice, cap_task_setnice),
1091     LSM_HOOK_INIT(vm_enough_memory, cap_vm_enough_memory),
1092 };
1093 
1094 void __init capability_add_hooks(void)
1095 {
1096     security_add_hooks(capability_hooks, ARRAY_SIZE(capability_hooks));
1097 }
1098 
1099 #endif /* CONFIG_SECURITY */