xref: /linux/security/commoncap.c (revision 1260ed77798502de9c98020040d2995008de10cc)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* Common capabilities, needed by capability.o.
3  */
4 
5 #include <linux/capability.h>
6 #include <linux/audit.h>
7 #include <linux/init.h>
8 #include <linux/kernel.h>
9 #include <linux/lsm_hooks.h>
10 #include <linux/file.h>
11 #include <linux/mm.h>
12 #include <linux/mman.h>
13 #include <linux/pagemap.h>
14 #include <linux/swap.h>
15 #include <linux/skbuff.h>
16 #include <linux/netlink.h>
17 #include <linux/ptrace.h>
18 #include <linux/xattr.h>
19 #include <linux/hugetlb.h>
20 #include <linux/mount.h>
21 #include <linux/sched.h>
22 #include <linux/prctl.h>
23 #include <linux/securebits.h>
24 #include <linux/user_namespace.h>
25 #include <linux/binfmts.h>
26 #include <linux/personality.h>
27 #include <linux/mnt_idmapping.h>
28 #include <uapi/linux/lsm.h>
29 
30 #define CREATE_TRACE_POINTS
31 #include <trace/events/capability.h>
32 
33 /*
34  * If a non-root user executes a setuid-root binary in
35  * !secure(SECURE_NOROOT) mode, then we raise capabilities.
36  * However if fE is also set, then the intent is for only
37  * the file capabilities to be applied, and the setuid-root
38  * bit is left on either to change the uid (plausible) or
39  * to get full privilege on a kernel without file capabilities
40  * support.  So in that case we do not raise capabilities.
41  *
42  * Warn if that happens, once per boot.
43  */
44 static void warn_setuid_and_fcaps_mixed(const char *fname)
45 {
46 	static int warned;
47 	if (!warned) {
48 		printk(KERN_INFO "warning: `%s' has both setuid-root and"
49 			" effective capabilities. Therefore not raising all"
50 			" capabilities.\n", fname);
51 		warned = 1;
52 	}
53 }
54 
55 /**
56  * cap_capable_helper - Determine whether a task has a particular effective
57  * capability.
58  * @cred: The credentials to use
59  * @target_ns:  The user namespace of the resource being accessed
60  * @cred_ns:  The user namespace of the credentials
61  * @cap: The capability to check for
62  *
63  * Determine whether the nominated task has the specified capability amongst
64  * its effective set, returning 0 if it does, -ve if it does not.
65  *
66  * See cap_capable for more details.
67  */
68 static inline int cap_capable_helper(const struct cred *cred,
69 				     struct user_namespace *target_ns,
70 				     const struct user_namespace *cred_ns,
71 				     int cap)
72 {
73 	struct user_namespace *ns = target_ns;
74 
75 	/* See if cred has the capability in the target user namespace
76 	 * by examining the target user namespace and all of the target
77 	 * user namespace's parents.
78 	 */
79 	for (;;) {
80 		/* Do we have the necessary capabilities? */
81 		if (likely(ns == cred_ns))
82 			return cap_raised(cred->cap_effective, cap) ? 0 : -EPERM;
83 
84 		/*
85 		 * If we're already at a lower level than we're looking for,
86 		 * we're done searching.
87 		 */
88 		if (ns->level <= cred_ns->level)
89 			return -EPERM;
90 
91 		/*
92 		 * The owner of the user namespace in the parent of the
93 		 * user namespace has all caps.
94 		 */
95 		if ((ns->parent == cred_ns) && uid_eq(ns->owner, cred->euid))
96 			return 0;
97 
98 		/*
99 		 * If you have a capability in a parent user ns, then you have
100 		 * it over all children user namespaces as well.
101 		 */
102 		ns = ns->parent;
103 	}
104 
105 	/* We never get here */
106 }
107 
108 /**
109  * cap_capable - Determine whether a task has a particular effective capability
110  * @cred: The credentials to use
111  * @target_ns:  The user namespace of the resource being accessed
112  * @cap: The capability to check for
113  * @opts: Bitmask of options defined in include/linux/security.h (unused)
114  *
115  * Determine whether the nominated task has the specified capability amongst
116  * its effective set, returning 0 if it does, -ve if it does not.
117  *
118  * NOTE WELL: cap_capable() has reverse semantics to the capable() call
119  * and friends. That is cap_capable() returns an int 0 when a task has
120  * a capability, while the kernel's capable(), has_ns_capability(),
121  * has_ns_capability_noaudit(), and has_capability_noaudit() return a
122  * bool true (1) for this case.
123  */
124 int cap_capable(const struct cred *cred, struct user_namespace *target_ns,
125 		int cap, unsigned int opts)
126 {
127 	const struct user_namespace *cred_ns = cred->user_ns;
128 	int ret = cap_capable_helper(cred, target_ns, cred_ns, cap);
129 
130 	trace_cap_capable(cred, target_ns, cred_ns, cap, ret);
131 	return ret;
132 }
133 
134 /**
135  * cap_settime - Determine whether the current process may set the system clock
136  * @ts: The time to set
137  * @tz: The timezone to set
138  *
139  * Determine whether the current process may set the system clock and timezone
140  * information, returning 0 if permission granted, -ve if denied.
141  */
142 int cap_settime(const struct timespec64 *ts, const struct timezone *tz)
143 {
144 	if (!capable(CAP_SYS_TIME))
145 		return -EPERM;
146 	return 0;
147 }
148 
149 /**
150  * cap_ptrace_access_check - Determine whether the current process may access
151  *			   another
152  * @child: The process to be accessed
153  * @mode: The mode of attachment.
154  *
155  * If we are in the same or an ancestor user_ns and have all the target
156  * task's capabilities, then ptrace access is allowed.
157  * If we have the ptrace capability to the target user_ns, then ptrace
158  * access is allowed.
159  * Else denied.
160  *
161  * Determine whether a process may access another, returning 0 if permission
162  * granted, -ve if denied.
163  */
164 int cap_ptrace_access_check(struct task_struct *child, unsigned int mode)
165 {
166 	int ret = 0;
167 	const struct cred *cred, *child_cred;
168 	const kernel_cap_t *caller_caps;
169 
170 	rcu_read_lock();
171 	cred = current_cred();
172 	child_cred = __task_cred(child);
173 	if (mode & PTRACE_MODE_FSCREDS)
174 		caller_caps = &cred->cap_effective;
175 	else
176 		caller_caps = &cred->cap_permitted;
177 	if (cred->user_ns == child_cred->user_ns &&
178 	    cap_issubset(child_cred->cap_permitted, *caller_caps))
179 		goto out;
180 	if (ns_capable(child_cred->user_ns, CAP_SYS_PTRACE))
181 		goto out;
182 	ret = -EPERM;
183 out:
184 	rcu_read_unlock();
185 	return ret;
186 }
187 
188 /**
189  * cap_ptrace_traceme - Determine whether another process may trace the current
190  * @parent: The task proposed to be the tracer
191  *
192  * If parent is in the same or an ancestor user_ns and has all current's
193  * capabilities, then ptrace access is allowed.
194  * If parent has the ptrace capability to current's user_ns, then ptrace
195  * access is allowed.
196  * Else denied.
197  *
198  * Determine whether the nominated task is permitted to trace the current
199  * process, returning 0 if permission is granted, -ve if denied.
200  */
201 int cap_ptrace_traceme(struct task_struct *parent)
202 {
203 	int ret = 0;
204 	const struct cred *cred, *child_cred;
205 
206 	rcu_read_lock();
207 	cred = __task_cred(parent);
208 	child_cred = current_cred();
209 	if (cred->user_ns == child_cred->user_ns &&
210 	    cap_issubset(child_cred->cap_permitted, cred->cap_permitted))
211 		goto out;
212 	if (has_ns_capability(parent, child_cred->user_ns, CAP_SYS_PTRACE))
213 		goto out;
214 	ret = -EPERM;
215 out:
216 	rcu_read_unlock();
217 	return ret;
218 }
219 
220 /**
221  * cap_capget - Retrieve a task's capability sets
222  * @target: The task from which to retrieve the capability sets
223  * @effective: The place to record the effective set
224  * @inheritable: The place to record the inheritable set
225  * @permitted: The place to record the permitted set
226  *
227  * This function retrieves the capabilities of the nominated task and returns
228  * them to the caller.
229  */
230 int cap_capget(const struct task_struct *target, kernel_cap_t *effective,
231 	       kernel_cap_t *inheritable, kernel_cap_t *permitted)
232 {
233 	const struct cred *cred;
234 
235 	/* Derived from kernel/capability.c:sys_capget. */
236 	rcu_read_lock();
237 	cred = __task_cred(target);
238 	*effective   = cred->cap_effective;
239 	*inheritable = cred->cap_inheritable;
240 	*permitted   = cred->cap_permitted;
241 	rcu_read_unlock();
242 	return 0;
243 }
244 
245 /*
246  * Determine whether the inheritable capabilities are limited to the old
247  * permitted set.  Returns 1 if they are limited, 0 if they are not.
248  */
249 static inline int cap_inh_is_capped(void)
250 {
251 	/* they are so limited unless the current task has the CAP_SETPCAP
252 	 * capability
253 	 */
254 	if (cap_capable(current_cred(), current_cred()->user_ns,
255 			CAP_SETPCAP, CAP_OPT_NONE) == 0)
256 		return 0;
257 	return 1;
258 }
259 
260 /**
261  * cap_capset - Validate and apply proposed changes to current's capabilities
262  * @new: The proposed new credentials; alterations should be made here
263  * @old: The current task's current credentials
264  * @effective: A pointer to the proposed new effective capabilities set
265  * @inheritable: A pointer to the proposed new inheritable capabilities set
266  * @permitted: A pointer to the proposed new permitted capabilities set
267  *
268  * This function validates and applies a proposed mass change to the current
269  * process's capability sets.  The changes are made to the proposed new
270  * credentials, and assuming no error, will be committed by the caller of LSM.
271  */
272 int cap_capset(struct cred *new,
273 	       const struct cred *old,
274 	       const kernel_cap_t *effective,
275 	       const kernel_cap_t *inheritable,
276 	       const kernel_cap_t *permitted)
277 {
278 	if (cap_inh_is_capped() &&
279 	    !cap_issubset(*inheritable,
280 			  cap_combine(old->cap_inheritable,
281 				      old->cap_permitted)))
282 		/* incapable of using this inheritable set */
283 		return -EPERM;
284 
285 	if (!cap_issubset(*inheritable,
286 			  cap_combine(old->cap_inheritable,
287 				      old->cap_bset)))
288 		/* no new pI capabilities outside bounding set */
289 		return -EPERM;
290 
291 	/* verify restrictions on target's new Permitted set */
292 	if (!cap_issubset(*permitted, old->cap_permitted))
293 		return -EPERM;
294 
295 	/* verify the _new_Effective_ is a subset of the _new_Permitted_ */
296 	if (!cap_issubset(*effective, *permitted))
297 		return -EPERM;
298 
299 	new->cap_effective   = *effective;
300 	new->cap_inheritable = *inheritable;
301 	new->cap_permitted   = *permitted;
302 
303 	/*
304 	 * Mask off ambient bits that are no longer both permitted and
305 	 * inheritable.
306 	 */
307 	new->cap_ambient = cap_intersect(new->cap_ambient,
308 					 cap_intersect(*permitted,
309 						       *inheritable));
310 	if (WARN_ON(!cap_ambient_invariant_ok(new)))
311 		return -EINVAL;
312 	return 0;
313 }
314 
315 /**
316  * cap_inode_need_killpriv - Determine if inode change affects privileges
317  * @dentry: The inode/dentry in being changed with change marked ATTR_KILL_PRIV
318  *
319  * Determine if an inode having a change applied that's marked ATTR_KILL_PRIV
320  * affects the security markings on that inode, and if it is, should
321  * inode_killpriv() be invoked or the change rejected.
322  *
323  * Return: 1 if security.capability has a value, meaning inode_killpriv()
324  * is required, 0 otherwise, meaning inode_killpriv() is not required.
325  */
326 int cap_inode_need_killpriv(struct dentry *dentry)
327 {
328 	struct inode *inode = d_backing_inode(dentry);
329 	int error;
330 
331 	error = __vfs_getxattr(dentry, inode, XATTR_NAME_CAPS, NULL, 0);
332 	return error > 0;
333 }
334 
335 /**
336  * cap_inode_killpriv - Erase the security markings on an inode
337  *
338  * @idmap:	idmap of the mount the inode was found from
339  * @dentry:	The inode/dentry to alter
340  *
341  * Erase the privilege-enhancing security markings on an inode.
342  *
343  * If the inode has been found through an idmapped mount the idmap of
344  * the vfsmount must be passed through @idmap. This function will then
345  * take care to map the inode according to @idmap before checking
346  * permissions. On non-idmapped mounts or if permission checking is to be
347  * performed on the raw inode simply pass @nop_mnt_idmap.
348  *
349  * Return: 0 if successful, -ve on error.
350  */
351 int cap_inode_killpriv(struct mnt_idmap *idmap, struct dentry *dentry)
352 {
353 	int error;
354 
355 	error = __vfs_removexattr(idmap, dentry, XATTR_NAME_CAPS);
356 	if (error == -EOPNOTSUPP)
357 		error = 0;
358 	return error;
359 }
360 
361 static bool rootid_owns_currentns(vfsuid_t rootvfsuid)
362 {
363 	struct user_namespace *ns;
364 	kuid_t kroot;
365 
366 	if (!vfsuid_valid(rootvfsuid))
367 		return false;
368 
369 	kroot = vfsuid_into_kuid(rootvfsuid);
370 	for (ns = current_user_ns();; ns = ns->parent) {
371 		if (from_kuid(ns, kroot) == 0)
372 			return true;
373 		if (ns == &init_user_ns)
374 			break;
375 	}
376 
377 	return false;
378 }
379 
380 static __u32 sansflags(__u32 m)
381 {
382 	return m & ~VFS_CAP_FLAGS_EFFECTIVE;
383 }
384 
385 static bool is_v2header(int size, const struct vfs_cap_data *cap)
386 {
387 	if (size != XATTR_CAPS_SZ_2)
388 		return false;
389 	return sansflags(le32_to_cpu(cap->magic_etc)) == VFS_CAP_REVISION_2;
390 }
391 
392 static bool is_v3header(int size, const struct vfs_cap_data *cap)
393 {
394 	if (size != XATTR_CAPS_SZ_3)
395 		return false;
396 	return sansflags(le32_to_cpu(cap->magic_etc)) == VFS_CAP_REVISION_3;
397 }
398 
399 /*
400  * getsecurity: We are called for security.* before any attempt to read the
401  * xattr from the inode itself.
402  *
403  * This gives us a chance to read the on-disk value and convert it.  If we
404  * return -EOPNOTSUPP, then vfs_getxattr() will call the i_op handler.
405  *
406  * Note we are not called by vfs_getxattr_alloc(), but that is only called
407  * by the integrity subsystem, which really wants the unconverted values -
408  * so that's good.
409  */
410 int cap_inode_getsecurity(struct mnt_idmap *idmap,
411 			  struct inode *inode, const char *name, void **buffer,
412 			  bool alloc)
413 {
414 	int size;
415 	kuid_t kroot;
416 	vfsuid_t vfsroot;
417 	u32 nsmagic, magic;
418 	uid_t root, mappedroot;
419 	char *tmpbuf = NULL;
420 	struct vfs_cap_data *cap;
421 	struct vfs_ns_cap_data *nscap = NULL;
422 	struct dentry *dentry;
423 	struct user_namespace *fs_ns;
424 
425 	if (strcmp(name, "capability") != 0)
426 		return -EOPNOTSUPP;
427 
428 	dentry = d_find_any_alias(inode);
429 	if (!dentry)
430 		return -EINVAL;
431 	size = vfs_getxattr_alloc(idmap, dentry, XATTR_NAME_CAPS, &tmpbuf,
432 				  sizeof(struct vfs_ns_cap_data), GFP_NOFS);
433 	dput(dentry);
434 	/* gcc11 complains if we don't check for !tmpbuf */
435 	if (size < 0 || !tmpbuf)
436 		goto out_free;
437 
438 	fs_ns = inode->i_sb->s_user_ns;
439 	cap = (struct vfs_cap_data *) tmpbuf;
440 	if (is_v2header(size, cap)) {
441 		root = 0;
442 	} else if (is_v3header(size, cap)) {
443 		nscap = (struct vfs_ns_cap_data *) tmpbuf;
444 		root = le32_to_cpu(nscap->rootid);
445 	} else {
446 		size = -EINVAL;
447 		goto out_free;
448 	}
449 
450 	kroot = make_kuid(fs_ns, root);
451 
452 	/* If this is an idmapped mount shift the kuid. */
453 	vfsroot = make_vfsuid(idmap, fs_ns, kroot);
454 
455 	/* If the root kuid maps to a valid uid in current ns, then return
456 	 * this as a nscap. */
457 	mappedroot = from_kuid(current_user_ns(), vfsuid_into_kuid(vfsroot));
458 	if (mappedroot != (uid_t)-1 && mappedroot != (uid_t)0) {
459 		size = sizeof(struct vfs_ns_cap_data);
460 		if (alloc) {
461 			if (!nscap) {
462 				/* v2 -> v3 conversion */
463 				nscap = kzalloc(size, GFP_ATOMIC);
464 				if (!nscap) {
465 					size = -ENOMEM;
466 					goto out_free;
467 				}
468 				nsmagic = VFS_CAP_REVISION_3;
469 				magic = le32_to_cpu(cap->magic_etc);
470 				if (magic & VFS_CAP_FLAGS_EFFECTIVE)
471 					nsmagic |= VFS_CAP_FLAGS_EFFECTIVE;
472 				memcpy(&nscap->data, &cap->data, sizeof(__le32) * 2 * VFS_CAP_U32);
473 				nscap->magic_etc = cpu_to_le32(nsmagic);
474 			} else {
475 				/* use allocated v3 buffer */
476 				tmpbuf = NULL;
477 			}
478 			nscap->rootid = cpu_to_le32(mappedroot);
479 			*buffer = nscap;
480 		}
481 		goto out_free;
482 	}
483 
484 	if (!rootid_owns_currentns(vfsroot)) {
485 		size = -EOVERFLOW;
486 		goto out_free;
487 	}
488 
489 	/* This comes from a parent namespace.  Return as a v2 capability */
490 	size = sizeof(struct vfs_cap_data);
491 	if (alloc) {
492 		if (nscap) {
493 			/* v3 -> v2 conversion */
494 			cap = kzalloc(size, GFP_ATOMIC);
495 			if (!cap) {
496 				size = -ENOMEM;
497 				goto out_free;
498 			}
499 			magic = VFS_CAP_REVISION_2;
500 			nsmagic = le32_to_cpu(nscap->magic_etc);
501 			if (nsmagic & VFS_CAP_FLAGS_EFFECTIVE)
502 				magic |= VFS_CAP_FLAGS_EFFECTIVE;
503 			memcpy(&cap->data, &nscap->data, sizeof(__le32) * 2 * VFS_CAP_U32);
504 			cap->magic_etc = cpu_to_le32(magic);
505 		} else {
506 			/* use unconverted v2 */
507 			tmpbuf = NULL;
508 		}
509 		*buffer = cap;
510 	}
511 out_free:
512 	kfree(tmpbuf);
513 	return size;
514 }
515 
516 /**
517  * rootid_from_xattr - translate root uid of vfs caps
518  *
519  * @value:	vfs caps value which may be modified by this function
520  * @size:	size of @ivalue
521  * @task_ns:	user namespace of the caller
522  */
523 static vfsuid_t rootid_from_xattr(const void *value, size_t size,
524 				  struct user_namespace *task_ns)
525 {
526 	const struct vfs_ns_cap_data *nscap = value;
527 	uid_t rootid = 0;
528 
529 	if (size == XATTR_CAPS_SZ_3)
530 		rootid = le32_to_cpu(nscap->rootid);
531 
532 	return VFSUIDT_INIT(make_kuid(task_ns, rootid));
533 }
534 
535 static bool validheader(size_t size, const struct vfs_cap_data *cap)
536 {
537 	return is_v2header(size, cap) || is_v3header(size, cap);
538 }
539 
540 /**
541  * cap_convert_nscap - check vfs caps
542  *
543  * @idmap:	idmap of the mount the inode was found from
544  * @dentry:	used to retrieve inode to check permissions on
545  * @ivalue:	vfs caps value which may be modified by this function
546  * @size:	size of @ivalue
547  *
548  * User requested a write of security.capability.  If needed, update the
549  * xattr to change from v2 to v3, or to fixup the v3 rootid.
550  *
551  * If the inode has been found through an idmapped mount the idmap of
552  * the vfsmount must be passed through @idmap. This function will then
553  * take care to map the inode according to @idmap before checking
554  * permissions. On non-idmapped mounts or if permission checking is to be
555  * performed on the raw inode simply pass @nop_mnt_idmap.
556  *
557  * Return: On success, return the new size; on error, return < 0.
558  */
559 int cap_convert_nscap(struct mnt_idmap *idmap, struct dentry *dentry,
560 		      const void **ivalue, size_t size)
561 {
562 	struct vfs_ns_cap_data *nscap;
563 	uid_t nsrootid;
564 	const struct vfs_cap_data *cap = *ivalue;
565 	__u32 magic, nsmagic;
566 	struct inode *inode = d_backing_inode(dentry);
567 	struct user_namespace *task_ns = current_user_ns(),
568 		*fs_ns = inode->i_sb->s_user_ns;
569 	kuid_t rootid;
570 	vfsuid_t vfsrootid;
571 	size_t newsize;
572 
573 	if (!*ivalue)
574 		return -EINVAL;
575 	if (!validheader(size, cap))
576 		return -EINVAL;
577 	if (!capable_wrt_inode_uidgid(idmap, inode, CAP_SETFCAP))
578 		return -EPERM;
579 	if (size == XATTR_CAPS_SZ_2 && (idmap == &nop_mnt_idmap))
580 		if (ns_capable(inode->i_sb->s_user_ns, CAP_SETFCAP))
581 			/* user is privileged, just write the v2 */
582 			return size;
583 
584 	vfsrootid = rootid_from_xattr(*ivalue, size, task_ns);
585 	if (!vfsuid_valid(vfsrootid))
586 		return -EINVAL;
587 
588 	rootid = from_vfsuid(idmap, fs_ns, vfsrootid);
589 	if (!uid_valid(rootid))
590 		return -EINVAL;
591 
592 	nsrootid = from_kuid(fs_ns, rootid);
593 	if (nsrootid == -1)
594 		return -EINVAL;
595 
596 	newsize = sizeof(struct vfs_ns_cap_data);
597 	nscap = kmalloc(newsize, GFP_ATOMIC);
598 	if (!nscap)
599 		return -ENOMEM;
600 	nscap->rootid = cpu_to_le32(nsrootid);
601 	nsmagic = VFS_CAP_REVISION_3;
602 	magic = le32_to_cpu(cap->magic_etc);
603 	if (magic & VFS_CAP_FLAGS_EFFECTIVE)
604 		nsmagic |= VFS_CAP_FLAGS_EFFECTIVE;
605 	nscap->magic_etc = cpu_to_le32(nsmagic);
606 	memcpy(&nscap->data, &cap->data, sizeof(__le32) * 2 * VFS_CAP_U32);
607 
608 	*ivalue = nscap;
609 	return newsize;
610 }
611 
612 /*
613  * Calculate the new process capability sets from the capability sets attached
614  * to a file.
615  */
616 static inline int bprm_caps_from_vfs_caps(struct cpu_vfs_cap_data *caps,
617 					  struct linux_binprm *bprm,
618 					  bool *effective,
619 					  bool *has_fcap)
620 {
621 	struct cred *new = bprm->cred;
622 	int ret = 0;
623 
624 	if (caps->magic_etc & VFS_CAP_FLAGS_EFFECTIVE)
625 		*effective = true;
626 
627 	if (caps->magic_etc & VFS_CAP_REVISION_MASK)
628 		*has_fcap = true;
629 
630 	/*
631 	 * pP' = (X & fP) | (pI & fI)
632 	 * The addition of pA' is handled later.
633 	 */
634 	new->cap_permitted.val =
635 		(new->cap_bset.val & caps->permitted.val) |
636 		(new->cap_inheritable.val & caps->inheritable.val);
637 
638 	if (caps->permitted.val & ~new->cap_permitted.val)
639 		/* insufficient to execute correctly */
640 		ret = -EPERM;
641 
642 	/*
643 	 * For legacy apps, with no internal support for recognizing they
644 	 * do not have enough capabilities, we return an error if they are
645 	 * missing some "forced" (aka file-permitted) capabilities.
646 	 */
647 	return *effective ? ret : 0;
648 }
649 
650 /**
651  * get_vfs_caps_from_disk - retrieve vfs caps from disk
652  *
653  * @idmap:	idmap of the mount the inode was found from
654  * @dentry:	dentry from which @inode is retrieved
655  * @cpu_caps:	vfs capabilities
656  *
657  * Extract the on-exec-apply capability sets for an executable file.
658  *
659  * If the inode has been found through an idmapped mount the idmap of
660  * the vfsmount must be passed through @idmap. This function will then
661  * take care to map the inode according to @idmap before checking
662  * permissions. On non-idmapped mounts or if permission checking is to be
663  * performed on the raw inode simply pass @nop_mnt_idmap.
664  */
665 int get_vfs_caps_from_disk(struct mnt_idmap *idmap,
666 			   const struct dentry *dentry,
667 			   struct cpu_vfs_cap_data *cpu_caps)
668 {
669 	struct inode *inode = d_backing_inode(dentry);
670 	__u32 magic_etc;
671 	int size;
672 	struct vfs_ns_cap_data data, *nscaps = &data;
673 	struct vfs_cap_data *caps = (struct vfs_cap_data *) &data;
674 	kuid_t rootkuid;
675 	vfsuid_t rootvfsuid;
676 	struct user_namespace *fs_ns;
677 
678 	memset(cpu_caps, 0, sizeof(struct cpu_vfs_cap_data));
679 
680 	if (!inode)
681 		return -ENODATA;
682 
683 	fs_ns = inode->i_sb->s_user_ns;
684 	size = __vfs_getxattr((struct dentry *)dentry, inode,
685 			      XATTR_NAME_CAPS, &data, XATTR_CAPS_SZ);
686 	if (size == -ENODATA || size == -EOPNOTSUPP)
687 		/* no data, that's ok */
688 		return -ENODATA;
689 
690 	if (size < 0)
691 		return size;
692 
693 	if (size < sizeof(magic_etc))
694 		return -EINVAL;
695 
696 	cpu_caps->magic_etc = magic_etc = le32_to_cpu(caps->magic_etc);
697 
698 	rootkuid = make_kuid(fs_ns, 0);
699 	switch (magic_etc & VFS_CAP_REVISION_MASK) {
700 	case VFS_CAP_REVISION_1:
701 		if (size != XATTR_CAPS_SZ_1)
702 			return -EINVAL;
703 		break;
704 	case VFS_CAP_REVISION_2:
705 		if (size != XATTR_CAPS_SZ_2)
706 			return -EINVAL;
707 		break;
708 	case VFS_CAP_REVISION_3:
709 		if (size != XATTR_CAPS_SZ_3)
710 			return -EINVAL;
711 		rootkuid = make_kuid(fs_ns, le32_to_cpu(nscaps->rootid));
712 		break;
713 
714 	default:
715 		return -EINVAL;
716 	}
717 
718 	rootvfsuid = make_vfsuid(idmap, fs_ns, rootkuid);
719 	if (!vfsuid_valid(rootvfsuid))
720 		return -ENODATA;
721 
722 	/* Limit the caps to the mounter of the filesystem
723 	 * or the more limited uid specified in the xattr.
724 	 */
725 	if (!rootid_owns_currentns(rootvfsuid))
726 		return -ENODATA;
727 
728 	cpu_caps->permitted.val = le32_to_cpu(caps->data[0].permitted);
729 	cpu_caps->inheritable.val = le32_to_cpu(caps->data[0].inheritable);
730 
731 	/*
732 	 * Rev1 had just a single 32-bit word, later expanded
733 	 * to a second one for the high bits
734 	 */
735 	if ((magic_etc & VFS_CAP_REVISION_MASK) != VFS_CAP_REVISION_1) {
736 		cpu_caps->permitted.val += (u64)le32_to_cpu(caps->data[1].permitted) << 32;
737 		cpu_caps->inheritable.val += (u64)le32_to_cpu(caps->data[1].inheritable) << 32;
738 	}
739 
740 	cpu_caps->permitted.val &= CAP_VALID_MASK;
741 	cpu_caps->inheritable.val &= CAP_VALID_MASK;
742 
743 	cpu_caps->rootid = vfsuid_into_kuid(rootvfsuid);
744 
745 	return 0;
746 }
747 
748 /*
749  * Attempt to get the on-exec apply capability sets for an executable file from
750  * its xattrs and, if present, apply them to the proposed credentials being
751  * constructed by execve().
752  */
753 static int get_file_caps(struct linux_binprm *bprm, const struct file *file,
754 			 bool *effective, bool *has_fcap)
755 {
756 	int rc = 0;
757 	struct cpu_vfs_cap_data vcaps;
758 
759 	cap_clear(bprm->cred->cap_permitted);
760 
761 	if (!file_caps_enabled)
762 		return 0;
763 
764 	if (!mnt_may_suid(file->f_path.mnt))
765 		return 0;
766 
767 	/*
768 	 * This check is redundant with mnt_may_suid() but is kept to make
769 	 * explicit that capability bits are limited to s_user_ns and its
770 	 * descendants.
771 	 */
772 	if (!current_in_userns(file->f_path.mnt->mnt_sb->s_user_ns))
773 		return 0;
774 
775 	rc = get_vfs_caps_from_disk(file_mnt_idmap(file),
776 				    file->f_path.dentry, &vcaps);
777 	if (rc < 0) {
778 		if (rc == -EINVAL)
779 			printk(KERN_NOTICE "Invalid argument reading file caps for %s\n",
780 					bprm->filename);
781 		else if (rc == -ENODATA)
782 			rc = 0;
783 		goto out;
784 	}
785 
786 	rc = bprm_caps_from_vfs_caps(&vcaps, bprm, effective, has_fcap);
787 
788 out:
789 	if (rc)
790 		cap_clear(bprm->cred->cap_permitted);
791 
792 	return rc;
793 }
794 
795 static inline bool root_privileged(void) { return !issecure(SECURE_NOROOT); }
796 
797 static inline bool __is_real(kuid_t uid, struct cred *cred)
798 { return uid_eq(cred->uid, uid); }
799 
800 static inline bool __is_eff(kuid_t uid, struct cred *cred)
801 { return uid_eq(cred->euid, uid); }
802 
803 static inline bool __is_suid(kuid_t uid, struct cred *cred)
804 { return !__is_real(uid, cred) && __is_eff(uid, cred); }
805 
806 /*
807  * handle_privileged_root - Handle case of privileged root
808  * @bprm: The execution parameters, including the proposed creds
809  * @has_fcap: Are any file capabilities set?
810  * @effective: Do we have effective root privilege?
811  * @root_uid: This namespace' root UID WRT initial USER namespace
812  *
813  * Handle the case where root is privileged and hasn't been neutered by
814  * SECURE_NOROOT.  If file capabilities are set, they won't be combined with
815  * set UID root and nothing is changed.  If we are root, cap_permitted is
816  * updated.  If we have become set UID root, the effective bit is set.
817  */
818 static void handle_privileged_root(struct linux_binprm *bprm, bool has_fcap,
819 				   bool *effective, kuid_t root_uid)
820 {
821 	const struct cred *old = current_cred();
822 	struct cred *new = bprm->cred;
823 
824 	if (!root_privileged())
825 		return;
826 	/*
827 	 * If the legacy file capability is set, then don't set privs
828 	 * for a setuid root binary run by a non-root user.  Do set it
829 	 * for a root user just to cause least surprise to an admin.
830 	 */
831 	if (has_fcap && __is_suid(root_uid, new)) {
832 		warn_setuid_and_fcaps_mixed(bprm->filename);
833 		return;
834 	}
835 	/*
836 	 * To support inheritance of root-permissions and suid-root
837 	 * executables under compatibility mode, we override the
838 	 * capability sets for the file.
839 	 */
840 	if (__is_eff(root_uid, new) || __is_real(root_uid, new)) {
841 		/* pP' = (cap_bset & ~0) | (pI & ~0) */
842 		new->cap_permitted = cap_combine(old->cap_bset,
843 						 old->cap_inheritable);
844 	}
845 	/*
846 	 * If only the real uid is 0, we do not set the effective bit.
847 	 */
848 	if (__is_eff(root_uid, new))
849 		*effective = true;
850 }
851 
852 #define __cap_gained(field, target, source) \
853 	!cap_issubset(target->cap_##field, source->cap_##field)
854 #define __cap_grew(target, source, cred) \
855 	!cap_issubset(cred->cap_##target, cred->cap_##source)
856 #define __cap_full(field, cred) \
857 	cap_issubset(CAP_FULL_SET, cred->cap_##field)
858 
859 static inline bool __is_setuid(struct cred *new, const struct cred *old)
860 { return !uid_eq(new->euid, old->uid); }
861 
862 static inline bool __is_setgid(struct cred *new, const struct cred *old)
863 { return !gid_eq(new->egid, old->gid); }
864 
865 /*
866  * 1) Audit candidate if current->cap_effective is set
867  *
868  * We do not bother to audit if 3 things are true:
869  *   1) cap_effective has all caps
870  *   2) we became root *OR* are were already root
871  *   3) root is supposed to have all caps (SECURE_NOROOT)
872  * Since this is just a normal root execing a process.
873  *
874  * Number 1 above might fail if you don't have a full bset, but I think
875  * that is interesting information to audit.
876  *
877  * A number of other conditions require logging:
878  * 2) something prevented setuid root getting all caps
879  * 3) non-setuid root gets fcaps
880  * 4) non-setuid root gets ambient
881  */
882 static inline bool nonroot_raised_pE(struct cred *new, const struct cred *old,
883 				     kuid_t root, bool has_fcap)
884 {
885 	bool ret = false;
886 
887 	if ((__cap_grew(effective, ambient, new) &&
888 	     !(__cap_full(effective, new) &&
889 	       (__is_eff(root, new) || __is_real(root, new)) &&
890 	       root_privileged())) ||
891 	    (root_privileged() &&
892 	     __is_suid(root, new) &&
893 	     !__cap_full(effective, new)) ||
894 	    (!__is_setuid(new, old) &&
895 	     ((has_fcap &&
896 	       __cap_gained(permitted, new, old)) ||
897 	      __cap_gained(ambient, new, old))))
898 
899 		ret = true;
900 
901 	return ret;
902 }
903 
904 /**
905  * cap_bprm_creds_from_file - Set up the proposed credentials for execve().
906  * @bprm: The execution parameters, including the proposed creds
907  * @file: The file to pull the credentials from
908  *
909  * Set up the proposed credentials for a new execution context being
910  * constructed by execve().  The proposed creds in @bprm->cred is altered,
911  * which won't take effect immediately.
912  *
913  * Return: 0 if successful, -ve on error.
914  */
915 int cap_bprm_creds_from_file(struct linux_binprm *bprm, const struct file *file)
916 {
917 	/* Process setpcap binaries and capabilities for uid 0 */
918 	const struct cred *old = current_cred();
919 	struct cred *new = bprm->cred;
920 	bool effective = false, has_fcap = false, is_setid;
921 	int ret;
922 	kuid_t root_uid;
923 
924 	if (WARN_ON(!cap_ambient_invariant_ok(old)))
925 		return -EPERM;
926 
927 	ret = get_file_caps(bprm, file, &effective, &has_fcap);
928 	if (ret < 0)
929 		return ret;
930 
931 	root_uid = make_kuid(new->user_ns, 0);
932 
933 	handle_privileged_root(bprm, has_fcap, &effective, root_uid);
934 
935 	/* if we have fs caps, clear dangerous personality flags */
936 	if (__cap_gained(permitted, new, old))
937 		bprm->per_clear |= PER_CLEAR_ON_SETID;
938 
939 	/* Don't let someone trace a set[ug]id/setpcap binary with the revised
940 	 * credentials unless they have the appropriate permit.
941 	 *
942 	 * In addition, if NO_NEW_PRIVS, then ensure we get no new privs.
943 	 */
944 	is_setid = __is_setuid(new, old) || __is_setgid(new, old);
945 
946 	if ((is_setid || __cap_gained(permitted, new, old)) &&
947 	    ((bprm->unsafe & ~LSM_UNSAFE_PTRACE) ||
948 	     !ptracer_capable(current, new->user_ns))) {
949 		/* downgrade; they get no more than they had, and maybe less */
950 		if (!ns_capable(new->user_ns, CAP_SETUID) ||
951 		    (bprm->unsafe & LSM_UNSAFE_NO_NEW_PRIVS)) {
952 			new->euid = new->uid;
953 			new->egid = new->gid;
954 		}
955 		new->cap_permitted = cap_intersect(new->cap_permitted,
956 						   old->cap_permitted);
957 	}
958 
959 	new->suid = new->fsuid = new->euid;
960 	new->sgid = new->fsgid = new->egid;
961 
962 	/* File caps or setid cancels ambient. */
963 	if (has_fcap || is_setid)
964 		cap_clear(new->cap_ambient);
965 
966 	/*
967 	 * Now that we've computed pA', update pP' to give:
968 	 *   pP' = (X & fP) | (pI & fI) | pA'
969 	 */
970 	new->cap_permitted = cap_combine(new->cap_permitted, new->cap_ambient);
971 
972 	/*
973 	 * Set pE' = (fE ? pP' : pA').  Because pA' is zero if fE is set,
974 	 * this is the same as pE' = (fE ? pP' : 0) | pA'.
975 	 */
976 	if (effective)
977 		new->cap_effective = new->cap_permitted;
978 	else
979 		new->cap_effective = new->cap_ambient;
980 
981 	if (WARN_ON(!cap_ambient_invariant_ok(new)))
982 		return -EPERM;
983 
984 	if (nonroot_raised_pE(new, old, root_uid, has_fcap)) {
985 		ret = audit_log_bprm_fcaps(bprm, new, old);
986 		if (ret < 0)
987 			return ret;
988 	}
989 
990 	new->securebits &= ~issecure_mask(SECURE_KEEP_CAPS);
991 
992 	if (WARN_ON(!cap_ambient_invariant_ok(new)))
993 		return -EPERM;
994 
995 	/* Check for privilege-elevated exec. */
996 	if (is_setid ||
997 	    (!__is_real(root_uid, new) &&
998 	     (effective ||
999 	      __cap_grew(permitted, ambient, new))))
1000 		bprm->secureexec = 1;
1001 
1002 	return 0;
1003 }
1004 
1005 /**
1006  * cap_inode_setxattr - Determine whether an xattr may be altered
1007  * @dentry: The inode/dentry being altered
1008  * @name: The name of the xattr to be changed
1009  * @value: The value that the xattr will be changed to
1010  * @size: The size of value
1011  * @flags: The replacement flag
1012  *
1013  * Determine whether an xattr may be altered or set on an inode, returning 0 if
1014  * permission is granted, -ve if denied.
1015  *
1016  * This is used to make sure security xattrs don't get updated or set by those
1017  * who aren't privileged to do so.
1018  */
1019 int cap_inode_setxattr(struct dentry *dentry, const char *name,
1020 		       const void *value, size_t size, int flags)
1021 {
1022 	struct user_namespace *user_ns = dentry->d_sb->s_user_ns;
1023 
1024 	/* Ignore non-security xattrs */
1025 	if (strncmp(name, XATTR_SECURITY_PREFIX,
1026 			XATTR_SECURITY_PREFIX_LEN) != 0)
1027 		return 0;
1028 
1029 	/*
1030 	 * For XATTR_NAME_CAPS the check will be done in
1031 	 * cap_convert_nscap(), called by setxattr()
1032 	 */
1033 	if (strcmp(name, XATTR_NAME_CAPS) == 0)
1034 		return 0;
1035 
1036 	if (!ns_capable(user_ns, CAP_SYS_ADMIN))
1037 		return -EPERM;
1038 	return 0;
1039 }
1040 
1041 /**
1042  * cap_inode_removexattr - Determine whether an xattr may be removed
1043  *
1044  * @idmap:	idmap of the mount the inode was found from
1045  * @dentry:	The inode/dentry being altered
1046  * @name:	The name of the xattr to be changed
1047  *
1048  * Determine whether an xattr may be removed from an inode, returning 0 if
1049  * permission is granted, -ve if denied.
1050  *
1051  * If the inode has been found through an idmapped mount the idmap of
1052  * the vfsmount must be passed through @idmap. This function will then
1053  * take care to map the inode according to @idmap before checking
1054  * permissions. On non-idmapped mounts or if permission checking is to be
1055  * performed on the raw inode simply pass @nop_mnt_idmap.
1056  *
1057  * This is used to make sure security xattrs don't get removed by those who
1058  * aren't privileged to remove them.
1059  */
1060 int cap_inode_removexattr(struct mnt_idmap *idmap,
1061 			  struct dentry *dentry, const char *name)
1062 {
1063 	struct user_namespace *user_ns = dentry->d_sb->s_user_ns;
1064 
1065 	/* Ignore non-security xattrs */
1066 	if (strncmp(name, XATTR_SECURITY_PREFIX,
1067 			XATTR_SECURITY_PREFIX_LEN) != 0)
1068 		return 0;
1069 
1070 	if (strcmp(name, XATTR_NAME_CAPS) == 0) {
1071 		/* security.capability gets namespaced */
1072 		struct inode *inode = d_backing_inode(dentry);
1073 		if (!inode)
1074 			return -EINVAL;
1075 		if (!capable_wrt_inode_uidgid(idmap, inode, CAP_SETFCAP))
1076 			return -EPERM;
1077 		return 0;
1078 	}
1079 
1080 	if (!ns_capable(user_ns, CAP_SYS_ADMIN))
1081 		return -EPERM;
1082 	return 0;
1083 }
1084 
1085 /*
1086  * cap_emulate_setxuid() fixes the effective / permitted capabilities of
1087  * a process after a call to setuid, setreuid, or setresuid.
1088  *
1089  *  1) When set*uiding _from_ one of {r,e,s}uid == 0 _to_ all of
1090  *  {r,e,s}uid != 0, the permitted and effective capabilities are
1091  *  cleared.
1092  *
1093  *  2) When set*uiding _from_ euid == 0 _to_ euid != 0, the effective
1094  *  capabilities of the process are cleared.
1095  *
1096  *  3) When set*uiding _from_ euid != 0 _to_ euid == 0, the effective
1097  *  capabilities are set to the permitted capabilities.
1098  *
1099  *  fsuid is handled elsewhere. fsuid == 0 and {r,e,s}uid!= 0 should
1100  *  never happen.
1101  *
1102  *  -astor
1103  *
1104  * cevans - New behaviour, Oct '99
1105  * A process may, via prctl(), elect to keep its capabilities when it
1106  * calls setuid() and switches away from uid==0. Both permitted and
1107  * effective sets will be retained.
1108  * Without this change, it was impossible for a daemon to drop only some
1109  * of its privilege. The call to setuid(!=0) would drop all privileges!
1110  * Keeping uid 0 is not an option because uid 0 owns too many vital
1111  * files..
1112  * Thanks to Olaf Kirch and Peter Benie for spotting this.
1113  */
1114 static inline void cap_emulate_setxuid(struct cred *new, const struct cred *old)
1115 {
1116 	kuid_t root_uid = make_kuid(old->user_ns, 0);
1117 
1118 	if ((uid_eq(old->uid, root_uid) ||
1119 	     uid_eq(old->euid, root_uid) ||
1120 	     uid_eq(old->suid, root_uid)) &&
1121 	    (!uid_eq(new->uid, root_uid) &&
1122 	     !uid_eq(new->euid, root_uid) &&
1123 	     !uid_eq(new->suid, root_uid))) {
1124 		if (!issecure(SECURE_KEEP_CAPS)) {
1125 			cap_clear(new->cap_permitted);
1126 			cap_clear(new->cap_effective);
1127 		}
1128 
1129 		/*
1130 		 * Pre-ambient programs expect setresuid to nonroot followed
1131 		 * by exec to drop capabilities.  We should make sure that
1132 		 * this remains the case.
1133 		 */
1134 		cap_clear(new->cap_ambient);
1135 	}
1136 	if (uid_eq(old->euid, root_uid) && !uid_eq(new->euid, root_uid))
1137 		cap_clear(new->cap_effective);
1138 	if (!uid_eq(old->euid, root_uid) && uid_eq(new->euid, root_uid))
1139 		new->cap_effective = new->cap_permitted;
1140 }
1141 
1142 /**
1143  * cap_task_fix_setuid - Fix up the results of setuid() call
1144  * @new: The proposed credentials
1145  * @old: The current task's current credentials
1146  * @flags: Indications of what has changed
1147  *
1148  * Fix up the results of setuid() call before the credential changes are
1149  * actually applied.
1150  *
1151  * Return: 0 to grant the changes, -ve to deny them.
1152  */
1153 int cap_task_fix_setuid(struct cred *new, const struct cred *old, int flags)
1154 {
1155 	switch (flags) {
1156 	case LSM_SETID_RE:
1157 	case LSM_SETID_ID:
1158 	case LSM_SETID_RES:
1159 		/* juggle the capabilities to follow [RES]UID changes unless
1160 		 * otherwise suppressed */
1161 		if (!issecure(SECURE_NO_SETUID_FIXUP))
1162 			cap_emulate_setxuid(new, old);
1163 		break;
1164 
1165 	case LSM_SETID_FS:
1166 		/* juggle the capabilities to follow FSUID changes, unless
1167 		 * otherwise suppressed
1168 		 *
1169 		 * FIXME - is fsuser used for all CAP_FS_MASK capabilities?
1170 		 *          if not, we might be a bit too harsh here.
1171 		 */
1172 		if (!issecure(SECURE_NO_SETUID_FIXUP)) {
1173 			kuid_t root_uid = make_kuid(old->user_ns, 0);
1174 			if (uid_eq(old->fsuid, root_uid) && !uid_eq(new->fsuid, root_uid))
1175 				new->cap_effective =
1176 					cap_drop_fs_set(new->cap_effective);
1177 
1178 			if (!uid_eq(old->fsuid, root_uid) && uid_eq(new->fsuid, root_uid))
1179 				new->cap_effective =
1180 					cap_raise_fs_set(new->cap_effective,
1181 							 new->cap_permitted);
1182 		}
1183 		break;
1184 
1185 	default:
1186 		return -EINVAL;
1187 	}
1188 
1189 	return 0;
1190 }
1191 
1192 /*
1193  * Rationale: code calling task_setscheduler, task_setioprio, and
1194  * task_setnice, assumes that
1195  *   . if capable(cap_sys_nice), then those actions should be allowed
1196  *   . if not capable(cap_sys_nice), but acting on your own processes,
1197  *   	then those actions should be allowed
1198  * This is insufficient now since you can call code without suid, but
1199  * yet with increased caps.
1200  * So we check for increased caps on the target process.
1201  */
1202 static int cap_safe_nice(struct task_struct *p)
1203 {
1204 	int is_subset, ret = 0;
1205 
1206 	rcu_read_lock();
1207 	is_subset = cap_issubset(__task_cred(p)->cap_permitted,
1208 				 current_cred()->cap_permitted);
1209 	if (!is_subset && !ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE))
1210 		ret = -EPERM;
1211 	rcu_read_unlock();
1212 
1213 	return ret;
1214 }
1215 
1216 /**
1217  * cap_task_setscheduler - Determine if scheduler policy change is permitted
1218  * @p: The task to affect
1219  *
1220  * Determine if the requested scheduler policy change is permitted for the
1221  * specified task.
1222  *
1223  * Return: 0 if permission is granted, -ve if denied.
1224  */
1225 int cap_task_setscheduler(struct task_struct *p)
1226 {
1227 	return cap_safe_nice(p);
1228 }
1229 
1230 /**
1231  * cap_task_setioprio - Determine if I/O priority change is permitted
1232  * @p: The task to affect
1233  * @ioprio: The I/O priority to set
1234  *
1235  * Determine if the requested I/O priority change is permitted for the specified
1236  * task.
1237  *
1238  * Return: 0 if permission is granted, -ve if denied.
1239  */
1240 int cap_task_setioprio(struct task_struct *p, int ioprio)
1241 {
1242 	return cap_safe_nice(p);
1243 }
1244 
1245 /**
1246  * cap_task_setnice - Determine if task priority change is permitted
1247  * @p: The task to affect
1248  * @nice: The nice value to set
1249  *
1250  * Determine if the requested task priority change is permitted for the
1251  * specified task.
1252  *
1253  * Return: 0 if permission is granted, -ve if denied.
1254  */
1255 int cap_task_setnice(struct task_struct *p, int nice)
1256 {
1257 	return cap_safe_nice(p);
1258 }
1259 
1260 /*
1261  * Implement PR_CAPBSET_DROP.  Attempt to remove the specified capability from
1262  * the current task's bounding set.  Returns 0 on success, -ve on error.
1263  */
1264 static int cap_prctl_drop(unsigned long cap)
1265 {
1266 	struct cred *new;
1267 
1268 	if (!ns_capable(current_user_ns(), CAP_SETPCAP))
1269 		return -EPERM;
1270 	if (!cap_valid(cap))
1271 		return -EINVAL;
1272 
1273 	new = prepare_creds();
1274 	if (!new)
1275 		return -ENOMEM;
1276 	cap_lower(new->cap_bset, cap);
1277 	return commit_creds(new);
1278 }
1279 
1280 /**
1281  * cap_task_prctl - Implement process control functions for this security module
1282  * @option: The process control function requested
1283  * @arg2: The argument data for this function
1284  * @arg3: The argument data for this function
1285  * @arg4: The argument data for this function
1286  * @arg5: The argument data for this function
1287  *
1288  * Allow process control functions (sys_prctl()) to alter capabilities; may
1289  * also deny access to other functions not otherwise implemented here.
1290  *
1291  * Return: 0 or +ve on success, -ENOSYS if this function is not implemented
1292  * here, other -ve on error.  If -ENOSYS is returned, sys_prctl() and other LSM
1293  * modules will consider performing the function.
1294  */
1295 int cap_task_prctl(int option, unsigned long arg2, unsigned long arg3,
1296 		   unsigned long arg4, unsigned long arg5)
1297 {
1298 	const struct cred *old = current_cred();
1299 	struct cred *new;
1300 
1301 	switch (option) {
1302 	case PR_CAPBSET_READ:
1303 		if (!cap_valid(arg2))
1304 			return -EINVAL;
1305 		return !!cap_raised(old->cap_bset, arg2);
1306 
1307 	case PR_CAPBSET_DROP:
1308 		return cap_prctl_drop(arg2);
1309 
1310 	/*
1311 	 * The next four prctl's remain to assist with transitioning a
1312 	 * system from legacy UID=0 based privilege (when filesystem
1313 	 * capabilities are not in use) to a system using filesystem
1314 	 * capabilities only - as the POSIX.1e draft intended.
1315 	 *
1316 	 * Note:
1317 	 *
1318 	 *  PR_SET_SECUREBITS =
1319 	 *      issecure_mask(SECURE_KEEP_CAPS_LOCKED)
1320 	 *    | issecure_mask(SECURE_NOROOT)
1321 	 *    | issecure_mask(SECURE_NOROOT_LOCKED)
1322 	 *    | issecure_mask(SECURE_NO_SETUID_FIXUP)
1323 	 *    | issecure_mask(SECURE_NO_SETUID_FIXUP_LOCKED)
1324 	 *
1325 	 * will ensure that the current process and all of its
1326 	 * children will be locked into a pure
1327 	 * capability-based-privilege environment.
1328 	 */
1329 	case PR_SET_SECUREBITS:
1330 		if ((((old->securebits & SECURE_ALL_LOCKS) >> 1)
1331 		     & (old->securebits ^ arg2))			/*[1]*/
1332 		    || ((old->securebits & SECURE_ALL_LOCKS & ~arg2))	/*[2]*/
1333 		    || (arg2 & ~(SECURE_ALL_LOCKS | SECURE_ALL_BITS))	/*[3]*/
1334 			/*
1335 			 * [1] no changing of bits that are locked
1336 			 * [2] no unlocking of locks
1337 			 * [3] no setting of unsupported bits
1338 			 */
1339 		    )
1340 			/* cannot change a locked bit */
1341 			return -EPERM;
1342 
1343 		/*
1344 		 * Doing anything requires privilege (go read about the
1345 		 * "sendmail capabilities bug"), except for unprivileged bits.
1346 		 * Indeed, the SECURE_ALL_UNPRIVILEGED bits are not
1347 		 * restrictions enforced by the kernel but by user space on
1348 		 * itself.
1349 		 */
1350 		if (cap_capable(current_cred(), current_cred()->user_ns,
1351 				CAP_SETPCAP, CAP_OPT_NONE) != 0) {
1352 			const unsigned long unpriv_and_locks =
1353 				SECURE_ALL_UNPRIVILEGED |
1354 				SECURE_ALL_UNPRIVILEGED << 1;
1355 			const unsigned long changed = old->securebits ^ arg2;
1356 
1357 			/* For legacy reason, denies non-change. */
1358 			if (!changed)
1359 				return -EPERM;
1360 
1361 			/* Denies privileged changes. */
1362 			if (changed & ~unpriv_and_locks)
1363 				return -EPERM;
1364 		}
1365 
1366 		new = prepare_creds();
1367 		if (!new)
1368 			return -ENOMEM;
1369 		new->securebits = arg2;
1370 		return commit_creds(new);
1371 
1372 	case PR_GET_SECUREBITS:
1373 		return old->securebits;
1374 
1375 	case PR_GET_KEEPCAPS:
1376 		return !!issecure(SECURE_KEEP_CAPS);
1377 
1378 	case PR_SET_KEEPCAPS:
1379 		if (arg2 > 1) /* Note, we rely on arg2 being unsigned here */
1380 			return -EINVAL;
1381 		if (issecure(SECURE_KEEP_CAPS_LOCKED))
1382 			return -EPERM;
1383 
1384 		new = prepare_creds();
1385 		if (!new)
1386 			return -ENOMEM;
1387 		if (arg2)
1388 			new->securebits |= issecure_mask(SECURE_KEEP_CAPS);
1389 		else
1390 			new->securebits &= ~issecure_mask(SECURE_KEEP_CAPS);
1391 		return commit_creds(new);
1392 
1393 	case PR_CAP_AMBIENT:
1394 		if (arg2 == PR_CAP_AMBIENT_CLEAR_ALL) {
1395 			if (arg3 | arg4 | arg5)
1396 				return -EINVAL;
1397 
1398 			new = prepare_creds();
1399 			if (!new)
1400 				return -ENOMEM;
1401 			cap_clear(new->cap_ambient);
1402 			return commit_creds(new);
1403 		}
1404 
1405 		if (((!cap_valid(arg3)) | arg4 | arg5))
1406 			return -EINVAL;
1407 
1408 		if (arg2 == PR_CAP_AMBIENT_IS_SET) {
1409 			return !!cap_raised(current_cred()->cap_ambient, arg3);
1410 		} else if (arg2 != PR_CAP_AMBIENT_RAISE &&
1411 			   arg2 != PR_CAP_AMBIENT_LOWER) {
1412 			return -EINVAL;
1413 		} else {
1414 			if (arg2 == PR_CAP_AMBIENT_RAISE &&
1415 			    (!cap_raised(current_cred()->cap_permitted, arg3) ||
1416 			     !cap_raised(current_cred()->cap_inheritable,
1417 					 arg3) ||
1418 			     issecure(SECURE_NO_CAP_AMBIENT_RAISE)))
1419 				return -EPERM;
1420 
1421 			new = prepare_creds();
1422 			if (!new)
1423 				return -ENOMEM;
1424 			if (arg2 == PR_CAP_AMBIENT_RAISE)
1425 				cap_raise(new->cap_ambient, arg3);
1426 			else
1427 				cap_lower(new->cap_ambient, arg3);
1428 			return commit_creds(new);
1429 		}
1430 
1431 	default:
1432 		/* No functionality available - continue with default */
1433 		return -ENOSYS;
1434 	}
1435 }
1436 
1437 /**
1438  * cap_vm_enough_memory - Determine whether a new virtual mapping is permitted
1439  * @mm: The VM space in which the new mapping is to be made
1440  * @pages: The size of the mapping
1441  *
1442  * Determine whether the allocation of a new virtual mapping by the current
1443  * task is permitted.
1444  *
1445  * Return: 0 if permission granted, negative error code if not.
1446  */
1447 int cap_vm_enough_memory(struct mm_struct *mm, long pages)
1448 {
1449 	return cap_capable(current_cred(), &init_user_ns, CAP_SYS_ADMIN,
1450 			   CAP_OPT_NOAUDIT);
1451 }
1452 
1453 /**
1454  * cap_mmap_addr - check if able to map given addr
1455  * @addr: address attempting to be mapped
1456  *
1457  * If the process is attempting to map memory below dac_mmap_min_addr they need
1458  * CAP_SYS_RAWIO.  The other parameters to this function are unused by the
1459  * capability security module.
1460  *
1461  * Return: 0 if this mapping should be allowed or -EPERM if not.
1462  */
1463 int cap_mmap_addr(unsigned long addr)
1464 {
1465 	int ret = 0;
1466 
1467 	if (addr < dac_mmap_min_addr) {
1468 		ret = cap_capable(current_cred(), &init_user_ns, CAP_SYS_RAWIO,
1469 				  CAP_OPT_NONE);
1470 		/* set PF_SUPERPRIV if it turns out we allow the low mmap */
1471 		if (ret == 0)
1472 			current->flags |= PF_SUPERPRIV;
1473 	}
1474 	return ret;
1475 }
1476 
1477 #ifdef CONFIG_SECURITY
1478 
1479 static const struct lsm_id capability_lsmid = {
1480 	.name = "capability",
1481 	.id = LSM_ID_CAPABILITY,
1482 };
1483 
1484 static struct security_hook_list capability_hooks[] __ro_after_init = {
1485 	LSM_HOOK_INIT(capable, cap_capable),
1486 	LSM_HOOK_INIT(settime, cap_settime),
1487 	LSM_HOOK_INIT(ptrace_access_check, cap_ptrace_access_check),
1488 	LSM_HOOK_INIT(ptrace_traceme, cap_ptrace_traceme),
1489 	LSM_HOOK_INIT(capget, cap_capget),
1490 	LSM_HOOK_INIT(capset, cap_capset),
1491 	LSM_HOOK_INIT(bprm_creds_from_file, cap_bprm_creds_from_file),
1492 	LSM_HOOK_INIT(inode_need_killpriv, cap_inode_need_killpriv),
1493 	LSM_HOOK_INIT(inode_killpriv, cap_inode_killpriv),
1494 	LSM_HOOK_INIT(inode_getsecurity, cap_inode_getsecurity),
1495 	LSM_HOOK_INIT(mmap_addr, cap_mmap_addr),
1496 	LSM_HOOK_INIT(task_fix_setuid, cap_task_fix_setuid),
1497 	LSM_HOOK_INIT(task_prctl, cap_task_prctl),
1498 	LSM_HOOK_INIT(task_setscheduler, cap_task_setscheduler),
1499 	LSM_HOOK_INIT(task_setioprio, cap_task_setioprio),
1500 	LSM_HOOK_INIT(task_setnice, cap_task_setnice),
1501 	LSM_HOOK_INIT(vm_enough_memory, cap_vm_enough_memory),
1502 };
1503 
1504 static int __init capability_init(void)
1505 {
1506 	security_add_hooks(capability_hooks, ARRAY_SIZE(capability_hooks),
1507 			   &capability_lsmid);
1508 	return 0;
1509 }
1510 
1511 DEFINE_LSM(capability) = {
1512 	.name = "capability",
1513 	.order = LSM_ORDER_FIRST,
1514 	.init = capability_init,
1515 };
1516 
1517 #endif /* CONFIG_SECURITY */
1518