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