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