xref: /linux/security/selinux/hooks.c (revision df34ecc52526480a1a4bb78bc75bfb009c6076a4)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  Security-Enhanced Linux (SELinux) security module
4  *
5  *  This file contains the SELinux hook function implementations.
6  *
7  *  Authors:  Stephen Smalley, <stephen.smalley.work@gmail.com>
8  *	      Chris Vance, <cvance@nai.com>
9  *	      Wayne Salamon, <wsalamon@nai.com>
10  *	      James Morris <jmorris@redhat.com>
11  *
12  *  Copyright (C) 2001,2002 Networks Associates Technology, Inc.
13  *  Copyright (C) 2003-2008 Red Hat, Inc., James Morris <jmorris@redhat.com>
14  *					   Eric Paris <eparis@redhat.com>
15  *  Copyright (C) 2004-2005 Trusted Computer Solutions, Inc.
16  *			    <dgoeddel@trustedcs.com>
17  *  Copyright (C) 2006, 2007, 2009 Hewlett-Packard Development Company, L.P.
18  *	Paul Moore <paul@paul-moore.com>
19  *  Copyright (C) 2007 Hitachi Software Engineering Co., Ltd.
20  *		       Yuichi Nakamura <ynakam@hitachisoft.jp>
21  *  Copyright (C) 2016 Mellanox Technologies
22  */
23 
24 #include <linux/init.h>
25 #include <linux/kd.h>
26 #include <linux/kernel.h>
27 #include <linux/kernel_read_file.h>
28 #include <linux/errno.h>
29 #include <linux/sched/signal.h>
30 #include <linux/sched/task.h>
31 #include <linux/lsm_hooks.h>
32 #include <linux/xattr.h>
33 #include <linux/capability.h>
34 #include <linux/unistd.h>
35 #include <linux/mm.h>
36 #include <linux/mman.h>
37 #include <linux/slab.h>
38 #include <linux/pagemap.h>
39 #include <linux/proc_fs.h>
40 #include <linux/swap.h>
41 #include <linux/spinlock.h>
42 #include <linux/syscalls.h>
43 #include <linux/dcache.h>
44 #include <linux/file.h>
45 #include <linux/fdtable.h>
46 #include <linux/namei.h>
47 #include <linux/mount.h>
48 #include <linux/fs_context.h>
49 #include <linux/fs_parser.h>
50 #include <linux/netfilter_ipv4.h>
51 #include <linux/netfilter_ipv6.h>
52 #include <linux/tty.h>
53 #include <net/icmp.h>
54 #include <net/ip.h>		/* for local_port_range[] */
55 #include <net/tcp.h>		/* struct or_callable used in sock_rcv_skb */
56 #include <net/inet_connection_sock.h>
57 #include <net/net_namespace.h>
58 #include <net/netlabel.h>
59 #include <linux/uaccess.h>
60 #include <asm/ioctls.h>
61 #include <linux/atomic.h>
62 #include <linux/bitops.h>
63 #include <linux/interrupt.h>
64 #include <linux/netdevice.h>	/* for network interface checks */
65 #include <net/netlink.h>
66 #include <linux/tcp.h>
67 #include <linux/udp.h>
68 #include <linux/sctp.h>
69 #include <net/sctp/structs.h>
70 #include <linux/quota.h>
71 #include <linux/un.h>		/* for Unix socket types */
72 #include <net/af_unix.h>	/* for Unix socket types */
73 #include <linux/parser.h>
74 #include <linux/nfs_mount.h>
75 #include <net/ipv6.h>
76 #include <linux/hugetlb.h>
77 #include <linux/personality.h>
78 #include <linux/audit.h>
79 #include <linux/string.h>
80 #include <linux/mutex.h>
81 #include <linux/posix-timers.h>
82 #include <linux/syslog.h>
83 #include <linux/user_namespace.h>
84 #include <linux/export.h>
85 #include <linux/msg.h>
86 #include <linux/shm.h>
87 #include <uapi/linux/shm.h>
88 #include <linux/bpf.h>
89 #include <linux/kernfs.h>
90 #include <linux/stringhash.h>	/* for hashlen_string() */
91 #include <uapi/linux/mount.h>
92 #include <linux/fsnotify.h>
93 #include <linux/fanotify.h>
94 #include <linux/io_uring/cmd.h>
95 #include <uapi/linux/lsm.h>
96 #include <linux/memfd.h>
97 
98 #include "initcalls.h"
99 #include "avc.h"
100 #include "objsec.h"
101 #include "netif.h"
102 #include "netnode.h"
103 #include "netport.h"
104 #include "ibpkey.h"
105 #include "xfrm.h"
106 #include "netlabel.h"
107 #include "audit.h"
108 #include "avc_ss.h"
109 
110 #define SELINUX_INODE_INIT_XATTRS 1
111 
112 struct selinux_state selinux_state;
113 
114 /* SECMARK reference count */
115 static atomic_t selinux_secmark_refcount = ATOMIC_INIT(0);
116 
117 #ifdef CONFIG_SECURITY_SELINUX_DEVELOP
118 static int selinux_enforcing_boot __initdata;
119 
120 static int __init enforcing_setup(char *str)
121 {
122 	unsigned long enforcing;
123 	if (!kstrtoul(str, 0, &enforcing))
124 		selinux_enforcing_boot = enforcing ? 1 : 0;
125 	return 1;
126 }
127 __setup("enforcing=", enforcing_setup);
128 #else
129 #define selinux_enforcing_boot 1
130 #endif
131 
132 int selinux_enabled_boot __initdata = 1;
133 #ifdef CONFIG_SECURITY_SELINUX_BOOTPARAM
134 static int __init selinux_enabled_setup(char *str)
135 {
136 	unsigned long enabled;
137 	if (!kstrtoul(str, 0, &enabled))
138 		selinux_enabled_boot = enabled ? 1 : 0;
139 	return 1;
140 }
141 __setup("selinux=", selinux_enabled_setup);
142 #endif
143 
144 static int __init checkreqprot_setup(char *str)
145 {
146 	unsigned long checkreqprot;
147 
148 	if (!kstrtoul(str, 0, &checkreqprot)) {
149 		if (checkreqprot)
150 			pr_err("SELinux: checkreqprot set to 1 via kernel parameter.  This is no longer supported.\n");
151 	}
152 	return 1;
153 }
154 __setup("checkreqprot=", checkreqprot_setup);
155 
156 /**
157  * selinux_secmark_enabled - Check to see if SECMARK is currently enabled
158  *
159  * Description:
160  * This function checks the SECMARK reference counter to see if any SECMARK
161  * targets are currently configured, if the reference counter is greater than
162  * zero SECMARK is considered to be enabled.  Returns true (1) if SECMARK is
163  * enabled, false (0) if SECMARK is disabled.  If the always_check_network
164  * policy capability is enabled, SECMARK is always considered enabled.
165  *
166  */
167 static int selinux_secmark_enabled(void)
168 {
169 	return (selinux_policycap_alwaysnetwork() ||
170 		atomic_read(&selinux_secmark_refcount));
171 }
172 
173 /**
174  * selinux_peerlbl_enabled - Check to see if peer labeling is currently enabled
175  *
176  * Description:
177  * This function checks if NetLabel or labeled IPSEC is enabled.  Returns true
178  * (1) if any are enabled or false (0) if neither are enabled.  If the
179  * always_check_network policy capability is enabled, peer labeling
180  * is always considered enabled.
181  *
182  */
183 static int selinux_peerlbl_enabled(void)
184 {
185 	return (selinux_policycap_alwaysnetwork() ||
186 		netlbl_enabled() || selinux_xfrm_enabled());
187 }
188 
189 static int selinux_netcache_avc_callback(u32 event)
190 {
191 	if (event == AVC_CALLBACK_RESET) {
192 		sel_netif_flush();
193 		sel_netnode_flush();
194 		sel_netport_flush();
195 		synchronize_net();
196 	}
197 	return 0;
198 }
199 
200 static int selinux_lsm_notifier_avc_callback(u32 event)
201 {
202 	if (event == AVC_CALLBACK_RESET) {
203 		sel_ib_pkey_flush();
204 		call_blocking_lsm_notifier(LSM_POLICY_CHANGE, NULL);
205 	}
206 
207 	return 0;
208 }
209 
210 /*
211  * initialise the security for the init task
212  */
213 static void cred_init_security(void)
214 {
215 	struct cred_security_struct *crsec;
216 
217 	/* NOTE: the lsm framework zeros out the buffer on allocation */
218 
219 	crsec = selinux_cred(unrcu_pointer(current->real_cred));
220 	crsec->osid = crsec->sid = SECINITSID_KERNEL;
221 }
222 
223 /*
224  * get the security ID of a set of credentials
225  */
226 static inline u32 cred_sid(const struct cred *cred)
227 {
228 	const struct cred_security_struct *crsec;
229 
230 	crsec = selinux_cred(cred);
231 	return crsec->sid;
232 }
233 
234 static void __ad_net_init(struct common_audit_data *ad,
235 			  struct lsm_network_audit *net,
236 			  int ifindex, struct sock *sk, u16 family)
237 {
238 	ad->type = LSM_AUDIT_DATA_NET;
239 	ad->u.net = net;
240 	net->netif = ifindex;
241 	net->sk = sk;
242 	net->family = family;
243 }
244 
245 static void ad_net_init_from_sk(struct common_audit_data *ad,
246 				struct lsm_network_audit *net,
247 				struct sock *sk)
248 {
249 	__ad_net_init(ad, net, 0, sk, 0);
250 }
251 
252 static void ad_net_init_from_iif(struct common_audit_data *ad,
253 				 struct lsm_network_audit *net,
254 				 int ifindex, u16 family)
255 {
256 	__ad_net_init(ad, net, ifindex, NULL, family);
257 }
258 
259 /*
260  * get the objective security ID of a task
261  */
262 static inline u32 task_sid_obj(const struct task_struct *task)
263 {
264 	u32 sid;
265 
266 	rcu_read_lock();
267 	sid = cred_sid(__task_cred(task));
268 	rcu_read_unlock();
269 	return sid;
270 }
271 
272 static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dentry);
273 
274 /*
275  * Try reloading inode security labels that have been marked as invalid.  The
276  * @may_sleep parameter indicates when sleeping and thus reloading labels is
277  * allowed; when set to false, returns -ECHILD when the label is
278  * invalid.  The @dentry parameter should be set to a dentry of the inode.
279  */
280 static int __inode_security_revalidate(struct inode *inode,
281 				       struct dentry *dentry,
282 				       bool may_sleep)
283 {
284 	if (!selinux_initialized())
285 		return 0;
286 
287 	if (may_sleep)
288 		might_sleep();
289 	else
290 		return -ECHILD;
291 
292 	/*
293 	 * Check to ensure that an inode's SELinux state is valid and try
294 	 * reloading the inode security label if necessary.  This will fail if
295 	 * @dentry is NULL and no dentry for this inode can be found; in that
296 	 * case, continue using the old label.
297 	 */
298 	inode_doinit_with_dentry(inode, dentry);
299 	return 0;
300 }
301 
302 static struct inode_security_struct *inode_security_novalidate(struct inode *inode)
303 {
304 	return selinux_inode(inode);
305 }
306 
307 static inline struct inode_security_struct *inode_security_rcu(struct inode *inode,
308 							       bool rcu)
309 {
310 	int rc;
311 	struct inode_security_struct *isec = selinux_inode(inode);
312 
313 	/* check below is racy, but revalidate will recheck with lock held */
314 	if (data_race(likely(isec->initialized == LABEL_INITIALIZED)))
315 		return isec;
316 	rc = __inode_security_revalidate(inode, NULL, !rcu);
317 	if (rc)
318 		return ERR_PTR(rc);
319 	return isec;
320 }
321 
322 /*
323  * Get the security label of an inode.
324  */
325 static inline struct inode_security_struct *inode_security(struct inode *inode)
326 {
327 	struct inode_security_struct *isec = selinux_inode(inode);
328 
329 	/* check below is racy, but revalidate will recheck with lock held */
330 	if (data_race(likely(isec->initialized == LABEL_INITIALIZED)))
331 		return isec;
332 	__inode_security_revalidate(inode, NULL, true);
333 	return isec;
334 }
335 
336 static inline struct inode_security_struct *backing_inode_security_novalidate(struct dentry *dentry)
337 {
338 	return selinux_inode(d_backing_inode(dentry));
339 }
340 
341 /*
342  * Get the security label of a dentry's backing inode.
343  */
344 static inline struct inode_security_struct *backing_inode_security(struct dentry *dentry)
345 {
346 	struct inode *inode = d_backing_inode(dentry);
347 	struct inode_security_struct *isec = selinux_inode(inode);
348 
349 	/* check below is racy, but revalidate will recheck with lock held */
350 	if (data_race(likely(isec->initialized == LABEL_INITIALIZED)))
351 		return isec;
352 	__inode_security_revalidate(inode, dentry, true);
353 	return isec;
354 }
355 
356 static void inode_free_security(struct inode *inode)
357 {
358 	struct inode_security_struct *isec = selinux_inode(inode);
359 	struct superblock_security_struct *sbsec;
360 
361 	if (!isec)
362 		return;
363 	sbsec = selinux_superblock(inode->i_sb);
364 	/*
365 	 * As not all inode security structures are in a list, we check for
366 	 * empty list outside of the lock to make sure that we won't waste
367 	 * time taking a lock doing nothing.
368 	 *
369 	 * The list_del_init() function can be safely called more than once.
370 	 * It should not be possible for this function to be called with
371 	 * concurrent list_add(), but for better safety against future changes
372 	 * in the code, we use list_empty_careful() here.
373 	 */
374 	if (!list_empty_careful(&isec->list)) {
375 		spin_lock(&sbsec->isec_lock);
376 		list_del_init(&isec->list);
377 		spin_unlock(&sbsec->isec_lock);
378 	}
379 }
380 
381 struct selinux_mnt_opts {
382 	u32 fscontext_sid;
383 	u32 context_sid;
384 	u32 rootcontext_sid;
385 	u32 defcontext_sid;
386 };
387 
388 static void selinux_free_mnt_opts(void *mnt_opts)
389 {
390 	kfree(mnt_opts);
391 }
392 
393 enum {
394 	Opt_error = -1,
395 	Opt_context = 0,
396 	Opt_defcontext = 1,
397 	Opt_fscontext = 2,
398 	Opt_rootcontext = 3,
399 	Opt_seclabel = 4,
400 };
401 
402 #define A(s, has_arg) {#s, sizeof(#s) - 1, Opt_##s, has_arg}
403 static const struct {
404 	const char *name;
405 	int len;
406 	int opt;
407 	bool has_arg;
408 } tokens[] = {
409 	A(context, true),
410 	A(fscontext, true),
411 	A(defcontext, true),
412 	A(rootcontext, true),
413 	A(seclabel, false),
414 };
415 #undef A
416 
417 static int match_opt_prefix(char *s, int l, char **arg)
418 {
419 	unsigned int i;
420 
421 	for (i = 0; i < ARRAY_SIZE(tokens); i++) {
422 		size_t len = tokens[i].len;
423 		if (len > l || memcmp(s, tokens[i].name, len))
424 			continue;
425 		if (tokens[i].has_arg) {
426 			if (len == l || s[len] != '=')
427 				continue;
428 			*arg = s + len + 1;
429 		} else if (len != l)
430 			continue;
431 		return tokens[i].opt;
432 	}
433 	return Opt_error;
434 }
435 
436 #define SEL_MOUNT_FAIL_MSG "SELinux:  duplicate or incompatible mount options\n"
437 
438 static int may_context_mount_sb_relabel(u32 sid,
439 			struct superblock_security_struct *sbsec,
440 			const struct cred *cred)
441 {
442 	const struct cred_security_struct *crsec = selinux_cred(cred);
443 	int rc;
444 
445 	rc = avc_has_perm(crsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
446 			  FILESYSTEM__RELABELFROM, NULL);
447 	if (rc)
448 		return rc;
449 
450 	rc = avc_has_perm(crsec->sid, sid, SECCLASS_FILESYSTEM,
451 			  FILESYSTEM__RELABELTO, NULL);
452 	return rc;
453 }
454 
455 static int may_context_mount_inode_relabel(u32 sid,
456 			struct superblock_security_struct *sbsec,
457 			const struct cred *cred)
458 {
459 	const struct cred_security_struct *crsec = selinux_cred(cred);
460 	int rc;
461 	rc = avc_has_perm(crsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
462 			  FILESYSTEM__RELABELFROM, NULL);
463 	if (rc)
464 		return rc;
465 
466 	rc = avc_has_perm(sid, sbsec->sid, SECCLASS_FILESYSTEM,
467 			  FILESYSTEM__ASSOCIATE, NULL);
468 	return rc;
469 }
470 
471 static int selinux_is_genfs_special_handling(struct super_block *sb)
472 {
473 	/* Special handling. Genfs but also in-core setxattr handler */
474 	return	!strcmp(sb->s_type->name, "sysfs") ||
475 		!strcmp(sb->s_type->name, "pstore") ||
476 		!strcmp(sb->s_type->name, "debugfs") ||
477 		!strcmp(sb->s_type->name, "tracefs") ||
478 		!strcmp(sb->s_type->name, "rootfs") ||
479 		(selinux_policycap_cgroupseclabel() &&
480 		 (!strcmp(sb->s_type->name, "cgroup") ||
481 		  !strcmp(sb->s_type->name, "cgroup2"))) ||
482 		(selinux_policycap_functionfs_seclabel() &&
483 		 !strcmp(sb->s_type->name, "functionfs"));
484 }
485 
486 static int selinux_is_sblabel_mnt(struct super_block *sb)
487 {
488 	struct superblock_security_struct *sbsec = selinux_superblock(sb);
489 
490 	/*
491 	 * IMPORTANT: Double-check logic in this function when adding a new
492 	 * SECURITY_FS_USE_* definition!
493 	 */
494 	BUILD_BUG_ON(SECURITY_FS_USE_MAX != 7);
495 
496 	switch (sbsec->behavior) {
497 	case SECURITY_FS_USE_XATTR:
498 	case SECURITY_FS_USE_TRANS:
499 	case SECURITY_FS_USE_TASK:
500 	case SECURITY_FS_USE_NATIVE:
501 		return 1;
502 
503 	case SECURITY_FS_USE_GENFS:
504 		return selinux_is_genfs_special_handling(sb);
505 
506 	/* Never allow relabeling on context mounts */
507 	case SECURITY_FS_USE_MNTPOINT:
508 	case SECURITY_FS_USE_NONE:
509 	default:
510 		return 0;
511 	}
512 }
513 
514 static int sb_check_xattr_support(struct super_block *sb)
515 {
516 	struct superblock_security_struct *sbsec = selinux_superblock(sb);
517 	struct dentry *root = sb->s_root;
518 	struct inode *root_inode = d_backing_inode(root);
519 	u32 sid;
520 	int rc;
521 
522 	/*
523 	 * Make sure that the xattr handler exists and that no
524 	 * error other than -ENODATA is returned by getxattr on
525 	 * the root directory.  -ENODATA is ok, as this may be
526 	 * the first boot of the SELinux kernel before we have
527 	 * assigned xattr values to the filesystem.
528 	 */
529 	if (!(root_inode->i_opflags & IOP_XATTR)) {
530 		pr_warn("SELinux: (dev %s, type %s) has no xattr support\n",
531 			sb->s_id, sb->s_type->name);
532 		goto fallback;
533 	}
534 
535 	rc = __vfs_getxattr(root, root_inode, XATTR_NAME_SELINUX, NULL, 0);
536 	if (rc < 0 && rc != -ENODATA) {
537 		if (rc == -EOPNOTSUPP) {
538 			pr_warn("SELinux: (dev %s, type %s) has no security xattr handler\n",
539 				sb->s_id, sb->s_type->name);
540 			goto fallback;
541 		} else {
542 			pr_warn("SELinux: (dev %s, type %s) getxattr errno %d\n",
543 				sb->s_id, sb->s_type->name, -rc);
544 			return rc;
545 		}
546 	}
547 	return 0;
548 
549 fallback:
550 	/* No xattr support - try to fallback to genfs if possible. */
551 	rc = security_genfs_sid(sb->s_type->name, "/",
552 				SECCLASS_DIR, &sid);
553 	if (rc)
554 		return -EOPNOTSUPP;
555 
556 	pr_warn("SELinux: (dev %s, type %s) falling back to genfs\n",
557 		sb->s_id, sb->s_type->name);
558 	sbsec->behavior = SECURITY_FS_USE_GENFS;
559 	sbsec->sid = sid;
560 	return 0;
561 }
562 
563 static int sb_finish_set_opts(struct super_block *sb)
564 {
565 	struct superblock_security_struct *sbsec = selinux_superblock(sb);
566 	struct dentry *root = sb->s_root;
567 	struct inode *root_inode = d_backing_inode(root);
568 	int rc = 0;
569 
570 	if (sbsec->behavior == SECURITY_FS_USE_XATTR) {
571 		rc = sb_check_xattr_support(sb);
572 		if (rc)
573 			return rc;
574 	}
575 
576 	sbsec->flags |= SE_SBINITIALIZED;
577 
578 	/*
579 	 * Explicitly set or clear SBLABEL_MNT.  It's not sufficient to simply
580 	 * leave the flag untouched because sb_clone_mnt_opts might be handing
581 	 * us a superblock that needs the flag to be cleared.
582 	 */
583 	if (selinux_is_sblabel_mnt(sb))
584 		sbsec->flags |= SBLABEL_MNT;
585 	else
586 		sbsec->flags &= ~SBLABEL_MNT;
587 
588 	/* Initialize the root inode. */
589 	rc = inode_doinit_with_dentry(root_inode, root);
590 
591 	/* Initialize any other inodes associated with the superblock, e.g.
592 	   inodes created prior to initial policy load or inodes created
593 	   during get_sb by a pseudo filesystem that directly
594 	   populates itself. */
595 	spin_lock(&sbsec->isec_lock);
596 	while (!list_empty(&sbsec->isec_head)) {
597 		struct inode_security_struct *isec =
598 				list_first_entry(&sbsec->isec_head,
599 					   struct inode_security_struct, list);
600 		struct inode *inode = isec->inode;
601 		list_del_init(&isec->list);
602 		spin_unlock(&sbsec->isec_lock);
603 		inode = igrab(inode);
604 		if (inode) {
605 			if (!IS_PRIVATE(inode))
606 				inode_doinit_with_dentry(inode, NULL);
607 			iput(inode);
608 		}
609 		spin_lock(&sbsec->isec_lock);
610 	}
611 	spin_unlock(&sbsec->isec_lock);
612 	return rc;
613 }
614 
615 static int bad_option(struct superblock_security_struct *sbsec, char flag,
616 		      u32 old_sid, u32 new_sid)
617 {
618 	char mnt_flags = sbsec->flags & SE_MNTMASK;
619 
620 	/* check if the old mount command had the same options */
621 	if (sbsec->flags & SE_SBINITIALIZED)
622 		if (!(sbsec->flags & flag) ||
623 		    (old_sid != new_sid))
624 			return 1;
625 
626 	/* check if we were passed the same options twice,
627 	 * aka someone passed context=a,context=b
628 	 */
629 	if (!(sbsec->flags & SE_SBINITIALIZED))
630 		if (mnt_flags & flag)
631 			return 1;
632 	return 0;
633 }
634 
635 /*
636  * Allow filesystems with binary mount data to explicitly set mount point
637  * labeling information.
638  */
639 static int selinux_set_mnt_opts(struct super_block *sb,
640 				void *mnt_opts,
641 				unsigned long kern_flags,
642 				unsigned long *set_kern_flags)
643 {
644 	const struct cred *cred = current_cred();
645 	struct superblock_security_struct *sbsec = selinux_superblock(sb);
646 	struct dentry *root = sb->s_root;
647 	struct selinux_mnt_opts *opts = mnt_opts;
648 	struct inode_security_struct *root_isec;
649 	u32 fscontext_sid = 0, context_sid = 0, rootcontext_sid = 0;
650 	u32 defcontext_sid = 0;
651 	int rc = 0;
652 
653 	/*
654 	 * Specifying internal flags without providing a place to
655 	 * place the results is not allowed
656 	 */
657 	if (kern_flags && !set_kern_flags)
658 		return -EINVAL;
659 
660 	mutex_lock(&sbsec->lock);
661 
662 	if (!selinux_initialized()) {
663 		if (!opts) {
664 			/* Defer initialization until selinux_complete_init,
665 			   after the initial policy is loaded and the security
666 			   server is ready to handle calls. */
667 			if (kern_flags & SECURITY_LSM_NATIVE_LABELS) {
668 				sbsec->flags |= SE_SBNATIVE;
669 				*set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
670 			}
671 			goto out;
672 		}
673 		rc = -EINVAL;
674 		pr_warn("SELinux: Unable to set superblock options "
675 			"before the security server is initialized\n");
676 		goto out;
677 	}
678 
679 	/*
680 	 * Binary mount data FS will come through this function twice.  Once
681 	 * from an explicit call and once from the generic calls from the vfs.
682 	 * Since the generic VFS calls will not contain any security mount data
683 	 * we need to skip the double mount verification.
684 	 *
685 	 * This does open a hole in which we will not notice if the first
686 	 * mount using this sb set explicit options and a second mount using
687 	 * this sb does not set any security options.  (The first options
688 	 * will be used for both mounts)
689 	 */
690 	if ((sbsec->flags & SE_SBINITIALIZED) && (sb->s_type->fs_flags & FS_BINARY_MOUNTDATA)
691 	    && !opts)
692 		goto out;
693 
694 	root_isec = backing_inode_security_novalidate(root);
695 
696 	/*
697 	 * parse the mount options, check if they are valid sids.
698 	 * also check if someone is trying to mount the same sb more
699 	 * than once with different security options.
700 	 */
701 	if (opts) {
702 		if (opts->fscontext_sid) {
703 			fscontext_sid = opts->fscontext_sid;
704 			if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid,
705 					fscontext_sid))
706 				goto out_double_mount;
707 			sbsec->flags |= FSCONTEXT_MNT;
708 		}
709 		if (opts->context_sid) {
710 			context_sid = opts->context_sid;
711 			if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid,
712 					context_sid))
713 				goto out_double_mount;
714 			sbsec->flags |= CONTEXT_MNT;
715 		}
716 		if (opts->rootcontext_sid) {
717 			rootcontext_sid = opts->rootcontext_sid;
718 			if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid,
719 					rootcontext_sid))
720 				goto out_double_mount;
721 			sbsec->flags |= ROOTCONTEXT_MNT;
722 		}
723 		if (opts->defcontext_sid) {
724 			defcontext_sid = opts->defcontext_sid;
725 			if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid,
726 					defcontext_sid))
727 				goto out_double_mount;
728 			sbsec->flags |= DEFCONTEXT_MNT;
729 		}
730 	}
731 
732 	if (sbsec->flags & SE_SBINITIALIZED) {
733 		/* previously mounted with options, but not on this attempt? */
734 		if ((sbsec->flags & SE_MNTMASK) && !opts)
735 			goto out_double_mount;
736 		rc = 0;
737 		goto out;
738 	}
739 
740 	sbsec->creator_sid = current_sid();
741 
742 	if (strcmp(sb->s_type->name, "proc") == 0)
743 		sbsec->flags |= SE_SBPROC | SE_SBGENFS;
744 
745 	if (!strcmp(sb->s_type->name, "debugfs") ||
746 	    !strcmp(sb->s_type->name, "tracefs") ||
747 	    !strcmp(sb->s_type->name, "binder") ||
748 	    !strcmp(sb->s_type->name, "bpf") ||
749 	    !strcmp(sb->s_type->name, "pstore") ||
750 	    !strcmp(sb->s_type->name, "securityfs") ||
751 	    (selinux_policycap_functionfs_seclabel() &&
752 	     !strcmp(sb->s_type->name, "functionfs")))
753 		sbsec->flags |= SE_SBGENFS;
754 
755 	if (!strcmp(sb->s_type->name, "sysfs") ||
756 	    !strcmp(sb->s_type->name, "cgroup") ||
757 	    !strcmp(sb->s_type->name, "cgroup2"))
758 		sbsec->flags |= SE_SBGENFS | SE_SBGENFS_XATTR;
759 
760 	if (!sbsec->behavior) {
761 		/*
762 		 * Determine the labeling behavior to use for this
763 		 * filesystem type.
764 		 */
765 		rc = security_fs_use(sb);
766 		if (rc) {
767 			pr_warn("%s: security_fs_use(%s) returned %d\n",
768 					__func__, sb->s_type->name, rc);
769 			goto out;
770 		}
771 	}
772 
773 	/*
774 	 * If this is a user namespace mount and the filesystem type is not
775 	 * explicitly whitelisted, then no contexts are allowed on the command
776 	 * line and security labels must be ignored.
777 	 */
778 	if (sb->s_user_ns != &init_user_ns &&
779 	    strcmp(sb->s_type->name, "tmpfs") &&
780 	    strcmp(sb->s_type->name, "ramfs") &&
781 	    strcmp(sb->s_type->name, "devpts") &&
782 	    strcmp(sb->s_type->name, "overlay")) {
783 		if (context_sid || fscontext_sid || rootcontext_sid ||
784 		    defcontext_sid) {
785 			rc = -EACCES;
786 			goto out;
787 		}
788 		if (sbsec->behavior == SECURITY_FS_USE_XATTR) {
789 			sbsec->behavior = SECURITY_FS_USE_MNTPOINT;
790 			rc = security_transition_sid(current_sid(),
791 						     current_sid(),
792 						     SECCLASS_FILE, NULL,
793 						     &sbsec->mntpoint_sid);
794 			if (rc)
795 				goto out;
796 		}
797 		goto out_set_opts;
798 	}
799 
800 	/* sets the context of the superblock for the fs being mounted. */
801 	if (fscontext_sid) {
802 		rc = may_context_mount_sb_relabel(fscontext_sid, sbsec, cred);
803 		if (rc)
804 			goto out;
805 
806 		sbsec->sid = fscontext_sid;
807 	}
808 
809 	/*
810 	 * Switch to using mount point labeling behavior.
811 	 * sets the label used on all file below the mountpoint, and will set
812 	 * the superblock context if not already set.
813 	 */
814 	if (sbsec->flags & SE_SBNATIVE) {
815 		/*
816 		 * This means we are initializing a superblock that has been
817 		 * mounted before the SELinux was initialized and the
818 		 * filesystem requested native labeling. We had already
819 		 * returned SECURITY_LSM_NATIVE_LABELS in *set_kern_flags
820 		 * in the original mount attempt, so now we just need to set
821 		 * the SECURITY_FS_USE_NATIVE behavior.
822 		 */
823 		sbsec->behavior = SECURITY_FS_USE_NATIVE;
824 	} else if (kern_flags & SECURITY_LSM_NATIVE_LABELS && !context_sid) {
825 		sbsec->behavior = SECURITY_FS_USE_NATIVE;
826 		*set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
827 	}
828 
829 	if (context_sid) {
830 		if (!fscontext_sid) {
831 			rc = may_context_mount_sb_relabel(context_sid, sbsec,
832 							  cred);
833 			if (rc)
834 				goto out;
835 			sbsec->sid = context_sid;
836 		} else {
837 			rc = may_context_mount_inode_relabel(context_sid, sbsec,
838 							     cred);
839 			if (rc)
840 				goto out;
841 		}
842 		if (!rootcontext_sid)
843 			rootcontext_sid = context_sid;
844 
845 		sbsec->mntpoint_sid = context_sid;
846 		sbsec->behavior = SECURITY_FS_USE_MNTPOINT;
847 	}
848 
849 	if (rootcontext_sid) {
850 		rc = may_context_mount_inode_relabel(rootcontext_sid, sbsec,
851 						     cred);
852 		if (rc)
853 			goto out;
854 
855 		root_isec->sid = rootcontext_sid;
856 		root_isec->initialized = LABEL_INITIALIZED;
857 	}
858 
859 	if (defcontext_sid) {
860 		if (sbsec->behavior != SECURITY_FS_USE_XATTR &&
861 			sbsec->behavior != SECURITY_FS_USE_NATIVE) {
862 			rc = -EINVAL;
863 			pr_warn("SELinux: defcontext option is "
864 			       "invalid for this filesystem type\n");
865 			goto out;
866 		}
867 
868 		if (defcontext_sid != sbsec->def_sid) {
869 			rc = may_context_mount_inode_relabel(defcontext_sid,
870 							     sbsec, cred);
871 			if (rc)
872 				goto out;
873 		}
874 
875 		sbsec->def_sid = defcontext_sid;
876 	}
877 
878 out_set_opts:
879 	rc = sb_finish_set_opts(sb);
880 out:
881 	mutex_unlock(&sbsec->lock);
882 	return rc;
883 out_double_mount:
884 	rc = -EINVAL;
885 	pr_warn("SELinux: mount invalid.  Same superblock, different "
886 	       "security settings for (dev %s, type %s)\n", sb->s_id,
887 	       sb->s_type->name);
888 	goto out;
889 }
890 
891 static int selinux_cmp_sb_context(const struct super_block *oldsb,
892 				    const struct super_block *newsb)
893 {
894 	struct superblock_security_struct *old = selinux_superblock(oldsb);
895 	struct superblock_security_struct *new = selinux_superblock(newsb);
896 	char oldflags = old->flags & SE_MNTMASK;
897 	char newflags = new->flags & SE_MNTMASK;
898 
899 	if (oldflags != newflags)
900 		goto mismatch;
901 	if ((oldflags & FSCONTEXT_MNT) && old->sid != new->sid)
902 		goto mismatch;
903 	if ((oldflags & CONTEXT_MNT) && old->mntpoint_sid != new->mntpoint_sid)
904 		goto mismatch;
905 	if ((oldflags & DEFCONTEXT_MNT) && old->def_sid != new->def_sid)
906 		goto mismatch;
907 	if (oldflags & ROOTCONTEXT_MNT) {
908 		struct inode_security_struct *oldroot = backing_inode_security(oldsb->s_root);
909 		struct inode_security_struct *newroot = backing_inode_security(newsb->s_root);
910 		if (oldroot->sid != newroot->sid)
911 			goto mismatch;
912 	}
913 	if (old->creator_sid != new->creator_sid)
914 		goto mismatch;
915 	return 0;
916 mismatch:
917 	pr_warn("SELinux: mount invalid.  Same superblock, "
918 			    "different security settings for (dev %s, "
919 			    "type %s)\n", newsb->s_id, newsb->s_type->name);
920 	return -EBUSY;
921 }
922 
923 static int selinux_sb_clone_mnt_opts(const struct super_block *oldsb,
924 					struct super_block *newsb,
925 					unsigned long kern_flags,
926 					unsigned long *set_kern_flags)
927 {
928 	int rc = 0;
929 	const struct superblock_security_struct *oldsbsec =
930 						selinux_superblock(oldsb);
931 	struct superblock_security_struct *newsbsec = selinux_superblock(newsb);
932 
933 	int set_fscontext =	(oldsbsec->flags & FSCONTEXT_MNT);
934 	int set_context =	(oldsbsec->flags & CONTEXT_MNT);
935 	int set_rootcontext =	(oldsbsec->flags & ROOTCONTEXT_MNT);
936 
937 	/*
938 	 * Specifying internal flags without providing a place to
939 	 * place the results is not allowed.
940 	 */
941 	if (kern_flags && !set_kern_flags)
942 		return -EINVAL;
943 
944 	mutex_lock(&newsbsec->lock);
945 
946 	/*
947 	 * if the parent was able to be mounted it clearly had no special lsm
948 	 * mount options.  thus we can safely deal with this superblock later
949 	 */
950 	if (!selinux_initialized()) {
951 		if (kern_flags & SECURITY_LSM_NATIVE_LABELS) {
952 			newsbsec->flags |= SE_SBNATIVE;
953 			*set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
954 		}
955 		goto out;
956 	}
957 
958 	/* how can we clone if the old one wasn't set up?? */
959 	BUG_ON(!(oldsbsec->flags & SE_SBINITIALIZED));
960 
961 	/* if fs is reusing a sb, make sure that the contexts match */
962 	if (newsbsec->flags & SE_SBINITIALIZED) {
963 		mutex_unlock(&newsbsec->lock);
964 		if ((kern_flags & SECURITY_LSM_NATIVE_LABELS) && !set_context)
965 			*set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
966 		return selinux_cmp_sb_context(oldsb, newsb);
967 	}
968 
969 	newsbsec->flags = oldsbsec->flags;
970 
971 	newsbsec->sid = oldsbsec->sid;
972 	newsbsec->def_sid = oldsbsec->def_sid;
973 	newsbsec->behavior = oldsbsec->behavior;
974 	newsbsec->creator_sid = oldsbsec->creator_sid;
975 
976 	if (newsbsec->behavior == SECURITY_FS_USE_NATIVE &&
977 		!(kern_flags & SECURITY_LSM_NATIVE_LABELS) && !set_context) {
978 		rc = security_fs_use(newsb);
979 		if (rc)
980 			goto out;
981 	}
982 
983 	if (kern_flags & SECURITY_LSM_NATIVE_LABELS && !set_context) {
984 		newsbsec->behavior = SECURITY_FS_USE_NATIVE;
985 		*set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
986 	}
987 
988 	if (set_context) {
989 		u32 sid = oldsbsec->mntpoint_sid;
990 
991 		if (!set_fscontext)
992 			newsbsec->sid = sid;
993 		if (!set_rootcontext) {
994 			struct inode_security_struct *newisec = backing_inode_security(newsb->s_root);
995 			newisec->sid = sid;
996 		}
997 		newsbsec->mntpoint_sid = sid;
998 	}
999 	if (set_rootcontext) {
1000 		const struct inode_security_struct *oldisec = backing_inode_security(oldsb->s_root);
1001 		struct inode_security_struct *newisec = backing_inode_security(newsb->s_root);
1002 
1003 		newisec->sid = oldisec->sid;
1004 	}
1005 
1006 	sb_finish_set_opts(newsb);
1007 out:
1008 	mutex_unlock(&newsbsec->lock);
1009 	return rc;
1010 }
1011 
1012 /*
1013  * NOTE: the caller is responsible for freeing the memory even if on error.
1014  */
1015 static int selinux_add_opt(int token, const char *s, void **mnt_opts)
1016 {
1017 	struct selinux_mnt_opts *opts = *mnt_opts;
1018 	u32 *dst_sid;
1019 	int rc;
1020 
1021 	if (token == Opt_seclabel)
1022 		/* eaten and completely ignored */
1023 		return 0;
1024 	if (!s)
1025 		return -EINVAL;
1026 
1027 	if (!selinux_initialized()) {
1028 		pr_warn("SELinux: Unable to set superblock options before the security server is initialized\n");
1029 		return -EINVAL;
1030 	}
1031 
1032 	if (!opts) {
1033 		opts = kzalloc_obj(*opts);
1034 		if (!opts)
1035 			return -ENOMEM;
1036 		*mnt_opts = opts;
1037 	}
1038 
1039 	switch (token) {
1040 	case Opt_context:
1041 		if (opts->context_sid || opts->defcontext_sid)
1042 			goto err;
1043 		dst_sid = &opts->context_sid;
1044 		break;
1045 	case Opt_fscontext:
1046 		if (opts->fscontext_sid)
1047 			goto err;
1048 		dst_sid = &opts->fscontext_sid;
1049 		break;
1050 	case Opt_rootcontext:
1051 		if (opts->rootcontext_sid)
1052 			goto err;
1053 		dst_sid = &opts->rootcontext_sid;
1054 		break;
1055 	case Opt_defcontext:
1056 		if (opts->context_sid || opts->defcontext_sid)
1057 			goto err;
1058 		dst_sid = &opts->defcontext_sid;
1059 		break;
1060 	default:
1061 		WARN_ON(1);
1062 		return -EINVAL;
1063 	}
1064 	rc = security_context_str_to_sid(s, dst_sid, GFP_KERNEL);
1065 	if (rc)
1066 		pr_warn("SELinux: security_context_str_to_sid (%s) failed with errno=%d\n",
1067 			s, rc);
1068 	return rc;
1069 
1070 err:
1071 	pr_warn(SEL_MOUNT_FAIL_MSG);
1072 	return -EINVAL;
1073 }
1074 
1075 static int show_sid(struct seq_file *m, u32 sid)
1076 {
1077 	char *context = NULL;
1078 	u32 len;
1079 	int rc;
1080 
1081 	rc = security_sid_to_context(sid, &context, &len);
1082 	if (!rc) {
1083 		bool has_comma = strchr(context, ',');
1084 
1085 		seq_putc(m, '=');
1086 		if (has_comma)
1087 			seq_putc(m, '\"');
1088 		seq_escape(m, context, "\"\n\\");
1089 		if (has_comma)
1090 			seq_putc(m, '\"');
1091 	}
1092 	kfree(context);
1093 	return rc;
1094 }
1095 
1096 static int selinux_sb_show_options(struct seq_file *m, struct super_block *sb)
1097 {
1098 	struct superblock_security_struct *sbsec = selinux_superblock(sb);
1099 	int rc;
1100 
1101 	if (!(sbsec->flags & SE_SBINITIALIZED))
1102 		return 0;
1103 
1104 	if (!selinux_initialized())
1105 		return 0;
1106 
1107 	if (sbsec->flags & FSCONTEXT_MNT) {
1108 		seq_putc(m, ',');
1109 		seq_puts(m, FSCONTEXT_STR);
1110 		rc = show_sid(m, sbsec->sid);
1111 		if (rc)
1112 			return rc;
1113 	}
1114 	if (sbsec->flags & CONTEXT_MNT) {
1115 		seq_putc(m, ',');
1116 		seq_puts(m, CONTEXT_STR);
1117 		rc = show_sid(m, sbsec->mntpoint_sid);
1118 		if (rc)
1119 			return rc;
1120 	}
1121 	if (sbsec->flags & DEFCONTEXT_MNT) {
1122 		seq_putc(m, ',');
1123 		seq_puts(m, DEFCONTEXT_STR);
1124 		rc = show_sid(m, sbsec->def_sid);
1125 		if (rc)
1126 			return rc;
1127 	}
1128 	if (sbsec->flags & ROOTCONTEXT_MNT) {
1129 		struct dentry *root = sb->s_root;
1130 		struct inode_security_struct *isec = backing_inode_security(root);
1131 		seq_putc(m, ',');
1132 		seq_puts(m, ROOTCONTEXT_STR);
1133 		rc = show_sid(m, isec->sid);
1134 		if (rc)
1135 			return rc;
1136 	}
1137 	if (sbsec->flags & SBLABEL_MNT) {
1138 		seq_putc(m, ',');
1139 		seq_puts(m, SECLABEL_STR);
1140 	}
1141 	return 0;
1142 }
1143 
1144 static inline u16 inode_mode_to_security_class(umode_t mode)
1145 {
1146 	switch (mode & S_IFMT) {
1147 	case S_IFSOCK:
1148 		return SECCLASS_SOCK_FILE;
1149 	case S_IFLNK:
1150 		return SECCLASS_LNK_FILE;
1151 	case S_IFREG:
1152 		return SECCLASS_FILE;
1153 	case S_IFBLK:
1154 		return SECCLASS_BLK_FILE;
1155 	case S_IFDIR:
1156 		return SECCLASS_DIR;
1157 	case S_IFCHR:
1158 		return SECCLASS_CHR_FILE;
1159 	case S_IFIFO:
1160 		return SECCLASS_FIFO_FILE;
1161 
1162 	}
1163 
1164 	return SECCLASS_FILE;
1165 }
1166 
1167 static inline int default_protocol_stream(int protocol)
1168 {
1169 	return (protocol == IPPROTO_IP || protocol == IPPROTO_TCP ||
1170 		protocol == IPPROTO_MPTCP);
1171 }
1172 
1173 static inline int default_protocol_dgram(int protocol)
1174 {
1175 	return (protocol == IPPROTO_IP || protocol == IPPROTO_UDP);
1176 }
1177 
1178 static inline u16 socket_type_to_security_class(int family, int type, int protocol)
1179 {
1180 	bool extsockclass = selinux_policycap_extsockclass();
1181 
1182 	switch (family) {
1183 	case PF_UNIX:
1184 		switch (type) {
1185 		case SOCK_STREAM:
1186 		case SOCK_SEQPACKET:
1187 			return SECCLASS_UNIX_STREAM_SOCKET;
1188 		case SOCK_DGRAM:
1189 		case SOCK_RAW:
1190 			return SECCLASS_UNIX_DGRAM_SOCKET;
1191 		}
1192 		break;
1193 	case PF_INET:
1194 	case PF_INET6:
1195 		switch (type) {
1196 		case SOCK_STREAM:
1197 		case SOCK_SEQPACKET:
1198 			if (default_protocol_stream(protocol))
1199 				return SECCLASS_TCP_SOCKET;
1200 			else if (extsockclass && protocol == IPPROTO_SCTP)
1201 				return SECCLASS_SCTP_SOCKET;
1202 			else
1203 				return SECCLASS_RAWIP_SOCKET;
1204 		case SOCK_DGRAM:
1205 			if (default_protocol_dgram(protocol))
1206 				return SECCLASS_UDP_SOCKET;
1207 			else if (extsockclass && (protocol == IPPROTO_ICMP ||
1208 						  protocol == IPPROTO_ICMPV6))
1209 				return SECCLASS_ICMP_SOCKET;
1210 			else
1211 				return SECCLASS_RAWIP_SOCKET;
1212 		default:
1213 			return SECCLASS_RAWIP_SOCKET;
1214 		}
1215 		break;
1216 	case PF_NETLINK:
1217 		switch (protocol) {
1218 		case NETLINK_ROUTE:
1219 			return SECCLASS_NETLINK_ROUTE_SOCKET;
1220 		case NETLINK_SOCK_DIAG:
1221 			return SECCLASS_NETLINK_TCPDIAG_SOCKET;
1222 		case NETLINK_NFLOG:
1223 			return SECCLASS_NETLINK_NFLOG_SOCKET;
1224 		case NETLINK_XFRM:
1225 			return SECCLASS_NETLINK_XFRM_SOCKET;
1226 		case NETLINK_SELINUX:
1227 			return SECCLASS_NETLINK_SELINUX_SOCKET;
1228 		case NETLINK_ISCSI:
1229 			return SECCLASS_NETLINK_ISCSI_SOCKET;
1230 		case NETLINK_AUDIT:
1231 			return SECCLASS_NETLINK_AUDIT_SOCKET;
1232 		case NETLINK_FIB_LOOKUP:
1233 			return SECCLASS_NETLINK_FIB_LOOKUP_SOCKET;
1234 		case NETLINK_CONNECTOR:
1235 			return SECCLASS_NETLINK_CONNECTOR_SOCKET;
1236 		case NETLINK_NETFILTER:
1237 			return SECCLASS_NETLINK_NETFILTER_SOCKET;
1238 		case NETLINK_DNRTMSG:
1239 			return SECCLASS_NETLINK_DNRT_SOCKET;
1240 		case NETLINK_KOBJECT_UEVENT:
1241 			return SECCLASS_NETLINK_KOBJECT_UEVENT_SOCKET;
1242 		case NETLINK_GENERIC:
1243 			return SECCLASS_NETLINK_GENERIC_SOCKET;
1244 		case NETLINK_SCSITRANSPORT:
1245 			return SECCLASS_NETLINK_SCSITRANSPORT_SOCKET;
1246 		case NETLINK_RDMA:
1247 			return SECCLASS_NETLINK_RDMA_SOCKET;
1248 		case NETLINK_CRYPTO:
1249 			return SECCLASS_NETLINK_CRYPTO_SOCKET;
1250 		default:
1251 			return SECCLASS_NETLINK_SOCKET;
1252 		}
1253 	case PF_PACKET:
1254 		return SECCLASS_PACKET_SOCKET;
1255 	case PF_KEY:
1256 		return SECCLASS_KEY_SOCKET;
1257 	case PF_APPLETALK:
1258 		return SECCLASS_APPLETALK_SOCKET;
1259 	}
1260 
1261 	if (extsockclass) {
1262 		switch (family) {
1263 		case PF_AX25:
1264 			return SECCLASS_AX25_SOCKET;
1265 		case PF_IPX:
1266 			return SECCLASS_IPX_SOCKET;
1267 		case PF_NETROM:
1268 			return SECCLASS_NETROM_SOCKET;
1269 		case PF_ATMPVC:
1270 			return SECCLASS_ATMPVC_SOCKET;
1271 		case PF_X25:
1272 			return SECCLASS_X25_SOCKET;
1273 		case PF_ROSE:
1274 			return SECCLASS_ROSE_SOCKET;
1275 		case PF_DECnet:
1276 			return SECCLASS_DECNET_SOCKET;
1277 		case PF_ATMSVC:
1278 			return SECCLASS_ATMSVC_SOCKET;
1279 		case PF_RDS:
1280 			return SECCLASS_RDS_SOCKET;
1281 		case PF_IRDA:
1282 			return SECCLASS_IRDA_SOCKET;
1283 		case PF_PPPOX:
1284 			return SECCLASS_PPPOX_SOCKET;
1285 		case PF_LLC:
1286 			return SECCLASS_LLC_SOCKET;
1287 		case PF_CAN:
1288 			return SECCLASS_CAN_SOCKET;
1289 		case PF_TIPC:
1290 			return SECCLASS_TIPC_SOCKET;
1291 		case PF_BLUETOOTH:
1292 			return SECCLASS_BLUETOOTH_SOCKET;
1293 		case PF_IUCV:
1294 			return SECCLASS_IUCV_SOCKET;
1295 		case PF_RXRPC:
1296 			return SECCLASS_RXRPC_SOCKET;
1297 		case PF_ISDN:
1298 			return SECCLASS_ISDN_SOCKET;
1299 		case PF_PHONET:
1300 			return SECCLASS_PHONET_SOCKET;
1301 		case PF_IEEE802154:
1302 			return SECCLASS_IEEE802154_SOCKET;
1303 		case PF_CAIF:
1304 			return SECCLASS_CAIF_SOCKET;
1305 		case PF_ALG:
1306 			return SECCLASS_ALG_SOCKET;
1307 		case PF_NFC:
1308 			return SECCLASS_NFC_SOCKET;
1309 		case PF_VSOCK:
1310 			return SECCLASS_VSOCK_SOCKET;
1311 		case PF_KCM:
1312 			return SECCLASS_KCM_SOCKET;
1313 		case PF_QIPCRTR:
1314 			return SECCLASS_QIPCRTR_SOCKET;
1315 		case PF_SMC:
1316 			return SECCLASS_SMC_SOCKET;
1317 		case PF_XDP:
1318 			return SECCLASS_XDP_SOCKET;
1319 		case PF_MCTP:
1320 			return SECCLASS_MCTP_SOCKET;
1321 #if PF_MAX > 46
1322 #error New address family defined, please update this function.
1323 #endif
1324 		}
1325 	}
1326 
1327 	return SECCLASS_SOCKET;
1328 }
1329 
1330 static int selinux_genfs_get_sid(struct dentry *dentry,
1331 				 u16 tclass,
1332 				 u16 flags,
1333 				 u32 *sid)
1334 {
1335 	int rc;
1336 	struct super_block *sb = dentry->d_sb;
1337 	char *buffer, *path;
1338 
1339 	buffer = (char *)__get_free_page(GFP_KERNEL);
1340 	if (!buffer)
1341 		return -ENOMEM;
1342 
1343 	path = dentry_path_raw(dentry, buffer, PAGE_SIZE);
1344 	if (IS_ERR(path))
1345 		rc = PTR_ERR(path);
1346 	else {
1347 		if (flags & SE_SBPROC) {
1348 			/* each process gets a /proc/PID/ entry. Strip off the
1349 			 * PID part to get a valid selinux labeling.
1350 			 * e.g. /proc/1/net/rpc/nfs -> /net/rpc/nfs */
1351 			while (path[1] >= '0' && path[1] <= '9') {
1352 				path[1] = '/';
1353 				path++;
1354 			}
1355 		}
1356 		rc = security_genfs_sid(sb->s_type->name,
1357 					path, tclass, sid);
1358 		if (rc == -ENOENT) {
1359 			/* No match in policy, mark as unlabeled. */
1360 			*sid = SECINITSID_UNLABELED;
1361 			rc = 0;
1362 		}
1363 	}
1364 	free_page((unsigned long)buffer);
1365 	return rc;
1366 }
1367 
1368 static int inode_doinit_use_xattr(struct inode *inode, struct dentry *dentry,
1369 				  u32 def_sid, u32 *sid)
1370 {
1371 #define INITCONTEXTLEN 255
1372 	char *context;
1373 	unsigned int len;
1374 	int rc;
1375 
1376 	len = INITCONTEXTLEN;
1377 	context = kmalloc(len + 1, GFP_NOFS);
1378 	if (!context)
1379 		return -ENOMEM;
1380 
1381 	context[len] = '\0';
1382 	rc = __vfs_getxattr(dentry, inode, XATTR_NAME_SELINUX, context, len);
1383 	if (rc == -ERANGE) {
1384 		kfree(context);
1385 
1386 		/* Need a larger buffer.  Query for the right size. */
1387 		rc = __vfs_getxattr(dentry, inode, XATTR_NAME_SELINUX, NULL, 0);
1388 		if (rc < 0)
1389 			return rc;
1390 
1391 		len = rc;
1392 		context = kmalloc(len + 1, GFP_NOFS);
1393 		if (!context)
1394 			return -ENOMEM;
1395 
1396 		context[len] = '\0';
1397 		rc = __vfs_getxattr(dentry, inode, XATTR_NAME_SELINUX,
1398 				    context, len);
1399 	}
1400 	if (rc < 0) {
1401 		kfree(context);
1402 		if (rc != -ENODATA) {
1403 			pr_warn("SELinux: %s:  getxattr returned %d for dev=%s ino=%llu\n",
1404 				__func__, -rc, inode->i_sb->s_id, inode->i_ino);
1405 			return rc;
1406 		}
1407 		*sid = def_sid;
1408 		return 0;
1409 	}
1410 
1411 	rc = security_context_to_sid_default(context, rc, sid,
1412 					     def_sid, GFP_NOFS);
1413 	if (rc) {
1414 		char *dev = inode->i_sb->s_id;
1415 		u64 ino = inode->i_ino;
1416 
1417 		if (rc == -EINVAL) {
1418 			pr_notice_ratelimited("SELinux: inode=%llu on dev=%s was found to have an invalid context=%s.  This indicates you may need to relabel the inode or the filesystem in question.\n",
1419 					      ino, dev, context);
1420 		} else {
1421 			pr_warn("SELinux: %s:  context_to_sid(%s) returned %d for dev=%s ino=%llu\n",
1422 				__func__, context, -rc, dev, ino);
1423 		}
1424 	}
1425 	kfree(context);
1426 	return 0;
1427 }
1428 
1429 /* The inode's security attributes must be initialized before first use. */
1430 static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dentry)
1431 {
1432 	struct superblock_security_struct *sbsec = NULL;
1433 	struct inode_security_struct *isec = selinux_inode(inode);
1434 	u32 task_sid, sid = 0;
1435 	u16 sclass;
1436 	struct dentry *dentry;
1437 	int rc = 0;
1438 
1439 	/* check below is racy, but we will recheck with lock held */
1440 	if (data_race(isec->initialized == LABEL_INITIALIZED))
1441 		return 0;
1442 
1443 	spin_lock(&isec->lock);
1444 	if (isec->initialized == LABEL_INITIALIZED)
1445 		goto out_unlock;
1446 
1447 	if (isec->sclass == SECCLASS_FILE)
1448 		isec->sclass = inode_mode_to_security_class(inode->i_mode);
1449 
1450 	sbsec = selinux_superblock(inode->i_sb);
1451 	if (!(sbsec->flags & SE_SBINITIALIZED)) {
1452 		/* Defer initialization until selinux_complete_init,
1453 		   after the initial policy is loaded and the security
1454 		   server is ready to handle calls. */
1455 		spin_lock(&sbsec->isec_lock);
1456 		if (list_empty(&isec->list))
1457 			list_add(&isec->list, &sbsec->isec_head);
1458 		spin_unlock(&sbsec->isec_lock);
1459 		goto out_unlock;
1460 	}
1461 
1462 	sclass = isec->sclass;
1463 	task_sid = isec->task_sid;
1464 	sid = isec->sid;
1465 	isec->initialized = LABEL_PENDING;
1466 	spin_unlock(&isec->lock);
1467 
1468 	switch (sbsec->behavior) {
1469 	/*
1470 	 * In case of SECURITY_FS_USE_NATIVE we need to re-fetch the labels
1471 	 * via xattr when called from delayed_superblock_init().
1472 	 */
1473 	case SECURITY_FS_USE_NATIVE:
1474 	case SECURITY_FS_USE_XATTR:
1475 		if (!(inode->i_opflags & IOP_XATTR)) {
1476 			sid = sbsec->def_sid;
1477 			break;
1478 		}
1479 		/* Need a dentry, since the xattr API requires one.
1480 		   Life would be simpler if we could just pass the inode. */
1481 		if (opt_dentry) {
1482 			/* Called from d_instantiate or d_splice_alias. */
1483 			dentry = dget(opt_dentry);
1484 		} else {
1485 			/*
1486 			 * Called from selinux_complete_init, try to find a dentry.
1487 			 * Some filesystems really want a connected one, so try
1488 			 * that first.  We could split SECURITY_FS_USE_XATTR in
1489 			 * two, depending upon that...
1490 			 */
1491 			dentry = d_find_alias(inode);
1492 			if (!dentry)
1493 				dentry = d_find_any_alias(inode);
1494 		}
1495 		if (!dentry) {
1496 			/*
1497 			 * this is can be hit on boot when a file is accessed
1498 			 * before the policy is loaded.  When we load policy we
1499 			 * may find inodes that have no dentry on the
1500 			 * sbsec->isec_head list.  No reason to complain as these
1501 			 * will get fixed up the next time we go through
1502 			 * inode_doinit with a dentry, before these inodes could
1503 			 * be used again by userspace.
1504 			 */
1505 			goto out_invalid;
1506 		}
1507 
1508 		rc = inode_doinit_use_xattr(inode, dentry, sbsec->def_sid,
1509 					    &sid);
1510 		dput(dentry);
1511 		if (rc)
1512 			goto out;
1513 		break;
1514 	case SECURITY_FS_USE_TASK:
1515 		sid = task_sid;
1516 		break;
1517 	case SECURITY_FS_USE_TRANS:
1518 		/* Default to the fs SID. */
1519 		sid = sbsec->sid;
1520 
1521 		/* Try to obtain a transition SID. */
1522 		rc = security_transition_sid(task_sid, sid,
1523 					     sclass, NULL, &sid);
1524 		if (rc)
1525 			goto out;
1526 		break;
1527 	case SECURITY_FS_USE_MNTPOINT:
1528 		sid = sbsec->mntpoint_sid;
1529 		break;
1530 	default:
1531 		/* Default to the fs superblock SID. */
1532 		sid = sbsec->sid;
1533 
1534 		if ((sbsec->flags & SE_SBGENFS) &&
1535 		     (!S_ISLNK(inode->i_mode) ||
1536 		      selinux_policycap_genfs_seclabel_symlinks())) {
1537 			/* We must have a dentry to determine the label on
1538 			 * procfs inodes */
1539 			if (opt_dentry) {
1540 				/* Called from d_instantiate or
1541 				 * d_splice_alias. */
1542 				dentry = dget(opt_dentry);
1543 			} else {
1544 				/* Called from selinux_complete_init, try to
1545 				 * find a dentry.  Some filesystems really want
1546 				 * a connected one, so try that first.
1547 				 */
1548 				dentry = d_find_alias(inode);
1549 				if (!dentry)
1550 					dentry = d_find_any_alias(inode);
1551 			}
1552 			/*
1553 			 * This can be hit on boot when a file is accessed
1554 			 * before the policy is loaded.  When we load policy we
1555 			 * may find inodes that have no dentry on the
1556 			 * sbsec->isec_head list.  No reason to complain as
1557 			 * these will get fixed up the next time we go through
1558 			 * inode_doinit() with a dentry, before these inodes
1559 			 * could be used again by userspace.
1560 			 */
1561 			if (!dentry)
1562 				goto out_invalid;
1563 			rc = selinux_genfs_get_sid(dentry, sclass,
1564 						   sbsec->flags, &sid);
1565 			if (rc) {
1566 				dput(dentry);
1567 				goto out;
1568 			}
1569 
1570 			if ((sbsec->flags & SE_SBGENFS_XATTR) &&
1571 			    (inode->i_opflags & IOP_XATTR)) {
1572 				rc = inode_doinit_use_xattr(inode, dentry,
1573 							    sid, &sid);
1574 				if (rc) {
1575 					dput(dentry);
1576 					goto out;
1577 				}
1578 			}
1579 			dput(dentry);
1580 		}
1581 		break;
1582 	}
1583 
1584 out:
1585 	spin_lock(&isec->lock);
1586 	if (isec->initialized == LABEL_PENDING) {
1587 		if (rc) {
1588 			isec->initialized = LABEL_INVALID;
1589 			goto out_unlock;
1590 		}
1591 		isec->initialized = LABEL_INITIALIZED;
1592 		isec->sid = sid;
1593 	}
1594 
1595 out_unlock:
1596 	spin_unlock(&isec->lock);
1597 	return rc;
1598 
1599 out_invalid:
1600 	spin_lock(&isec->lock);
1601 	if (isec->initialized == LABEL_PENDING) {
1602 		isec->initialized = LABEL_INVALID;
1603 		isec->sid = sid;
1604 	}
1605 	spin_unlock(&isec->lock);
1606 	return 0;
1607 }
1608 
1609 /* Convert a Linux signal to an access vector. */
1610 static inline u32 signal_to_av(int sig)
1611 {
1612 	u32 perm = 0;
1613 
1614 	switch (sig) {
1615 	case SIGCHLD:
1616 		/* Commonly granted from child to parent. */
1617 		perm = PROCESS__SIGCHLD;
1618 		break;
1619 	case SIGKILL:
1620 		/* Cannot be caught or ignored */
1621 		perm = PROCESS__SIGKILL;
1622 		break;
1623 	case SIGSTOP:
1624 		/* Cannot be caught or ignored */
1625 		perm = PROCESS__SIGSTOP;
1626 		break;
1627 	default:
1628 		/* All other signals. */
1629 		perm = PROCESS__SIGNAL;
1630 		break;
1631 	}
1632 
1633 	return perm;
1634 }
1635 
1636 #if CAP_LAST_CAP > 63
1637 #error Fix SELinux to handle capabilities > 63.
1638 #endif
1639 
1640 /* Check whether a task is allowed to use a capability. */
1641 static int cred_has_capability(const struct cred *cred,
1642 			       int cap, unsigned int opts, bool initns)
1643 {
1644 	struct common_audit_data ad;
1645 	struct av_decision avd;
1646 	u16 sclass;
1647 	u32 sid = cred_sid(cred);
1648 	u32 av = CAP_TO_MASK(cap);
1649 	int rc;
1650 
1651 	ad.type = LSM_AUDIT_DATA_CAP;
1652 	ad.u.cap = cap;
1653 
1654 	switch (CAP_TO_INDEX(cap)) {
1655 	case 0:
1656 		sclass = initns ? SECCLASS_CAPABILITY : SECCLASS_CAP_USERNS;
1657 		break;
1658 	case 1:
1659 		sclass = initns ? SECCLASS_CAPABILITY2 : SECCLASS_CAP2_USERNS;
1660 		break;
1661 	default:
1662 		pr_err("SELinux:  out of range capability %d\n", cap);
1663 		return -EINVAL;
1664 	}
1665 
1666 	rc = avc_has_perm_noaudit(sid, sid, sclass, av, 0, &avd);
1667 	if (!(opts & CAP_OPT_NOAUDIT)) {
1668 		int rc2 = avc_audit(sid, sid, sclass, av, &avd, rc, &ad);
1669 		if (rc2)
1670 			return rc2;
1671 	}
1672 	return rc;
1673 }
1674 
1675 /* Check whether a task has a particular permission to an inode.
1676    The 'adp' parameter is optional and allows other audit
1677    data to be passed (e.g. the dentry). */
1678 static int inode_has_perm(const struct cred *cred,
1679 			  struct inode *inode,
1680 			  u32 perms,
1681 			  struct common_audit_data *adp)
1682 {
1683 	struct inode_security_struct *isec;
1684 	u32 sid;
1685 
1686 	if (unlikely(IS_PRIVATE(inode)))
1687 		return 0;
1688 
1689 	sid = cred_sid(cred);
1690 	isec = selinux_inode(inode);
1691 
1692 	return avc_has_perm(sid, isec->sid, isec->sclass, perms, adp);
1693 }
1694 
1695 /* Same as inode_has_perm, but pass explicit audit data containing
1696    the dentry to help the auditing code to more easily generate the
1697    pathname if needed. */
1698 static inline int dentry_has_perm(const struct cred *cred,
1699 				  struct dentry *dentry,
1700 				  u32 av)
1701 {
1702 	struct common_audit_data ad;
1703 	struct inode *inode = d_backing_inode(dentry);
1704 	struct inode_security_struct *isec = selinux_inode(inode);
1705 
1706 	ad.type = LSM_AUDIT_DATA_DENTRY;
1707 	ad.u.dentry = dentry;
1708 	/* check below is racy, but revalidate will recheck with lock held */
1709 	if (data_race(unlikely(isec->initialized != LABEL_INITIALIZED)))
1710 		__inode_security_revalidate(inode, dentry, true);
1711 	return inode_has_perm(cred, inode, av, &ad);
1712 }
1713 
1714 /* Same as inode_has_perm, but pass explicit audit data containing
1715    the path to help the auditing code to more easily generate the
1716    pathname if needed. */
1717 static inline int path_has_perm(const struct cred *cred,
1718 				const struct path *path,
1719 				u32 av)
1720 {
1721 	struct common_audit_data ad;
1722 	struct inode *inode = d_backing_inode(path->dentry);
1723 	struct inode_security_struct *isec = selinux_inode(inode);
1724 
1725 	ad.type = LSM_AUDIT_DATA_PATH;
1726 	ad.u.path = *path;
1727 	/* check below is racy, but revalidate will recheck with lock held */
1728 	if (data_race(unlikely(isec->initialized != LABEL_INITIALIZED)))
1729 		__inode_security_revalidate(inode, path->dentry, true);
1730 	return inode_has_perm(cred, inode, av, &ad);
1731 }
1732 
1733 /* Same as path_has_perm, but uses the inode from the file struct. */
1734 static inline int file_path_has_perm(const struct cred *cred,
1735 				     struct file *file,
1736 				     u32 av)
1737 {
1738 	struct common_audit_data ad;
1739 
1740 	ad.type = LSM_AUDIT_DATA_FILE;
1741 	ad.u.file = file;
1742 	return inode_has_perm(cred, file_inode(file), av, &ad);
1743 }
1744 
1745 #ifdef CONFIG_BPF_SYSCALL
1746 static int bpf_fd_pass(const struct file *file, u32 sid);
1747 #endif
1748 
1749 static int __file_has_perm(const struct cred *cred, const struct file *file,
1750 			   u32 av, bool bf_user_file)
1751 
1752 {
1753 	struct common_audit_data ad;
1754 	struct inode *inode;
1755 	u32 ssid = cred_sid(cred);
1756 	u32 tsid_fd;
1757 	int rc;
1758 
1759 	if (bf_user_file) {
1760 		struct backing_file_security_struct *bfsec;
1761 		const struct path *path;
1762 
1763 		if (WARN_ON(!(file->f_mode & FMODE_BACKING)))
1764 			return -EIO;
1765 
1766 		bfsec = selinux_backing_file(file);
1767 		path = backing_file_user_path(file);
1768 		tsid_fd = bfsec->uf_sid;
1769 		inode = d_inode(path->dentry);
1770 
1771 		ad.type = LSM_AUDIT_DATA_PATH;
1772 		ad.u.path = *path;
1773 	} else {
1774 		struct file_security_struct *fsec = selinux_file(file);
1775 
1776 		tsid_fd = fsec->sid;
1777 		inode = file_inode(file);
1778 
1779 		ad.type = LSM_AUDIT_DATA_FILE;
1780 		ad.u.file = file;
1781 	}
1782 
1783 	if (ssid != tsid_fd) {
1784 		rc = avc_has_perm(ssid, tsid_fd, SECCLASS_FD, FD__USE, &ad);
1785 		if (rc)
1786 			return rc;
1787 	}
1788 
1789 #ifdef CONFIG_BPF_SYSCALL
1790 	/* regardless of backing vs user file, use the underlying file here */
1791 	rc = bpf_fd_pass(file, ssid);
1792 	if (rc)
1793 		return rc;
1794 #endif
1795 
1796 	/* av is zero if only checking access to the descriptor. */
1797 	if (av)
1798 		return inode_has_perm(cred, inode, av, &ad);
1799 
1800 	return 0;
1801 }
1802 
1803 /* Check whether a task can use an open file descriptor to
1804    access an inode in a given way.  Check access to the
1805    descriptor itself, and then use dentry_has_perm to
1806    check a particular permission to the file.
1807    Access to the descriptor is implicitly granted if it
1808    has the same SID as the process.  If av is zero, then
1809    access to the file is not checked, e.g. for cases
1810    where only the descriptor is affected like seek. */
1811 static inline int file_has_perm(const struct cred *cred,
1812 				const struct file *file, u32 av)
1813 {
1814 	return __file_has_perm(cred, file, av, false);
1815 }
1816 
1817 /*
1818  * Determine the label for an inode that might be unioned.
1819  */
1820 static int
1821 selinux_determine_inode_label(const struct cred_security_struct *crsec,
1822 				 struct inode *dir,
1823 				 const struct qstr *name, u16 tclass,
1824 				 u32 *_new_isid)
1825 {
1826 	const struct superblock_security_struct *sbsec =
1827 						selinux_superblock(dir->i_sb);
1828 
1829 	if ((sbsec->flags & SE_SBINITIALIZED) &&
1830 	    (sbsec->behavior == SECURITY_FS_USE_MNTPOINT)) {
1831 		*_new_isid = sbsec->mntpoint_sid;
1832 	} else if ((sbsec->flags & SBLABEL_MNT) &&
1833 		   crsec->create_sid) {
1834 		*_new_isid = crsec->create_sid;
1835 	} else {
1836 		const struct inode_security_struct *dsec = inode_security(dir);
1837 		return security_transition_sid(crsec->sid,
1838 					       dsec->sid, tclass,
1839 					       name, _new_isid);
1840 	}
1841 
1842 	return 0;
1843 }
1844 
1845 /* Check whether a task can create a file. */
1846 static int may_create(struct inode *dir,
1847 		      struct dentry *dentry,
1848 		      u16 tclass)
1849 {
1850 	const struct cred_security_struct *crsec = selinux_cred(current_cred());
1851 	struct inode_security_struct *dsec;
1852 	struct superblock_security_struct *sbsec;
1853 	u32 sid, newsid;
1854 	struct common_audit_data ad;
1855 	int rc;
1856 
1857 	dsec = inode_security(dir);
1858 	sbsec = selinux_superblock(dir->i_sb);
1859 
1860 	sid = crsec->sid;
1861 
1862 	ad.type = LSM_AUDIT_DATA_DENTRY;
1863 	ad.u.dentry = dentry;
1864 
1865 	rc = avc_has_perm(sid, dsec->sid, SECCLASS_DIR,
1866 			  DIR__ADD_NAME | DIR__SEARCH,
1867 			  &ad);
1868 	if (rc)
1869 		return rc;
1870 
1871 	rc = selinux_determine_inode_label(crsec, dir, &dentry->d_name, tclass,
1872 					   &newsid);
1873 	if (rc)
1874 		return rc;
1875 
1876 	rc = avc_has_perm(sid, newsid, tclass, FILE__CREATE, &ad);
1877 	if (rc)
1878 		return rc;
1879 
1880 	return avc_has_perm(newsid, sbsec->sid,
1881 			    SECCLASS_FILESYSTEM,
1882 			    FILESYSTEM__ASSOCIATE, &ad);
1883 }
1884 
1885 #define MAY_LINK	0
1886 #define MAY_UNLINK	1
1887 #define MAY_RMDIR	2
1888 
1889 /* Check whether a task can link, unlink, or rmdir a file/directory. */
1890 static int may_link(struct inode *dir,
1891 		    struct dentry *dentry,
1892 		    int kind)
1893 
1894 {
1895 	struct inode_security_struct *dsec, *isec;
1896 	struct common_audit_data ad;
1897 	u32 sid = current_sid();
1898 	u32 av;
1899 	int rc;
1900 
1901 	dsec = inode_security(dir);
1902 	isec = backing_inode_security(dentry);
1903 
1904 	ad.type = LSM_AUDIT_DATA_DENTRY;
1905 	ad.u.dentry = dentry;
1906 
1907 	av = DIR__SEARCH;
1908 	av |= (kind ? DIR__REMOVE_NAME : DIR__ADD_NAME);
1909 	rc = avc_has_perm(sid, dsec->sid, SECCLASS_DIR, av, &ad);
1910 	if (rc)
1911 		return rc;
1912 
1913 	switch (kind) {
1914 	case MAY_LINK:
1915 		av = FILE__LINK;
1916 		break;
1917 	case MAY_UNLINK:
1918 		av = FILE__UNLINK;
1919 		break;
1920 	case MAY_RMDIR:
1921 		av = DIR__RMDIR;
1922 		break;
1923 	default:
1924 		pr_warn("SELinux: %s:  unrecognized kind %d\n",
1925 			__func__, kind);
1926 		return 0;
1927 	}
1928 
1929 	rc = avc_has_perm(sid, isec->sid, isec->sclass, av, &ad);
1930 	return rc;
1931 }
1932 
1933 static inline int may_rename(struct inode *old_dir,
1934 			     struct dentry *old_dentry,
1935 			     struct inode *new_dir,
1936 			     struct dentry *new_dentry)
1937 {
1938 	struct inode_security_struct *old_dsec, *new_dsec, *old_isec, *new_isec;
1939 	struct common_audit_data ad;
1940 	u32 sid = current_sid();
1941 	u32 av;
1942 	int old_is_dir, new_is_dir;
1943 	int rc;
1944 
1945 	old_dsec = inode_security(old_dir);
1946 	old_isec = backing_inode_security(old_dentry);
1947 	old_is_dir = d_is_dir(old_dentry);
1948 	new_dsec = inode_security(new_dir);
1949 
1950 	ad.type = LSM_AUDIT_DATA_DENTRY;
1951 
1952 	ad.u.dentry = old_dentry;
1953 	rc = avc_has_perm(sid, old_dsec->sid, SECCLASS_DIR,
1954 			  DIR__REMOVE_NAME | DIR__SEARCH, &ad);
1955 	if (rc)
1956 		return rc;
1957 	rc = avc_has_perm(sid, old_isec->sid,
1958 			  old_isec->sclass, FILE__RENAME, &ad);
1959 	if (rc)
1960 		return rc;
1961 	if (old_is_dir && new_dir != old_dir) {
1962 		rc = avc_has_perm(sid, old_isec->sid,
1963 				  old_isec->sclass, DIR__REPARENT, &ad);
1964 		if (rc)
1965 			return rc;
1966 	}
1967 
1968 	ad.u.dentry = new_dentry;
1969 	av = DIR__ADD_NAME | DIR__SEARCH;
1970 	if (d_is_positive(new_dentry))
1971 		av |= DIR__REMOVE_NAME;
1972 	rc = avc_has_perm(sid, new_dsec->sid, SECCLASS_DIR, av, &ad);
1973 	if (rc)
1974 		return rc;
1975 	if (d_is_positive(new_dentry)) {
1976 		new_isec = backing_inode_security(new_dentry);
1977 		new_is_dir = d_is_dir(new_dentry);
1978 		rc = avc_has_perm(sid, new_isec->sid,
1979 				  new_isec->sclass,
1980 				  (new_is_dir ? DIR__RMDIR : FILE__UNLINK), &ad);
1981 		if (rc)
1982 			return rc;
1983 	}
1984 
1985 	return 0;
1986 }
1987 
1988 /* Check whether a task can perform a filesystem operation. */
1989 static int superblock_has_perm(const struct cred *cred,
1990 			       const struct super_block *sb,
1991 			       u32 perms,
1992 			       struct common_audit_data *ad)
1993 {
1994 	struct superblock_security_struct *sbsec;
1995 	u32 sid = cred_sid(cred);
1996 
1997 	sbsec = selinux_superblock(sb);
1998 	return avc_has_perm(sid, sbsec->sid, SECCLASS_FILESYSTEM, perms, ad);
1999 }
2000 
2001 /* Convert a Linux mode and permission mask to an access vector. */
2002 static inline u32 file_mask_to_av(int mode, int mask)
2003 {
2004 	u32 av = 0;
2005 
2006 	if (!S_ISDIR(mode)) {
2007 		if (mask & MAY_EXEC)
2008 			av |= FILE__EXECUTE;
2009 		if (mask & MAY_READ)
2010 			av |= FILE__READ;
2011 
2012 		if (mask & MAY_APPEND)
2013 			av |= FILE__APPEND;
2014 		else if (mask & MAY_WRITE)
2015 			av |= FILE__WRITE;
2016 
2017 	} else {
2018 		if (mask & MAY_EXEC)
2019 			av |= DIR__SEARCH;
2020 		if (mask & MAY_WRITE)
2021 			av |= DIR__WRITE;
2022 		if (mask & MAY_READ)
2023 			av |= DIR__READ;
2024 	}
2025 
2026 	return av;
2027 }
2028 
2029 /* Convert a Linux file to an access vector. */
2030 static inline u32 file_to_av(const struct file *file)
2031 {
2032 	u32 av = 0;
2033 
2034 	if (file->f_mode & FMODE_READ)
2035 		av |= FILE__READ;
2036 	if (file->f_mode & FMODE_WRITE) {
2037 		if (file->f_flags & O_APPEND)
2038 			av |= FILE__APPEND;
2039 		else
2040 			av |= FILE__WRITE;
2041 	}
2042 	if (!av) {
2043 		/*
2044 		 * Special file opened with flags 3 for ioctl-only use.
2045 		 */
2046 		av = FILE__IOCTL;
2047 	}
2048 
2049 	return av;
2050 }
2051 
2052 /*
2053  * Convert a file to an access vector and include the correct
2054  * open permission.
2055  */
2056 static inline u32 open_file_to_av(struct file *file)
2057 {
2058 	u32 av = file_to_av(file);
2059 	struct inode *inode = file_inode(file);
2060 
2061 	if (selinux_policycap_openperm() &&
2062 	    inode->i_sb->s_magic != SOCKFS_MAGIC)
2063 		av |= FILE__OPEN;
2064 
2065 	return av;
2066 }
2067 
2068 /* Hook functions begin here. */
2069 
2070 static int selinux_binder_set_context_mgr(const struct cred *mgr)
2071 {
2072 	return avc_has_perm(current_sid(), cred_sid(mgr), SECCLASS_BINDER,
2073 			    BINDER__SET_CONTEXT_MGR, NULL);
2074 }
2075 
2076 static int selinux_binder_transaction(const struct cred *from,
2077 				      const struct cred *to)
2078 {
2079 	u32 mysid = current_sid();
2080 	u32 fromsid = cred_sid(from);
2081 	u32 tosid = cred_sid(to);
2082 	int rc;
2083 
2084 	if (mysid != fromsid) {
2085 		rc = avc_has_perm(mysid, fromsid, SECCLASS_BINDER,
2086 				  BINDER__IMPERSONATE, NULL);
2087 		if (rc)
2088 			return rc;
2089 	}
2090 
2091 	return avc_has_perm(fromsid, tosid,
2092 			    SECCLASS_BINDER, BINDER__CALL, NULL);
2093 }
2094 
2095 static int selinux_binder_transfer_binder(const struct cred *from,
2096 					  const struct cred *to)
2097 {
2098 	return avc_has_perm(cred_sid(from), cred_sid(to),
2099 			    SECCLASS_BINDER, BINDER__TRANSFER,
2100 			    NULL);
2101 }
2102 
2103 static int selinux_binder_transfer_file(const struct cred *from,
2104 					const struct cred *to,
2105 					const struct file *file)
2106 {
2107 	u32 sid = cred_sid(to);
2108 	struct file_security_struct *fsec = selinux_file(file);
2109 	struct dentry *dentry = file->f_path.dentry;
2110 	struct inode_security_struct *isec;
2111 	struct common_audit_data ad;
2112 	int rc;
2113 
2114 	ad.type = LSM_AUDIT_DATA_PATH;
2115 	ad.u.path = file->f_path;
2116 
2117 	if (sid != fsec->sid) {
2118 		rc = avc_has_perm(sid, fsec->sid,
2119 				  SECCLASS_FD,
2120 				  FD__USE,
2121 				  &ad);
2122 		if (rc)
2123 			return rc;
2124 	}
2125 
2126 #ifdef CONFIG_BPF_SYSCALL
2127 	rc = bpf_fd_pass(file, sid);
2128 	if (rc)
2129 		return rc;
2130 #endif
2131 
2132 	if (unlikely(IS_PRIVATE(d_backing_inode(dentry))))
2133 		return 0;
2134 
2135 	isec = backing_inode_security(dentry);
2136 	return avc_has_perm(sid, isec->sid, isec->sclass, file_to_av(file),
2137 			    &ad);
2138 }
2139 
2140 static int selinux_ptrace_access_check(struct task_struct *child,
2141 				       unsigned int mode)
2142 {
2143 	u32 sid = current_sid();
2144 	u32 csid = task_sid_obj(child);
2145 
2146 	if (mode & PTRACE_MODE_READ)
2147 		return avc_has_perm(sid, csid, SECCLASS_FILE, FILE__READ,
2148 				NULL);
2149 
2150 	return avc_has_perm(sid, csid, SECCLASS_PROCESS, PROCESS__PTRACE,
2151 			NULL);
2152 }
2153 
2154 static int selinux_ptrace_traceme(struct task_struct *parent)
2155 {
2156 	return avc_has_perm(task_sid_obj(parent), task_sid_obj(current),
2157 			    SECCLASS_PROCESS, PROCESS__PTRACE, NULL);
2158 }
2159 
2160 static int selinux_capget(const struct task_struct *target, kernel_cap_t *effective,
2161 			  kernel_cap_t *inheritable, kernel_cap_t *permitted)
2162 {
2163 	return avc_has_perm(current_sid(), task_sid_obj(target),
2164 			SECCLASS_PROCESS, PROCESS__GETCAP, NULL);
2165 }
2166 
2167 static int selinux_capset(struct cred *new, const struct cred *old,
2168 			  const kernel_cap_t *effective,
2169 			  const kernel_cap_t *inheritable,
2170 			  const kernel_cap_t *permitted)
2171 {
2172 	return avc_has_perm(cred_sid(old), cred_sid(new), SECCLASS_PROCESS,
2173 			    PROCESS__SETCAP, NULL);
2174 }
2175 
2176 /*
2177  * (This comment used to live with the selinux_task_setuid hook,
2178  * which was removed).
2179  *
2180  * Since setuid only affects the current process, and since the SELinux
2181  * controls are not based on the Linux identity attributes, SELinux does not
2182  * need to control this operation.  However, SELinux does control the use of
2183  * the CAP_SETUID and CAP_SETGID capabilities using the capable hook.
2184  */
2185 
2186 static int selinux_capable(const struct cred *cred, struct user_namespace *ns,
2187 			   int cap, unsigned int opts)
2188 {
2189 	return cred_has_capability(cred, cap, opts, ns == &init_user_ns);
2190 }
2191 
2192 static int selinux_quotactl(int cmds, int type, int id, const struct super_block *sb)
2193 {
2194 	const struct cred *cred = current_cred();
2195 	int rc = 0;
2196 
2197 	if (!sb)
2198 		return 0;
2199 
2200 	switch (cmds) {
2201 	case Q_SYNC:
2202 	case Q_QUOTAON:
2203 	case Q_QUOTAOFF:
2204 	case Q_SETINFO:
2205 	case Q_SETQUOTA:
2206 	case Q_XQUOTAOFF:
2207 	case Q_XQUOTAON:
2208 	case Q_XSETQLIM:
2209 		rc = superblock_has_perm(cred, sb, FILESYSTEM__QUOTAMOD, NULL);
2210 		break;
2211 	case Q_GETFMT:
2212 	case Q_GETINFO:
2213 	case Q_GETQUOTA:
2214 	case Q_XGETQUOTA:
2215 	case Q_XGETQSTAT:
2216 	case Q_XGETQSTATV:
2217 	case Q_XGETNEXTQUOTA:
2218 		rc = superblock_has_perm(cred, sb, FILESYSTEM__QUOTAGET, NULL);
2219 		break;
2220 	default:
2221 		rc = 0;  /* let the kernel handle invalid cmds */
2222 		break;
2223 	}
2224 	return rc;
2225 }
2226 
2227 static int selinux_quota_on(struct dentry *dentry)
2228 {
2229 	const struct cred *cred = current_cred();
2230 
2231 	return dentry_has_perm(cred, dentry, FILE__QUOTAON);
2232 }
2233 
2234 static int selinux_syslog(int type)
2235 {
2236 	switch (type) {
2237 	case SYSLOG_ACTION_READ_ALL:	/* Read last kernel messages */
2238 	case SYSLOG_ACTION_SIZE_BUFFER:	/* Return size of the log buffer */
2239 		return avc_has_perm(current_sid(), SECINITSID_KERNEL,
2240 				    SECCLASS_SYSTEM, SYSTEM__SYSLOG_READ, NULL);
2241 	case SYSLOG_ACTION_CONSOLE_OFF:	/* Disable logging to console */
2242 	case SYSLOG_ACTION_CONSOLE_ON:	/* Enable logging to console */
2243 	/* Set level of messages printed to console */
2244 	case SYSLOG_ACTION_CONSOLE_LEVEL:
2245 		return avc_has_perm(current_sid(), SECINITSID_KERNEL,
2246 				    SECCLASS_SYSTEM, SYSTEM__SYSLOG_CONSOLE,
2247 				    NULL);
2248 	}
2249 	/* All other syslog types */
2250 	return avc_has_perm(current_sid(), SECINITSID_KERNEL,
2251 			    SECCLASS_SYSTEM, SYSTEM__SYSLOG_MOD, NULL);
2252 }
2253 
2254 /*
2255  * Check permission for allocating a new virtual mapping. Returns
2256  * 0 if permission is granted, negative error code if not.
2257  *
2258  * Do not audit the selinux permission check, as this is applied to all
2259  * processes that allocate mappings.
2260  */
2261 static int selinux_vm_enough_memory(struct mm_struct *mm, long pages)
2262 {
2263 	return cred_has_capability(current_cred(), CAP_SYS_ADMIN,
2264 				   CAP_OPT_NOAUDIT, true);
2265 }
2266 
2267 /* binprm security operations */
2268 
2269 static u32 ptrace_parent_sid(void)
2270 {
2271 	u32 sid = 0;
2272 	struct task_struct *tracer;
2273 
2274 	rcu_read_lock();
2275 	tracer = ptrace_parent(current);
2276 	if (tracer)
2277 		sid = task_sid_obj(tracer);
2278 	rcu_read_unlock();
2279 
2280 	return sid;
2281 }
2282 
2283 static int check_nnp_nosuid(const struct linux_binprm *bprm,
2284 			    const struct cred_security_struct *old_crsec,
2285 			    const struct cred_security_struct *new_crsec)
2286 {
2287 	int nnp = (bprm->unsafe & LSM_UNSAFE_NO_NEW_PRIVS);
2288 	int nosuid = !mnt_may_suid(bprm->file->f_path.mnt);
2289 	int rc;
2290 	u32 av;
2291 
2292 	if (!nnp && !nosuid)
2293 		return 0; /* neither NNP nor nosuid */
2294 
2295 	if (new_crsec->sid == old_crsec->sid)
2296 		return 0; /* No change in credentials */
2297 
2298 	/*
2299 	 * If the policy enables the nnp_nosuid_transition policy capability,
2300 	 * then we permit transitions under NNP or nosuid if the
2301 	 * policy allows the corresponding permission between
2302 	 * the old and new contexts.
2303 	 */
2304 	if (selinux_policycap_nnp_nosuid_transition()) {
2305 		av = 0;
2306 		if (nnp)
2307 			av |= PROCESS2__NNP_TRANSITION;
2308 		if (nosuid)
2309 			av |= PROCESS2__NOSUID_TRANSITION;
2310 		rc = avc_has_perm(old_crsec->sid, new_crsec->sid,
2311 				  SECCLASS_PROCESS2, av, NULL);
2312 		if (!rc)
2313 			return 0;
2314 	}
2315 
2316 	/*
2317 	 * We also permit NNP or nosuid transitions to bounded SIDs,
2318 	 * i.e. SIDs that are guaranteed to only be allowed a subset
2319 	 * of the permissions of the current SID.
2320 	 */
2321 	rc = security_bounded_transition(old_crsec->sid,
2322 					 new_crsec->sid);
2323 	if (!rc)
2324 		return 0;
2325 
2326 	/*
2327 	 * On failure, preserve the errno values for NNP vs nosuid.
2328 	 * NNP:  Operation not permitted for caller.
2329 	 * nosuid:  Permission denied to file.
2330 	 */
2331 	if (nnp)
2332 		return -EPERM;
2333 	return -EACCES;
2334 }
2335 
2336 static int selinux_bprm_creds_for_exec(struct linux_binprm *bprm)
2337 {
2338 	const struct cred_security_struct *old_crsec;
2339 	struct cred_security_struct *new_crsec;
2340 	struct inode_security_struct *isec;
2341 	struct common_audit_data ad;
2342 	struct inode *inode = file_inode(bprm->file);
2343 	int rc;
2344 
2345 	/* SELinux context only depends on initial program or script and not
2346 	 * the script interpreter */
2347 
2348 	old_crsec = selinux_cred(current_cred());
2349 	new_crsec = selinux_cred(bprm->cred);
2350 	isec = inode_security(inode);
2351 
2352 	if (WARN_ON(isec->sclass != SECCLASS_FILE &&
2353 		    isec->sclass != SECCLASS_MEMFD_FILE))
2354 		return -EACCES;
2355 
2356 	/* Default to the current task SID. */
2357 	new_crsec->sid = old_crsec->sid;
2358 	new_crsec->osid = old_crsec->sid;
2359 
2360 	/* Reset fs, key, and sock SIDs on execve. */
2361 	new_crsec->create_sid = 0;
2362 	new_crsec->keycreate_sid = 0;
2363 	new_crsec->sockcreate_sid = 0;
2364 
2365 	/*
2366 	 * Before policy is loaded, label any task outside kernel space
2367 	 * as SECINITSID_INIT, so that any userspace tasks surviving from
2368 	 * early boot end up with a label different from SECINITSID_KERNEL
2369 	 * (if the policy chooses to set SECINITSID_INIT != SECINITSID_KERNEL).
2370 	 */
2371 	if (!selinux_initialized()) {
2372 		new_crsec->sid = SECINITSID_INIT;
2373 		/* also clear the exec_sid just in case */
2374 		new_crsec->exec_sid = 0;
2375 		return 0;
2376 	}
2377 
2378 	if (old_crsec->exec_sid) {
2379 		new_crsec->sid = old_crsec->exec_sid;
2380 		/* Reset exec SID on execve. */
2381 		new_crsec->exec_sid = 0;
2382 
2383 		/* Fail on NNP or nosuid if not an allowed transition. */
2384 		rc = check_nnp_nosuid(bprm, old_crsec, new_crsec);
2385 		if (rc)
2386 			return rc;
2387 	} else {
2388 		/* Check for a default transition on this program. */
2389 		rc = security_transition_sid(old_crsec->sid,
2390 					     isec->sid, SECCLASS_PROCESS, NULL,
2391 					     &new_crsec->sid);
2392 		if (rc)
2393 			return rc;
2394 
2395 		/*
2396 		 * Fallback to old SID on NNP or nosuid if not an allowed
2397 		 * transition.
2398 		 */
2399 		rc = check_nnp_nosuid(bprm, old_crsec, new_crsec);
2400 		if (rc)
2401 			new_crsec->sid = old_crsec->sid;
2402 	}
2403 
2404 	ad.type = LSM_AUDIT_DATA_FILE;
2405 	ad.u.file = bprm->file;
2406 
2407 	if (new_crsec->sid == old_crsec->sid) {
2408 		rc = avc_has_perm(old_crsec->sid, isec->sid, isec->sclass,
2409 				  FILE__EXECUTE_NO_TRANS, &ad);
2410 		if (rc)
2411 			return rc;
2412 	} else {
2413 		/* Check permissions for the transition. */
2414 		rc = avc_has_perm(old_crsec->sid, new_crsec->sid,
2415 				  SECCLASS_PROCESS, PROCESS__TRANSITION, &ad);
2416 		if (rc)
2417 			return rc;
2418 
2419 		rc = avc_has_perm(new_crsec->sid, isec->sid, isec->sclass,
2420 				  FILE__ENTRYPOINT, &ad);
2421 		if (rc)
2422 			return rc;
2423 
2424 		/* Check for shared state */
2425 		if (bprm->unsafe & LSM_UNSAFE_SHARE) {
2426 			rc = avc_has_perm(old_crsec->sid, new_crsec->sid,
2427 					  SECCLASS_PROCESS, PROCESS__SHARE,
2428 					  NULL);
2429 			if (rc)
2430 				return -EPERM;
2431 		}
2432 
2433 		/* Make sure that anyone attempting to ptrace over a task that
2434 		 * changes its SID has the appropriate permit */
2435 		if (bprm->unsafe & LSM_UNSAFE_PTRACE) {
2436 			u32 ptsid = ptrace_parent_sid();
2437 			if (ptsid != 0) {
2438 				rc = avc_has_perm(ptsid, new_crsec->sid,
2439 						  SECCLASS_PROCESS,
2440 						  PROCESS__PTRACE, NULL);
2441 				if (rc)
2442 					return -EPERM;
2443 			}
2444 		}
2445 
2446 		/* Clear any possibly unsafe personality bits on exec: */
2447 		bprm->per_clear |= PER_CLEAR_ON_SETID;
2448 
2449 		/* Enable secure mode for SIDs transitions unless
2450 		   the noatsecure permission is granted between
2451 		   the two SIDs, i.e. ahp returns 0. */
2452 		rc = avc_has_perm(old_crsec->sid, new_crsec->sid,
2453 				  SECCLASS_PROCESS, PROCESS__NOATSECURE,
2454 				  NULL);
2455 		bprm->secureexec |= !!rc;
2456 	}
2457 
2458 	return 0;
2459 }
2460 
2461 static int match_file(const void *p, struct file *file, unsigned fd)
2462 {
2463 	return file_has_perm(p, file, file_to_av(file)) ? fd + 1 : 0;
2464 }
2465 
2466 /* Derived from fs/exec.c:flush_old_files. */
2467 static inline void flush_unauthorized_files(const struct cred *cred,
2468 					    struct files_struct *files)
2469 {
2470 	struct file *file, *devnull = NULL;
2471 	struct tty_struct *tty;
2472 	int drop_tty = 0;
2473 	unsigned n;
2474 
2475 	tty = get_current_tty();
2476 	if (tty) {
2477 		spin_lock(&tty->files_lock);
2478 		if (!list_empty(&tty->tty_files)) {
2479 			struct tty_file_private *file_priv;
2480 
2481 			/* Revalidate access to controlling tty.
2482 			   Use file_path_has_perm on the tty path directly
2483 			   rather than using file_has_perm, as this particular
2484 			   open file may belong to another process and we are
2485 			   only interested in the inode-based check here. */
2486 			file_priv = list_first_entry(&tty->tty_files,
2487 						struct tty_file_private, list);
2488 			file = file_priv->file;
2489 			if (file_path_has_perm(cred, file, FILE__READ | FILE__WRITE))
2490 				drop_tty = 1;
2491 		}
2492 		spin_unlock(&tty->files_lock);
2493 		tty_kref_put(tty);
2494 	}
2495 	/* Reset controlling tty. */
2496 	if (drop_tty)
2497 		no_tty();
2498 
2499 	/* Revalidate access to inherited open files. */
2500 	n = iterate_fd(files, 0, match_file, cred);
2501 	if (!n) /* none found? */
2502 		return;
2503 
2504 	devnull = dentry_open(&selinux_null, O_RDWR, cred);
2505 	if (IS_ERR(devnull))
2506 		devnull = NULL;
2507 	/* replace all the matching ones with this */
2508 	do {
2509 		replace_fd(n - 1, devnull, 0);
2510 	} while ((n = iterate_fd(files, n, match_file, cred)) != 0);
2511 	if (devnull)
2512 		fput(devnull);
2513 }
2514 
2515 /*
2516  * Prepare a process for imminent new credential changes due to exec
2517  */
2518 static void selinux_bprm_committing_creds(const struct linux_binprm *bprm)
2519 {
2520 	struct cred_security_struct *new_crsec;
2521 	struct rlimit *rlim, *initrlim;
2522 	int rc, i;
2523 
2524 	new_crsec = selinux_cred(bprm->cred);
2525 	if (new_crsec->sid == new_crsec->osid)
2526 		return;
2527 
2528 	/* Close files for which the new task SID is not authorized. */
2529 	flush_unauthorized_files(bprm->cred, current->files);
2530 
2531 	/* Always clear parent death signal on SID transitions. */
2532 	current->pdeath_signal = 0;
2533 
2534 	/* Check whether the new SID can inherit resource limits from the old
2535 	 * SID.  If not, reset all soft limits to the lower of the current
2536 	 * task's hard limit and the init task's soft limit.
2537 	 *
2538 	 * Note that the setting of hard limits (even to lower them) can be
2539 	 * controlled by the setrlimit check.  The inclusion of the init task's
2540 	 * soft limit into the computation is to avoid resetting soft limits
2541 	 * higher than the default soft limit for cases where the default is
2542 	 * lower than the hard limit, e.g. RLIMIT_CORE or RLIMIT_STACK.
2543 	 */
2544 	rc = avc_has_perm(new_crsec->osid, new_crsec->sid, SECCLASS_PROCESS,
2545 			  PROCESS__RLIMITINH, NULL);
2546 	if (rc) {
2547 		/* protect against do_prlimit() */
2548 		task_lock(current);
2549 		for (i = 0; i < RLIM_NLIMITS; i++) {
2550 			rlim = current->signal->rlim + i;
2551 			initrlim = init_task.signal->rlim + i;
2552 			rlim->rlim_cur = min(rlim->rlim_max, initrlim->rlim_cur);
2553 		}
2554 		task_unlock(current);
2555 		if (IS_ENABLED(CONFIG_POSIX_TIMERS))
2556 			update_rlimit_cpu(current, rlimit(RLIMIT_CPU));
2557 	}
2558 }
2559 
2560 /*
2561  * Clean up the process immediately after the installation of new credentials
2562  * due to exec
2563  */
2564 static void selinux_bprm_committed_creds(const struct linux_binprm *bprm)
2565 {
2566 	const struct cred_security_struct *crsec = selinux_cred(current_cred());
2567 	u32 osid, sid;
2568 	int rc;
2569 
2570 	osid = crsec->osid;
2571 	sid = crsec->sid;
2572 
2573 	if (sid == osid)
2574 		return;
2575 
2576 	/* Check whether the new SID can inherit signal state from the old SID.
2577 	 * If not, clear itimers to avoid subsequent signal generation and
2578 	 * flush and unblock signals.
2579 	 *
2580 	 * This must occur _after_ the task SID has been updated so that any
2581 	 * kill done after the flush will be checked against the new SID.
2582 	 */
2583 	rc = avc_has_perm(osid, sid, SECCLASS_PROCESS, PROCESS__SIGINH, NULL);
2584 	if (rc) {
2585 		clear_itimer();
2586 
2587 		spin_lock_irq(&unrcu_pointer(current->sighand)->siglock);
2588 		if (!fatal_signal_pending(current)) {
2589 			flush_sigqueue(&current->pending);
2590 			flush_sigqueue(&current->signal->shared_pending);
2591 			flush_signal_handlers(current, 1);
2592 			sigemptyset(&current->blocked);
2593 			recalc_sigpending();
2594 		}
2595 		spin_unlock_irq(&unrcu_pointer(current->sighand)->siglock);
2596 	}
2597 
2598 	/* Wake up the parent if it is waiting so that it can recheck
2599 	 * wait permission to the new task SID. */
2600 	read_lock(&tasklist_lock);
2601 	__wake_up_parent(current, unrcu_pointer(current->real_parent));
2602 	read_unlock(&tasklist_lock);
2603 }
2604 
2605 /* superblock security operations */
2606 
2607 static int selinux_sb_alloc_security(struct super_block *sb)
2608 {
2609 	struct superblock_security_struct *sbsec = selinux_superblock(sb);
2610 
2611 	mutex_init(&sbsec->lock);
2612 	INIT_LIST_HEAD(&sbsec->isec_head);
2613 	spin_lock_init(&sbsec->isec_lock);
2614 	sbsec->sid = SECINITSID_UNLABELED;
2615 	sbsec->def_sid = SECINITSID_FILE;
2616 	sbsec->mntpoint_sid = SECINITSID_UNLABELED;
2617 	sbsec->creator_sid = SECINITSID_UNLABELED;
2618 
2619 	return 0;
2620 }
2621 
2622 static inline int opt_len(const char *s)
2623 {
2624 	bool open_quote = false;
2625 	int len;
2626 	char c;
2627 
2628 	for (len = 0; (c = s[len]) != '\0'; len++) {
2629 		if (c == '"')
2630 			open_quote = !open_quote;
2631 		if (c == ',' && !open_quote)
2632 			break;
2633 	}
2634 	return len;
2635 }
2636 
2637 static int selinux_sb_eat_lsm_opts(char *options, void **mnt_opts)
2638 {
2639 	char *from = options;
2640 	char *to = options;
2641 	bool first = true;
2642 	int rc;
2643 
2644 	while (1) {
2645 		int len = opt_len(from);
2646 		int token;
2647 		char *arg = NULL;
2648 
2649 		token = match_opt_prefix(from, len, &arg);
2650 
2651 		if (token != Opt_error) {
2652 			char *p, *q;
2653 
2654 			/* strip quotes */
2655 			if (arg) {
2656 				for (p = q = arg; p < from + len; p++) {
2657 					char c = *p;
2658 					if (c != '"')
2659 						*q++ = c;
2660 				}
2661 				arg = kmemdup_nul(arg, q - arg, GFP_KERNEL);
2662 				if (!arg) {
2663 					rc = -ENOMEM;
2664 					goto free_opt;
2665 				}
2666 			}
2667 			rc = selinux_add_opt(token, arg, mnt_opts);
2668 			kfree(arg);
2669 			arg = NULL;
2670 			if (unlikely(rc)) {
2671 				goto free_opt;
2672 			}
2673 		} else {
2674 			if (!first) {	// copy with preceding comma
2675 				from--;
2676 				len++;
2677 			}
2678 			if (to != from)
2679 				memmove(to, from, len);
2680 			to += len;
2681 			first = false;
2682 		}
2683 		if (!from[len])
2684 			break;
2685 		from += len + 1;
2686 	}
2687 	*to = '\0';
2688 	return 0;
2689 
2690 free_opt:
2691 	if (*mnt_opts) {
2692 		selinux_free_mnt_opts(*mnt_opts);
2693 		*mnt_opts = NULL;
2694 	}
2695 	return rc;
2696 }
2697 
2698 static int selinux_sb_mnt_opts_compat(struct super_block *sb, void *mnt_opts)
2699 {
2700 	struct selinux_mnt_opts *opts = mnt_opts;
2701 	struct superblock_security_struct *sbsec = selinux_superblock(sb);
2702 
2703 	/*
2704 	 * Superblock not initialized (i.e. no options) - reject if any
2705 	 * options specified, otherwise accept.
2706 	 */
2707 	if (!(sbsec->flags & SE_SBINITIALIZED))
2708 		return opts ? 1 : 0;
2709 
2710 	/*
2711 	 * Superblock initialized and no options specified - reject if
2712 	 * superblock has any options set, otherwise accept.
2713 	 */
2714 	if (!opts)
2715 		return (sbsec->flags & SE_MNTMASK) ? 1 : 0;
2716 
2717 	if (opts->fscontext_sid) {
2718 		if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid,
2719 			       opts->fscontext_sid))
2720 			return 1;
2721 	}
2722 	if (opts->context_sid) {
2723 		if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid,
2724 			       opts->context_sid))
2725 			return 1;
2726 	}
2727 	if (opts->rootcontext_sid) {
2728 		struct inode_security_struct *root_isec;
2729 
2730 		root_isec = backing_inode_security(sb->s_root);
2731 		if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid,
2732 			       opts->rootcontext_sid))
2733 			return 1;
2734 	}
2735 	if (opts->defcontext_sid) {
2736 		if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid,
2737 			       opts->defcontext_sid))
2738 			return 1;
2739 	}
2740 	return 0;
2741 }
2742 
2743 static int selinux_sb_remount(struct super_block *sb, void *mnt_opts)
2744 {
2745 	struct selinux_mnt_opts *opts = mnt_opts;
2746 	struct superblock_security_struct *sbsec = selinux_superblock(sb);
2747 
2748 	if (!(sbsec->flags & SE_SBINITIALIZED))
2749 		return 0;
2750 
2751 	if (!opts)
2752 		return 0;
2753 
2754 	if (opts->fscontext_sid) {
2755 		if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid,
2756 			       opts->fscontext_sid))
2757 			goto out_bad_option;
2758 	}
2759 	if (opts->context_sid) {
2760 		if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid,
2761 			       opts->context_sid))
2762 			goto out_bad_option;
2763 	}
2764 	if (opts->rootcontext_sid) {
2765 		struct inode_security_struct *root_isec;
2766 		root_isec = backing_inode_security(sb->s_root);
2767 		if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid,
2768 			       opts->rootcontext_sid))
2769 			goto out_bad_option;
2770 	}
2771 	if (opts->defcontext_sid) {
2772 		if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid,
2773 			       opts->defcontext_sid))
2774 			goto out_bad_option;
2775 	}
2776 	return 0;
2777 
2778 out_bad_option:
2779 	pr_warn("SELinux: unable to change security options "
2780 	       "during remount (dev %s, type=%s)\n", sb->s_id,
2781 	       sb->s_type->name);
2782 	return -EINVAL;
2783 }
2784 
2785 static int selinux_sb_kern_mount(const struct super_block *sb)
2786 {
2787 	const struct cred *cred = current_cred();
2788 	struct common_audit_data ad;
2789 
2790 	ad.type = LSM_AUDIT_DATA_DENTRY;
2791 	ad.u.dentry = sb->s_root;
2792 	return superblock_has_perm(cred, sb, FILESYSTEM__MOUNT, &ad);
2793 }
2794 
2795 static int selinux_sb_statfs(struct dentry *dentry)
2796 {
2797 	const struct cred *cred = current_cred();
2798 	struct common_audit_data ad;
2799 
2800 	ad.type = LSM_AUDIT_DATA_DENTRY;
2801 	ad.u.dentry = dentry->d_sb->s_root;
2802 	return superblock_has_perm(cred, dentry->d_sb, FILESYSTEM__GETATTR, &ad);
2803 }
2804 
2805 static int selinux_mount(const char *dev_name,
2806 			 const struct path *path,
2807 			 const char *type,
2808 			 unsigned long flags,
2809 			 void *data)
2810 {
2811 	const struct cred *cred = current_cred();
2812 
2813 	if (flags & MS_REMOUNT)
2814 		return superblock_has_perm(cred, path->dentry->d_sb,
2815 					   FILESYSTEM__REMOUNT, NULL);
2816 	else
2817 		return path_has_perm(cred, path, FILE__MOUNTON);
2818 }
2819 
2820 static int selinux_move_mount(const struct path *from_path,
2821 			      const struct path *to_path)
2822 {
2823 	const struct cred *cred = current_cred();
2824 
2825 	return path_has_perm(cred, to_path, FILE__MOUNTON);
2826 }
2827 
2828 static int selinux_umount(struct vfsmount *mnt, int flags)
2829 {
2830 	const struct cred *cred = current_cred();
2831 
2832 	return superblock_has_perm(cred, mnt->mnt_sb,
2833 				   FILESYSTEM__UNMOUNT, NULL);
2834 }
2835 
2836 static int selinux_fs_context_submount(struct fs_context *fc,
2837 				   struct super_block *reference)
2838 {
2839 	const struct superblock_security_struct *sbsec = selinux_superblock(reference);
2840 	struct selinux_mnt_opts *opts;
2841 
2842 	/*
2843 	 * Ensure that fc->security remains NULL when no options are set
2844 	 * as expected by selinux_set_mnt_opts().
2845 	 */
2846 	if (!(sbsec->flags & (FSCONTEXT_MNT|CONTEXT_MNT|DEFCONTEXT_MNT)))
2847 		return 0;
2848 
2849 	opts = kzalloc_obj(*opts);
2850 	if (!opts)
2851 		return -ENOMEM;
2852 
2853 	if (sbsec->flags & FSCONTEXT_MNT)
2854 		opts->fscontext_sid = sbsec->sid;
2855 	if (sbsec->flags & CONTEXT_MNT)
2856 		opts->context_sid = sbsec->mntpoint_sid;
2857 	if (sbsec->flags & DEFCONTEXT_MNT)
2858 		opts->defcontext_sid = sbsec->def_sid;
2859 	fc->security = opts;
2860 	return 0;
2861 }
2862 
2863 static int selinux_fs_context_dup(struct fs_context *fc,
2864 				  struct fs_context *src_fc)
2865 {
2866 	const struct selinux_mnt_opts *src = src_fc->security;
2867 
2868 	if (!src)
2869 		return 0;
2870 
2871 	fc->security = kmemdup(src, sizeof(*src), GFP_KERNEL);
2872 	return fc->security ? 0 : -ENOMEM;
2873 }
2874 
2875 static const struct fs_parameter_spec selinux_fs_parameters[] = {
2876 	fsparam_string(CONTEXT_STR,	Opt_context),
2877 	fsparam_string(DEFCONTEXT_STR,	Opt_defcontext),
2878 	fsparam_string(FSCONTEXT_STR,	Opt_fscontext),
2879 	fsparam_string(ROOTCONTEXT_STR,	Opt_rootcontext),
2880 	fsparam_flag  (SECLABEL_STR,	Opt_seclabel),
2881 	{}
2882 };
2883 
2884 static int selinux_fs_context_parse_param(struct fs_context *fc,
2885 					  struct fs_parameter *param)
2886 {
2887 	struct fs_parse_result result;
2888 	int opt;
2889 
2890 	opt = fs_parse(fc, selinux_fs_parameters, param, &result);
2891 	if (opt < 0)
2892 		return opt;
2893 
2894 	return selinux_add_opt(opt, param->string, &fc->security);
2895 }
2896 
2897 /* inode security operations */
2898 
2899 static int selinux_inode_alloc_security(struct inode *inode)
2900 {
2901 	struct inode_security_struct *isec = selinux_inode(inode);
2902 	u32 sid = current_sid();
2903 
2904 	spin_lock_init(&isec->lock);
2905 	INIT_LIST_HEAD(&isec->list);
2906 	isec->inode = inode;
2907 	isec->sid = SECINITSID_UNLABELED;
2908 	isec->sclass = SECCLASS_FILE;
2909 	isec->task_sid = sid;
2910 	isec->initialized = LABEL_INVALID;
2911 
2912 	return 0;
2913 }
2914 
2915 static void selinux_inode_free_security(struct inode *inode)
2916 {
2917 	inode_free_security(inode);
2918 }
2919 
2920 static int selinux_dentry_init_security(struct dentry *dentry, int mode,
2921 					const struct qstr *name,
2922 					const char **xattr_name,
2923 					struct lsm_context *cp)
2924 {
2925 	u32 newsid;
2926 	int rc;
2927 
2928 	rc = selinux_determine_inode_label(selinux_cred(current_cred()),
2929 					   d_inode(dentry->d_parent), name,
2930 					   inode_mode_to_security_class(mode),
2931 					   &newsid);
2932 	if (rc)
2933 		return rc;
2934 
2935 	if (xattr_name)
2936 		*xattr_name = XATTR_NAME_SELINUX;
2937 
2938 	cp->id = LSM_ID_SELINUX;
2939 	return security_sid_to_context(newsid, &cp->context, &cp->len);
2940 }
2941 
2942 static int selinux_dentry_create_files_as(struct dentry *dentry, int mode,
2943 					  const struct qstr *name,
2944 					  const struct cred *old,
2945 					  struct cred *new)
2946 {
2947 	u32 newsid;
2948 	int rc;
2949 	struct cred_security_struct *crsec;
2950 
2951 	rc = selinux_determine_inode_label(selinux_cred(old),
2952 					   d_inode(dentry->d_parent), name,
2953 					   inode_mode_to_security_class(mode),
2954 					   &newsid);
2955 	if (rc)
2956 		return rc;
2957 
2958 	crsec = selinux_cred(new);
2959 	crsec->create_sid = newsid;
2960 	return 0;
2961 }
2962 
2963 static int selinux_inode_init_security(struct inode *inode, struct inode *dir,
2964 				       const struct qstr *qstr,
2965 				       struct xattr *xattrs, int *xattr_count)
2966 {
2967 	const struct cred_security_struct *crsec = selinux_cred(current_cred());
2968 	struct superblock_security_struct *sbsec;
2969 	struct xattr *xattr;
2970 	u32 newsid, clen;
2971 	u16 newsclass;
2972 	int rc;
2973 	char *context;
2974 
2975 	sbsec = selinux_superblock(dir->i_sb);
2976 
2977 	newsid = crsec->create_sid;
2978 	newsclass = inode_mode_to_security_class(inode->i_mode);
2979 	rc = selinux_determine_inode_label(crsec, dir, qstr, newsclass, &newsid);
2980 	if (rc)
2981 		return rc;
2982 
2983 	/* Possibly defer initialization to selinux_complete_init. */
2984 	if (sbsec->flags & SE_SBINITIALIZED) {
2985 		struct inode_security_struct *isec = selinux_inode(inode);
2986 		isec->sclass = newsclass;
2987 		isec->sid = newsid;
2988 		isec->initialized = LABEL_INITIALIZED;
2989 	}
2990 
2991 	if (!selinux_initialized() ||
2992 	    !(sbsec->flags & SBLABEL_MNT))
2993 		return -EOPNOTSUPP;
2994 
2995 	xattr = lsm_get_xattr_slot(xattrs, xattr_count);
2996 	if (xattr) {
2997 		rc = security_sid_to_context_force(newsid,
2998 						   &context, &clen);
2999 		if (rc)
3000 			return rc;
3001 		xattr->value = context;
3002 		xattr->value_len = clen;
3003 		xattr->name = XATTR_SELINUX_SUFFIX;
3004 	}
3005 
3006 	return 0;
3007 }
3008 
3009 static int selinux_inode_init_security_anon(struct inode *inode,
3010 					    const struct qstr *name,
3011 					    const struct inode *context_inode)
3012 {
3013 	u32 sid = current_sid();
3014 	struct common_audit_data ad;
3015 	struct inode_security_struct *isec;
3016 	int rc;
3017 	bool is_memfd = false;
3018 
3019 	if (unlikely(!selinux_initialized()))
3020 		return 0;
3021 
3022 	if (name != NULL && name->name != NULL &&
3023 	    !strcmp(name->name, MEMFD_ANON_NAME)) {
3024 		if (!selinux_policycap_memfd_class())
3025 			return 0;
3026 		is_memfd = true;
3027 	}
3028 
3029 	isec = selinux_inode(inode);
3030 
3031 	/*
3032 	 * We only get here once per ephemeral inode.  The inode has
3033 	 * been initialized via inode_alloc_security but is otherwise
3034 	 * untouched.
3035 	 */
3036 
3037 	if (context_inode) {
3038 		struct inode_security_struct *context_isec =
3039 			selinux_inode(context_inode);
3040 		if (context_isec->initialized != LABEL_INITIALIZED) {
3041 			pr_err("SELinux:  context_inode is not initialized\n");
3042 			return -EACCES;
3043 		}
3044 
3045 		isec->sclass = context_isec->sclass;
3046 		isec->sid = context_isec->sid;
3047 	} else {
3048 		if (is_memfd)
3049 			isec->sclass = SECCLASS_MEMFD_FILE;
3050 		else
3051 			isec->sclass = SECCLASS_ANON_INODE;
3052 		rc = security_transition_sid(
3053 			sid, sid,
3054 			isec->sclass, name, &isec->sid);
3055 		if (rc)
3056 			return rc;
3057 	}
3058 
3059 	isec->initialized = LABEL_INITIALIZED;
3060 	/*
3061 	 * Now that we've initialized security, check whether we're
3062 	 * allowed to actually create this type of anonymous inode.
3063 	 */
3064 
3065 	ad.type = LSM_AUDIT_DATA_ANONINODE;
3066 	ad.u.anonclass = name ? (const char *)name->name : "?";
3067 
3068 	return avc_has_perm(sid,
3069 			    isec->sid,
3070 			    isec->sclass,
3071 			    FILE__CREATE,
3072 			    &ad);
3073 }
3074 
3075 static int selinux_inode_create(struct inode *dir, struct dentry *dentry, umode_t mode)
3076 {
3077 	return may_create(dir, dentry, SECCLASS_FILE);
3078 }
3079 
3080 static int selinux_inode_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry)
3081 {
3082 	return may_link(dir, old_dentry, MAY_LINK);
3083 }
3084 
3085 static int selinux_inode_unlink(struct inode *dir, struct dentry *dentry)
3086 {
3087 	return may_link(dir, dentry, MAY_UNLINK);
3088 }
3089 
3090 static int selinux_inode_symlink(struct inode *dir, struct dentry *dentry, const char *name)
3091 {
3092 	return may_create(dir, dentry, SECCLASS_LNK_FILE);
3093 }
3094 
3095 static int selinux_inode_mkdir(struct inode *dir, struct dentry *dentry, umode_t mask)
3096 {
3097 	return may_create(dir, dentry, SECCLASS_DIR);
3098 }
3099 
3100 static int selinux_inode_rmdir(struct inode *dir, struct dentry *dentry)
3101 {
3102 	return may_link(dir, dentry, MAY_RMDIR);
3103 }
3104 
3105 static int selinux_inode_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
3106 {
3107 	return may_create(dir, dentry, inode_mode_to_security_class(mode));
3108 }
3109 
3110 static int selinux_inode_rename(struct inode *old_inode, struct dentry *old_dentry,
3111 				struct inode *new_inode, struct dentry *new_dentry)
3112 {
3113 	return may_rename(old_inode, old_dentry, new_inode, new_dentry);
3114 }
3115 
3116 static int selinux_inode_readlink(struct dentry *dentry)
3117 {
3118 	const struct cred *cred = current_cred();
3119 
3120 	return dentry_has_perm(cred, dentry, FILE__READ);
3121 }
3122 
3123 static int selinux_inode_follow_link(struct dentry *dentry, struct inode *inode,
3124 				     bool rcu)
3125 {
3126 	struct common_audit_data ad;
3127 	struct inode_security_struct *isec;
3128 	u32 sid = current_sid();
3129 
3130 	ad.type = LSM_AUDIT_DATA_DENTRY;
3131 	ad.u.dentry = dentry;
3132 	isec = inode_security_rcu(inode, rcu);
3133 	if (IS_ERR(isec))
3134 		return PTR_ERR(isec);
3135 
3136 	return avc_has_perm(sid, isec->sid, isec->sclass, FILE__READ, &ad);
3137 }
3138 
3139 static noinline int audit_inode_permission(struct inode *inode,
3140 					   u32 perms, u32 audited, u32 denied,
3141 					   int result)
3142 {
3143 	struct common_audit_data ad;
3144 	struct inode_security_struct *isec = selinux_inode(inode);
3145 
3146 	ad.type = LSM_AUDIT_DATA_INODE;
3147 	ad.u.inode = inode;
3148 
3149 	return slow_avc_audit(current_sid(), isec->sid, isec->sclass, perms,
3150 			    audited, denied, result, &ad);
3151 }
3152 
3153 /**
3154  * task_avdcache_reset - Reset the task's AVD cache
3155  * @tsec: the task's security state
3156  *
3157  * Clear the task's AVD cache in @tsec and reset it to the current policy's
3158  * and task's info.
3159  */
3160 static inline void task_avdcache_reset(struct task_security_struct *tsec)
3161 {
3162 	memset(&tsec->avdcache.dir, 0, sizeof(tsec->avdcache.dir));
3163 	tsec->avdcache.sid = current_sid();
3164 	tsec->avdcache.seqno = avc_policy_seqno();
3165 	tsec->avdcache.dir_spot = TSEC_AVDC_DIR_SIZE - 1;
3166 }
3167 
3168 /**
3169  * task_avdcache_search - Search the task's AVD cache
3170  * @tsec: the task's security state
3171  * @isec: the inode to search for in the cache
3172  * @avdc: matching avd cache entry returned to the caller
3173  *
3174  * Search @tsec for a AVD cache entry that matches @isec and return it to the
3175  * caller via @avdc.  Returns 0 if a match is found, negative values otherwise.
3176  */
3177 static inline int task_avdcache_search(struct task_security_struct *tsec,
3178 				       struct inode_security_struct *isec,
3179 				       struct avdc_entry **avdc)
3180 {
3181 	int orig, iter;
3182 
3183 	/* focused on path walk optimization, only cache directories */
3184 	if (isec->sclass != SECCLASS_DIR)
3185 		return -ENOENT;
3186 
3187 	if (unlikely(current_sid() != tsec->avdcache.sid ||
3188 		     tsec->avdcache.seqno != avc_policy_seqno())) {
3189 		task_avdcache_reset(tsec);
3190 		return -ENOENT;
3191 	}
3192 
3193 	orig = iter = tsec->avdcache.dir_spot;
3194 	do {
3195 		if (tsec->avdcache.dir[iter].isid == isec->sid) {
3196 			/* cache hit */
3197 			tsec->avdcache.dir_spot = iter;
3198 			*avdc = &tsec->avdcache.dir[iter];
3199 			return 0;
3200 		}
3201 		iter = (iter - 1) & (TSEC_AVDC_DIR_SIZE - 1);
3202 	} while (iter != orig);
3203 
3204 	return -ENOENT;
3205 }
3206 
3207 /**
3208  * task_avdcache_update - Update the task's AVD cache
3209  * @tsec: the task's security state
3210  * @isec: the inode associated with the cache entry
3211  * @avd: the AVD to cache
3212  *
3213  * Update the AVD cache in @tsec with the @avd info associated
3214  * with @isec.
3215  */
3216 static inline void task_avdcache_update(struct task_security_struct *tsec,
3217 					struct inode_security_struct *isec,
3218 					struct av_decision *avd)
3219 {
3220 	int spot;
3221 
3222 	/* focused on path walk optimization, only cache directories */
3223 	if (isec->sclass != SECCLASS_DIR)
3224 		return;
3225 
3226 	/* update cache */
3227 	spot = (tsec->avdcache.dir_spot + 1) & (TSEC_AVDC_DIR_SIZE - 1);
3228 	tsec->avdcache.dir_spot = spot;
3229 	tsec->avdcache.dir[spot].isid = isec->sid;
3230 	tsec->avdcache.dir[spot].avd = *avd;
3231 	tsec->avdcache.permissive_neveraudit =
3232 		(avd->flags == (AVD_FLAGS_PERMISSIVE|AVD_FLAGS_NEVERAUDIT));
3233 }
3234 
3235 /**
3236  * selinux_inode_permission - Check if the current task can access an inode
3237  * @inode: the inode that is being accessed
3238  * @requested: the accesses being requested
3239  *
3240  * Check if the current task is allowed to access @inode according to
3241  * @requested.  Returns 0 if allowed, negative values otherwise.
3242  */
3243 static int selinux_inode_permission(struct inode *inode, int requested)
3244 {
3245 	int mask;
3246 	u32 perms;
3247 	u32 sid = current_sid();
3248 	struct task_security_struct *tsec;
3249 	struct inode_security_struct *isec;
3250 	struct avdc_entry *avdc;
3251 	struct av_decision avd, *avdp = &avd;
3252 	int rc, rc2;
3253 	u32 audited, denied;
3254 
3255 	mask = requested & (MAY_READ|MAY_WRITE|MAY_EXEC|MAY_APPEND);
3256 
3257 	/* No permission to check.  Existence test. */
3258 	if (!mask)
3259 		return 0;
3260 
3261 	tsec = selinux_task(current);
3262 	if (task_avdcache_permnoaudit(tsec, sid))
3263 		return 0;
3264 
3265 	isec = inode_security_rcu(inode, requested & MAY_NOT_BLOCK);
3266 	if (IS_ERR(isec))
3267 		return PTR_ERR(isec);
3268 	perms = file_mask_to_av(inode->i_mode, mask);
3269 
3270 	rc = task_avdcache_search(tsec, isec, &avdc);
3271 	if (likely(!rc)) {
3272 		/* Cache hit. */
3273 		avdp = &avdc->avd;
3274 		denied = perms & ~avdp->allowed;
3275 		if (unlikely(denied) && enforcing_enabled() &&
3276 			!(avdp->flags & AVD_FLAGS_PERMISSIVE))
3277 			rc = -EACCES;
3278 	} else {
3279 		/* Cache miss. */
3280 		rc = avc_has_perm_noaudit(sid, isec->sid, isec->sclass,
3281 					  perms, 0, avdp);
3282 		task_avdcache_update(tsec, isec, avdp);
3283 	}
3284 
3285 	audited = avc_audit_required(perms, avdp, rc,
3286 				     (requested & MAY_ACCESS) ?
3287 				     FILE__AUDIT_ACCESS : 0, &denied);
3288 	if (likely(!audited))
3289 		return rc;
3290 
3291 	rc2 = audit_inode_permission(inode, perms, audited, denied, rc);
3292 	if (rc2)
3293 		return rc2;
3294 
3295 	return rc;
3296 }
3297 
3298 static int selinux_inode_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
3299 				 struct iattr *iattr)
3300 {
3301 	const struct cred *cred = current_cred();
3302 	struct inode *inode = d_backing_inode(dentry);
3303 	unsigned int ia_valid = iattr->ia_valid;
3304 	u32 av = FILE__WRITE;
3305 
3306 	/* ATTR_FORCE is just used for ATTR_KILL_S[UG]ID. */
3307 	if (ia_valid & ATTR_FORCE) {
3308 		ia_valid &= ~(ATTR_KILL_SUID | ATTR_KILL_SGID | ATTR_MODE |
3309 			      ATTR_FORCE);
3310 		if (!ia_valid)
3311 			return 0;
3312 	}
3313 
3314 	if (ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID |
3315 			ATTR_ATIME_SET | ATTR_MTIME_SET | ATTR_TIMES_SET))
3316 		return dentry_has_perm(cred, dentry, FILE__SETATTR);
3317 
3318 	if (selinux_policycap_openperm() &&
3319 	    inode->i_sb->s_magic != SOCKFS_MAGIC &&
3320 	    (ia_valid & ATTR_SIZE) &&
3321 	    !(ia_valid & ATTR_FILE))
3322 		av |= FILE__OPEN;
3323 
3324 	return dentry_has_perm(cred, dentry, av);
3325 }
3326 
3327 static int selinux_inode_getattr(const struct path *path)
3328 {
3329 	struct task_security_struct *tsec;
3330 
3331 	tsec = selinux_task(current);
3332 
3333 	if (task_avdcache_permnoaudit(tsec, current_sid()))
3334 		return 0;
3335 
3336 	return path_has_perm(current_cred(), path, FILE__GETATTR);
3337 }
3338 
3339 static bool has_cap_mac_admin(bool audit)
3340 {
3341 	const struct cred *cred = current_cred();
3342 	unsigned int opts = audit ? CAP_OPT_NONE : CAP_OPT_NOAUDIT;
3343 
3344 	if (cap_capable(cred, &init_user_ns, CAP_MAC_ADMIN, opts))
3345 		return false;
3346 	if (cred_has_capability(cred, CAP_MAC_ADMIN, opts, true))
3347 		return false;
3348 	return true;
3349 }
3350 
3351 /**
3352  * selinux_inode_xattr_skipcap - Skip the xattr capability checks?
3353  * @name: name of the xattr
3354  *
3355  * Returns 1 to indicate that SELinux "owns" the access control rights to xattrs
3356  * named @name; the LSM layer should avoid enforcing any traditional
3357  * capability based access controls on this xattr.  Returns 0 to indicate that
3358  * SELinux does not "own" the access control rights to xattrs named @name and is
3359  * deferring to the LSM layer for further access controls, including capability
3360  * based controls.
3361  */
3362 static int selinux_inode_xattr_skipcap(const char *name)
3363 {
3364 	/* require capability check if not a selinux xattr */
3365 	return !strcmp(name, XATTR_NAME_SELINUX);
3366 }
3367 
3368 static int selinux_inode_setxattr(struct mnt_idmap *idmap,
3369 				  struct dentry *dentry, const char *name,
3370 				  const void *value, size_t size, int flags)
3371 {
3372 	struct inode *inode = d_backing_inode(dentry);
3373 	struct inode_security_struct *isec;
3374 	struct superblock_security_struct *sbsec;
3375 	struct common_audit_data ad;
3376 	u32 newsid, sid = current_sid();
3377 	int rc = 0;
3378 
3379 	/* if not a selinux xattr, only check the ordinary setattr perm */
3380 	if (strcmp(name, XATTR_NAME_SELINUX))
3381 		return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3382 
3383 	if (!selinux_initialized())
3384 		return (inode_owner_or_capable(idmap, inode) ? 0 : -EPERM);
3385 
3386 	sbsec = selinux_superblock(inode->i_sb);
3387 	if (!(sbsec->flags & SBLABEL_MNT))
3388 		return -EOPNOTSUPP;
3389 
3390 	if (!inode_owner_or_capable(idmap, inode))
3391 		return -EPERM;
3392 
3393 	ad.type = LSM_AUDIT_DATA_DENTRY;
3394 	ad.u.dentry = dentry;
3395 
3396 	isec = backing_inode_security(dentry);
3397 	rc = avc_has_perm(sid, isec->sid, isec->sclass,
3398 			  FILE__RELABELFROM, &ad);
3399 	if (rc)
3400 		return rc;
3401 
3402 	rc = security_context_to_sid(value, size, &newsid,
3403 				     GFP_KERNEL);
3404 	if (rc == -EINVAL) {
3405 		if (!has_cap_mac_admin(true)) {
3406 			struct audit_buffer *ab;
3407 			size_t audit_size;
3408 
3409 			/* We strip a nul only if it is at the end, otherwise the
3410 			 * context contains a nul and we should audit that */
3411 			if (value) {
3412 				const char *str = value;
3413 
3414 				if (str[size - 1] == '\0')
3415 					audit_size = size - 1;
3416 				else
3417 					audit_size = size;
3418 			} else {
3419 				audit_size = 0;
3420 			}
3421 			ab = audit_log_start(audit_context(),
3422 					     GFP_ATOMIC, AUDIT_SELINUX_ERR);
3423 			if (!ab)
3424 				return rc;
3425 			audit_log_format(ab, "op=setxattr invalid_context=");
3426 			audit_log_n_untrustedstring(ab, value, audit_size);
3427 			audit_log_end(ab);
3428 
3429 			return rc;
3430 		}
3431 		rc = security_context_to_sid_force(value,
3432 						   size, &newsid);
3433 	}
3434 	if (rc)
3435 		return rc;
3436 
3437 	rc = avc_has_perm(sid, newsid, isec->sclass,
3438 			  FILE__RELABELTO, &ad);
3439 	if (rc)
3440 		return rc;
3441 
3442 	rc = security_validate_transition(isec->sid, newsid,
3443 					  sid, isec->sclass);
3444 	if (rc)
3445 		return rc;
3446 
3447 	return avc_has_perm(newsid,
3448 			    sbsec->sid,
3449 			    SECCLASS_FILESYSTEM,
3450 			    FILESYSTEM__ASSOCIATE,
3451 			    &ad);
3452 }
3453 
3454 static int selinux_inode_set_acl(struct mnt_idmap *idmap,
3455 				 struct dentry *dentry, const char *acl_name,
3456 				 struct posix_acl *kacl)
3457 {
3458 	return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3459 }
3460 
3461 static int selinux_inode_get_acl(struct mnt_idmap *idmap,
3462 				 struct dentry *dentry, const char *acl_name)
3463 {
3464 	return dentry_has_perm(current_cred(), dentry, FILE__GETATTR);
3465 }
3466 
3467 static int selinux_inode_remove_acl(struct mnt_idmap *idmap,
3468 				    struct dentry *dentry, const char *acl_name)
3469 {
3470 	return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3471 }
3472 
3473 static void selinux_inode_post_setxattr(struct dentry *dentry, const char *name,
3474 					const void *value, size_t size,
3475 					int flags)
3476 {
3477 	struct inode *inode = d_backing_inode(dentry);
3478 	struct inode_security_struct *isec;
3479 	u32 newsid;
3480 	int rc;
3481 
3482 	if (strcmp(name, XATTR_NAME_SELINUX)) {
3483 		/* Not an attribute we recognize, so nothing to do. */
3484 		return;
3485 	}
3486 
3487 	if (!selinux_initialized()) {
3488 		/* If we haven't even been initialized, then we can't validate
3489 		 * against a policy, so leave the label as invalid. It may
3490 		 * resolve to a valid label on the next revalidation try if
3491 		 * we've since initialized.
3492 		 */
3493 		return;
3494 	}
3495 
3496 	rc = security_context_to_sid_force(value, size,
3497 					   &newsid);
3498 	if (rc) {
3499 		pr_err("SELinux:  unable to map context to SID"
3500 		       "for (%s, %llu), rc=%d\n",
3501 		       inode->i_sb->s_id, inode->i_ino, -rc);
3502 		return;
3503 	}
3504 
3505 	isec = backing_inode_security(dentry);
3506 	spin_lock(&isec->lock);
3507 	isec->sclass = inode_mode_to_security_class(inode->i_mode);
3508 	isec->sid = newsid;
3509 	isec->initialized = LABEL_INITIALIZED;
3510 	spin_unlock(&isec->lock);
3511 }
3512 
3513 static int selinux_inode_getxattr(struct dentry *dentry, const char *name)
3514 {
3515 	const struct cred *cred = current_cred();
3516 
3517 	return dentry_has_perm(cred, dentry, FILE__GETATTR);
3518 }
3519 
3520 static int selinux_inode_listxattr(struct dentry *dentry)
3521 {
3522 	const struct cred *cred = current_cred();
3523 
3524 	return dentry_has_perm(cred, dentry, FILE__GETATTR);
3525 }
3526 
3527 static int selinux_inode_removexattr(struct mnt_idmap *idmap,
3528 				     struct dentry *dentry, const char *name)
3529 {
3530 	/* if not a selinux xattr, only check the ordinary setattr perm */
3531 	if (strcmp(name, XATTR_NAME_SELINUX))
3532 		return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3533 
3534 	if (!selinux_initialized())
3535 		return 0;
3536 
3537 	/* No one is allowed to remove a SELinux security label.
3538 	   You can change the label, but all data must be labeled. */
3539 	return -EACCES;
3540 }
3541 
3542 static int selinux_inode_file_setattr(struct dentry *dentry,
3543 				      struct file_kattr *fa)
3544 {
3545 	return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3546 }
3547 
3548 static int selinux_inode_file_getattr(struct dentry *dentry,
3549 				      struct file_kattr *fa)
3550 {
3551 	return dentry_has_perm(current_cred(), dentry, FILE__GETATTR);
3552 }
3553 
3554 static int selinux_path_notify(const struct path *path, u64 mask,
3555 						unsigned int obj_type)
3556 {
3557 	int ret;
3558 	u32 perm;
3559 
3560 	struct common_audit_data ad;
3561 
3562 	ad.type = LSM_AUDIT_DATA_PATH;
3563 	ad.u.path = *path;
3564 
3565 	/*
3566 	 * Set permission needed based on the type of mark being set.
3567 	 * Performs an additional check for sb watches.
3568 	 */
3569 	switch (obj_type) {
3570 	case FSNOTIFY_OBJ_TYPE_VFSMOUNT:
3571 		perm = FILE__WATCH_MOUNT;
3572 		break;
3573 	case FSNOTIFY_OBJ_TYPE_SB:
3574 		perm = FILE__WATCH_SB;
3575 		ret = superblock_has_perm(current_cred(), path->dentry->d_sb,
3576 						FILESYSTEM__WATCH, &ad);
3577 		if (ret)
3578 			return ret;
3579 		break;
3580 	case FSNOTIFY_OBJ_TYPE_INODE:
3581 		perm = FILE__WATCH;
3582 		break;
3583 	case FSNOTIFY_OBJ_TYPE_MNTNS:
3584 		perm = FILE__WATCH_MOUNTNS;
3585 		break;
3586 	default:
3587 		return -EINVAL;
3588 	}
3589 
3590 	/* blocking watches require the file:watch_with_perm permission */
3591 	if (mask & (ALL_FSNOTIFY_PERM_EVENTS))
3592 		perm |= FILE__WATCH_WITH_PERM;
3593 
3594 	/* watches on read-like events need the file:watch_reads permission */
3595 	if (mask & (FS_ACCESS | FS_ACCESS_PERM | FS_PRE_ACCESS |
3596 		    FS_CLOSE_NOWRITE))
3597 		perm |= FILE__WATCH_READS;
3598 
3599 	return path_has_perm(current_cred(), path, perm);
3600 }
3601 
3602 /*
3603  * Copy the inode security context value to the user.
3604  *
3605  * Permission check is handled by selinux_inode_getxattr hook.
3606  */
3607 static int selinux_inode_getsecurity(struct mnt_idmap *idmap,
3608 				     struct inode *inode, const char *name,
3609 				     void **buffer, bool alloc)
3610 {
3611 	u32 size;
3612 	int error;
3613 	char *context = NULL;
3614 	struct inode_security_struct *isec;
3615 
3616 	/*
3617 	 * If we're not initialized yet, then we can't validate contexts, so
3618 	 * just let vfs_getxattr fall back to using the on-disk xattr.
3619 	 */
3620 	if (!selinux_initialized() ||
3621 	    strcmp(name, XATTR_SELINUX_SUFFIX))
3622 		return -EOPNOTSUPP;
3623 
3624 	/*
3625 	 * If the caller has CAP_MAC_ADMIN, then get the raw context
3626 	 * value even if it is not defined by current policy; otherwise,
3627 	 * use the in-core value under current policy.
3628 	 * Use the non-auditing forms of the permission checks since
3629 	 * getxattr may be called by unprivileged processes commonly
3630 	 * and lack of permission just means that we fall back to the
3631 	 * in-core context value, not a denial.
3632 	 */
3633 	isec = inode_security(inode);
3634 	if (has_cap_mac_admin(false))
3635 		error = security_sid_to_context_force(isec->sid, &context,
3636 						      &size);
3637 	else
3638 		error = security_sid_to_context(isec->sid,
3639 						&context, &size);
3640 	if (error)
3641 		return error;
3642 	error = size;
3643 	if (alloc) {
3644 		*buffer = context;
3645 		goto out_nofree;
3646 	}
3647 	kfree(context);
3648 out_nofree:
3649 	return error;
3650 }
3651 
3652 static int selinux_inode_setsecurity(struct inode *inode, const char *name,
3653 				     const void *value, size_t size, int flags)
3654 {
3655 	struct inode_security_struct *isec = inode_security_novalidate(inode);
3656 	struct superblock_security_struct *sbsec;
3657 	u32 newsid;
3658 	int rc;
3659 
3660 	if (strcmp(name, XATTR_SELINUX_SUFFIX))
3661 		return -EOPNOTSUPP;
3662 
3663 	sbsec = selinux_superblock(inode->i_sb);
3664 	if (!(sbsec->flags & SBLABEL_MNT))
3665 		return -EOPNOTSUPP;
3666 
3667 	if (!value || !size)
3668 		return -EACCES;
3669 
3670 	rc = security_context_to_sid(value, size, &newsid,
3671 				     GFP_KERNEL);
3672 	if (rc)
3673 		return rc;
3674 
3675 	spin_lock(&isec->lock);
3676 	isec->sclass = inode_mode_to_security_class(inode->i_mode);
3677 	isec->sid = newsid;
3678 	isec->initialized = LABEL_INITIALIZED;
3679 	spin_unlock(&isec->lock);
3680 	return 0;
3681 }
3682 
3683 static int selinux_inode_listsecurity(struct inode *inode, char **buffer,
3684 				ssize_t *remaining_size)
3685 {
3686 	if (!selinux_initialized())
3687 		return 0;
3688 	return xattr_list_one(buffer, remaining_size, XATTR_NAME_SELINUX);
3689 }
3690 
3691 static void selinux_inode_getlsmprop(struct inode *inode, struct lsm_prop *prop)
3692 {
3693 	struct inode_security_struct *isec = inode_security_novalidate(inode);
3694 
3695 	prop->selinux.secid = isec->sid;
3696 }
3697 
3698 static int selinux_inode_copy_up(struct dentry *src, struct cred **new)
3699 {
3700 	struct lsm_prop prop;
3701 	struct cred_security_struct *crsec;
3702 	struct cred *new_creds = *new;
3703 
3704 	if (new_creds == NULL) {
3705 		new_creds = prepare_creds();
3706 		if (!new_creds)
3707 			return -ENOMEM;
3708 	}
3709 
3710 	crsec = selinux_cred(new_creds);
3711 	/* Get label from overlay inode and set it in create_sid */
3712 	selinux_inode_getlsmprop(d_inode(src), &prop);
3713 	crsec->create_sid = prop.selinux.secid;
3714 	*new = new_creds;
3715 	return 0;
3716 }
3717 
3718 static int selinux_inode_copy_up_xattr(struct dentry *dentry, const char *name)
3719 {
3720 	/* The copy_up hook above sets the initial context on an inode, but we
3721 	 * don't then want to overwrite it by blindly copying all the lower
3722 	 * xattrs up.  Instead, filter out SELinux-related xattrs following
3723 	 * policy load.
3724 	 */
3725 	if (selinux_initialized() && !strcmp(name, XATTR_NAME_SELINUX))
3726 		return -ECANCELED; /* Discard */
3727 	/*
3728 	 * Any other attribute apart from SELINUX is not claimed, supported
3729 	 * by selinux.
3730 	 */
3731 	return -EOPNOTSUPP;
3732 }
3733 
3734 /* kernfs node operations */
3735 
3736 static int selinux_kernfs_init_security(struct kernfs_node *kn_dir,
3737 					struct kernfs_node *kn)
3738 {
3739 	const struct cred_security_struct *crsec = selinux_cred(current_cred());
3740 	u32 parent_sid, newsid, clen;
3741 	int rc;
3742 	char *context;
3743 
3744 	rc = kernfs_xattr_get(kn_dir, XATTR_NAME_SELINUX, NULL, 0);
3745 	if (rc == -ENODATA)
3746 		return 0;
3747 	else if (rc < 0)
3748 		return rc;
3749 
3750 	clen = (u32)rc;
3751 	context = kmalloc(clen, GFP_KERNEL);
3752 	if (!context)
3753 		return -ENOMEM;
3754 
3755 	rc = kernfs_xattr_get(kn_dir, XATTR_NAME_SELINUX, context, clen);
3756 	if (rc < 0) {
3757 		kfree(context);
3758 		return rc;
3759 	}
3760 
3761 	rc = security_context_to_sid(context, clen, &parent_sid,
3762 				     GFP_KERNEL);
3763 	kfree(context);
3764 	if (rc)
3765 		return rc;
3766 
3767 	if (crsec->create_sid) {
3768 		newsid = crsec->create_sid;
3769 	} else {
3770 		u16 secclass = inode_mode_to_security_class(kn->mode);
3771 		const char *kn_name;
3772 		struct qstr q;
3773 
3774 		/* kn is fresh, can't be renamed, name goes not away */
3775 		kn_name = rcu_dereference_check(kn->name, true);
3776 		q.name = kn_name;
3777 		q.hash_len = hashlen_string(kn_dir, kn_name);
3778 
3779 		rc = security_transition_sid(crsec->sid,
3780 					     parent_sid, secclass, &q,
3781 					     &newsid);
3782 		if (rc)
3783 			return rc;
3784 	}
3785 
3786 	rc = security_sid_to_context_force(newsid,
3787 					   &context, &clen);
3788 	if (rc)
3789 		return rc;
3790 
3791 	rc = kernfs_xattr_set(kn, XATTR_NAME_SELINUX, context, clen,
3792 			      XATTR_CREATE);
3793 	kfree(context);
3794 	return rc;
3795 }
3796 
3797 
3798 /* file security operations */
3799 
3800 static int selinux_revalidate_file_permission(struct file *file, int mask)
3801 {
3802 	const struct cred *cred = current_cred();
3803 	struct inode *inode = file_inode(file);
3804 
3805 	/* file_mask_to_av won't add FILE__WRITE if MAY_APPEND is set */
3806 	if ((file->f_flags & O_APPEND) && (mask & MAY_WRITE))
3807 		mask |= MAY_APPEND;
3808 
3809 	return file_has_perm(cred, file,
3810 			     file_mask_to_av(inode->i_mode, mask));
3811 }
3812 
3813 static int selinux_file_permission(struct file *file, int mask)
3814 {
3815 	struct inode *inode = file_inode(file);
3816 	struct file_security_struct *fsec = selinux_file(file);
3817 	struct inode_security_struct *isec;
3818 	u32 sid = current_sid();
3819 
3820 	if (!mask)
3821 		/* No permission to check.  Existence test. */
3822 		return 0;
3823 
3824 	isec = inode_security(inode);
3825 	if (sid == fsec->sid && fsec->isid == isec->sid &&
3826 	    fsec->pseqno == avc_policy_seqno())
3827 		/* No change since file_open check. */
3828 		return 0;
3829 
3830 	return selinux_revalidate_file_permission(file, mask);
3831 }
3832 
3833 static int selinux_file_alloc_security(struct file *file)
3834 {
3835 	struct file_security_struct *fsec = selinux_file(file);
3836 	u32 sid = current_sid();
3837 
3838 	fsec->sid = sid;
3839 	fsec->fown_sid = sid;
3840 
3841 	return 0;
3842 }
3843 
3844 static int selinux_backing_file_alloc(struct file *backing_file,
3845 				      const struct file *user_file)
3846 {
3847 	struct backing_file_security_struct *bfsec;
3848 
3849 	bfsec = selinux_backing_file(backing_file);
3850 	bfsec->uf_sid = selinux_file(user_file)->sid;
3851 
3852 	return 0;
3853 }
3854 
3855 /*
3856  * Check whether a task has the ioctl permission and cmd
3857  * operation to an inode.
3858  */
3859 static int ioctl_has_perm(const struct cred *cred, struct file *file,
3860 		u32 requested, u16 cmd)
3861 {
3862 	struct common_audit_data ad;
3863 	struct file_security_struct *fsec = selinux_file(file);
3864 	struct inode *inode = file_inode(file);
3865 	struct inode_security_struct *isec;
3866 	struct lsm_ioctlop_audit ioctl;
3867 	u32 ssid = cred_sid(cred);
3868 	int rc;
3869 	u8 driver = cmd >> 8;
3870 	u8 xperm = cmd & 0xff;
3871 
3872 	ad.type = LSM_AUDIT_DATA_IOCTL_OP;
3873 	ad.u.op = &ioctl;
3874 	ad.u.op->cmd = cmd;
3875 	ad.u.op->path = file->f_path;
3876 
3877 	if (ssid != fsec->sid) {
3878 		rc = avc_has_perm(ssid, fsec->sid,
3879 				SECCLASS_FD,
3880 				FD__USE,
3881 				&ad);
3882 		if (rc)
3883 			goto out;
3884 	}
3885 
3886 	if (unlikely(IS_PRIVATE(inode)))
3887 		return 0;
3888 
3889 	isec = inode_security(inode);
3890 	rc = avc_has_extended_perms(ssid, isec->sid, isec->sclass, requested,
3891 				    driver, AVC_EXT_IOCTL, xperm, &ad);
3892 out:
3893 	return rc;
3894 }
3895 
3896 static int selinux_file_ioctl(struct file *file, unsigned int cmd,
3897 			      unsigned long arg)
3898 {
3899 	const struct cred *cred = current_cred();
3900 	int error = 0;
3901 
3902 	switch (cmd) {
3903 	case FIONREAD:
3904 	case FIBMAP:
3905 	case FIGETBSZ:
3906 	case FS_IOC_GETFLAGS:
3907 	case FS_IOC_GETVERSION:
3908 		error = file_has_perm(cred, file, FILE__GETATTR);
3909 		break;
3910 
3911 	case FS_IOC_SETFLAGS:
3912 	case FS_IOC_SETVERSION:
3913 		error = file_has_perm(cred, file, FILE__SETATTR);
3914 		break;
3915 
3916 	/* sys_ioctl() checks */
3917 	case FIONBIO:
3918 	case FIOASYNC:
3919 		error = file_has_perm(cred, file, 0);
3920 		break;
3921 
3922 	case KDSKBENT:
3923 	case KDSKBSENT:
3924 		error = cred_has_capability(cred, CAP_SYS_TTY_CONFIG,
3925 					    CAP_OPT_NONE, true);
3926 		break;
3927 
3928 	case FIOCLEX:
3929 	case FIONCLEX:
3930 		if (!selinux_policycap_ioctl_skip_cloexec())
3931 			error = ioctl_has_perm(cred, file, FILE__IOCTL, (u16) cmd);
3932 		break;
3933 
3934 	/* default case assumes that the command will go
3935 	 * to the file's ioctl() function.
3936 	 */
3937 	default:
3938 		error = ioctl_has_perm(cred, file, FILE__IOCTL, (u16) cmd);
3939 	}
3940 	return error;
3941 }
3942 
3943 static int selinux_file_ioctl_compat(struct file *file, unsigned int cmd,
3944 			      unsigned long arg)
3945 {
3946 	/*
3947 	 * If we are in a 64-bit kernel running 32-bit userspace, we need to
3948 	 * make sure we don't compare 32-bit flags to 64-bit flags.
3949 	 */
3950 	switch (cmd) {
3951 	case FS_IOC32_GETFLAGS:
3952 		cmd = FS_IOC_GETFLAGS;
3953 		break;
3954 	case FS_IOC32_SETFLAGS:
3955 		cmd = FS_IOC_SETFLAGS;
3956 		break;
3957 	case FS_IOC32_GETVERSION:
3958 		cmd = FS_IOC_GETVERSION;
3959 		break;
3960 	case FS_IOC32_SETVERSION:
3961 		cmd = FS_IOC_SETVERSION;
3962 		break;
3963 	default:
3964 		break;
3965 	}
3966 
3967 	return selinux_file_ioctl(file, cmd, arg);
3968 }
3969 
3970 static int default_noexec __ro_after_init;
3971 
3972 static int __file_map_prot_check(const struct cred *cred,
3973 				 const struct file *file, unsigned long prot,
3974 				 bool shared, bool bf_user_file)
3975 {
3976 	struct inode *inode = NULL;
3977 	bool prot_exec = prot & PROT_EXEC;
3978 	bool prot_write = prot & PROT_WRITE;
3979 
3980 	if (file) {
3981 		if (bf_user_file)
3982 			inode = d_inode(backing_file_user_path(file)->dentry);
3983 		else
3984 			inode = file_inode(file);
3985 	}
3986 
3987 	if (default_noexec && prot_exec &&
3988 	    (!file || IS_PRIVATE(inode) || (!shared && prot_write))) {
3989 		int rc;
3990 		u32 sid = cred_sid(cred);
3991 
3992 		/*
3993 		 * We are making executable an anonymous mapping or a private
3994 		 * file mapping that will also be writable.
3995 		 */
3996 		rc = avc_has_perm(sid, sid, SECCLASS_PROCESS, PROCESS__EXECMEM,
3997 				  NULL);
3998 		if (rc)
3999 			return rc;
4000 	}
4001 
4002 	if (file) {
4003 		/* "read" always possible, "write" only if shared */
4004 		u32 av = FILE__READ;
4005 		if (shared && prot_write)
4006 			av |= FILE__WRITE;
4007 		if (prot_exec)
4008 			av |= FILE__EXECUTE;
4009 
4010 		return __file_has_perm(cred, file, av, bf_user_file);
4011 	}
4012 
4013 	return 0;
4014 }
4015 
4016 static inline int file_map_prot_check(const struct cred *cred,
4017 				      const struct file *file,
4018 				      unsigned long prot, bool shared)
4019 {
4020 	return __file_map_prot_check(cred, file, prot, shared, false);
4021 }
4022 
4023 static int selinux_mmap_addr(unsigned long addr)
4024 {
4025 	int rc = 0;
4026 
4027 	if (addr < CONFIG_LSM_MMAP_MIN_ADDR) {
4028 		u32 sid = current_sid();
4029 		rc = avc_has_perm(sid, sid, SECCLASS_MEMPROTECT,
4030 				  MEMPROTECT__MMAP_ZERO, NULL);
4031 	}
4032 
4033 	return rc;
4034 }
4035 
4036 static int selinux_mmap_file_common(const struct cred *cred, struct file *file,
4037 				    unsigned long prot, bool shared)
4038 {
4039 	if (file) {
4040 		int rc;
4041 		struct common_audit_data ad;
4042 
4043 		ad.type = LSM_AUDIT_DATA_FILE;
4044 		ad.u.file = file;
4045 		rc = inode_has_perm(cred, file_inode(file), FILE__MAP, &ad);
4046 		if (rc)
4047 			return rc;
4048 	}
4049 
4050 	return file_map_prot_check(cred, file, prot, shared);
4051 }
4052 
4053 static int selinux_mmap_file(struct file *file,
4054 			     unsigned long reqprot __always_unused,
4055 			     unsigned long prot, unsigned long flags)
4056 {
4057 	return selinux_mmap_file_common(current_cred(), file, prot,
4058 					(flags & MAP_TYPE) == MAP_SHARED);
4059 }
4060 
4061 /**
4062  * selinux_mmap_backing_file - Check mmap permissions on a backing file
4063  * @vma: memory region
4064  * @backing_file: stacked filesystem backing file
4065  * @user_file: user visible file
4066  *
4067  * This is called after selinux_mmap_file() on stacked filesystems, and it
4068  * is this function's responsibility to verify access to @backing_file and
4069  * setup the SELinux state for possible later use in the mprotect() code path.
4070  *
4071  * By the time this function is called, mmap() access to @user_file has already
4072  * been authorized and @vma->vm_file has been set to point to @backing_file.
4073  *
4074  * Return zero on success, negative values otherwise.
4075  */
4076 static int selinux_mmap_backing_file(struct vm_area_struct *vma,
4077 				     struct file *backing_file,
4078 				     struct file *user_file __always_unused)
4079 {
4080 	unsigned long prot = 0;
4081 
4082 	/* translate vma->vm_flags perms into PROT perms */
4083 	if (vma->vm_flags & VM_READ)
4084 		prot |= PROT_READ;
4085 	if (vma->vm_flags & VM_WRITE)
4086 		prot |= PROT_WRITE;
4087 	if (vma->vm_flags & VM_EXEC)
4088 		prot |= PROT_EXEC;
4089 
4090 	return selinux_mmap_file_common(backing_file->f_cred, backing_file,
4091 					prot, vma->vm_flags & VM_SHARED);
4092 }
4093 
4094 static int selinux_file_mprotect(struct vm_area_struct *vma,
4095 				 unsigned long reqprot __always_unused,
4096 				 unsigned long prot)
4097 {
4098 	int rc;
4099 	const struct cred *cred = current_cred();
4100 	u32 sid = cred_sid(cred);
4101 	const struct file *file = vma->vm_file;
4102 	bool backing_file;
4103 	bool shared = vma->vm_flags & VM_SHARED;
4104 
4105 	/* check if we need to trigger the "backing files are awful" mode */
4106 	backing_file = file && (file->f_mode & FMODE_BACKING);
4107 
4108 	if (default_noexec &&
4109 	    (prot & PROT_EXEC) && !(vma->vm_flags & VM_EXEC)) {
4110 		/*
4111 		 * We don't use the vma_is_initial_heap() helper as it has
4112 		 * a history of problems and is currently broken on systems
4113 		 * where there is no heap, e.g. brk == start_brk.  Before
4114 		 * replacing the conditional below with vma_is_initial_heap(),
4115 		 * or something similar, please ensure that the logic is the
4116 		 * same as what we have below or you have tested every possible
4117 		 * corner case you can think to test.
4118 		 */
4119 		if (vma->vm_start >= vma->vm_mm->start_brk &&
4120 		    vma->vm_end <= vma->vm_mm->brk) {
4121 			rc = avc_has_perm(sid, sid, SECCLASS_PROCESS,
4122 					  PROCESS__EXECHEAP, NULL);
4123 			if (rc)
4124 				return rc;
4125 		} else if (!file && (vma_is_initial_stack(vma) ||
4126 			    vma_is_stack_for_current(vma))) {
4127 			rc = avc_has_perm(sid, sid, SECCLASS_PROCESS,
4128 					  PROCESS__EXECSTACK, NULL);
4129 			if (rc)
4130 				return rc;
4131 		} else if (file && vma->anon_vma) {
4132 			/*
4133 			 * We are making executable a file mapping that has
4134 			 * had some COW done. Since pages might have been
4135 			 * written, check ability to execute the possibly
4136 			 * modified content.  This typically should only
4137 			 * occur for text relocations.
4138 			 */
4139 			rc = __file_has_perm(cred, file, FILE__EXECMOD,
4140 					     backing_file);
4141 			if (rc)
4142 				return rc;
4143 			if (backing_file) {
4144 				rc = file_has_perm(file->f_cred, file,
4145 						   FILE__EXECMOD);
4146 				if (rc)
4147 					return rc;
4148 			}
4149 		}
4150 	}
4151 
4152 	rc = __file_map_prot_check(cred, file, prot, shared, backing_file);
4153 	if (rc)
4154 		return rc;
4155 	if (backing_file) {
4156 		rc = file_map_prot_check(file->f_cred, file, prot, shared);
4157 		if (rc)
4158 			return rc;
4159 	}
4160 
4161 	return 0;
4162 }
4163 
4164 static int selinux_file_lock(struct file *file, unsigned int cmd)
4165 {
4166 	const struct cred *cred = current_cred();
4167 
4168 	return file_has_perm(cred, file, FILE__LOCK);
4169 }
4170 
4171 static int selinux_file_fcntl(struct file *file, unsigned int cmd,
4172 			      unsigned long arg)
4173 {
4174 	const struct cred *cred = current_cred();
4175 	int err = 0;
4176 
4177 	switch (cmd) {
4178 	case F_SETFL:
4179 		if ((file->f_flags & O_APPEND) && !(arg & O_APPEND)) {
4180 			err = file_has_perm(cred, file, FILE__WRITE);
4181 			break;
4182 		}
4183 		fallthrough;
4184 	case F_SETOWN:
4185 	case F_SETSIG:
4186 	case F_GETFL:
4187 	case F_GETOWN:
4188 	case F_GETSIG:
4189 	case F_GETOWNER_UIDS:
4190 		/* Just check FD__USE permission */
4191 		err = file_has_perm(cred, file, 0);
4192 		break;
4193 	case F_GETLK:
4194 	case F_SETLK:
4195 	case F_SETLKW:
4196 	case F_OFD_GETLK:
4197 	case F_OFD_SETLK:
4198 	case F_OFD_SETLKW:
4199 #if BITS_PER_LONG == 32
4200 	case F_GETLK64:
4201 	case F_SETLK64:
4202 	case F_SETLKW64:
4203 #endif
4204 		err = file_has_perm(cred, file, FILE__LOCK);
4205 		break;
4206 	}
4207 
4208 	return err;
4209 }
4210 
4211 static void selinux_file_set_fowner(struct file *file)
4212 {
4213 	struct file_security_struct *fsec;
4214 
4215 	fsec = selinux_file(file);
4216 	fsec->fown_sid = current_sid();
4217 }
4218 
4219 static int selinux_file_send_sigiotask(struct task_struct *tsk,
4220 				       struct fown_struct *fown, int signum)
4221 {
4222 	struct file *file;
4223 	u32 sid = task_sid_obj(tsk);
4224 	u32 perm;
4225 	struct file_security_struct *fsec;
4226 
4227 	/* struct fown_struct is never outside the context of a struct file */
4228 	file = fown->file;
4229 
4230 	fsec = selinux_file(file);
4231 
4232 	if (!signum)
4233 		perm = signal_to_av(SIGIO); /* as per send_sigio_to_task */
4234 	else
4235 		perm = signal_to_av(signum);
4236 
4237 	return avc_has_perm(fsec->fown_sid, sid,
4238 			    SECCLASS_PROCESS, perm, NULL);
4239 }
4240 
4241 static int selinux_file_receive(struct file *file)
4242 {
4243 	const struct cred *cred = current_cred();
4244 
4245 	return file_has_perm(cred, file, file_to_av(file));
4246 }
4247 
4248 static int selinux_file_open(struct file *file)
4249 {
4250 	struct file_security_struct *fsec;
4251 	struct inode_security_struct *isec;
4252 
4253 	fsec = selinux_file(file);
4254 	isec = inode_security(file_inode(file));
4255 	/*
4256 	 * Save inode label and policy sequence number
4257 	 * at open-time so that selinux_file_permission
4258 	 * can determine whether revalidation is necessary.
4259 	 * Task label is already saved in the file security
4260 	 * struct as its SID.
4261 	 */
4262 	fsec->isid = isec->sid;
4263 	fsec->pseqno = avc_policy_seqno();
4264 	/*
4265 	 * Since the inode label or policy seqno may have changed
4266 	 * between the selinux_inode_permission check and the saving
4267 	 * of state above, recheck that access is still permitted.
4268 	 * Otherwise, access might never be revalidated against the
4269 	 * new inode label or new policy.
4270 	 * This check is not redundant - do not remove.
4271 	 */
4272 	return file_path_has_perm(file->f_cred, file, open_file_to_av(file));
4273 }
4274 
4275 /* task security operations */
4276 
4277 static int selinux_task_alloc(struct task_struct *task,
4278 			      u64 clone_flags)
4279 {
4280 	u32 sid = current_sid();
4281 	struct task_security_struct *old_tsec = selinux_task(current);
4282 	struct task_security_struct *new_tsec = selinux_task(task);
4283 
4284 	*new_tsec = *old_tsec;
4285 	return avc_has_perm(sid, sid, SECCLASS_PROCESS, PROCESS__FORK, NULL);
4286 }
4287 
4288 /*
4289  * prepare a new set of credentials for modification
4290  */
4291 static int selinux_cred_prepare(struct cred *new, const struct cred *old,
4292 				gfp_t gfp)
4293 {
4294 	const struct cred_security_struct *old_crsec = selinux_cred(old);
4295 	struct cred_security_struct *crsec = selinux_cred(new);
4296 
4297 	*crsec = *old_crsec;
4298 	return 0;
4299 }
4300 
4301 /*
4302  * transfer the SELinux data to a blank set of creds
4303  */
4304 static void selinux_cred_transfer(struct cred *new, const struct cred *old)
4305 {
4306 	const struct cred_security_struct *old_crsec = selinux_cred(old);
4307 	struct cred_security_struct *crsec = selinux_cred(new);
4308 
4309 	*crsec = *old_crsec;
4310 }
4311 
4312 static void selinux_cred_getsecid(const struct cred *c, u32 *secid)
4313 {
4314 	*secid = cred_sid(c);
4315 }
4316 
4317 static void selinux_cred_getlsmprop(const struct cred *c, struct lsm_prop *prop)
4318 {
4319 	prop->selinux.secid = cred_sid(c);
4320 }
4321 
4322 /*
4323  * set the security data for a kernel service
4324  * - all the creation contexts are set to unlabelled
4325  */
4326 static int selinux_kernel_act_as(struct cred *new, u32 secid)
4327 {
4328 	struct cred_security_struct *crsec = selinux_cred(new);
4329 	u32 sid = current_sid();
4330 	int ret;
4331 
4332 	ret = avc_has_perm(sid, secid,
4333 			   SECCLASS_KERNEL_SERVICE,
4334 			   KERNEL_SERVICE__USE_AS_OVERRIDE,
4335 			   NULL);
4336 	if (ret == 0) {
4337 		crsec->sid = secid;
4338 		crsec->create_sid = 0;
4339 		crsec->keycreate_sid = 0;
4340 		crsec->sockcreate_sid = 0;
4341 	}
4342 	return ret;
4343 }
4344 
4345 /*
4346  * set the file creation context in a security record to the same as the
4347  * objective context of the specified inode
4348  */
4349 static int selinux_kernel_create_files_as(struct cred *new, struct inode *inode)
4350 {
4351 	struct inode_security_struct *isec = inode_security(inode);
4352 	struct cred_security_struct *crsec = selinux_cred(new);
4353 	u32 sid = current_sid();
4354 	int ret;
4355 
4356 	ret = avc_has_perm(sid, isec->sid,
4357 			   SECCLASS_KERNEL_SERVICE,
4358 			   KERNEL_SERVICE__CREATE_FILES_AS,
4359 			   NULL);
4360 
4361 	if (ret == 0)
4362 		crsec->create_sid = isec->sid;
4363 	return ret;
4364 }
4365 
4366 static int selinux_kernel_module_request(char *kmod_name)
4367 {
4368 	struct common_audit_data ad;
4369 
4370 	ad.type = LSM_AUDIT_DATA_KMOD;
4371 	ad.u.kmod_name = kmod_name;
4372 
4373 	return avc_has_perm(current_sid(), SECINITSID_KERNEL, SECCLASS_SYSTEM,
4374 			    SYSTEM__MODULE_REQUEST, &ad);
4375 }
4376 
4377 static int selinux_kernel_load_from_file(struct file *file, u32 requested)
4378 {
4379 	struct common_audit_data ad;
4380 	struct inode_security_struct *isec;
4381 	struct file_security_struct *fsec;
4382 	u32 sid = current_sid();
4383 	int rc;
4384 
4385 	if (file == NULL)
4386 		return avc_has_perm(sid, sid, SECCLASS_SYSTEM, requested, NULL);
4387 
4388 	ad.type = LSM_AUDIT_DATA_FILE;
4389 	ad.u.file = file;
4390 
4391 	fsec = selinux_file(file);
4392 	if (sid != fsec->sid) {
4393 		rc = avc_has_perm(sid, fsec->sid, SECCLASS_FD, FD__USE, &ad);
4394 		if (rc)
4395 			return rc;
4396 	}
4397 
4398 	isec = inode_security(file_inode(file));
4399 	return avc_has_perm(sid, isec->sid, SECCLASS_SYSTEM, requested, &ad);
4400 }
4401 
4402 static int selinux_kernel_read_file(struct file *file,
4403 				    enum kernel_read_file_id id,
4404 				    bool contents)
4405 {
4406 	int rc = 0;
4407 
4408 	BUILD_BUG_ON_MSG(READING_MAX_ID > 8,
4409 			 "New kernel_read_file_id introduced; update SELinux!");
4410 
4411 	switch (id) {
4412 	case READING_FIRMWARE:
4413 		rc = selinux_kernel_load_from_file(file, SYSTEM__FIRMWARE_LOAD);
4414 		break;
4415 	case READING_MODULE:
4416 	case READING_MODULE_COMPRESSED:
4417 		rc = selinux_kernel_load_from_file(file, SYSTEM__MODULE_LOAD);
4418 		break;
4419 	case READING_KEXEC_IMAGE:
4420 		rc = selinux_kernel_load_from_file(file,
4421 						   SYSTEM__KEXEC_IMAGE_LOAD);
4422 		break;
4423 	case READING_KEXEC_INITRAMFS:
4424 		rc = selinux_kernel_load_from_file(file,
4425 						SYSTEM__KEXEC_INITRAMFS_LOAD);
4426 		break;
4427 	case READING_POLICY:
4428 		rc = selinux_kernel_load_from_file(file, SYSTEM__POLICY_LOAD);
4429 		break;
4430 	case READING_X509_CERTIFICATE:
4431 		rc = selinux_kernel_load_from_file(file,
4432 						SYSTEM__X509_CERTIFICATE_LOAD);
4433 		break;
4434 	default:
4435 		break;
4436 	}
4437 
4438 	return rc;
4439 }
4440 
4441 static int selinux_kernel_load_data(enum kernel_load_data_id id, bool contents)
4442 {
4443 	int rc = 0;
4444 
4445 	BUILD_BUG_ON_MSG(LOADING_MAX_ID > 8,
4446 			 "New kernel_load_data_id introduced; update SELinux!");
4447 
4448 	switch (id) {
4449 	case LOADING_FIRMWARE:
4450 		rc = selinux_kernel_load_from_file(NULL, SYSTEM__FIRMWARE_LOAD);
4451 		break;
4452 	case LOADING_MODULE:
4453 		rc = selinux_kernel_load_from_file(NULL, SYSTEM__MODULE_LOAD);
4454 		break;
4455 	case LOADING_KEXEC_IMAGE:
4456 		rc = selinux_kernel_load_from_file(NULL,
4457 						   SYSTEM__KEXEC_IMAGE_LOAD);
4458 		break;
4459 	case LOADING_KEXEC_INITRAMFS:
4460 		rc = selinux_kernel_load_from_file(NULL,
4461 						SYSTEM__KEXEC_INITRAMFS_LOAD);
4462 		break;
4463 	case LOADING_POLICY:
4464 		rc = selinux_kernel_load_from_file(NULL,
4465 						   SYSTEM__POLICY_LOAD);
4466 		break;
4467 	case LOADING_X509_CERTIFICATE:
4468 		rc = selinux_kernel_load_from_file(NULL,
4469 						SYSTEM__X509_CERTIFICATE_LOAD);
4470 		break;
4471 	default:
4472 		break;
4473 	}
4474 
4475 	return rc;
4476 }
4477 
4478 static int selinux_task_setpgid(struct task_struct *p, pid_t pgid)
4479 {
4480 	return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4481 			    PROCESS__SETPGID, NULL);
4482 }
4483 
4484 static int selinux_task_getpgid(struct task_struct *p)
4485 {
4486 	return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4487 			    PROCESS__GETPGID, NULL);
4488 }
4489 
4490 static int selinux_task_getsid(struct task_struct *p)
4491 {
4492 	return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4493 			    PROCESS__GETSESSION, NULL);
4494 }
4495 
4496 static void selinux_current_getlsmprop_subj(struct lsm_prop *prop)
4497 {
4498 	prop->selinux.secid = current_sid();
4499 }
4500 
4501 static void selinux_task_getlsmprop_obj(struct task_struct *p,
4502 					struct lsm_prop *prop)
4503 {
4504 	prop->selinux.secid = task_sid_obj(p);
4505 }
4506 
4507 static int selinux_task_setnice(struct task_struct *p, int nice)
4508 {
4509 	return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4510 			    PROCESS__SETSCHED, NULL);
4511 }
4512 
4513 static int selinux_task_setioprio(struct task_struct *p, int ioprio)
4514 {
4515 	return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4516 			    PROCESS__SETSCHED, NULL);
4517 }
4518 
4519 static int selinux_task_getioprio(struct task_struct *p)
4520 {
4521 	return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4522 			    PROCESS__GETSCHED, NULL);
4523 }
4524 
4525 static int selinux_task_prlimit(const struct cred *cred, const struct cred *tcred,
4526 				unsigned int flags)
4527 {
4528 	u32 av = 0;
4529 
4530 	if (!flags)
4531 		return 0;
4532 	if (flags & LSM_PRLIMIT_WRITE)
4533 		av |= PROCESS__SETRLIMIT;
4534 	if (flags & LSM_PRLIMIT_READ)
4535 		av |= PROCESS__GETRLIMIT;
4536 	return avc_has_perm(cred_sid(cred), cred_sid(tcred),
4537 			    SECCLASS_PROCESS, av, NULL);
4538 }
4539 
4540 static int selinux_task_setrlimit(struct task_struct *p, unsigned int resource,
4541 		struct rlimit *new_rlim)
4542 {
4543 	struct rlimit *old_rlim = p->signal->rlim + resource;
4544 
4545 	/* Control the ability to change the hard limit (whether
4546 	   lowering or raising it), so that the hard limit can
4547 	   later be used as a safe reset point for the soft limit
4548 	   upon context transitions.  See selinux_bprm_committing_creds. */
4549 	if (old_rlim->rlim_max != new_rlim->rlim_max)
4550 		return avc_has_perm(current_sid(), task_sid_obj(p),
4551 				    SECCLASS_PROCESS, PROCESS__SETRLIMIT, NULL);
4552 
4553 	return 0;
4554 }
4555 
4556 static int selinux_task_setscheduler(struct task_struct *p)
4557 {
4558 	return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4559 			    PROCESS__SETSCHED, NULL);
4560 }
4561 
4562 static int selinux_task_getscheduler(struct task_struct *p)
4563 {
4564 	return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4565 			    PROCESS__GETSCHED, NULL);
4566 }
4567 
4568 static int selinux_task_movememory(struct task_struct *p)
4569 {
4570 	return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4571 			    PROCESS__SETSCHED, NULL);
4572 }
4573 
4574 static int selinux_task_kill(struct task_struct *p, struct kernel_siginfo *info,
4575 				int sig, const struct cred *cred)
4576 {
4577 	u32 secid;
4578 	u32 perm;
4579 
4580 	if (!sig)
4581 		perm = PROCESS__SIGNULL; /* null signal; existence test */
4582 	else
4583 		perm = signal_to_av(sig);
4584 	if (!cred)
4585 		secid = current_sid();
4586 	else
4587 		secid = cred_sid(cred);
4588 	return avc_has_perm(secid, task_sid_obj(p), SECCLASS_PROCESS, perm, NULL);
4589 }
4590 
4591 static void selinux_task_to_inode(struct task_struct *p,
4592 				  struct inode *inode)
4593 {
4594 	struct inode_security_struct *isec = selinux_inode(inode);
4595 	u32 sid = task_sid_obj(p);
4596 
4597 	spin_lock(&isec->lock);
4598 	isec->sclass = inode_mode_to_security_class(inode->i_mode);
4599 	isec->sid = sid;
4600 	isec->initialized = LABEL_INITIALIZED;
4601 	spin_unlock(&isec->lock);
4602 }
4603 
4604 static int selinux_userns_create(const struct cred *cred)
4605 {
4606 	u32 sid = current_sid();
4607 
4608 	return avc_has_perm(sid, sid, SECCLASS_USER_NAMESPACE,
4609 			USER_NAMESPACE__CREATE, NULL);
4610 }
4611 
4612 /* Returns error only if unable to parse addresses */
4613 static int selinux_parse_skb_ipv4(struct sk_buff *skb,
4614 			struct common_audit_data *ad, u8 *proto)
4615 {
4616 	int offset, ihlen, ret = -EINVAL;
4617 	struct iphdr _iph, *ih;
4618 
4619 	offset = skb_network_offset(skb);
4620 	ih = skb_header_pointer(skb, offset, sizeof(_iph), &_iph);
4621 	if (ih == NULL)
4622 		goto out;
4623 
4624 	ihlen = ih->ihl * 4;
4625 	if (ihlen < sizeof(_iph))
4626 		goto out;
4627 
4628 	ad->u.net->v4info.saddr = ih->saddr;
4629 	ad->u.net->v4info.daddr = ih->daddr;
4630 	ret = 0;
4631 
4632 	if (proto)
4633 		*proto = ih->protocol;
4634 
4635 	switch (ih->protocol) {
4636 	case IPPROTO_TCP: {
4637 		struct tcphdr _tcph, *th;
4638 
4639 		if (ntohs(ih->frag_off) & IP_OFFSET)
4640 			break;
4641 
4642 		offset += ihlen;
4643 		th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
4644 		if (th == NULL)
4645 			break;
4646 
4647 		ad->u.net->sport = th->source;
4648 		ad->u.net->dport = th->dest;
4649 		break;
4650 	}
4651 
4652 	case IPPROTO_UDP: {
4653 		struct udphdr _udph, *uh;
4654 
4655 		if (ntohs(ih->frag_off) & IP_OFFSET)
4656 			break;
4657 
4658 		offset += ihlen;
4659 		uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
4660 		if (uh == NULL)
4661 			break;
4662 
4663 		ad->u.net->sport = uh->source;
4664 		ad->u.net->dport = uh->dest;
4665 		break;
4666 	}
4667 
4668 #if IS_ENABLED(CONFIG_IP_SCTP)
4669 	case IPPROTO_SCTP: {
4670 		struct sctphdr _sctph, *sh;
4671 
4672 		if (ntohs(ih->frag_off) & IP_OFFSET)
4673 			break;
4674 
4675 		offset += ihlen;
4676 		sh = skb_header_pointer(skb, offset, sizeof(_sctph), &_sctph);
4677 		if (sh == NULL)
4678 			break;
4679 
4680 		ad->u.net->sport = sh->source;
4681 		ad->u.net->dport = sh->dest;
4682 		break;
4683 	}
4684 #endif
4685 	default:
4686 		break;
4687 	}
4688 out:
4689 	return ret;
4690 }
4691 
4692 #if IS_ENABLED(CONFIG_IPV6)
4693 
4694 /* Returns error only if unable to parse addresses */
4695 static int selinux_parse_skb_ipv6(struct sk_buff *skb,
4696 			struct common_audit_data *ad, u8 *proto)
4697 {
4698 	u8 nexthdr;
4699 	int ret = -EINVAL, offset;
4700 	struct ipv6hdr _ipv6h, *ip6;
4701 	__be16 frag_off;
4702 
4703 	offset = skb_network_offset(skb);
4704 	ip6 = skb_header_pointer(skb, offset, sizeof(_ipv6h), &_ipv6h);
4705 	if (ip6 == NULL)
4706 		goto out;
4707 
4708 	ad->u.net->v6info.saddr = ip6->saddr;
4709 	ad->u.net->v6info.daddr = ip6->daddr;
4710 	ret = 0;
4711 
4712 	nexthdr = ip6->nexthdr;
4713 	offset += sizeof(_ipv6h);
4714 	offset = ipv6_skip_exthdr(skb, offset, &nexthdr, &frag_off);
4715 	if (offset < 0)
4716 		goto out;
4717 
4718 	if (proto)
4719 		*proto = nexthdr;
4720 
4721 	switch (nexthdr) {
4722 	case IPPROTO_TCP: {
4723 		struct tcphdr _tcph, *th;
4724 
4725 		th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
4726 		if (th == NULL)
4727 			break;
4728 
4729 		ad->u.net->sport = th->source;
4730 		ad->u.net->dport = th->dest;
4731 		break;
4732 	}
4733 
4734 	case IPPROTO_UDP: {
4735 		struct udphdr _udph, *uh;
4736 
4737 		uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
4738 		if (uh == NULL)
4739 			break;
4740 
4741 		ad->u.net->sport = uh->source;
4742 		ad->u.net->dport = uh->dest;
4743 		break;
4744 	}
4745 
4746 #if IS_ENABLED(CONFIG_IP_SCTP)
4747 	case IPPROTO_SCTP: {
4748 		struct sctphdr _sctph, *sh;
4749 
4750 		sh = skb_header_pointer(skb, offset, sizeof(_sctph), &_sctph);
4751 		if (sh == NULL)
4752 			break;
4753 
4754 		ad->u.net->sport = sh->source;
4755 		ad->u.net->dport = sh->dest;
4756 		break;
4757 	}
4758 #endif
4759 	/* includes fragments */
4760 	default:
4761 		break;
4762 	}
4763 out:
4764 	return ret;
4765 }
4766 
4767 #endif /* IPV6 */
4768 
4769 static int selinux_parse_skb(struct sk_buff *skb, struct common_audit_data *ad,
4770 			     char **_addrp, int src, u8 *proto)
4771 {
4772 	char *addrp;
4773 	int ret;
4774 
4775 	switch (ad->u.net->family) {
4776 	case PF_INET:
4777 		ret = selinux_parse_skb_ipv4(skb, ad, proto);
4778 		if (ret)
4779 			goto parse_error;
4780 		addrp = (char *)(src ? &ad->u.net->v4info.saddr :
4781 				       &ad->u.net->v4info.daddr);
4782 		goto okay;
4783 
4784 #if IS_ENABLED(CONFIG_IPV6)
4785 	case PF_INET6:
4786 		ret = selinux_parse_skb_ipv6(skb, ad, proto);
4787 		if (ret)
4788 			goto parse_error;
4789 		addrp = (char *)(src ? &ad->u.net->v6info.saddr :
4790 				       &ad->u.net->v6info.daddr);
4791 		goto okay;
4792 #endif	/* IPV6 */
4793 	default:
4794 		addrp = NULL;
4795 		goto okay;
4796 	}
4797 
4798 parse_error:
4799 	pr_warn(
4800 	       "SELinux: failure in selinux_parse_skb(),"
4801 	       " unable to parse packet\n");
4802 	return ret;
4803 
4804 okay:
4805 	if (_addrp)
4806 		*_addrp = addrp;
4807 	return 0;
4808 }
4809 
4810 /**
4811  * selinux_skb_peerlbl_sid - Determine the peer label of a packet
4812  * @skb: the packet
4813  * @family: protocol family
4814  * @sid: the packet's peer label SID
4815  *
4816  * Description:
4817  * Check the various different forms of network peer labeling and determine
4818  * the peer label/SID for the packet; most of the magic actually occurs in
4819  * the security server function security_net_peersid_cmp().  The function
4820  * returns zero if the value in @sid is valid (although it may be SECSID_NULL)
4821  * or -EACCES if @sid is invalid due to inconsistencies with the different
4822  * peer labels.
4823  *
4824  */
4825 static int selinux_skb_peerlbl_sid(struct sk_buff *skb, u16 family, u32 *sid)
4826 {
4827 	int err;
4828 	u32 xfrm_sid;
4829 	u32 nlbl_sid;
4830 	u32 nlbl_type;
4831 
4832 	err = selinux_xfrm_skb_sid(skb, &xfrm_sid);
4833 	if (unlikely(err))
4834 		return -EACCES;
4835 	err = selinux_netlbl_skbuff_getsid(skb, family, &nlbl_type, &nlbl_sid);
4836 	if (unlikely(err))
4837 		return -EACCES;
4838 
4839 	err = security_net_peersid_resolve(nlbl_sid,
4840 					   nlbl_type, xfrm_sid, sid);
4841 	if (unlikely(err)) {
4842 		pr_warn(
4843 		       "SELinux: failure in selinux_skb_peerlbl_sid(),"
4844 		       " unable to determine packet's peer label\n");
4845 		return -EACCES;
4846 	}
4847 
4848 	return 0;
4849 }
4850 
4851 /**
4852  * selinux_conn_sid - Determine the child socket label for a connection
4853  * @sk_sid: the parent socket's SID
4854  * @skb_sid: the packet's SID
4855  * @conn_sid: the resulting connection SID
4856  *
4857  * If @skb_sid is valid then the user:role:type information from @sk_sid is
4858  * combined with the MLS information from @skb_sid in order to create
4859  * @conn_sid.  If @skb_sid is not valid then @conn_sid is simply a copy
4860  * of @sk_sid.  Returns zero on success, negative values on failure.
4861  *
4862  */
4863 static int selinux_conn_sid(u32 sk_sid, u32 skb_sid, u32 *conn_sid)
4864 {
4865 	int err = 0;
4866 
4867 	if (skb_sid != SECSID_NULL)
4868 		err = security_sid_mls_copy(sk_sid, skb_sid,
4869 					    conn_sid);
4870 	else
4871 		*conn_sid = sk_sid;
4872 
4873 	return err;
4874 }
4875 
4876 /* socket security operations */
4877 
4878 static int socket_sockcreate_sid(const struct cred_security_struct *crsec,
4879 				 u16 secclass, u32 *socksid)
4880 {
4881 	if (crsec->sockcreate_sid > SECSID_NULL) {
4882 		*socksid = crsec->sockcreate_sid;
4883 		return 0;
4884 	}
4885 
4886 	return security_transition_sid(crsec->sid, crsec->sid,
4887 				       secclass, NULL, socksid);
4888 }
4889 
4890 static bool sock_skip_has_perm(u32 sid)
4891 {
4892 	if (sid == SECINITSID_KERNEL)
4893 		return true;
4894 
4895 	/*
4896 	 * Before POLICYDB_CAP_USERSPACE_INITIAL_CONTEXT, sockets that
4897 	 * inherited the kernel context from early boot used to be skipped
4898 	 * here, so preserve that behavior unless the capability is set.
4899 	 *
4900 	 * By setting the capability the policy signals that it is ready
4901 	 * for this quirk to be fixed. Note that sockets created by a kernel
4902 	 * thread or a usermode helper executed without a transition will
4903 	 * still be skipped in this check regardless of the policycap
4904 	 * setting.
4905 	 */
4906 	if (!selinux_policycap_userspace_initial_context() &&
4907 	    sid == SECINITSID_INIT)
4908 		return true;
4909 	return false;
4910 }
4911 
4912 
4913 static int sock_has_perm(struct sock *sk, u32 perms)
4914 {
4915 	struct sk_security_struct *sksec = selinux_sock(sk);
4916 	struct common_audit_data ad;
4917 	struct lsm_network_audit net;
4918 
4919 	if (sock_skip_has_perm(sksec->sid))
4920 		return 0;
4921 
4922 	ad_net_init_from_sk(&ad, &net, sk);
4923 
4924 	return avc_has_perm(current_sid(), sksec->sid, sksec->sclass, perms,
4925 			    &ad);
4926 }
4927 
4928 static int selinux_socket_create(int family, int type,
4929 				 int protocol, int kern)
4930 {
4931 	const struct cred_security_struct *crsec = selinux_cred(current_cred());
4932 	u32 newsid;
4933 	u16 secclass;
4934 	int rc;
4935 
4936 	if (kern)
4937 		return 0;
4938 
4939 	secclass = socket_type_to_security_class(family, type, protocol);
4940 	rc = socket_sockcreate_sid(crsec, secclass, &newsid);
4941 	if (rc)
4942 		return rc;
4943 
4944 	return avc_has_perm(crsec->sid, newsid, secclass, SOCKET__CREATE, NULL);
4945 }
4946 
4947 static int selinux_socket_post_create(struct socket *sock, int family,
4948 				      int type, int protocol, int kern)
4949 {
4950 	const struct cred_security_struct *crsec = selinux_cred(current_cred());
4951 	struct inode_security_struct *isec = inode_security_novalidate(SOCK_INODE(sock));
4952 	struct sk_security_struct *sksec;
4953 	u16 sclass = socket_type_to_security_class(family, type, protocol);
4954 	u32 sid = SECINITSID_KERNEL;
4955 	int err = 0;
4956 
4957 	if (!kern) {
4958 		err = socket_sockcreate_sid(crsec, sclass, &sid);
4959 		if (err)
4960 			return err;
4961 	}
4962 
4963 	isec->sclass = sclass;
4964 	isec->sid = sid;
4965 	isec->initialized = LABEL_INITIALIZED;
4966 
4967 	if (sock->sk) {
4968 		sksec = selinux_sock(sock->sk);
4969 		sksec->sclass = sclass;
4970 		sksec->sid = sid;
4971 		/* Allows detection of the first association on this socket */
4972 		if (sksec->sclass == SECCLASS_SCTP_SOCKET)
4973 			sksec->sctp_assoc_state = SCTP_ASSOC_UNSET;
4974 
4975 		err = selinux_netlbl_socket_post_create(sock->sk, family);
4976 	}
4977 
4978 	return err;
4979 }
4980 
4981 static int selinux_socket_socketpair(struct socket *socka,
4982 				     struct socket *sockb)
4983 {
4984 	struct sk_security_struct *sksec_a = selinux_sock(socka->sk);
4985 	struct sk_security_struct *sksec_b = selinux_sock(sockb->sk);
4986 
4987 	sksec_a->peer_sid = sksec_b->sid;
4988 	sksec_b->peer_sid = sksec_a->sid;
4989 
4990 	return 0;
4991 }
4992 
4993 /* Range of port numbers used to automatically bind.
4994    Need to determine whether we should perform a name_bind
4995    permission check between the socket and the port number. */
4996 
4997 static int __selinux_socket_bind(struct sock *sk, struct sockaddr *address, int addrlen)
4998 {
4999 	struct sk_security_struct *sksec = selinux_sock(sk);
5000 	u16 family;
5001 	int err;
5002 
5003 	err = sock_has_perm(sk, SOCKET__BIND);
5004 	if (err)
5005 		goto out;
5006 
5007 	/* If PF_INET or PF_INET6, check name_bind permission for the port. */
5008 	family = sk->sk_family;
5009 	if (family == PF_INET || family == PF_INET6) {
5010 		char *addrp;
5011 		struct common_audit_data ad;
5012 		struct lsm_network_audit net = {0,};
5013 		struct sockaddr_in *addr4 = NULL;
5014 		struct sockaddr_in6 *addr6 = NULL;
5015 		u16 family_sa;
5016 		unsigned short snum;
5017 		u32 sid, node_perm;
5018 
5019 		/*
5020 		 * sctp_bindx(3) calls via selinux_sctp_bind_connect()
5021 		 * that validates multiple binding addresses. Because of this
5022 		 * need to check address->sa_family as it is possible to have
5023 		 * sk->sk_family = PF_INET6 with addr->sa_family = AF_INET.
5024 		 */
5025 		if (addrlen < offsetofend(struct sockaddr, sa_family))
5026 			return -EINVAL;
5027 		family_sa = address->sa_family;
5028 		switch (family_sa) {
5029 		case AF_UNSPEC:
5030 		case AF_INET:
5031 			if (addrlen < sizeof(struct sockaddr_in))
5032 				return -EINVAL;
5033 			addr4 = (struct sockaddr_in *)address;
5034 			if (family_sa == AF_UNSPEC) {
5035 				if (family == PF_INET6) {
5036 					/* Length check from inet6_bind_sk() */
5037 					if (addrlen < SIN6_LEN_RFC2133)
5038 						return -EINVAL;
5039 					/* Family check from __inet6_bind() */
5040 					goto err_af;
5041 				}
5042 				/* see __inet_bind(), we only want to allow
5043 				 * AF_UNSPEC if the address is INADDR_ANY
5044 				 */
5045 				if (addr4->sin_addr.s_addr != htonl(INADDR_ANY))
5046 					goto err_af;
5047 				family_sa = AF_INET;
5048 			}
5049 			snum = ntohs(addr4->sin_port);
5050 			addrp = (char *)&addr4->sin_addr.s_addr;
5051 			break;
5052 		case AF_INET6:
5053 			if (addrlen < SIN6_LEN_RFC2133)
5054 				return -EINVAL;
5055 			addr6 = (struct sockaddr_in6 *)address;
5056 			snum = ntohs(addr6->sin6_port);
5057 			addrp = (char *)&addr6->sin6_addr.s6_addr;
5058 			break;
5059 		default:
5060 			goto err_af;
5061 		}
5062 
5063 		ad.type = LSM_AUDIT_DATA_NET;
5064 		ad.u.net = &net;
5065 		ad.u.net->sport = htons(snum);
5066 		ad.u.net->family = family_sa;
5067 
5068 		if (snum) {
5069 			int low, high;
5070 
5071 			inet_get_local_port_range(sock_net(sk), &low, &high);
5072 
5073 			if (inet_port_requires_bind_service(sock_net(sk), snum) ||
5074 			    snum < low || snum > high) {
5075 				err = sel_netport_sid(sk->sk_protocol,
5076 						      snum, &sid);
5077 				if (err)
5078 					goto out;
5079 				err = avc_has_perm(sksec->sid, sid,
5080 						   sksec->sclass,
5081 						   SOCKET__NAME_BIND, &ad);
5082 				if (err)
5083 					goto out;
5084 			}
5085 		}
5086 
5087 		switch (sksec->sclass) {
5088 		case SECCLASS_TCP_SOCKET:
5089 			node_perm = TCP_SOCKET__NODE_BIND;
5090 			break;
5091 
5092 		case SECCLASS_UDP_SOCKET:
5093 			node_perm = UDP_SOCKET__NODE_BIND;
5094 			break;
5095 
5096 		case SECCLASS_SCTP_SOCKET:
5097 			node_perm = SCTP_SOCKET__NODE_BIND;
5098 			break;
5099 
5100 		default:
5101 			node_perm = RAWIP_SOCKET__NODE_BIND;
5102 			break;
5103 		}
5104 
5105 		err = sel_netnode_sid(addrp, family_sa, &sid);
5106 		if (err)
5107 			goto out;
5108 
5109 		if (family_sa == AF_INET)
5110 			ad.u.net->v4info.saddr = addr4->sin_addr.s_addr;
5111 		else
5112 			ad.u.net->v6info.saddr = addr6->sin6_addr;
5113 
5114 		err = avc_has_perm(sksec->sid, sid,
5115 				   sksec->sclass, node_perm, &ad);
5116 		if (err)
5117 			goto out;
5118 	}
5119 out:
5120 	return err;
5121 err_af:
5122 	/* Note that SCTP services expect -EINVAL, others -EAFNOSUPPORT. */
5123 	if (sk->sk_protocol == IPPROTO_SCTP)
5124 		return -EINVAL;
5125 	return -EAFNOSUPPORT;
5126 }
5127 
5128 static int selinux_socket_bind(struct socket *sock, struct sockaddr *address, int addrlen)
5129 {
5130 	return __selinux_socket_bind(sock->sk, address, addrlen);
5131 }
5132 
5133 /* This supports connect(2) and SCTP connect services such as sctp_connectx(3)
5134  * and sctp_sendmsg(3) as described in Documentation/security/SCTP.rst
5135  */
5136 static int selinux_socket_connect_helper(struct sock *sk,
5137 					 struct sockaddr *address, int addrlen)
5138 {
5139 	struct sk_security_struct *sksec = selinux_sock(sk);
5140 	int err;
5141 
5142 	err = sock_has_perm(sk, SOCKET__CONNECT);
5143 	if (err)
5144 		return err;
5145 	if (addrlen < offsetofend(struct sockaddr, sa_family))
5146 		return -EINVAL;
5147 
5148 	/* connect(AF_UNSPEC) has special handling, as it is a documented
5149 	 * way to disconnect the socket
5150 	 */
5151 	if (address->sa_family == AF_UNSPEC)
5152 		return 0;
5153 
5154 	/*
5155 	 * If a TCP or SCTP socket, check name_connect permission
5156 	 * for the port.
5157 	 */
5158 	if (sksec->sclass == SECCLASS_TCP_SOCKET ||
5159 	    sksec->sclass == SECCLASS_SCTP_SOCKET) {
5160 		struct common_audit_data ad;
5161 		struct lsm_network_audit net = {0,};
5162 		struct sockaddr_in *addr4 = NULL;
5163 		struct sockaddr_in6 *addr6 = NULL;
5164 		unsigned short snum;
5165 		u32 sid, perm;
5166 
5167 		/* sctp_connectx(3) calls via selinux_sctp_bind_connect()
5168 		 * that validates multiple connect addresses. Because of this
5169 		 * need to check address->sa_family as it is possible to have
5170 		 * sk->sk_family = PF_INET6 with addr->sa_family = AF_INET.
5171 		 */
5172 		switch (address->sa_family) {
5173 		case AF_INET:
5174 			addr4 = (struct sockaddr_in *)address;
5175 			if (addrlen < sizeof(struct sockaddr_in))
5176 				return -EINVAL;
5177 			snum = ntohs(addr4->sin_port);
5178 			break;
5179 		case AF_INET6:
5180 			addr6 = (struct sockaddr_in6 *)address;
5181 			if (addrlen < SIN6_LEN_RFC2133)
5182 				return -EINVAL;
5183 			snum = ntohs(addr6->sin6_port);
5184 			break;
5185 		default:
5186 			/* Note that SCTP services expect -EINVAL, whereas
5187 			 * others expect -EAFNOSUPPORT.
5188 			 */
5189 			if (sksec->sclass == SECCLASS_SCTP_SOCKET)
5190 				return -EINVAL;
5191 			else
5192 				return -EAFNOSUPPORT;
5193 		}
5194 
5195 		err = sel_netport_sid(sk->sk_protocol, snum, &sid);
5196 		if (err)
5197 			return err;
5198 
5199 		switch (sksec->sclass) {
5200 		case SECCLASS_TCP_SOCKET:
5201 			perm = TCP_SOCKET__NAME_CONNECT;
5202 			break;
5203 		case SECCLASS_SCTP_SOCKET:
5204 			perm = SCTP_SOCKET__NAME_CONNECT;
5205 			break;
5206 		}
5207 
5208 		ad.type = LSM_AUDIT_DATA_NET;
5209 		ad.u.net = &net;
5210 		ad.u.net->dport = htons(snum);
5211 		ad.u.net->family = address->sa_family;
5212 		err = avc_has_perm(sksec->sid, sid, sksec->sclass, perm, &ad);
5213 		if (err)
5214 			return err;
5215 	}
5216 
5217 	return 0;
5218 }
5219 
5220 /* Supports connect(2), see comments in selinux_socket_connect_helper() */
5221 static int selinux_socket_connect(struct socket *sock,
5222 				  struct sockaddr *address, int addrlen)
5223 {
5224 	int err;
5225 	struct sock *sk = sock->sk;
5226 
5227 	err = selinux_socket_connect_helper(sk, address, addrlen);
5228 	if (err)
5229 		return err;
5230 
5231 	return selinux_netlbl_socket_connect(sk, address);
5232 }
5233 
5234 static int selinux_socket_listen(struct socket *sock, int backlog)
5235 {
5236 	return sock_has_perm(sock->sk, SOCKET__LISTEN);
5237 }
5238 
5239 static int selinux_socket_accept(struct socket *sock, struct socket *newsock)
5240 {
5241 	int err;
5242 	struct inode_security_struct *isec;
5243 	struct inode_security_struct *newisec;
5244 	u16 sclass;
5245 	u32 sid;
5246 
5247 	err = sock_has_perm(sock->sk, SOCKET__ACCEPT);
5248 	if (err)
5249 		return err;
5250 
5251 	isec = inode_security_novalidate(SOCK_INODE(sock));
5252 	spin_lock(&isec->lock);
5253 	sclass = isec->sclass;
5254 	sid = isec->sid;
5255 	spin_unlock(&isec->lock);
5256 
5257 	newisec = inode_security_novalidate(SOCK_INODE(newsock));
5258 	newisec->sclass = sclass;
5259 	newisec->sid = sid;
5260 	newisec->initialized = LABEL_INITIALIZED;
5261 
5262 	return 0;
5263 }
5264 
5265 static int selinux_socket_sendmsg(struct socket *sock, struct msghdr *msg,
5266 				  int size)
5267 {
5268 	int rc;
5269 	struct sockaddr *const addr = msg->msg_name;
5270 	const int addrlen = msg->msg_namelen;
5271 
5272 	rc = sock_has_perm(sock->sk, SOCKET__WRITE);
5273 	if (rc)
5274 		return rc;
5275 
5276 	if (addr && (msg->msg_flags & MSG_FASTOPEN) &&
5277 	    (sk_is_tcp(sock->sk) ||
5278 	     (sk_is_inet(sock->sk) && sock->sk->sk_type == SOCK_STREAM &&
5279 	      sock->sk->sk_protocol == IPPROTO_MPTCP))) {
5280 		rc = selinux_socket_connect(sock, addr, addrlen);
5281 		if (rc)
5282 			return rc;
5283 	}
5284 
5285 	return 0;
5286 }
5287 
5288 static int selinux_socket_recvmsg(struct socket *sock, struct msghdr *msg,
5289 				  int size, int flags)
5290 {
5291 	return sock_has_perm(sock->sk, SOCKET__READ);
5292 }
5293 
5294 static int selinux_socket_getsockname(struct socket *sock)
5295 {
5296 	return sock_has_perm(sock->sk, SOCKET__GETATTR);
5297 }
5298 
5299 static int selinux_socket_getpeername(struct socket *sock)
5300 {
5301 	return sock_has_perm(sock->sk, SOCKET__GETATTR);
5302 }
5303 
5304 static int selinux_socket_setsockopt(struct socket *sock, int level, int optname)
5305 {
5306 	int err;
5307 
5308 	err = sock_has_perm(sock->sk, SOCKET__SETOPT);
5309 	if (err)
5310 		return err;
5311 
5312 	return selinux_netlbl_socket_setsockopt(sock, level, optname);
5313 }
5314 
5315 static int selinux_socket_getsockopt(struct socket *sock, int level,
5316 				     int optname)
5317 {
5318 	return sock_has_perm(sock->sk, SOCKET__GETOPT);
5319 }
5320 
5321 static int selinux_socket_shutdown(struct socket *sock, int how)
5322 {
5323 	return sock_has_perm(sock->sk, SOCKET__SHUTDOWN);
5324 }
5325 
5326 static int selinux_socket_unix_stream_connect(struct sock *sock,
5327 					      struct sock *other,
5328 					      struct sock *newsk)
5329 {
5330 	struct sk_security_struct *sksec_sock = selinux_sock(sock);
5331 	struct sk_security_struct *sksec_other = selinux_sock(other);
5332 	struct sk_security_struct *sksec_new = selinux_sock(newsk);
5333 	struct common_audit_data ad;
5334 	struct lsm_network_audit net;
5335 	int err;
5336 
5337 	ad_net_init_from_sk(&ad, &net, other);
5338 
5339 	err = avc_has_perm(sksec_sock->sid, sksec_other->sid,
5340 			   sksec_other->sclass,
5341 			   UNIX_STREAM_SOCKET__CONNECTTO, &ad);
5342 	if (err)
5343 		return err;
5344 
5345 	/* server child socket */
5346 	sksec_new->peer_sid = sksec_sock->sid;
5347 	err = security_sid_mls_copy(sksec_other->sid,
5348 				    sksec_sock->sid, &sksec_new->sid);
5349 	if (err)
5350 		return err;
5351 
5352 	/* connecting socket */
5353 	sksec_sock->peer_sid = sksec_new->sid;
5354 
5355 	return 0;
5356 }
5357 
5358 static int selinux_socket_unix_may_send(struct socket *sock,
5359 					struct socket *other)
5360 {
5361 	struct sk_security_struct *ssec = selinux_sock(sock->sk);
5362 	struct sk_security_struct *osec = selinux_sock(other->sk);
5363 	struct common_audit_data ad;
5364 	struct lsm_network_audit net;
5365 
5366 	ad_net_init_from_sk(&ad, &net, other->sk);
5367 
5368 	return avc_has_perm(ssec->sid, osec->sid, osec->sclass, SOCKET__SENDTO,
5369 			    &ad);
5370 }
5371 
5372 static int selinux_inet_sys_rcv_skb(struct net *ns, int ifindex,
5373 				    char *addrp, u16 family, u32 peer_sid,
5374 				    struct common_audit_data *ad)
5375 {
5376 	int err;
5377 	u32 if_sid;
5378 	u32 node_sid;
5379 
5380 	err = sel_netif_sid(ns, ifindex, &if_sid);
5381 	if (err)
5382 		return err;
5383 	err = avc_has_perm(peer_sid, if_sid,
5384 			   SECCLASS_NETIF, NETIF__INGRESS, ad);
5385 	if (err)
5386 		return err;
5387 
5388 	err = sel_netnode_sid(addrp, family, &node_sid);
5389 	if (err)
5390 		return err;
5391 	return avc_has_perm(peer_sid, node_sid,
5392 			    SECCLASS_NODE, NODE__RECVFROM, ad);
5393 }
5394 
5395 static int selinux_sock_rcv_skb_compat(struct sock *sk, struct sk_buff *skb,
5396 				       u16 family)
5397 {
5398 	int err = 0;
5399 	struct sk_security_struct *sksec = selinux_sock(sk);
5400 	u32 sk_sid = sksec->sid;
5401 	struct common_audit_data ad;
5402 	struct lsm_network_audit net;
5403 	char *addrp;
5404 
5405 	ad_net_init_from_iif(&ad, &net, skb->skb_iif, family);
5406 	err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
5407 	if (err)
5408 		return err;
5409 
5410 	if (selinux_secmark_enabled()) {
5411 		err = avc_has_perm(sk_sid, skb->secmark, SECCLASS_PACKET,
5412 				   PACKET__RECV, &ad);
5413 		if (err)
5414 			return err;
5415 	}
5416 
5417 	err = selinux_netlbl_sock_rcv_skb(sksec, skb, family, &ad);
5418 	if (err)
5419 		return err;
5420 	err = selinux_xfrm_sock_rcv_skb(sksec->sid, skb, &ad);
5421 
5422 	return err;
5423 }
5424 
5425 static int selinux_socket_sock_rcv_skb(struct sock *sk, struct sk_buff *skb)
5426 {
5427 	int err, peerlbl_active, secmark_active;
5428 	struct sk_security_struct *sksec = selinux_sock(sk);
5429 	u16 family = sk->sk_family;
5430 	u32 sk_sid = sksec->sid;
5431 	struct common_audit_data ad;
5432 	struct lsm_network_audit net;
5433 	char *addrp;
5434 
5435 	if (family != PF_INET && family != PF_INET6)
5436 		return 0;
5437 
5438 	/* Handle mapped IPv4 packets arriving via IPv6 sockets */
5439 	if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
5440 		family = PF_INET;
5441 
5442 	/* If any sort of compatibility mode is enabled then handoff processing
5443 	 * to the selinux_sock_rcv_skb_compat() function to deal with the
5444 	 * special handling.  We do this in an attempt to keep this function
5445 	 * as fast and as clean as possible. */
5446 	if (!selinux_policycap_netpeer())
5447 		return selinux_sock_rcv_skb_compat(sk, skb, family);
5448 
5449 	secmark_active = selinux_secmark_enabled();
5450 	peerlbl_active = selinux_peerlbl_enabled();
5451 	if (!secmark_active && !peerlbl_active)
5452 		return 0;
5453 
5454 	ad_net_init_from_iif(&ad, &net, skb->skb_iif, family);
5455 	err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
5456 	if (err)
5457 		return err;
5458 
5459 	if (peerlbl_active) {
5460 		u32 peer_sid;
5461 
5462 		err = selinux_skb_peerlbl_sid(skb, family, &peer_sid);
5463 		if (err)
5464 			return err;
5465 		err = selinux_inet_sys_rcv_skb(sock_net(sk), skb->skb_iif,
5466 					       addrp, family, peer_sid, &ad);
5467 		if (err) {
5468 			selinux_netlbl_err(skb, family, err, 0);
5469 			return err;
5470 		}
5471 		err = avc_has_perm(sk_sid, peer_sid, SECCLASS_PEER,
5472 				   PEER__RECV, &ad);
5473 		if (err) {
5474 			selinux_netlbl_err(skb, family, err, 0);
5475 			return err;
5476 		}
5477 	}
5478 
5479 	if (secmark_active) {
5480 		err = avc_has_perm(sk_sid, skb->secmark, SECCLASS_PACKET,
5481 				   PACKET__RECV, &ad);
5482 		if (err)
5483 			return err;
5484 	}
5485 
5486 	return err;
5487 }
5488 
5489 static int selinux_socket_getpeersec_stream(struct socket *sock,
5490 					    sockptr_t optval, sockptr_t optlen,
5491 					    unsigned int len)
5492 {
5493 	int err = 0;
5494 	char *scontext = NULL;
5495 	u32 scontext_len;
5496 	struct sk_security_struct *sksec = selinux_sock(sock->sk);
5497 	u32 peer_sid = SECSID_NULL;
5498 
5499 	if (sksec->sclass == SECCLASS_UNIX_STREAM_SOCKET ||
5500 	    sksec->sclass == SECCLASS_TCP_SOCKET ||
5501 	    sksec->sclass == SECCLASS_SCTP_SOCKET)
5502 		peer_sid = sksec->peer_sid;
5503 	if (peer_sid == SECSID_NULL)
5504 		return -ENOPROTOOPT;
5505 
5506 	err = security_sid_to_context(peer_sid, &scontext,
5507 				      &scontext_len);
5508 	if (err)
5509 		return err;
5510 	if (scontext_len > len) {
5511 		err = -ERANGE;
5512 		goto out_len;
5513 	}
5514 
5515 	if (copy_to_sockptr(optval, scontext, scontext_len))
5516 		err = -EFAULT;
5517 out_len:
5518 	if (copy_to_sockptr(optlen, &scontext_len, sizeof(scontext_len)))
5519 		err = -EFAULT;
5520 	kfree(scontext);
5521 	return err;
5522 }
5523 
5524 static int selinux_socket_getpeersec_dgram(struct socket *sock,
5525 					   struct sk_buff *skb, u32 *secid)
5526 {
5527 	u32 peer_secid = SECSID_NULL;
5528 	u16 family;
5529 
5530 	if (skb && skb->protocol == htons(ETH_P_IP))
5531 		family = PF_INET;
5532 	else if (skb && skb->protocol == htons(ETH_P_IPV6))
5533 		family = PF_INET6;
5534 	else if (sock)
5535 		family = sock->sk->sk_family;
5536 	else {
5537 		*secid = SECSID_NULL;
5538 		return -EINVAL;
5539 	}
5540 
5541 	if (sock && family == PF_UNIX) {
5542 		struct inode_security_struct *isec;
5543 		isec = inode_security_novalidate(SOCK_INODE(sock));
5544 		peer_secid = isec->sid;
5545 	} else if (skb)
5546 		selinux_skb_peerlbl_sid(skb, family, &peer_secid);
5547 
5548 	*secid = peer_secid;
5549 	if (peer_secid == SECSID_NULL)
5550 		return -ENOPROTOOPT;
5551 	return 0;
5552 }
5553 
5554 static int selinux_sk_alloc_security(struct sock *sk, int family, gfp_t priority)
5555 {
5556 	struct sk_security_struct *sksec = selinux_sock(sk);
5557 
5558 	sksec->peer_sid = SECINITSID_UNLABELED;
5559 	sksec->sid = SECINITSID_UNLABELED;
5560 	sksec->sclass = SECCLASS_SOCKET;
5561 	selinux_netlbl_sk_security_reset(sksec);
5562 
5563 	return 0;
5564 }
5565 
5566 static void selinux_sk_free_security(struct sock *sk)
5567 {
5568 	struct sk_security_struct *sksec = selinux_sock(sk);
5569 
5570 	selinux_netlbl_sk_security_free(sksec);
5571 }
5572 
5573 static void selinux_sk_clone_security(const struct sock *sk, struct sock *newsk)
5574 {
5575 	struct sk_security_struct *sksec = selinux_sock(sk);
5576 	struct sk_security_struct *newsksec = selinux_sock(newsk);
5577 
5578 	newsksec->sid = sksec->sid;
5579 	newsksec->peer_sid = sksec->peer_sid;
5580 	newsksec->sclass = sksec->sclass;
5581 
5582 	selinux_netlbl_sk_security_reset(newsksec);
5583 }
5584 
5585 static void selinux_sk_getsecid(const struct sock *sk, u32 *secid)
5586 {
5587 	if (!sk)
5588 		*secid = SECINITSID_ANY_SOCKET;
5589 	else {
5590 		const struct sk_security_struct *sksec = selinux_sock(sk);
5591 
5592 		*secid = sksec->sid;
5593 	}
5594 }
5595 
5596 static void selinux_sock_graft(struct sock *sk, struct socket *parent)
5597 {
5598 	struct inode_security_struct *isec =
5599 		inode_security_novalidate(SOCK_INODE(parent));
5600 	struct sk_security_struct *sksec = selinux_sock(sk);
5601 
5602 	if (sk->sk_family == PF_INET || sk->sk_family == PF_INET6 ||
5603 	    sk->sk_family == PF_UNIX)
5604 		isec->sid = sksec->sid;
5605 	sksec->sclass = isec->sclass;
5606 }
5607 
5608 /*
5609  * Determines peer_secid for the asoc and updates socket's peer label
5610  * if it's the first association on the socket.
5611  */
5612 static int selinux_sctp_process_new_assoc(struct sctp_association *asoc,
5613 					  struct sk_buff *skb)
5614 {
5615 	struct sock *sk = asoc->base.sk;
5616 	u16 family = sk->sk_family;
5617 	struct sk_security_struct *sksec = selinux_sock(sk);
5618 	struct common_audit_data ad;
5619 	struct lsm_network_audit net;
5620 	int err;
5621 
5622 	/* handle mapped IPv4 packets arriving via IPv6 sockets */
5623 	if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
5624 		family = PF_INET;
5625 
5626 	if (selinux_peerlbl_enabled()) {
5627 		asoc->peer_secid = SECSID_NULL;
5628 
5629 		/* This will return peer_sid = SECSID_NULL if there are
5630 		 * no peer labels, see security_net_peersid_resolve().
5631 		 */
5632 		err = selinux_skb_peerlbl_sid(skb, family, &asoc->peer_secid);
5633 		if (err)
5634 			return err;
5635 
5636 		if (asoc->peer_secid == SECSID_NULL)
5637 			asoc->peer_secid = SECINITSID_UNLABELED;
5638 	} else {
5639 		asoc->peer_secid = SECINITSID_UNLABELED;
5640 	}
5641 
5642 	if (sksec->sctp_assoc_state == SCTP_ASSOC_UNSET) {
5643 		sksec->sctp_assoc_state = SCTP_ASSOC_SET;
5644 
5645 		/* Here as first association on socket. As the peer SID
5646 		 * was allowed by peer recv (and the netif/node checks),
5647 		 * then it is approved by policy and used as the primary
5648 		 * peer SID for getpeercon(3).
5649 		 */
5650 		sksec->peer_sid = asoc->peer_secid;
5651 	} else if (sksec->peer_sid != asoc->peer_secid) {
5652 		/* Other association peer SIDs are checked to enforce
5653 		 * consistency among the peer SIDs.
5654 		 */
5655 		ad_net_init_from_sk(&ad, &net, asoc->base.sk);
5656 		err = avc_has_perm(sksec->peer_sid, asoc->peer_secid,
5657 				   sksec->sclass, SCTP_SOCKET__ASSOCIATION,
5658 				   &ad);
5659 		if (err)
5660 			return err;
5661 	}
5662 	return 0;
5663 }
5664 
5665 /* Called whenever SCTP receives an INIT or COOKIE ECHO chunk. This
5666  * happens on an incoming connect(2), sctp_connectx(3) or
5667  * sctp_sendmsg(3) (with no association already present).
5668  */
5669 static int selinux_sctp_assoc_request(struct sctp_association *asoc,
5670 				      struct sk_buff *skb)
5671 {
5672 	struct sk_security_struct *sksec = selinux_sock(asoc->base.sk);
5673 	u32 conn_sid;
5674 	int err;
5675 
5676 	if (!selinux_policycap_extsockclass())
5677 		return 0;
5678 
5679 	err = selinux_sctp_process_new_assoc(asoc, skb);
5680 	if (err)
5681 		return err;
5682 
5683 	/* Compute the MLS component for the connection and store
5684 	 * the information in asoc. This will be used by SCTP TCP type
5685 	 * sockets and peeled off connections as they cause a new
5686 	 * socket to be generated. selinux_sctp_sk_clone() will then
5687 	 * plug this into the new socket.
5688 	 */
5689 	err = selinux_conn_sid(sksec->sid, asoc->peer_secid, &conn_sid);
5690 	if (err)
5691 		return err;
5692 
5693 	asoc->secid = conn_sid;
5694 
5695 	/* Set any NetLabel labels including CIPSO/CALIPSO options. */
5696 	return selinux_netlbl_sctp_assoc_request(asoc, skb);
5697 }
5698 
5699 /* Called when SCTP receives a COOKIE ACK chunk as the final
5700  * response to an association request (initited by us).
5701  */
5702 static int selinux_sctp_assoc_established(struct sctp_association *asoc,
5703 					  struct sk_buff *skb)
5704 {
5705 	struct sk_security_struct *sksec = selinux_sock(asoc->base.sk);
5706 
5707 	if (!selinux_policycap_extsockclass())
5708 		return 0;
5709 
5710 	/* Inherit secid from the parent socket - this will be picked up
5711 	 * by selinux_sctp_sk_clone() if the association gets peeled off
5712 	 * into a new socket.
5713 	 */
5714 	asoc->secid = sksec->sid;
5715 
5716 	return selinux_sctp_process_new_assoc(asoc, skb);
5717 }
5718 
5719 /* Check if sctp IPv4/IPv6 addresses are valid for binding or connecting
5720  * based on their @optname.
5721  */
5722 static int selinux_sctp_bind_connect(struct sock *sk, int optname,
5723 				     struct sockaddr *address,
5724 				     int addrlen)
5725 {
5726 	int len, err = 0, walk_size = 0;
5727 	void *addr_buf;
5728 	struct sockaddr *addr;
5729 
5730 	if (!selinux_policycap_extsockclass())
5731 		return 0;
5732 
5733 	/* Process one or more addresses that may be IPv4 or IPv6 */
5734 	addr_buf = address;
5735 
5736 	while (walk_size < addrlen) {
5737 		if (walk_size + sizeof(sa_family_t) > addrlen)
5738 			return -EINVAL;
5739 
5740 		addr = addr_buf;
5741 		switch (addr->sa_family) {
5742 		case AF_UNSPEC:
5743 		case AF_INET:
5744 			len = sizeof(struct sockaddr_in);
5745 			break;
5746 		case AF_INET6:
5747 			len = sizeof(struct sockaddr_in6);
5748 			break;
5749 		default:
5750 			return -EINVAL;
5751 		}
5752 
5753 		if (walk_size + len > addrlen)
5754 			return -EINVAL;
5755 
5756 		err = -EINVAL;
5757 		switch (optname) {
5758 		/* Bind checks */
5759 		case SCTP_PRIMARY_ADDR:
5760 		case SCTP_SET_PEER_PRIMARY_ADDR:
5761 		case SCTP_SOCKOPT_BINDX_ADD:
5762 			err = __selinux_socket_bind(sk, addr, len);
5763 			break;
5764 		/* Connect checks */
5765 		case SCTP_SOCKOPT_CONNECTX:
5766 		case SCTP_PARAM_SET_PRIMARY:
5767 		case SCTP_PARAM_ADD_IP:
5768 		case SCTP_SENDMSG_CONNECT:
5769 			err = selinux_socket_connect_helper(sk, addr, len);
5770 			if (err)
5771 				return err;
5772 
5773 			/* As selinux_sctp_bind_connect() is called by the
5774 			 * SCTP protocol layer, the socket is already locked,
5775 			 * therefore selinux_netlbl_socket_connect_locked()
5776 			 * is called here. The situations handled are:
5777 			 * sctp_connectx(3), sctp_sendmsg(3), sendmsg(2),
5778 			 * whenever a new IP address is added or when a new
5779 			 * primary address is selected.
5780 			 * Note that an SCTP connect(2) call happens before
5781 			 * the SCTP protocol layer and is handled via
5782 			 * selinux_socket_connect().
5783 			 */
5784 			err = selinux_netlbl_socket_connect_locked(sk, addr);
5785 			break;
5786 		}
5787 
5788 		if (err)
5789 			return err;
5790 
5791 		addr_buf += len;
5792 		walk_size += len;
5793 	}
5794 
5795 	return 0;
5796 }
5797 
5798 /* Called whenever a new socket is created by accept(2) or sctp_peeloff(3). */
5799 static void selinux_sctp_sk_clone(struct sctp_association *asoc, struct sock *sk,
5800 				  struct sock *newsk)
5801 {
5802 	struct sk_security_struct *sksec = selinux_sock(sk);
5803 	struct sk_security_struct *newsksec = selinux_sock(newsk);
5804 
5805 	/* If policy does not support SECCLASS_SCTP_SOCKET then call
5806 	 * the non-sctp clone version.
5807 	 */
5808 	if (!selinux_policycap_extsockclass())
5809 		return selinux_sk_clone_security(sk, newsk);
5810 
5811 	newsksec->sid = asoc->secid;
5812 	newsksec->peer_sid = asoc->peer_secid;
5813 	newsksec->sclass = sksec->sclass;
5814 	selinux_netlbl_sctp_sk_clone(sk, newsk);
5815 }
5816 
5817 static int selinux_mptcp_add_subflow(struct sock *sk, struct sock *ssk)
5818 {
5819 	struct sk_security_struct *ssksec = selinux_sock(ssk);
5820 	struct sk_security_struct *sksec = selinux_sock(sk);
5821 
5822 	ssksec->sclass = sksec->sclass;
5823 	ssksec->sid = sksec->sid;
5824 
5825 	/* replace the existing subflow label deleting the existing one
5826 	 * and re-recreating a new label using the updated context
5827 	 */
5828 	selinux_netlbl_sk_security_free(ssksec);
5829 	return selinux_netlbl_socket_post_create(ssk, ssk->sk_family);
5830 }
5831 
5832 static int selinux_inet_conn_request(const struct sock *sk, struct sk_buff *skb,
5833 				     struct request_sock *req)
5834 {
5835 	struct sk_security_struct *sksec = selinux_sock(sk);
5836 	int err;
5837 	u16 family = req->rsk_ops->family;
5838 	u32 connsid;
5839 	u32 peersid;
5840 
5841 	err = selinux_skb_peerlbl_sid(skb, family, &peersid);
5842 	if (err)
5843 		return err;
5844 	err = selinux_conn_sid(sksec->sid, peersid, &connsid);
5845 	if (err)
5846 		return err;
5847 	req->secid = connsid;
5848 	req->peer_secid = peersid;
5849 
5850 	return selinux_netlbl_inet_conn_request(req, family);
5851 }
5852 
5853 static void selinux_inet_csk_clone(struct sock *newsk,
5854 				   const struct request_sock *req)
5855 {
5856 	struct sk_security_struct *newsksec = selinux_sock(newsk);
5857 
5858 	newsksec->sid = req->secid;
5859 	newsksec->peer_sid = req->peer_secid;
5860 	/* NOTE: Ideally, we should also get the isec->sid for the
5861 	   new socket in sync, but we don't have the isec available yet.
5862 	   So we will wait until sock_graft to do it, by which
5863 	   time it will have been created and available. */
5864 
5865 	/* We don't need to take any sort of lock here as we are the only
5866 	 * thread with access to newsksec */
5867 	selinux_netlbl_inet_csk_clone(newsk, req->rsk_ops->family);
5868 }
5869 
5870 static void selinux_inet_conn_established(struct sock *sk, struct sk_buff *skb)
5871 {
5872 	u16 family = sk->sk_family;
5873 	struct sk_security_struct *sksec = selinux_sock(sk);
5874 
5875 	/* handle mapped IPv4 packets arriving via IPv6 sockets */
5876 	if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
5877 		family = PF_INET;
5878 
5879 	selinux_skb_peerlbl_sid(skb, family, &sksec->peer_sid);
5880 }
5881 
5882 static int selinux_secmark_relabel_packet(u32 sid)
5883 {
5884 	return avc_has_perm(current_sid(), sid, SECCLASS_PACKET, PACKET__RELABELTO,
5885 			    NULL);
5886 }
5887 
5888 static void selinux_secmark_refcount_inc(void)
5889 {
5890 	atomic_inc(&selinux_secmark_refcount);
5891 }
5892 
5893 static void selinux_secmark_refcount_dec(void)
5894 {
5895 	atomic_dec(&selinux_secmark_refcount);
5896 }
5897 
5898 static void selinux_req_classify_flow(const struct request_sock *req,
5899 				      struct flowi_common *flic)
5900 {
5901 	flic->flowic_secid = req->secid;
5902 }
5903 
5904 static int selinux_tun_dev_alloc_security(void *security)
5905 {
5906 	struct tun_security_struct *tunsec = selinux_tun_dev(security);
5907 
5908 	tunsec->sid = current_sid();
5909 	return 0;
5910 }
5911 
5912 static int selinux_tun_dev_create(void)
5913 {
5914 	u32 sid = current_sid();
5915 
5916 	/* we aren't taking into account the "sockcreate" SID since the socket
5917 	 * that is being created here is not a socket in the traditional sense,
5918 	 * instead it is a private sock, accessible only to the kernel, and
5919 	 * representing a wide range of network traffic spanning multiple
5920 	 * connections unlike traditional sockets - check the TUN driver to
5921 	 * get a better understanding of why this socket is special */
5922 
5923 	return avc_has_perm(sid, sid, SECCLASS_TUN_SOCKET, TUN_SOCKET__CREATE,
5924 			    NULL);
5925 }
5926 
5927 static int selinux_tun_dev_attach_queue(void *security)
5928 {
5929 	struct tun_security_struct *tunsec = selinux_tun_dev(security);
5930 
5931 	return avc_has_perm(current_sid(), tunsec->sid, SECCLASS_TUN_SOCKET,
5932 			    TUN_SOCKET__ATTACH_QUEUE, NULL);
5933 }
5934 
5935 static int selinux_tun_dev_attach(struct sock *sk, void *security)
5936 {
5937 	struct tun_security_struct *tunsec = selinux_tun_dev(security);
5938 	struct sk_security_struct *sksec = selinux_sock(sk);
5939 
5940 	/* we don't currently perform any NetLabel based labeling here and it
5941 	 * isn't clear that we would want to do so anyway; while we could apply
5942 	 * labeling without the support of the TUN user the resulting labeled
5943 	 * traffic from the other end of the connection would almost certainly
5944 	 * cause confusion to the TUN user that had no idea network labeling
5945 	 * protocols were being used */
5946 
5947 	sksec->sid = tunsec->sid;
5948 	sksec->sclass = SECCLASS_TUN_SOCKET;
5949 
5950 	return 0;
5951 }
5952 
5953 static int selinux_tun_dev_open(void *security)
5954 {
5955 	struct tun_security_struct *tunsec = selinux_tun_dev(security);
5956 	u32 sid = current_sid();
5957 	int err;
5958 
5959 	err = avc_has_perm(sid, tunsec->sid, SECCLASS_TUN_SOCKET,
5960 			   TUN_SOCKET__RELABELFROM, NULL);
5961 	if (err)
5962 		return err;
5963 	err = avc_has_perm(sid, sid, SECCLASS_TUN_SOCKET,
5964 			   TUN_SOCKET__RELABELTO, NULL);
5965 	if (err)
5966 		return err;
5967 	tunsec->sid = sid;
5968 
5969 	return 0;
5970 }
5971 
5972 #ifdef CONFIG_NETFILTER
5973 
5974 static unsigned int selinux_ip_forward(void *priv, struct sk_buff *skb,
5975 				       const struct nf_hook_state *state)
5976 {
5977 	int ifindex;
5978 	u16 family;
5979 	char *addrp;
5980 	u32 peer_sid;
5981 	struct common_audit_data ad;
5982 	struct lsm_network_audit net;
5983 	int secmark_active, peerlbl_active;
5984 
5985 	if (!selinux_policycap_netpeer())
5986 		return NF_ACCEPT;
5987 
5988 	secmark_active = selinux_secmark_enabled();
5989 	peerlbl_active = selinux_peerlbl_enabled();
5990 	if (!secmark_active && !peerlbl_active)
5991 		return NF_ACCEPT;
5992 
5993 	family = state->pf;
5994 	if (selinux_skb_peerlbl_sid(skb, family, &peer_sid) != 0)
5995 		return NF_DROP;
5996 
5997 	ifindex = state->in->ifindex;
5998 	ad_net_init_from_iif(&ad, &net, ifindex, family);
5999 	if (selinux_parse_skb(skb, &ad, &addrp, 1, NULL) != 0)
6000 		return NF_DROP;
6001 
6002 	if (peerlbl_active) {
6003 		int err;
6004 
6005 		err = selinux_inet_sys_rcv_skb(state->net, ifindex,
6006 					       addrp, family, peer_sid, &ad);
6007 		if (err) {
6008 			selinux_netlbl_err(skb, family, err, 1);
6009 			return NF_DROP;
6010 		}
6011 	}
6012 
6013 	if (secmark_active)
6014 		if (avc_has_perm(peer_sid, skb->secmark,
6015 				 SECCLASS_PACKET, PACKET__FORWARD_IN, &ad))
6016 			return NF_DROP;
6017 
6018 	if (netlbl_enabled())
6019 		/* we do this in the FORWARD path and not the POST_ROUTING
6020 		 * path because we want to make sure we apply the necessary
6021 		 * labeling before IPsec is applied so we can leverage AH
6022 		 * protection */
6023 		if (selinux_netlbl_skbuff_setsid(skb, family, peer_sid) != 0)
6024 			return NF_DROP;
6025 
6026 	return NF_ACCEPT;
6027 }
6028 
6029 static unsigned int selinux_ip_output(void *priv, struct sk_buff *skb,
6030 				      const struct nf_hook_state *state)
6031 {
6032 	struct sock *sk;
6033 	u32 sid;
6034 
6035 	if (!netlbl_enabled())
6036 		return NF_ACCEPT;
6037 
6038 	/* we do this in the LOCAL_OUT path and not the POST_ROUTING path
6039 	 * because we want to make sure we apply the necessary labeling
6040 	 * before IPsec is applied so we can leverage AH protection */
6041 	sk = skb_to_full_sk(skb);
6042 	if (sk) {
6043 		struct sk_security_struct *sksec;
6044 
6045 		if (sk_listener(sk))
6046 			/* if the socket is the listening state then this
6047 			 * packet is a SYN-ACK packet which means it needs to
6048 			 * be labeled based on the connection/request_sock and
6049 			 * not the parent socket.  unfortunately, we can't
6050 			 * lookup the request_sock yet as it isn't queued on
6051 			 * the parent socket until after the SYN-ACK is sent.
6052 			 * the "solution" is to simply pass the packet as-is
6053 			 * as any IP option based labeling should be copied
6054 			 * from the initial connection request (in the IP
6055 			 * layer).  it is far from ideal, but until we get a
6056 			 * security label in the packet itself this is the
6057 			 * best we can do. */
6058 			return NF_ACCEPT;
6059 
6060 		/* standard practice, label using the parent socket */
6061 		sksec = selinux_sock(sk);
6062 		sid = sksec->sid;
6063 	} else
6064 		sid = SECINITSID_KERNEL;
6065 	if (selinux_netlbl_skbuff_setsid(skb, state->pf, sid) != 0)
6066 		return NF_DROP;
6067 
6068 	return NF_ACCEPT;
6069 }
6070 
6071 
6072 static unsigned int selinux_ip_postroute_compat(struct sk_buff *skb,
6073 					const struct nf_hook_state *state)
6074 {
6075 	struct sock *sk;
6076 	struct sk_security_struct *sksec;
6077 	struct common_audit_data ad;
6078 	struct lsm_network_audit net;
6079 	u8 proto = 0;
6080 
6081 	sk = skb_to_full_sk(skb);
6082 	if (sk == NULL)
6083 		return NF_ACCEPT;
6084 	sksec = selinux_sock(sk);
6085 
6086 	ad_net_init_from_iif(&ad, &net, state->out->ifindex, state->pf);
6087 	if (selinux_parse_skb(skb, &ad, NULL, 0, &proto))
6088 		return NF_DROP;
6089 
6090 	if (selinux_secmark_enabled())
6091 		if (avc_has_perm(sksec->sid, skb->secmark,
6092 				 SECCLASS_PACKET, PACKET__SEND, &ad))
6093 			return NF_DROP_ERR(-ECONNREFUSED);
6094 
6095 	if (selinux_xfrm_postroute_last(sksec->sid, skb, &ad, proto))
6096 		return NF_DROP_ERR(-ECONNREFUSED);
6097 
6098 	return NF_ACCEPT;
6099 }
6100 
6101 static unsigned int selinux_ip_postroute(void *priv,
6102 					 struct sk_buff *skb,
6103 					 const struct nf_hook_state *state)
6104 {
6105 	u16 family;
6106 	u32 secmark_perm;
6107 	u32 peer_sid;
6108 	int ifindex;
6109 	struct sock *sk;
6110 	struct common_audit_data ad;
6111 	struct lsm_network_audit net;
6112 	char *addrp;
6113 	int secmark_active, peerlbl_active;
6114 
6115 	/* If any sort of compatibility mode is enabled then handoff processing
6116 	 * to the selinux_ip_postroute_compat() function to deal with the
6117 	 * special handling.  We do this in an attempt to keep this function
6118 	 * as fast and as clean as possible. */
6119 	if (!selinux_policycap_netpeer())
6120 		return selinux_ip_postroute_compat(skb, state);
6121 
6122 	secmark_active = selinux_secmark_enabled();
6123 	peerlbl_active = selinux_peerlbl_enabled();
6124 	if (!secmark_active && !peerlbl_active)
6125 		return NF_ACCEPT;
6126 
6127 	sk = skb_to_full_sk(skb);
6128 
6129 #ifdef CONFIG_XFRM
6130 	/* If skb->dst->xfrm is non-NULL then the packet is undergoing an IPsec
6131 	 * packet transformation so allow the packet to pass without any checks
6132 	 * since we'll have another chance to perform access control checks
6133 	 * when the packet is on it's final way out.
6134 	 * NOTE: there appear to be some IPv6 multicast cases where skb->dst
6135 	 *       is NULL, in this case go ahead and apply access control.
6136 	 * NOTE: if this is a local socket (skb->sk != NULL) that is in the
6137 	 *       TCP listening state we cannot wait until the XFRM processing
6138 	 *       is done as we will miss out on the SA label if we do;
6139 	 *       unfortunately, this means more work, but it is only once per
6140 	 *       connection. */
6141 	if (skb_dst(skb) != NULL && skb_dst(skb)->xfrm != NULL &&
6142 	    !(sk && sk_listener(sk)))
6143 		return NF_ACCEPT;
6144 #endif
6145 
6146 	family = state->pf;
6147 	if (sk == NULL) {
6148 		/* Without an associated socket the packet is either coming
6149 		 * from the kernel or it is being forwarded; check the packet
6150 		 * to determine which and if the packet is being forwarded
6151 		 * query the packet directly to determine the security label. */
6152 		if (skb->skb_iif) {
6153 			secmark_perm = PACKET__FORWARD_OUT;
6154 			if (selinux_skb_peerlbl_sid(skb, family, &peer_sid))
6155 				return NF_DROP;
6156 		} else {
6157 			secmark_perm = PACKET__SEND;
6158 			peer_sid = SECINITSID_KERNEL;
6159 		}
6160 	} else if (sk_listener(sk)) {
6161 		/* Locally generated packet but the associated socket is in the
6162 		 * listening state which means this is a SYN-ACK packet.  In
6163 		 * this particular case the correct security label is assigned
6164 		 * to the connection/request_sock but unfortunately we can't
6165 		 * query the request_sock as it isn't queued on the parent
6166 		 * socket until after the SYN-ACK packet is sent; the only
6167 		 * viable choice is to regenerate the label like we do in
6168 		 * selinux_inet_conn_request().  See also selinux_ip_output()
6169 		 * for similar problems. */
6170 		u32 skb_sid;
6171 		struct sk_security_struct *sksec;
6172 
6173 		sksec = selinux_sock(sk);
6174 		if (selinux_skb_peerlbl_sid(skb, family, &skb_sid))
6175 			return NF_DROP;
6176 		/* At this point, if the returned skb peerlbl is SECSID_NULL
6177 		 * and the packet has been through at least one XFRM
6178 		 * transformation then we must be dealing with the "final"
6179 		 * form of labeled IPsec packet; since we've already applied
6180 		 * all of our access controls on this packet we can safely
6181 		 * pass the packet. */
6182 		if (skb_sid == SECSID_NULL) {
6183 			switch (family) {
6184 			case PF_INET:
6185 				if (IPCB(skb)->flags & IPSKB_XFRM_TRANSFORMED)
6186 					return NF_ACCEPT;
6187 				break;
6188 			case PF_INET6:
6189 				if (IP6CB(skb)->flags & IP6SKB_XFRM_TRANSFORMED)
6190 					return NF_ACCEPT;
6191 				break;
6192 			default:
6193 				return NF_DROP_ERR(-ECONNREFUSED);
6194 			}
6195 		}
6196 		if (selinux_conn_sid(sksec->sid, skb_sid, &peer_sid))
6197 			return NF_DROP;
6198 		secmark_perm = PACKET__SEND;
6199 	} else {
6200 		/* Locally generated packet, fetch the security label from the
6201 		 * associated socket. */
6202 		struct sk_security_struct *sksec = selinux_sock(sk);
6203 		peer_sid = sksec->sid;
6204 		secmark_perm = PACKET__SEND;
6205 	}
6206 
6207 	ifindex = state->out->ifindex;
6208 	ad_net_init_from_iif(&ad, &net, ifindex, family);
6209 	if (selinux_parse_skb(skb, &ad, &addrp, 0, NULL))
6210 		return NF_DROP;
6211 
6212 	if (secmark_active)
6213 		if (avc_has_perm(peer_sid, skb->secmark,
6214 				 SECCLASS_PACKET, secmark_perm, &ad))
6215 			return NF_DROP_ERR(-ECONNREFUSED);
6216 
6217 	if (peerlbl_active) {
6218 		u32 if_sid;
6219 		u32 node_sid;
6220 
6221 		if (sel_netif_sid(state->net, ifindex, &if_sid))
6222 			return NF_DROP;
6223 		if (avc_has_perm(peer_sid, if_sid,
6224 				 SECCLASS_NETIF, NETIF__EGRESS, &ad))
6225 			return NF_DROP_ERR(-ECONNREFUSED);
6226 
6227 		if (sel_netnode_sid(addrp, family, &node_sid))
6228 			return NF_DROP;
6229 		if (avc_has_perm(peer_sid, node_sid,
6230 				 SECCLASS_NODE, NODE__SENDTO, &ad))
6231 			return NF_DROP_ERR(-ECONNREFUSED);
6232 	}
6233 
6234 	return NF_ACCEPT;
6235 }
6236 #endif	/* CONFIG_NETFILTER */
6237 
6238 static int nlmsg_sock_has_extended_perms(struct sock *sk, u32 perms, u16 nlmsg_type)
6239 {
6240 	struct sk_security_struct *sksec = selinux_sock(sk);
6241 	struct common_audit_data ad;
6242 	u8 driver;
6243 	u8 xperm;
6244 
6245 	if (sock_skip_has_perm(sksec->sid))
6246 		return 0;
6247 
6248 	ad.type = LSM_AUDIT_DATA_NLMSGTYPE;
6249 	ad.u.nlmsg_type = nlmsg_type;
6250 
6251 	driver = nlmsg_type >> 8;
6252 	xperm = nlmsg_type & 0xff;
6253 
6254 	return avc_has_extended_perms(current_sid(), sksec->sid, sksec->sclass,
6255 				      perms, driver, AVC_EXT_NLMSG, xperm, &ad);
6256 }
6257 
6258 static int selinux_netlink_send(struct sock *sk, struct sk_buff *skb)
6259 {
6260 	int rc = 0;
6261 	unsigned int msg_len;
6262 	unsigned int data_len = skb->len;
6263 	unsigned char *data = skb->data;
6264 	struct nlmsghdr *nlh;
6265 	struct sk_security_struct *sksec = selinux_sock(sk);
6266 	u16 sclass = sksec->sclass;
6267 	u32 perm;
6268 
6269 	while (data_len >= nlmsg_total_size(0)) {
6270 		nlh = (struct nlmsghdr *)data;
6271 
6272 		/* NOTE: the nlmsg_len field isn't reliably set by some netlink
6273 		 *       users which means we can't reject skb's with bogus
6274 		 *       length fields; our solution is to follow what
6275 		 *       netlink_rcv_skb() does and simply skip processing at
6276 		 *       messages with length fields that are clearly junk
6277 		 */
6278 		if (nlh->nlmsg_len < NLMSG_HDRLEN || nlh->nlmsg_len > data_len)
6279 			return 0;
6280 
6281 		rc = selinux_nlmsg_lookup(sclass, nlh->nlmsg_type, &perm);
6282 		if (rc == 0) {
6283 			if (selinux_policycap_netlink_xperm()) {
6284 				rc = nlmsg_sock_has_extended_perms(
6285 					sk, perm, nlh->nlmsg_type);
6286 			} else {
6287 				rc = sock_has_perm(sk, perm);
6288 			}
6289 			if (rc)
6290 				return rc;
6291 		} else if (rc == -EINVAL) {
6292 			/* -EINVAL is a missing msg/perm mapping */
6293 			pr_warn_ratelimited("SELinux: unrecognized netlink"
6294 				" message: protocol=%hu nlmsg_type=%hu sclass=%s"
6295 				" pid=%d comm=%s\n",
6296 				sk->sk_protocol, nlh->nlmsg_type,
6297 				secclass_map[sclass - 1].name,
6298 				task_pid_nr(current), current->comm);
6299 			if (enforcing_enabled() &&
6300 			    !security_get_allow_unknown())
6301 				return rc;
6302 			rc = 0;
6303 		} else if (rc == -ENOENT) {
6304 			/* -ENOENT is a missing socket/class mapping, ignore */
6305 			rc = 0;
6306 		} else {
6307 			return rc;
6308 		}
6309 
6310 		/* move to the next message after applying netlink padding */
6311 		msg_len = NLMSG_ALIGN(nlh->nlmsg_len);
6312 		if (msg_len >= data_len)
6313 			return 0;
6314 		data_len -= msg_len;
6315 		data += msg_len;
6316 	}
6317 
6318 	return rc;
6319 }
6320 
6321 static void ipc_init_security(struct ipc_security_struct *isec, u16 sclass)
6322 {
6323 	isec->sclass = sclass;
6324 	isec->sid = current_sid();
6325 }
6326 
6327 static int ipc_has_perm(struct kern_ipc_perm *ipc_perms,
6328 			u32 perms)
6329 {
6330 	struct ipc_security_struct *isec;
6331 	struct common_audit_data ad;
6332 	u32 sid = current_sid();
6333 
6334 	isec = selinux_ipc(ipc_perms);
6335 
6336 	ad.type = LSM_AUDIT_DATA_IPC;
6337 	ad.u.ipc_id = ipc_perms->key;
6338 
6339 	return avc_has_perm(sid, isec->sid, isec->sclass, perms, &ad);
6340 }
6341 
6342 static int selinux_msg_msg_alloc_security(struct msg_msg *msg)
6343 {
6344 	struct msg_security_struct *msec;
6345 
6346 	msec = selinux_msg_msg(msg);
6347 	msec->sid = SECINITSID_UNLABELED;
6348 
6349 	return 0;
6350 }
6351 
6352 /* message queue security operations */
6353 static int selinux_msg_queue_alloc_security(struct kern_ipc_perm *msq)
6354 {
6355 	struct ipc_security_struct *isec;
6356 	struct common_audit_data ad;
6357 	u32 sid = current_sid();
6358 
6359 	isec = selinux_ipc(msq);
6360 	ipc_init_security(isec, SECCLASS_MSGQ);
6361 
6362 	ad.type = LSM_AUDIT_DATA_IPC;
6363 	ad.u.ipc_id = msq->key;
6364 
6365 	return avc_has_perm(sid, isec->sid, SECCLASS_MSGQ,
6366 			    MSGQ__CREATE, &ad);
6367 }
6368 
6369 static int selinux_msg_queue_associate(struct kern_ipc_perm *msq, int msqflg)
6370 {
6371 	struct ipc_security_struct *isec;
6372 	struct common_audit_data ad;
6373 	u32 sid = current_sid();
6374 
6375 	isec = selinux_ipc(msq);
6376 
6377 	ad.type = LSM_AUDIT_DATA_IPC;
6378 	ad.u.ipc_id = msq->key;
6379 
6380 	return avc_has_perm(sid, isec->sid, SECCLASS_MSGQ,
6381 			    MSGQ__ASSOCIATE, &ad);
6382 }
6383 
6384 static int selinux_msg_queue_msgctl(struct kern_ipc_perm *msq, int cmd)
6385 {
6386 	u32 perms;
6387 
6388 	switch (cmd) {
6389 	case IPC_INFO:
6390 	case MSG_INFO:
6391 		/* No specific object, just general system-wide information. */
6392 		return avc_has_perm(current_sid(), SECINITSID_KERNEL,
6393 				    SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
6394 	case IPC_STAT:
6395 	case MSG_STAT:
6396 	case MSG_STAT_ANY:
6397 		perms = MSGQ__GETATTR | MSGQ__ASSOCIATE;
6398 		break;
6399 	case IPC_SET:
6400 		perms = MSGQ__SETATTR;
6401 		break;
6402 	case IPC_RMID:
6403 		perms = MSGQ__DESTROY;
6404 		break;
6405 	default:
6406 		return 0;
6407 	}
6408 
6409 	return ipc_has_perm(msq, perms);
6410 }
6411 
6412 static int selinux_msg_queue_msgsnd(struct kern_ipc_perm *msq, struct msg_msg *msg, int msqflg)
6413 {
6414 	struct ipc_security_struct *isec;
6415 	struct msg_security_struct *msec;
6416 	struct common_audit_data ad;
6417 	u32 sid = current_sid();
6418 	int rc;
6419 
6420 	isec = selinux_ipc(msq);
6421 	msec = selinux_msg_msg(msg);
6422 
6423 	/*
6424 	 * First time through, need to assign label to the message
6425 	 */
6426 	if (msec->sid == SECINITSID_UNLABELED) {
6427 		/*
6428 		 * Compute new sid based on current process and
6429 		 * message queue this message will be stored in
6430 		 */
6431 		rc = security_transition_sid(sid, isec->sid,
6432 					     SECCLASS_MSG, NULL, &msec->sid);
6433 		if (rc)
6434 			return rc;
6435 	}
6436 
6437 	ad.type = LSM_AUDIT_DATA_IPC;
6438 	ad.u.ipc_id = msq->key;
6439 
6440 	/* Can this process write to the queue? */
6441 	rc = avc_has_perm(sid, isec->sid, SECCLASS_MSGQ,
6442 			  MSGQ__WRITE, &ad);
6443 	if (!rc)
6444 		/* Can this process send the message */
6445 		rc = avc_has_perm(sid, msec->sid, SECCLASS_MSG,
6446 				  MSG__SEND, &ad);
6447 	if (!rc)
6448 		/* Can the message be put in the queue? */
6449 		rc = avc_has_perm(msec->sid, isec->sid, SECCLASS_MSGQ,
6450 				  MSGQ__ENQUEUE, &ad);
6451 
6452 	return rc;
6453 }
6454 
6455 static int selinux_msg_queue_msgrcv(struct kern_ipc_perm *msq, struct msg_msg *msg,
6456 				    struct task_struct *target,
6457 				    long type, int mode)
6458 {
6459 	struct ipc_security_struct *isec;
6460 	struct msg_security_struct *msec;
6461 	struct common_audit_data ad;
6462 	u32 sid = task_sid_obj(target);
6463 	int rc;
6464 
6465 	isec = selinux_ipc(msq);
6466 	msec = selinux_msg_msg(msg);
6467 
6468 	ad.type = LSM_AUDIT_DATA_IPC;
6469 	ad.u.ipc_id = msq->key;
6470 
6471 	rc = avc_has_perm(sid, isec->sid,
6472 			  SECCLASS_MSGQ, MSGQ__READ, &ad);
6473 	if (!rc)
6474 		rc = avc_has_perm(sid, msec->sid,
6475 				  SECCLASS_MSG, MSG__RECEIVE, &ad);
6476 	return rc;
6477 }
6478 
6479 /* Shared Memory security operations */
6480 static int selinux_shm_alloc_security(struct kern_ipc_perm *shp)
6481 {
6482 	struct ipc_security_struct *isec;
6483 	struct common_audit_data ad;
6484 	u32 sid = current_sid();
6485 
6486 	isec = selinux_ipc(shp);
6487 	ipc_init_security(isec, SECCLASS_SHM);
6488 
6489 	ad.type = LSM_AUDIT_DATA_IPC;
6490 	ad.u.ipc_id = shp->key;
6491 
6492 	return avc_has_perm(sid, isec->sid, SECCLASS_SHM,
6493 			    SHM__CREATE, &ad);
6494 }
6495 
6496 static int selinux_shm_associate(struct kern_ipc_perm *shp, int shmflg)
6497 {
6498 	struct ipc_security_struct *isec;
6499 	struct common_audit_data ad;
6500 	u32 sid = current_sid();
6501 
6502 	isec = selinux_ipc(shp);
6503 
6504 	ad.type = LSM_AUDIT_DATA_IPC;
6505 	ad.u.ipc_id = shp->key;
6506 
6507 	return avc_has_perm(sid, isec->sid, SECCLASS_SHM,
6508 			    SHM__ASSOCIATE, &ad);
6509 }
6510 
6511 /* Note, at this point, shp is locked down */
6512 static int selinux_shm_shmctl(struct kern_ipc_perm *shp, int cmd)
6513 {
6514 	u32 perms;
6515 
6516 	switch (cmd) {
6517 	case IPC_INFO:
6518 	case SHM_INFO:
6519 		/* No specific object, just general system-wide information. */
6520 		return avc_has_perm(current_sid(), SECINITSID_KERNEL,
6521 				    SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
6522 	case IPC_STAT:
6523 	case SHM_STAT:
6524 	case SHM_STAT_ANY:
6525 		perms = SHM__GETATTR | SHM__ASSOCIATE;
6526 		break;
6527 	case IPC_SET:
6528 		perms = SHM__SETATTR;
6529 		break;
6530 	case SHM_LOCK:
6531 	case SHM_UNLOCK:
6532 		perms = SHM__LOCK;
6533 		break;
6534 	case IPC_RMID:
6535 		perms = SHM__DESTROY;
6536 		break;
6537 	default:
6538 		return 0;
6539 	}
6540 
6541 	return ipc_has_perm(shp, perms);
6542 }
6543 
6544 static int selinux_shm_shmat(struct kern_ipc_perm *shp,
6545 			     char __user *shmaddr, int shmflg)
6546 {
6547 	u32 perms;
6548 
6549 	if (shmflg & SHM_RDONLY)
6550 		perms = SHM__READ;
6551 	else
6552 		perms = SHM__READ | SHM__WRITE;
6553 
6554 	return ipc_has_perm(shp, perms);
6555 }
6556 
6557 /* Semaphore security operations */
6558 static int selinux_sem_alloc_security(struct kern_ipc_perm *sma)
6559 {
6560 	struct ipc_security_struct *isec;
6561 	struct common_audit_data ad;
6562 	u32 sid = current_sid();
6563 
6564 	isec = selinux_ipc(sma);
6565 	ipc_init_security(isec, SECCLASS_SEM);
6566 
6567 	ad.type = LSM_AUDIT_DATA_IPC;
6568 	ad.u.ipc_id = sma->key;
6569 
6570 	return avc_has_perm(sid, isec->sid, SECCLASS_SEM,
6571 			    SEM__CREATE, &ad);
6572 }
6573 
6574 static int selinux_sem_associate(struct kern_ipc_perm *sma, int semflg)
6575 {
6576 	struct ipc_security_struct *isec;
6577 	struct common_audit_data ad;
6578 	u32 sid = current_sid();
6579 
6580 	isec = selinux_ipc(sma);
6581 
6582 	ad.type = LSM_AUDIT_DATA_IPC;
6583 	ad.u.ipc_id = sma->key;
6584 
6585 	return avc_has_perm(sid, isec->sid, SECCLASS_SEM,
6586 			    SEM__ASSOCIATE, &ad);
6587 }
6588 
6589 /* Note, at this point, sma is locked down */
6590 static int selinux_sem_semctl(struct kern_ipc_perm *sma, int cmd)
6591 {
6592 	int err;
6593 	u32 perms;
6594 
6595 	switch (cmd) {
6596 	case IPC_INFO:
6597 	case SEM_INFO:
6598 		/* No specific object, just general system-wide information. */
6599 		return avc_has_perm(current_sid(), SECINITSID_KERNEL,
6600 				    SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
6601 	case GETPID:
6602 	case GETNCNT:
6603 	case GETZCNT:
6604 		perms = SEM__GETATTR;
6605 		break;
6606 	case GETVAL:
6607 	case GETALL:
6608 		perms = SEM__READ;
6609 		break;
6610 	case SETVAL:
6611 	case SETALL:
6612 		perms = SEM__WRITE;
6613 		break;
6614 	case IPC_RMID:
6615 		perms = SEM__DESTROY;
6616 		break;
6617 	case IPC_SET:
6618 		perms = SEM__SETATTR;
6619 		break;
6620 	case IPC_STAT:
6621 	case SEM_STAT:
6622 	case SEM_STAT_ANY:
6623 		perms = SEM__GETATTR | SEM__ASSOCIATE;
6624 		break;
6625 	default:
6626 		return 0;
6627 	}
6628 
6629 	err = ipc_has_perm(sma, perms);
6630 	return err;
6631 }
6632 
6633 static int selinux_sem_semop(struct kern_ipc_perm *sma,
6634 			     struct sembuf *sops, unsigned nsops, int alter)
6635 {
6636 	u32 perms;
6637 
6638 	if (alter)
6639 		perms = SEM__READ | SEM__WRITE;
6640 	else
6641 		perms = SEM__READ;
6642 
6643 	return ipc_has_perm(sma, perms);
6644 }
6645 
6646 static int selinux_ipc_permission(struct kern_ipc_perm *ipcp, short flag)
6647 {
6648 	u32 av = 0;
6649 
6650 	av = 0;
6651 	if (flag & S_IRUGO)
6652 		av |= IPC__UNIX_READ;
6653 	if (flag & S_IWUGO)
6654 		av |= IPC__UNIX_WRITE;
6655 
6656 	if (av == 0)
6657 		return 0;
6658 
6659 	return ipc_has_perm(ipcp, av);
6660 }
6661 
6662 static void selinux_ipc_getlsmprop(struct kern_ipc_perm *ipcp,
6663 				   struct lsm_prop *prop)
6664 {
6665 	struct ipc_security_struct *isec = selinux_ipc(ipcp);
6666 	prop->selinux.secid = isec->sid;
6667 }
6668 
6669 static void selinux_d_instantiate(struct dentry *dentry, struct inode *inode)
6670 {
6671 	if (inode)
6672 		inode_doinit_with_dentry(inode, dentry);
6673 }
6674 
6675 static int selinux_lsm_getattr(unsigned int attr, struct task_struct *p,
6676 			       char **value)
6677 {
6678 	const struct cred_security_struct *crsec;
6679 	int error;
6680 	u32 sid;
6681 	u32 len;
6682 
6683 	rcu_read_lock();
6684 	crsec = selinux_cred(__task_cred(p));
6685 	if (p != current) {
6686 		error = avc_has_perm(current_sid(), crsec->sid,
6687 				     SECCLASS_PROCESS, PROCESS__GETATTR, NULL);
6688 		if (error)
6689 			goto err_unlock;
6690 	}
6691 	switch (attr) {
6692 	case LSM_ATTR_CURRENT:
6693 		sid = crsec->sid;
6694 		break;
6695 	case LSM_ATTR_PREV:
6696 		sid = crsec->osid;
6697 		break;
6698 	case LSM_ATTR_EXEC:
6699 		sid = crsec->exec_sid;
6700 		break;
6701 	case LSM_ATTR_FSCREATE:
6702 		sid = crsec->create_sid;
6703 		break;
6704 	case LSM_ATTR_KEYCREATE:
6705 		sid = crsec->keycreate_sid;
6706 		break;
6707 	case LSM_ATTR_SOCKCREATE:
6708 		sid = crsec->sockcreate_sid;
6709 		break;
6710 	default:
6711 		error = -EOPNOTSUPP;
6712 		goto err_unlock;
6713 	}
6714 	rcu_read_unlock();
6715 
6716 	if (sid == SECSID_NULL) {
6717 		*value = NULL;
6718 		return 0;
6719 	}
6720 
6721 	error = security_sid_to_context(sid, value, &len);
6722 	if (error)
6723 		return error;
6724 	return len;
6725 
6726 err_unlock:
6727 	rcu_read_unlock();
6728 	return error;
6729 }
6730 
6731 static int selinux_lsm_setattr(u64 attr, void *value, size_t size)
6732 {
6733 	struct cred_security_struct *crsec;
6734 	struct cred *new;
6735 	u32 mysid = current_sid(), sid = 0, ptsid;
6736 	int error;
6737 	char *str = value;
6738 
6739 	/*
6740 	 * Basic control over ability to set these attributes at all.
6741 	 */
6742 	switch (attr) {
6743 	case LSM_ATTR_EXEC:
6744 		error = avc_has_perm(mysid, mysid, SECCLASS_PROCESS,
6745 				     PROCESS__SETEXEC, NULL);
6746 		break;
6747 	case LSM_ATTR_FSCREATE:
6748 		error = avc_has_perm(mysid, mysid, SECCLASS_PROCESS,
6749 				     PROCESS__SETFSCREATE, NULL);
6750 		break;
6751 	case LSM_ATTR_KEYCREATE:
6752 		error = avc_has_perm(mysid, mysid, SECCLASS_PROCESS,
6753 				     PROCESS__SETKEYCREATE, NULL);
6754 		break;
6755 	case LSM_ATTR_SOCKCREATE:
6756 		error = avc_has_perm(mysid, mysid, SECCLASS_PROCESS,
6757 				     PROCESS__SETSOCKCREATE, NULL);
6758 		break;
6759 	case LSM_ATTR_CURRENT:
6760 		error = avc_has_perm(mysid, mysid, SECCLASS_PROCESS,
6761 				     PROCESS__SETCURRENT, NULL);
6762 		break;
6763 	default:
6764 		error = -EOPNOTSUPP;
6765 		break;
6766 	}
6767 	if (error)
6768 		return error;
6769 
6770 	/* Obtain a SID for the context, if one was specified. */
6771 	if (size && str[0] && str[0] != '\n') {
6772 		if (str[size-1] == '\n') {
6773 			str[size-1] = 0;
6774 			size--;
6775 		}
6776 		error = security_context_to_sid(value, size,
6777 						&sid, GFP_KERNEL);
6778 		if (error == -EINVAL && attr == LSM_ATTR_FSCREATE) {
6779 			if (!has_cap_mac_admin(true)) {
6780 				struct audit_buffer *ab;
6781 				size_t audit_size;
6782 
6783 				/* We strip a nul only if it is at the end,
6784 				 * otherwise the context contains a nul and
6785 				 * we should audit that */
6786 				if (str[size - 1] == '\0')
6787 					audit_size = size - 1;
6788 				else
6789 					audit_size = size;
6790 				ab = audit_log_start(audit_context(),
6791 						     GFP_ATOMIC,
6792 						     AUDIT_SELINUX_ERR);
6793 				if (!ab)
6794 					return error;
6795 				audit_log_format(ab, "op=fscreate invalid_context=");
6796 				audit_log_n_untrustedstring(ab, value,
6797 							    audit_size);
6798 				audit_log_end(ab);
6799 
6800 				return error;
6801 			}
6802 			error = security_context_to_sid_force(value, size,
6803 							&sid);
6804 		}
6805 		if (error)
6806 			return error;
6807 	}
6808 
6809 	new = prepare_creds();
6810 	if (!new)
6811 		return -ENOMEM;
6812 
6813 	/* Permission checking based on the specified context is
6814 	   performed during the actual operation (execve,
6815 	   open/mkdir/...), when we know the full context of the
6816 	   operation.  See selinux_bprm_creds_for_exec for the execve
6817 	   checks and may_create for the file creation checks. The
6818 	   operation will then fail if the context is not permitted. */
6819 	crsec = selinux_cred(new);
6820 	if (attr == LSM_ATTR_EXEC) {
6821 		crsec->exec_sid = sid;
6822 	} else if (attr == LSM_ATTR_FSCREATE) {
6823 		crsec->create_sid = sid;
6824 	} else if (attr == LSM_ATTR_KEYCREATE) {
6825 		if (sid) {
6826 			error = avc_has_perm(mysid, sid,
6827 					     SECCLASS_KEY, KEY__CREATE, NULL);
6828 			if (error)
6829 				goto abort_change;
6830 		}
6831 		crsec->keycreate_sid = sid;
6832 	} else if (attr == LSM_ATTR_SOCKCREATE) {
6833 		crsec->sockcreate_sid = sid;
6834 	} else if (attr == LSM_ATTR_CURRENT) {
6835 		error = -EINVAL;
6836 		if (sid == 0)
6837 			goto abort_change;
6838 
6839 		if (!current_is_single_threaded()) {
6840 			error = security_bounded_transition(crsec->sid, sid);
6841 			if (error)
6842 				goto abort_change;
6843 		}
6844 
6845 		/* Check permissions for the transition. */
6846 		error = avc_has_perm(crsec->sid, sid, SECCLASS_PROCESS,
6847 				     PROCESS__DYNTRANSITION, NULL);
6848 		if (error)
6849 			goto abort_change;
6850 
6851 		/* Check for ptracing, and update the task SID if ok.
6852 		   Otherwise, leave SID unchanged and fail. */
6853 		ptsid = ptrace_parent_sid();
6854 		if (ptsid != 0) {
6855 			error = avc_has_perm(ptsid, sid, SECCLASS_PROCESS,
6856 					     PROCESS__PTRACE, NULL);
6857 			if (error)
6858 				goto abort_change;
6859 		}
6860 
6861 		crsec->sid = sid;
6862 	} else {
6863 		error = -EINVAL;
6864 		goto abort_change;
6865 	}
6866 
6867 	commit_creds(new);
6868 	return size;
6869 
6870 abort_change:
6871 	abort_creds(new);
6872 	return error;
6873 }
6874 
6875 /**
6876  * selinux_getselfattr - Get SELinux current task attributes
6877  * @attr: the requested attribute
6878  * @ctx: buffer to receive the result
6879  * @size: buffer size (input), buffer size used (output)
6880  * @flags: unused
6881  *
6882  * Fill the passed user space @ctx with the details of the requested
6883  * attribute.
6884  *
6885  * Returns the number of attributes on success, an error code otherwise.
6886  * There will only ever be one attribute.
6887  */
6888 static int selinux_getselfattr(unsigned int attr, struct lsm_ctx __user *ctx,
6889 			       u32 *size, u32 flags)
6890 {
6891 	int rc;
6892 	char *val = NULL;
6893 	int val_len;
6894 
6895 	val_len = selinux_lsm_getattr(attr, current, &val);
6896 	if (val_len < 0)
6897 		return val_len;
6898 	rc = lsm_fill_user_ctx(ctx, size, val, val_len, LSM_ID_SELINUX, 0);
6899 	kfree(val);
6900 	return (!rc ? 1 : rc);
6901 }
6902 
6903 static int selinux_setselfattr(unsigned int attr, struct lsm_ctx *ctx,
6904 			       u32 size, u32 flags)
6905 {
6906 	int rc;
6907 
6908 	rc = selinux_lsm_setattr(attr, ctx->ctx, ctx->ctx_len);
6909 	if (rc > 0)
6910 		return 0;
6911 	return rc;
6912 }
6913 
6914 static int selinux_getprocattr(struct task_struct *p,
6915 			       const char *name, char **value)
6916 {
6917 	unsigned int attr = lsm_name_to_attr(name);
6918 	int rc;
6919 
6920 	if (attr) {
6921 		rc = selinux_lsm_getattr(attr, p, value);
6922 		if (rc != -EOPNOTSUPP)
6923 			return rc;
6924 	}
6925 
6926 	return -EINVAL;
6927 }
6928 
6929 static int selinux_setprocattr(const char *name, void *value, size_t size)
6930 {
6931 	int attr = lsm_name_to_attr(name);
6932 
6933 	if (attr)
6934 		return selinux_lsm_setattr(attr, value, size);
6935 	return -EINVAL;
6936 }
6937 
6938 static int selinux_ismaclabel(const char *name)
6939 {
6940 	return (strcmp(name, XATTR_SELINUX_SUFFIX) == 0);
6941 }
6942 
6943 static int selinux_secid_to_secctx(u32 secid, struct lsm_context *cp)
6944 {
6945 	u32 seclen;
6946 	int ret;
6947 
6948 	if (cp) {
6949 		cp->id = LSM_ID_SELINUX;
6950 		ret = security_sid_to_context(secid, &cp->context, &cp->len);
6951 		if (ret < 0)
6952 			return ret;
6953 		return cp->len;
6954 	}
6955 	ret = security_sid_to_context(secid, NULL, &seclen);
6956 	if (ret < 0)
6957 		return ret;
6958 	return seclen;
6959 }
6960 
6961 static int selinux_lsmprop_to_secctx(struct lsm_prop *prop,
6962 				     struct lsm_context *cp)
6963 {
6964 	return selinux_secid_to_secctx(prop->selinux.secid, cp);
6965 }
6966 
6967 static int selinux_secctx_to_secid(const char *secdata, u32 seclen, u32 *secid)
6968 {
6969 	return security_context_to_sid(secdata, seclen,
6970 				       secid, GFP_KERNEL);
6971 }
6972 
6973 static void selinux_release_secctx(struct lsm_context *cp)
6974 {
6975 	if (cp->id == LSM_ID_SELINUX) {
6976 		kfree(cp->context);
6977 		cp->context = NULL;
6978 		cp->id = LSM_ID_UNDEF;
6979 	}
6980 }
6981 
6982 static void selinux_inode_invalidate_secctx(struct inode *inode)
6983 {
6984 	struct inode_security_struct *isec = selinux_inode(inode);
6985 
6986 	spin_lock(&isec->lock);
6987 	isec->initialized = LABEL_INVALID;
6988 	spin_unlock(&isec->lock);
6989 }
6990 
6991 /*
6992  *	called with inode->i_mutex locked
6993  */
6994 static int selinux_inode_notifysecctx(struct inode *inode, void *ctx, u32 ctxlen)
6995 {
6996 	int rc = selinux_inode_setsecurity(inode, XATTR_SELINUX_SUFFIX,
6997 					   ctx, ctxlen, 0);
6998 	/* Do not return error when suppressing label (SBLABEL_MNT not set). */
6999 	return rc == -EOPNOTSUPP ? 0 : rc;
7000 }
7001 
7002 /*
7003  *	called with inode->i_mutex locked
7004  */
7005 static int selinux_inode_setsecctx(struct dentry *dentry, void *ctx, u32 ctxlen)
7006 {
7007 	return __vfs_setxattr_locked(&nop_mnt_idmap, dentry, XATTR_NAME_SELINUX,
7008 				     ctx, ctxlen, 0, NULL);
7009 }
7010 
7011 static int selinux_inode_getsecctx(struct inode *inode, struct lsm_context *cp)
7012 {
7013 	int len;
7014 	len = selinux_inode_getsecurity(&nop_mnt_idmap, inode,
7015 					XATTR_SELINUX_SUFFIX,
7016 					(void **)&cp->context, true);
7017 	if (len < 0)
7018 		return len;
7019 	cp->len = len;
7020 	cp->id = LSM_ID_SELINUX;
7021 	return 0;
7022 }
7023 #ifdef CONFIG_KEYS
7024 
7025 static int selinux_key_alloc(struct key *k, const struct cred *cred,
7026 			     unsigned long flags)
7027 {
7028 	const struct cred_security_struct *crsec;
7029 	struct key_security_struct *ksec = selinux_key(k);
7030 
7031 	crsec = selinux_cred(cred);
7032 	if (crsec->keycreate_sid)
7033 		ksec->sid = crsec->keycreate_sid;
7034 	else
7035 		ksec->sid = crsec->sid;
7036 
7037 	return 0;
7038 }
7039 
7040 static int selinux_key_permission(key_ref_t key_ref,
7041 				  const struct cred *cred,
7042 				  enum key_need_perm need_perm)
7043 {
7044 	struct key *key;
7045 	struct key_security_struct *ksec;
7046 	u32 perm, sid;
7047 
7048 	switch (need_perm) {
7049 	case KEY_NEED_VIEW:
7050 		perm = KEY__VIEW;
7051 		break;
7052 	case KEY_NEED_READ:
7053 		perm = KEY__READ;
7054 		break;
7055 	case KEY_NEED_WRITE:
7056 		perm = KEY__WRITE;
7057 		break;
7058 	case KEY_NEED_SEARCH:
7059 		perm = KEY__SEARCH;
7060 		break;
7061 	case KEY_NEED_LINK:
7062 		perm = KEY__LINK;
7063 		break;
7064 	case KEY_NEED_SETATTR:
7065 		perm = KEY__SETATTR;
7066 		break;
7067 	case KEY_NEED_UNLINK:
7068 	case KEY_SYSADMIN_OVERRIDE:
7069 	case KEY_AUTHTOKEN_OVERRIDE:
7070 	case KEY_DEFER_PERM_CHECK:
7071 		return 0;
7072 	default:
7073 		WARN_ON(1);
7074 		return -EPERM;
7075 
7076 	}
7077 
7078 	sid = cred_sid(cred);
7079 	key = key_ref_to_ptr(key_ref);
7080 	ksec = selinux_key(key);
7081 
7082 	return avc_has_perm(sid, ksec->sid, SECCLASS_KEY, perm, NULL);
7083 }
7084 
7085 static int selinux_key_getsecurity(struct key *key, char **_buffer)
7086 {
7087 	struct key_security_struct *ksec = selinux_key(key);
7088 	char *context = NULL;
7089 	unsigned len;
7090 	int rc;
7091 
7092 	rc = security_sid_to_context(ksec->sid,
7093 				     &context, &len);
7094 	if (!rc)
7095 		rc = len;
7096 	*_buffer = context;
7097 	return rc;
7098 }
7099 
7100 #ifdef CONFIG_KEY_NOTIFICATIONS
7101 static int selinux_watch_key(struct key *key)
7102 {
7103 	struct key_security_struct *ksec = selinux_key(key);
7104 	u32 sid = current_sid();
7105 
7106 	return avc_has_perm(sid, ksec->sid, SECCLASS_KEY, KEY__VIEW, NULL);
7107 }
7108 #endif
7109 #endif
7110 
7111 #ifdef CONFIG_SECURITY_INFINIBAND
7112 static int selinux_ib_pkey_access(void *ib_sec, u64 subnet_prefix, u16 pkey_val)
7113 {
7114 	struct common_audit_data ad;
7115 	int err;
7116 	u32 sid = 0;
7117 	struct ib_security_struct *sec = ib_sec;
7118 	struct lsm_ibpkey_audit ibpkey;
7119 
7120 	err = sel_ib_pkey_sid(subnet_prefix, pkey_val, &sid);
7121 	if (err)
7122 		return err;
7123 
7124 	ad.type = LSM_AUDIT_DATA_IBPKEY;
7125 	ibpkey.subnet_prefix = subnet_prefix;
7126 	ibpkey.pkey = pkey_val;
7127 	ad.u.ibpkey = &ibpkey;
7128 	return avc_has_perm(sec->sid, sid,
7129 			    SECCLASS_INFINIBAND_PKEY,
7130 			    INFINIBAND_PKEY__ACCESS, &ad);
7131 }
7132 
7133 static int selinux_ib_endport_manage_subnet(void *ib_sec, const char *dev_name,
7134 					    u8 port_num)
7135 {
7136 	struct common_audit_data ad;
7137 	int err;
7138 	u32 sid = 0;
7139 	struct ib_security_struct *sec = ib_sec;
7140 	struct lsm_ibendport_audit ibendport;
7141 
7142 	err = security_ib_endport_sid(dev_name, port_num,
7143 				      &sid);
7144 
7145 	if (err)
7146 		return err;
7147 
7148 	ad.type = LSM_AUDIT_DATA_IBENDPORT;
7149 	ibendport.dev_name = dev_name;
7150 	ibendport.port = port_num;
7151 	ad.u.ibendport = &ibendport;
7152 	return avc_has_perm(sec->sid, sid,
7153 			    SECCLASS_INFINIBAND_ENDPORT,
7154 			    INFINIBAND_ENDPORT__MANAGE_SUBNET, &ad);
7155 }
7156 
7157 static int selinux_ib_alloc_security(void *ib_sec)
7158 {
7159 	struct ib_security_struct *sec = selinux_ib(ib_sec);
7160 
7161 	sec->sid = current_sid();
7162 	return 0;
7163 }
7164 #endif
7165 
7166 #ifdef CONFIG_BPF_SYSCALL
7167 static int selinux_bpf(int cmd, union bpf_attr *attr,
7168 		       unsigned int size, bool kernel)
7169 {
7170 	u32 sid = current_sid();
7171 	int ret;
7172 
7173 	if (selinux_policycap_bpf_token_perms())
7174 		return 0;
7175 
7176 	switch (cmd) {
7177 	case BPF_MAP_CREATE:
7178 		ret = avc_has_perm(sid, sid, SECCLASS_BPF, BPF__MAP_CREATE,
7179 				   NULL);
7180 		break;
7181 	case BPF_PROG_LOAD:
7182 		ret = avc_has_perm(sid, sid, SECCLASS_BPF, BPF__PROG_LOAD,
7183 				   NULL);
7184 		break;
7185 	default:
7186 		ret = 0;
7187 		break;
7188 	}
7189 
7190 	return ret;
7191 }
7192 
7193 static u32 bpf_map_fmode_to_av(fmode_t fmode)
7194 {
7195 	u32 av = 0;
7196 
7197 	if (fmode & FMODE_READ)
7198 		av |= BPF__MAP_READ;
7199 	if (fmode & FMODE_WRITE)
7200 		av |= BPF__MAP_WRITE;
7201 	return av;
7202 }
7203 
7204 /* This function will check the file pass through unix socket or binder to see
7205  * if it is a bpf related object. And apply corresponding checks on the bpf
7206  * object based on the type. The bpf maps and programs, not like other files and
7207  * socket, are using a shared anonymous inode inside the kernel as their inode.
7208  * So checking that inode cannot identify if the process have privilege to
7209  * access the bpf object and that's why we have to add this additional check in
7210  * selinux_file_receive and selinux_binder_transfer_files.
7211  */
7212 static int bpf_fd_pass(const struct file *file, u32 sid)
7213 {
7214 	struct bpf_security_struct *bpfsec;
7215 	struct bpf_prog *prog;
7216 	struct bpf_map *map;
7217 	int ret;
7218 
7219 	if (file->f_op == &bpf_map_fops) {
7220 		map = file->private_data;
7221 		bpfsec = selinux_bpf_map_security(map);
7222 		ret = avc_has_perm(sid, bpfsec->sid, SECCLASS_BPF,
7223 				   bpf_map_fmode_to_av(file->f_mode), NULL);
7224 		if (ret)
7225 			return ret;
7226 	} else if (file->f_op == &bpf_prog_fops) {
7227 		prog = file->private_data;
7228 		bpfsec = selinux_bpf_prog_security(prog);
7229 		ret = avc_has_perm(sid, bpfsec->sid, SECCLASS_BPF,
7230 				   BPF__PROG_RUN, NULL);
7231 		if (ret)
7232 			return ret;
7233 	}
7234 	return 0;
7235 }
7236 
7237 static int selinux_bpf_map(struct bpf_map *map, fmode_t fmode)
7238 {
7239 	u32 sid = current_sid();
7240 	struct bpf_security_struct *bpfsec;
7241 
7242 	bpfsec = selinux_bpf_map_security(map);
7243 	return avc_has_perm(sid, bpfsec->sid, SECCLASS_BPF,
7244 			    bpf_map_fmode_to_av(fmode), NULL);
7245 }
7246 
7247 static int selinux_bpf_prog(struct bpf_prog *prog)
7248 {
7249 	u32 sid = current_sid();
7250 	struct bpf_security_struct *bpfsec;
7251 
7252 	bpfsec = selinux_bpf_prog_security(prog);
7253 	return avc_has_perm(sid, bpfsec->sid, SECCLASS_BPF,
7254 			    BPF__PROG_RUN, NULL);
7255 }
7256 
7257 static u32 selinux_bpffs_creator_sid(u32 fd)
7258 {
7259 	struct path path;
7260 	struct super_block *sb;
7261 	struct superblock_security_struct *sbsec;
7262 
7263 	CLASS(fd, f)(fd);
7264 
7265 	if (fd_empty(f))
7266 		return SECSID_NULL;
7267 
7268 	path = fd_file(f)->f_path;
7269 	sb = path.dentry->d_sb;
7270 	sbsec = selinux_superblock(sb);
7271 
7272 	return sbsec->creator_sid;
7273 }
7274 
7275 static int selinux_bpf_map_create(struct bpf_map *map, union bpf_attr *attr,
7276 				  struct bpf_token *token, bool kernel)
7277 {
7278 	struct bpf_security_struct *bpfsec;
7279 	u32 ssid;
7280 
7281 	bpfsec = selinux_bpf_map_security(map);
7282 	bpfsec->sid = current_sid();
7283 
7284 	if (!token)
7285 		ssid = bpfsec->sid;
7286 	else
7287 		ssid = selinux_bpffs_creator_sid(attr->map_token_fd);
7288 
7289 	return avc_has_perm(ssid, bpfsec->sid, SECCLASS_BPF, BPF__MAP_CREATE,
7290 			    NULL);
7291 }
7292 
7293 static int selinux_bpf_prog_load(struct bpf_prog *prog, union bpf_attr *attr,
7294 				 struct bpf_token *token, bool kernel)
7295 {
7296 	struct bpf_security_struct *bpfsec;
7297 	u32 ssid;
7298 
7299 	bpfsec = selinux_bpf_prog_security(prog);
7300 	bpfsec->sid = current_sid();
7301 
7302 	if (!token)
7303 		ssid = bpfsec->sid;
7304 	else
7305 		ssid = selinux_bpffs_creator_sid(attr->prog_token_fd);
7306 
7307 	return avc_has_perm(ssid, bpfsec->sid, SECCLASS_BPF, BPF__PROG_LOAD,
7308 			    NULL);
7309 }
7310 
7311 #define bpf_token_cmd(T, C) \
7312 	((T)->allowed_cmds & (1ULL << (C)))
7313 
7314 static int selinux_bpf_token_create(struct bpf_token *token,
7315 				    union bpf_attr *attr,
7316 				    const struct path *path)
7317 {
7318 	struct bpf_security_struct *bpfsec;
7319 	u32 sid = selinux_bpffs_creator_sid(attr->token_create.bpffs_fd);
7320 	int err;
7321 
7322 	bpfsec = selinux_bpf_token_security(token);
7323 	bpfsec->sid = current_sid();
7324 	bpfsec->grantor_sid = sid;
7325 
7326 	bpfsec->perms = 0;
7327 	/**
7328 	 * 'token->allowed_cmds' is a bit mask of allowed commands
7329 	 * Convert the BPF command enum to a bitmask representing its position
7330 	 * in the allowed_cmds bitmap.
7331 	 */
7332 	if (bpf_token_cmd(token, BPF_MAP_CREATE)) {
7333 		err = avc_has_perm(bpfsec->sid, sid, SECCLASS_BPF,
7334 				   BPF__MAP_CREATE_AS, NULL);
7335 		if (err)
7336 			return err;
7337 		bpfsec->perms |= BPF__MAP_CREATE;
7338 	}
7339 	if (bpf_token_cmd(token, BPF_PROG_LOAD)) {
7340 		err = avc_has_perm(bpfsec->sid, sid, SECCLASS_BPF,
7341 				   BPF__PROG_LOAD_AS, NULL);
7342 		if (err)
7343 			return err;
7344 		bpfsec->perms |= BPF__PROG_LOAD;
7345 	}
7346 
7347 	return 0;
7348 }
7349 
7350 static int selinux_bpf_token_cmd(const struct bpf_token *token,
7351 				 enum bpf_cmd cmd)
7352 {
7353 	struct bpf_security_struct *bpfsec;
7354 
7355 	bpfsec = token->security;
7356 	switch (cmd) {
7357 	case BPF_MAP_CREATE:
7358 		if (!(bpfsec->perms & BPF__MAP_CREATE))
7359 			return -EACCES;
7360 		break;
7361 	case BPF_PROG_LOAD:
7362 		if (!(bpfsec->perms & BPF__PROG_LOAD))
7363 			return -EACCES;
7364 		break;
7365 	default:
7366 		break;
7367 	}
7368 
7369 	return 0;
7370 }
7371 
7372 static int selinux_bpf_token_capable(const struct bpf_token *token, int cap)
7373 {
7374 	u16 sclass;
7375 	struct bpf_security_struct *bpfsec = token->security;
7376 	bool initns = (token->userns == &init_user_ns);
7377 	u32 av = CAP_TO_MASK(cap);
7378 
7379 	switch (CAP_TO_INDEX(cap)) {
7380 	case 0:
7381 		sclass = initns ? SECCLASS_CAPABILITY : SECCLASS_CAP_USERNS;
7382 		break;
7383 	case 1:
7384 		sclass = initns ? SECCLASS_CAPABILITY2 : SECCLASS_CAP2_USERNS;
7385 		break;
7386 	default:
7387 		pr_err("SELinux:  out of range capability %d\n", cap);
7388 		return -EINVAL;
7389 	}
7390 
7391 	return avc_has_perm(current_sid(), bpfsec->grantor_sid, sclass, av,
7392 			    NULL);
7393 }
7394 #endif
7395 
7396 #ifdef CONFIG_PERF_EVENTS
7397 static int selinux_perf_event_open(int type)
7398 {
7399 	u32 requested, sid = current_sid();
7400 
7401 	if (type == PERF_SECURITY_OPEN)
7402 		requested = PERF_EVENT__OPEN;
7403 	else if (type == PERF_SECURITY_CPU)
7404 		requested = PERF_EVENT__CPU;
7405 	else if (type == PERF_SECURITY_KERNEL)
7406 		requested = PERF_EVENT__KERNEL;
7407 	else if (type == PERF_SECURITY_TRACEPOINT)
7408 		requested = PERF_EVENT__TRACEPOINT;
7409 	else
7410 		return -EINVAL;
7411 
7412 	return avc_has_perm(sid, sid, SECCLASS_PERF_EVENT,
7413 			    requested, NULL);
7414 }
7415 
7416 static int selinux_perf_event_alloc(struct perf_event *event)
7417 {
7418 	struct perf_event_security_struct *perfsec;
7419 
7420 	perfsec = selinux_perf_event(event->security);
7421 	perfsec->sid = current_sid();
7422 
7423 	return 0;
7424 }
7425 
7426 static int selinux_perf_event_read(struct perf_event *event)
7427 {
7428 	struct perf_event_security_struct *perfsec = event->security;
7429 	u32 sid = current_sid();
7430 
7431 	return avc_has_perm(sid, perfsec->sid,
7432 			    SECCLASS_PERF_EVENT, PERF_EVENT__READ, NULL);
7433 }
7434 
7435 static int selinux_perf_event_write(struct perf_event *event)
7436 {
7437 	struct perf_event_security_struct *perfsec = event->security;
7438 	u32 sid = current_sid();
7439 
7440 	return avc_has_perm(sid, perfsec->sid,
7441 			    SECCLASS_PERF_EVENT, PERF_EVENT__WRITE, NULL);
7442 }
7443 #endif
7444 
7445 #ifdef CONFIG_IO_URING
7446 /**
7447  * selinux_uring_override_creds - check the requested cred override
7448  * @new: the target creds
7449  *
7450  * Check to see if the current task is allowed to override it's credentials
7451  * to service an io_uring operation.
7452  */
7453 static int selinux_uring_override_creds(const struct cred *new)
7454 {
7455 	return avc_has_perm(current_sid(), cred_sid(new),
7456 			    SECCLASS_IO_URING, IO_URING__OVERRIDE_CREDS, NULL);
7457 }
7458 
7459 /**
7460  * selinux_uring_sqpoll - check if a io_uring polling thread can be created
7461  *
7462  * Check to see if the current task is allowed to create a new io_uring
7463  * kernel polling thread.
7464  */
7465 static int selinux_uring_sqpoll(void)
7466 {
7467 	u32 sid = current_sid();
7468 
7469 	return avc_has_perm(sid, sid,
7470 			    SECCLASS_IO_URING, IO_URING__SQPOLL, NULL);
7471 }
7472 
7473 /**
7474  * selinux_uring_cmd - check if IORING_OP_URING_CMD is allowed
7475  * @ioucmd: the io_uring command structure
7476  *
7477  * Check to see if the current domain is allowed to execute an
7478  * IORING_OP_URING_CMD against the device/file specified in @ioucmd.
7479  *
7480  */
7481 static int selinux_uring_cmd(struct io_uring_cmd *ioucmd)
7482 {
7483 	struct file *file = ioucmd->file;
7484 	struct inode *inode = file_inode(file);
7485 	struct inode_security_struct *isec = selinux_inode(inode);
7486 	struct common_audit_data ad;
7487 
7488 	ad.type = LSM_AUDIT_DATA_FILE;
7489 	ad.u.file = file;
7490 
7491 	return avc_has_perm(current_sid(), isec->sid,
7492 			    SECCLASS_IO_URING, IO_URING__CMD, &ad);
7493 }
7494 
7495 /**
7496  * selinux_uring_allowed - check if io_uring_setup() can be called
7497  *
7498  * Check to see if the current task is allowed to call io_uring_setup().
7499  */
7500 static int selinux_uring_allowed(void)
7501 {
7502 	u32 sid = current_sid();
7503 
7504 	return avc_has_perm(sid, sid, SECCLASS_IO_URING, IO_URING__ALLOWED,
7505 			    NULL);
7506 }
7507 #endif /* CONFIG_IO_URING */
7508 
7509 static const struct lsm_id selinux_lsmid = {
7510 	.name = "selinux",
7511 	.id = LSM_ID_SELINUX,
7512 };
7513 
7514 struct lsm_blob_sizes selinux_blob_sizes __ro_after_init = {
7515 	.lbs_cred = sizeof(struct cred_security_struct),
7516 	.lbs_task = sizeof(struct task_security_struct),
7517 	.lbs_file = sizeof(struct file_security_struct),
7518 	.lbs_backing_file = sizeof(struct backing_file_security_struct),
7519 	.lbs_inode = sizeof(struct inode_security_struct),
7520 	.lbs_ipc = sizeof(struct ipc_security_struct),
7521 	.lbs_key = sizeof(struct key_security_struct),
7522 	.lbs_msg_msg = sizeof(struct msg_security_struct),
7523 #ifdef CONFIG_PERF_EVENTS
7524 	.lbs_perf_event = sizeof(struct perf_event_security_struct),
7525 #endif
7526 	.lbs_sock = sizeof(struct sk_security_struct),
7527 	.lbs_superblock = sizeof(struct superblock_security_struct),
7528 	.lbs_xattr_count = SELINUX_INODE_INIT_XATTRS,
7529 	.lbs_tun_dev = sizeof(struct tun_security_struct),
7530 	.lbs_ib = sizeof(struct ib_security_struct),
7531 	.lbs_bpf_map = sizeof(struct bpf_security_struct),
7532 	.lbs_bpf_prog = sizeof(struct bpf_security_struct),
7533 	.lbs_bpf_token = sizeof(struct bpf_security_struct),
7534 };
7535 
7536 /*
7537  * IMPORTANT NOTE: When adding new hooks, please be careful to keep this order:
7538  * 1. any hooks that don't belong to (2.) or (3.) below,
7539  * 2. hooks that both access structures allocated by other hooks, and allocate
7540  *    structures that can be later accessed by other hooks (mostly "cloning"
7541  *    hooks),
7542  * 3. hooks that only allocate structures that can be later accessed by other
7543  *    hooks ("allocating" hooks).
7544  *
7545  * Please follow block comment delimiters in the list to keep this order.
7546  */
7547 static struct security_hook_list selinux_hooks[] __ro_after_init = {
7548 	LSM_HOOK_INIT(binder_set_context_mgr, selinux_binder_set_context_mgr),
7549 	LSM_HOOK_INIT(binder_transaction, selinux_binder_transaction),
7550 	LSM_HOOK_INIT(binder_transfer_binder, selinux_binder_transfer_binder),
7551 	LSM_HOOK_INIT(binder_transfer_file, selinux_binder_transfer_file),
7552 
7553 	LSM_HOOK_INIT(ptrace_access_check, selinux_ptrace_access_check),
7554 	LSM_HOOK_INIT(ptrace_traceme, selinux_ptrace_traceme),
7555 	LSM_HOOK_INIT(capget, selinux_capget),
7556 	LSM_HOOK_INIT(capset, selinux_capset),
7557 	LSM_HOOK_INIT(capable, selinux_capable),
7558 	LSM_HOOK_INIT(quotactl, selinux_quotactl),
7559 	LSM_HOOK_INIT(quota_on, selinux_quota_on),
7560 	LSM_HOOK_INIT(syslog, selinux_syslog),
7561 	LSM_HOOK_INIT(vm_enough_memory, selinux_vm_enough_memory),
7562 
7563 	LSM_HOOK_INIT(netlink_send, selinux_netlink_send),
7564 
7565 	LSM_HOOK_INIT(bprm_creds_for_exec, selinux_bprm_creds_for_exec),
7566 	LSM_HOOK_INIT(bprm_committing_creds, selinux_bprm_committing_creds),
7567 	LSM_HOOK_INIT(bprm_committed_creds, selinux_bprm_committed_creds),
7568 
7569 	LSM_HOOK_INIT(sb_free_mnt_opts, selinux_free_mnt_opts),
7570 	LSM_HOOK_INIT(sb_mnt_opts_compat, selinux_sb_mnt_opts_compat),
7571 	LSM_HOOK_INIT(sb_remount, selinux_sb_remount),
7572 	LSM_HOOK_INIT(sb_kern_mount, selinux_sb_kern_mount),
7573 	LSM_HOOK_INIT(sb_show_options, selinux_sb_show_options),
7574 	LSM_HOOK_INIT(sb_statfs, selinux_sb_statfs),
7575 	LSM_HOOK_INIT(sb_mount, selinux_mount),
7576 	LSM_HOOK_INIT(sb_umount, selinux_umount),
7577 	LSM_HOOK_INIT(sb_set_mnt_opts, selinux_set_mnt_opts),
7578 	LSM_HOOK_INIT(sb_clone_mnt_opts, selinux_sb_clone_mnt_opts),
7579 
7580 	LSM_HOOK_INIT(move_mount, selinux_move_mount),
7581 
7582 	LSM_HOOK_INIT(dentry_init_security, selinux_dentry_init_security),
7583 	LSM_HOOK_INIT(dentry_create_files_as, selinux_dentry_create_files_as),
7584 
7585 	LSM_HOOK_INIT(inode_free_security, selinux_inode_free_security),
7586 	LSM_HOOK_INIT(inode_init_security, selinux_inode_init_security),
7587 	LSM_HOOK_INIT(inode_init_security_anon, selinux_inode_init_security_anon),
7588 	LSM_HOOK_INIT(inode_create, selinux_inode_create),
7589 	LSM_HOOK_INIT(inode_link, selinux_inode_link),
7590 	LSM_HOOK_INIT(inode_unlink, selinux_inode_unlink),
7591 	LSM_HOOK_INIT(inode_symlink, selinux_inode_symlink),
7592 	LSM_HOOK_INIT(inode_mkdir, selinux_inode_mkdir),
7593 	LSM_HOOK_INIT(inode_rmdir, selinux_inode_rmdir),
7594 	LSM_HOOK_INIT(inode_mknod, selinux_inode_mknod),
7595 	LSM_HOOK_INIT(inode_rename, selinux_inode_rename),
7596 	LSM_HOOK_INIT(inode_readlink, selinux_inode_readlink),
7597 	LSM_HOOK_INIT(inode_follow_link, selinux_inode_follow_link),
7598 	LSM_HOOK_INIT(inode_permission, selinux_inode_permission),
7599 	LSM_HOOK_INIT(inode_setattr, selinux_inode_setattr),
7600 	LSM_HOOK_INIT(inode_getattr, selinux_inode_getattr),
7601 	LSM_HOOK_INIT(inode_xattr_skipcap, selinux_inode_xattr_skipcap),
7602 	LSM_HOOK_INIT(inode_setxattr, selinux_inode_setxattr),
7603 	LSM_HOOK_INIT(inode_post_setxattr, selinux_inode_post_setxattr),
7604 	LSM_HOOK_INIT(inode_getxattr, selinux_inode_getxattr),
7605 	LSM_HOOK_INIT(inode_listxattr, selinux_inode_listxattr),
7606 	LSM_HOOK_INIT(inode_removexattr, selinux_inode_removexattr),
7607 	LSM_HOOK_INIT(inode_file_getattr, selinux_inode_file_getattr),
7608 	LSM_HOOK_INIT(inode_file_setattr, selinux_inode_file_setattr),
7609 	LSM_HOOK_INIT(inode_set_acl, selinux_inode_set_acl),
7610 	LSM_HOOK_INIT(inode_get_acl, selinux_inode_get_acl),
7611 	LSM_HOOK_INIT(inode_remove_acl, selinux_inode_remove_acl),
7612 	LSM_HOOK_INIT(inode_getsecurity, selinux_inode_getsecurity),
7613 	LSM_HOOK_INIT(inode_setsecurity, selinux_inode_setsecurity),
7614 	LSM_HOOK_INIT(inode_listsecurity, selinux_inode_listsecurity),
7615 	LSM_HOOK_INIT(inode_getlsmprop, selinux_inode_getlsmprop),
7616 	LSM_HOOK_INIT(inode_copy_up, selinux_inode_copy_up),
7617 	LSM_HOOK_INIT(inode_copy_up_xattr, selinux_inode_copy_up_xattr),
7618 	LSM_HOOK_INIT(path_notify, selinux_path_notify),
7619 
7620 	LSM_HOOK_INIT(kernfs_init_security, selinux_kernfs_init_security),
7621 
7622 	LSM_HOOK_INIT(file_permission, selinux_file_permission),
7623 	LSM_HOOK_INIT(file_alloc_security, selinux_file_alloc_security),
7624 	LSM_HOOK_INIT(backing_file_alloc, selinux_backing_file_alloc),
7625 	LSM_HOOK_INIT(file_ioctl, selinux_file_ioctl),
7626 	LSM_HOOK_INIT(file_ioctl_compat, selinux_file_ioctl_compat),
7627 	LSM_HOOK_INIT(mmap_file, selinux_mmap_file),
7628 	LSM_HOOK_INIT(mmap_backing_file, selinux_mmap_backing_file),
7629 	LSM_HOOK_INIT(mmap_addr, selinux_mmap_addr),
7630 	LSM_HOOK_INIT(file_mprotect, selinux_file_mprotect),
7631 	LSM_HOOK_INIT(file_lock, selinux_file_lock),
7632 	LSM_HOOK_INIT(file_fcntl, selinux_file_fcntl),
7633 	LSM_HOOK_INIT(file_set_fowner, selinux_file_set_fowner),
7634 	LSM_HOOK_INIT(file_send_sigiotask, selinux_file_send_sigiotask),
7635 	LSM_HOOK_INIT(file_receive, selinux_file_receive),
7636 
7637 	LSM_HOOK_INIT(file_open, selinux_file_open),
7638 
7639 	LSM_HOOK_INIT(task_alloc, selinux_task_alloc),
7640 	LSM_HOOK_INIT(cred_prepare, selinux_cred_prepare),
7641 	LSM_HOOK_INIT(cred_transfer, selinux_cred_transfer),
7642 	LSM_HOOK_INIT(cred_getsecid, selinux_cred_getsecid),
7643 	LSM_HOOK_INIT(cred_getlsmprop, selinux_cred_getlsmprop),
7644 	LSM_HOOK_INIT(kernel_act_as, selinux_kernel_act_as),
7645 	LSM_HOOK_INIT(kernel_create_files_as, selinux_kernel_create_files_as),
7646 	LSM_HOOK_INIT(kernel_module_request, selinux_kernel_module_request),
7647 	LSM_HOOK_INIT(kernel_load_data, selinux_kernel_load_data),
7648 	LSM_HOOK_INIT(kernel_read_file, selinux_kernel_read_file),
7649 	LSM_HOOK_INIT(task_setpgid, selinux_task_setpgid),
7650 	LSM_HOOK_INIT(task_getpgid, selinux_task_getpgid),
7651 	LSM_HOOK_INIT(task_getsid, selinux_task_getsid),
7652 	LSM_HOOK_INIT(current_getlsmprop_subj, selinux_current_getlsmprop_subj),
7653 	LSM_HOOK_INIT(task_getlsmprop_obj, selinux_task_getlsmprop_obj),
7654 	LSM_HOOK_INIT(task_setnice, selinux_task_setnice),
7655 	LSM_HOOK_INIT(task_setioprio, selinux_task_setioprio),
7656 	LSM_HOOK_INIT(task_getioprio, selinux_task_getioprio),
7657 	LSM_HOOK_INIT(task_prlimit, selinux_task_prlimit),
7658 	LSM_HOOK_INIT(task_setrlimit, selinux_task_setrlimit),
7659 	LSM_HOOK_INIT(task_setscheduler, selinux_task_setscheduler),
7660 	LSM_HOOK_INIT(task_getscheduler, selinux_task_getscheduler),
7661 	LSM_HOOK_INIT(task_movememory, selinux_task_movememory),
7662 	LSM_HOOK_INIT(task_kill, selinux_task_kill),
7663 	LSM_HOOK_INIT(task_to_inode, selinux_task_to_inode),
7664 	LSM_HOOK_INIT(userns_create, selinux_userns_create),
7665 
7666 	LSM_HOOK_INIT(ipc_permission, selinux_ipc_permission),
7667 	LSM_HOOK_INIT(ipc_getlsmprop, selinux_ipc_getlsmprop),
7668 
7669 	LSM_HOOK_INIT(msg_queue_associate, selinux_msg_queue_associate),
7670 	LSM_HOOK_INIT(msg_queue_msgctl, selinux_msg_queue_msgctl),
7671 	LSM_HOOK_INIT(msg_queue_msgsnd, selinux_msg_queue_msgsnd),
7672 	LSM_HOOK_INIT(msg_queue_msgrcv, selinux_msg_queue_msgrcv),
7673 
7674 	LSM_HOOK_INIT(shm_associate, selinux_shm_associate),
7675 	LSM_HOOK_INIT(shm_shmctl, selinux_shm_shmctl),
7676 	LSM_HOOK_INIT(shm_shmat, selinux_shm_shmat),
7677 
7678 	LSM_HOOK_INIT(sem_associate, selinux_sem_associate),
7679 	LSM_HOOK_INIT(sem_semctl, selinux_sem_semctl),
7680 	LSM_HOOK_INIT(sem_semop, selinux_sem_semop),
7681 
7682 	LSM_HOOK_INIT(d_instantiate, selinux_d_instantiate),
7683 
7684 	LSM_HOOK_INIT(getselfattr, selinux_getselfattr),
7685 	LSM_HOOK_INIT(setselfattr, selinux_setselfattr),
7686 	LSM_HOOK_INIT(getprocattr, selinux_getprocattr),
7687 	LSM_HOOK_INIT(setprocattr, selinux_setprocattr),
7688 
7689 	LSM_HOOK_INIT(ismaclabel, selinux_ismaclabel),
7690 	LSM_HOOK_INIT(secctx_to_secid, selinux_secctx_to_secid),
7691 	LSM_HOOK_INIT(release_secctx, selinux_release_secctx),
7692 	LSM_HOOK_INIT(inode_invalidate_secctx, selinux_inode_invalidate_secctx),
7693 	LSM_HOOK_INIT(inode_notifysecctx, selinux_inode_notifysecctx),
7694 	LSM_HOOK_INIT(inode_setsecctx, selinux_inode_setsecctx),
7695 
7696 	LSM_HOOK_INIT(unix_stream_connect, selinux_socket_unix_stream_connect),
7697 	LSM_HOOK_INIT(unix_may_send, selinux_socket_unix_may_send),
7698 
7699 	LSM_HOOK_INIT(socket_create, selinux_socket_create),
7700 	LSM_HOOK_INIT(socket_post_create, selinux_socket_post_create),
7701 	LSM_HOOK_INIT(socket_socketpair, selinux_socket_socketpair),
7702 	LSM_HOOK_INIT(socket_bind, selinux_socket_bind),
7703 	LSM_HOOK_INIT(socket_connect, selinux_socket_connect),
7704 	LSM_HOOK_INIT(socket_listen, selinux_socket_listen),
7705 	LSM_HOOK_INIT(socket_accept, selinux_socket_accept),
7706 	LSM_HOOK_INIT(socket_sendmsg, selinux_socket_sendmsg),
7707 	LSM_HOOK_INIT(socket_recvmsg, selinux_socket_recvmsg),
7708 	LSM_HOOK_INIT(socket_getsockname, selinux_socket_getsockname),
7709 	LSM_HOOK_INIT(socket_getpeername, selinux_socket_getpeername),
7710 	LSM_HOOK_INIT(socket_getsockopt, selinux_socket_getsockopt),
7711 	LSM_HOOK_INIT(socket_setsockopt, selinux_socket_setsockopt),
7712 	LSM_HOOK_INIT(socket_shutdown, selinux_socket_shutdown),
7713 	LSM_HOOK_INIT(socket_sock_rcv_skb, selinux_socket_sock_rcv_skb),
7714 	LSM_HOOK_INIT(socket_getpeersec_stream,
7715 			selinux_socket_getpeersec_stream),
7716 	LSM_HOOK_INIT(socket_getpeersec_dgram, selinux_socket_getpeersec_dgram),
7717 	LSM_HOOK_INIT(sk_free_security, selinux_sk_free_security),
7718 	LSM_HOOK_INIT(sk_clone_security, selinux_sk_clone_security),
7719 	LSM_HOOK_INIT(sk_getsecid, selinux_sk_getsecid),
7720 	LSM_HOOK_INIT(sock_graft, selinux_sock_graft),
7721 	LSM_HOOK_INIT(sctp_assoc_request, selinux_sctp_assoc_request),
7722 	LSM_HOOK_INIT(sctp_sk_clone, selinux_sctp_sk_clone),
7723 	LSM_HOOK_INIT(sctp_bind_connect, selinux_sctp_bind_connect),
7724 	LSM_HOOK_INIT(sctp_assoc_established, selinux_sctp_assoc_established),
7725 	LSM_HOOK_INIT(mptcp_add_subflow, selinux_mptcp_add_subflow),
7726 	LSM_HOOK_INIT(inet_conn_request, selinux_inet_conn_request),
7727 	LSM_HOOK_INIT(inet_csk_clone, selinux_inet_csk_clone),
7728 	LSM_HOOK_INIT(inet_conn_established, selinux_inet_conn_established),
7729 	LSM_HOOK_INIT(secmark_relabel_packet, selinux_secmark_relabel_packet),
7730 	LSM_HOOK_INIT(secmark_refcount_inc, selinux_secmark_refcount_inc),
7731 	LSM_HOOK_INIT(secmark_refcount_dec, selinux_secmark_refcount_dec),
7732 	LSM_HOOK_INIT(req_classify_flow, selinux_req_classify_flow),
7733 	LSM_HOOK_INIT(tun_dev_create, selinux_tun_dev_create),
7734 	LSM_HOOK_INIT(tun_dev_attach_queue, selinux_tun_dev_attach_queue),
7735 	LSM_HOOK_INIT(tun_dev_attach, selinux_tun_dev_attach),
7736 	LSM_HOOK_INIT(tun_dev_open, selinux_tun_dev_open),
7737 #ifdef CONFIG_SECURITY_INFINIBAND
7738 	LSM_HOOK_INIT(ib_pkey_access, selinux_ib_pkey_access),
7739 	LSM_HOOK_INIT(ib_endport_manage_subnet,
7740 		      selinux_ib_endport_manage_subnet),
7741 #endif
7742 #ifdef CONFIG_SECURITY_NETWORK_XFRM
7743 	LSM_HOOK_INIT(xfrm_policy_free_security, selinux_xfrm_policy_free),
7744 	LSM_HOOK_INIT(xfrm_policy_delete_security, selinux_xfrm_policy_delete),
7745 	LSM_HOOK_INIT(xfrm_state_free_security, selinux_xfrm_state_free),
7746 	LSM_HOOK_INIT(xfrm_state_delete_security, selinux_xfrm_state_delete),
7747 	LSM_HOOK_INIT(xfrm_policy_lookup, selinux_xfrm_policy_lookup),
7748 	LSM_HOOK_INIT(xfrm_state_pol_flow_match,
7749 			selinux_xfrm_state_pol_flow_match),
7750 	LSM_HOOK_INIT(xfrm_decode_session, selinux_xfrm_decode_session),
7751 #endif
7752 
7753 #ifdef CONFIG_KEYS
7754 	LSM_HOOK_INIT(key_permission, selinux_key_permission),
7755 	LSM_HOOK_INIT(key_getsecurity, selinux_key_getsecurity),
7756 #ifdef CONFIG_KEY_NOTIFICATIONS
7757 	LSM_HOOK_INIT(watch_key, selinux_watch_key),
7758 #endif
7759 #endif
7760 
7761 #ifdef CONFIG_AUDIT
7762 	LSM_HOOK_INIT(audit_rule_known, selinux_audit_rule_known),
7763 	LSM_HOOK_INIT(audit_rule_match, selinux_audit_rule_match),
7764 	LSM_HOOK_INIT(audit_rule_free, selinux_audit_rule_free),
7765 #endif
7766 
7767 #ifdef CONFIG_BPF_SYSCALL
7768 	LSM_HOOK_INIT(bpf, selinux_bpf),
7769 	LSM_HOOK_INIT(bpf_map, selinux_bpf_map),
7770 	LSM_HOOK_INIT(bpf_prog, selinux_bpf_prog),
7771 #endif
7772 
7773 #ifdef CONFIG_PERF_EVENTS
7774 	LSM_HOOK_INIT(perf_event_open, selinux_perf_event_open),
7775 	LSM_HOOK_INIT(perf_event_read, selinux_perf_event_read),
7776 	LSM_HOOK_INIT(perf_event_write, selinux_perf_event_write),
7777 #endif
7778 
7779 #ifdef CONFIG_IO_URING
7780 	LSM_HOOK_INIT(uring_override_creds, selinux_uring_override_creds),
7781 	LSM_HOOK_INIT(uring_sqpoll, selinux_uring_sqpoll),
7782 	LSM_HOOK_INIT(uring_cmd, selinux_uring_cmd),
7783 	LSM_HOOK_INIT(uring_allowed, selinux_uring_allowed),
7784 #endif
7785 
7786 	/*
7787 	 * PUT "CLONING" (ACCESSING + ALLOCATING) HOOKS HERE
7788 	 */
7789 	LSM_HOOK_INIT(fs_context_submount, selinux_fs_context_submount),
7790 	LSM_HOOK_INIT(fs_context_dup, selinux_fs_context_dup),
7791 	LSM_HOOK_INIT(fs_context_parse_param, selinux_fs_context_parse_param),
7792 	LSM_HOOK_INIT(sb_eat_lsm_opts, selinux_sb_eat_lsm_opts),
7793 #ifdef CONFIG_SECURITY_NETWORK_XFRM
7794 	LSM_HOOK_INIT(xfrm_policy_clone_security, selinux_xfrm_policy_clone),
7795 #endif
7796 
7797 	/*
7798 	 * PUT "ALLOCATING" HOOKS HERE
7799 	 */
7800 	LSM_HOOK_INIT(msg_msg_alloc_security, selinux_msg_msg_alloc_security),
7801 	LSM_HOOK_INIT(msg_queue_alloc_security,
7802 		      selinux_msg_queue_alloc_security),
7803 	LSM_HOOK_INIT(shm_alloc_security, selinux_shm_alloc_security),
7804 	LSM_HOOK_INIT(sb_alloc_security, selinux_sb_alloc_security),
7805 	LSM_HOOK_INIT(inode_alloc_security, selinux_inode_alloc_security),
7806 	LSM_HOOK_INIT(sem_alloc_security, selinux_sem_alloc_security),
7807 	LSM_HOOK_INIT(secid_to_secctx, selinux_secid_to_secctx),
7808 	LSM_HOOK_INIT(lsmprop_to_secctx, selinux_lsmprop_to_secctx),
7809 	LSM_HOOK_INIT(inode_getsecctx, selinux_inode_getsecctx),
7810 	LSM_HOOK_INIT(sk_alloc_security, selinux_sk_alloc_security),
7811 	LSM_HOOK_INIT(tun_dev_alloc_security, selinux_tun_dev_alloc_security),
7812 #ifdef CONFIG_SECURITY_INFINIBAND
7813 	LSM_HOOK_INIT(ib_alloc_security, selinux_ib_alloc_security),
7814 #endif
7815 #ifdef CONFIG_SECURITY_NETWORK_XFRM
7816 	LSM_HOOK_INIT(xfrm_policy_alloc_security, selinux_xfrm_policy_alloc),
7817 	LSM_HOOK_INIT(xfrm_state_alloc, selinux_xfrm_state_alloc),
7818 	LSM_HOOK_INIT(xfrm_state_alloc_acquire,
7819 		      selinux_xfrm_state_alloc_acquire),
7820 #endif
7821 #ifdef CONFIG_KEYS
7822 	LSM_HOOK_INIT(key_alloc, selinux_key_alloc),
7823 #endif
7824 #ifdef CONFIG_AUDIT
7825 	LSM_HOOK_INIT(audit_rule_init, selinux_audit_rule_init),
7826 #endif
7827 #ifdef CONFIG_BPF_SYSCALL
7828 	LSM_HOOK_INIT(bpf_map_create, selinux_bpf_map_create),
7829 	LSM_HOOK_INIT(bpf_prog_load, selinux_bpf_prog_load),
7830 	LSM_HOOK_INIT(bpf_token_create, selinux_bpf_token_create),
7831 	LSM_HOOK_INIT(bpf_token_cmd, selinux_bpf_token_cmd),
7832 	LSM_HOOK_INIT(bpf_token_capable, selinux_bpf_token_capable),
7833 #endif
7834 #ifdef CONFIG_PERF_EVENTS
7835 	LSM_HOOK_INIT(perf_event_alloc, selinux_perf_event_alloc),
7836 #endif
7837 };
7838 
7839 static __init int selinux_init(void)
7840 {
7841 	vma_flags_t data_default_flags = VMA_DATA_DEFAULT_FLAGS;
7842 
7843 	pr_info("SELinux:  Initializing.\n");
7844 
7845 	memset(&selinux_state, 0, sizeof(selinux_state));
7846 	enforcing_set(selinux_enforcing_boot);
7847 	selinux_avc_init();
7848 	mutex_init(&selinux_state.status_lock);
7849 	mutex_init(&selinux_state.policy_mutex);
7850 
7851 	/* Set the security state for the initial task. */
7852 	cred_init_security();
7853 
7854 	/* Inform the audit system that secctx is used */
7855 	audit_cfg_lsm(&selinux_lsmid,
7856 		      AUDIT_CFG_LSM_SECCTX_SUBJECT |
7857 		      AUDIT_CFG_LSM_SECCTX_OBJECT);
7858 
7859 	default_noexec = !vma_flags_test(&data_default_flags, VMA_EXEC_BIT);
7860 	if (!default_noexec)
7861 		pr_notice("SELinux:  virtual memory is executable by default\n");
7862 
7863 	avc_init();
7864 
7865 	avtab_cache_init();
7866 
7867 	ebitmap_cache_init();
7868 
7869 	hashtab_cache_init();
7870 
7871 	security_add_hooks(selinux_hooks, ARRAY_SIZE(selinux_hooks),
7872 			   &selinux_lsmid);
7873 
7874 	if (avc_add_callback(selinux_netcache_avc_callback, AVC_CALLBACK_RESET))
7875 		panic("SELinux: Unable to register AVC netcache callback\n");
7876 
7877 	if (avc_add_callback(selinux_lsm_notifier_avc_callback, AVC_CALLBACK_RESET))
7878 		panic("SELinux: Unable to register AVC LSM notifier callback\n");
7879 
7880 	if (avc_add_callback(selinux_audit_rule_avc_callback,
7881 			     AVC_CALLBACK_RESET))
7882 		panic("SELinux: Unable to register AVC audit callback\n");
7883 
7884 	if (selinux_enforcing_boot)
7885 		pr_debug("SELinux:  Starting in enforcing mode\n");
7886 	else
7887 		pr_debug("SELinux:  Starting in permissive mode\n");
7888 
7889 	fs_validate_description("selinux", selinux_fs_parameters);
7890 
7891 	return 0;
7892 }
7893 
7894 static void delayed_superblock_init(struct super_block *sb, void *unused)
7895 {
7896 	selinux_set_mnt_opts(sb, NULL, 0, NULL);
7897 }
7898 
7899 void selinux_complete_init(void)
7900 {
7901 	pr_debug("SELinux:  Completing initialization.\n");
7902 
7903 	/* Set up any superblocks initialized prior to the policy load. */
7904 	pr_debug("SELinux:  Setting up existing superblocks.\n");
7905 	iterate_supers(delayed_superblock_init, NULL);
7906 }
7907 
7908 /* SELinux requires early initialization in order to label
7909    all processes and objects when they are created. */
7910 DEFINE_LSM(selinux) = {
7911 	.id = &selinux_lsmid,
7912 	.flags = LSM_FLAG_LEGACY_MAJOR | LSM_FLAG_EXCLUSIVE,
7913 	.enabled = &selinux_enabled_boot,
7914 	.blobs = &selinux_blob_sizes,
7915 	.init = selinux_init,
7916 	.initcall_device = selinux_initcall,
7917 };
7918 
7919 #if defined(CONFIG_NETFILTER)
7920 static const struct nf_hook_ops selinux_nf_ops[] = {
7921 	{
7922 		.hook =		selinux_ip_postroute,
7923 		.pf =		NFPROTO_IPV4,
7924 		.hooknum =	NF_INET_POST_ROUTING,
7925 		.priority =	NF_IP_PRI_SELINUX_LAST,
7926 	},
7927 	{
7928 		.hook =		selinux_ip_forward,
7929 		.pf =		NFPROTO_IPV4,
7930 		.hooknum =	NF_INET_FORWARD,
7931 		.priority =	NF_IP_PRI_SELINUX_FIRST,
7932 	},
7933 	{
7934 		.hook =		selinux_ip_output,
7935 		.pf =		NFPROTO_IPV4,
7936 		.hooknum =	NF_INET_LOCAL_OUT,
7937 		.priority =	NF_IP_PRI_SELINUX_FIRST,
7938 	},
7939 #if IS_ENABLED(CONFIG_IPV6)
7940 	{
7941 		.hook =		selinux_ip_postroute,
7942 		.pf =		NFPROTO_IPV6,
7943 		.hooknum =	NF_INET_POST_ROUTING,
7944 		.priority =	NF_IP6_PRI_SELINUX_LAST,
7945 	},
7946 	{
7947 		.hook =		selinux_ip_forward,
7948 		.pf =		NFPROTO_IPV6,
7949 		.hooknum =	NF_INET_FORWARD,
7950 		.priority =	NF_IP6_PRI_SELINUX_FIRST,
7951 	},
7952 	{
7953 		.hook =		selinux_ip_output,
7954 		.pf =		NFPROTO_IPV6,
7955 		.hooknum =	NF_INET_LOCAL_OUT,
7956 		.priority =	NF_IP6_PRI_SELINUX_FIRST,
7957 	},
7958 #endif	/* IPV6 */
7959 };
7960 
7961 static int __net_init selinux_nf_register(struct net *net)
7962 {
7963 	return nf_register_net_hooks(net, selinux_nf_ops,
7964 				     ARRAY_SIZE(selinux_nf_ops));
7965 }
7966 
7967 static void __net_exit selinux_nf_unregister(struct net *net)
7968 {
7969 	nf_unregister_net_hooks(net, selinux_nf_ops,
7970 				ARRAY_SIZE(selinux_nf_ops));
7971 }
7972 
7973 static struct pernet_operations selinux_net_ops = {
7974 	.init = selinux_nf_register,
7975 	.exit = selinux_nf_unregister,
7976 };
7977 
7978 int __init selinux_nf_ip_init(void)
7979 {
7980 	int err;
7981 
7982 	if (!selinux_enabled_boot)
7983 		return 0;
7984 
7985 	pr_debug("SELinux:  Registering netfilter hooks\n");
7986 
7987 	err = register_pernet_subsys(&selinux_net_ops);
7988 	if (err)
7989 		panic("SELinux: register_pernet_subsys: error %d\n", err);
7990 
7991 	return 0;
7992 }
7993 #endif /* CONFIG_NETFILTER */
7994