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