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