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