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