xref: /linux/security/selinux/hooks.c (revision 204a920f284e7264aa6dcd5876cbb1e03a7e4ebc)
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 > 7,
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 		rc = selinux_kernel_load_from_file(file, SYSTEM__MODULE_LOAD);
4308 		break;
4309 	case READING_KEXEC_IMAGE:
4310 		rc = selinux_kernel_load_from_file(file,
4311 						   SYSTEM__KEXEC_IMAGE_LOAD);
4312 		break;
4313 	case READING_KEXEC_INITRAMFS:
4314 		rc = selinux_kernel_load_from_file(file,
4315 						SYSTEM__KEXEC_INITRAMFS_LOAD);
4316 		break;
4317 	case READING_POLICY:
4318 		rc = selinux_kernel_load_from_file(file, SYSTEM__POLICY_LOAD);
4319 		break;
4320 	case READING_X509_CERTIFICATE:
4321 		rc = selinux_kernel_load_from_file(file,
4322 						SYSTEM__X509_CERTIFICATE_LOAD);
4323 		break;
4324 	default:
4325 		break;
4326 	}
4327 
4328 	return rc;
4329 }
4330 
4331 static int selinux_kernel_load_data(enum kernel_load_data_id id, bool contents)
4332 {
4333 	int rc = 0;
4334 
4335 	BUILD_BUG_ON_MSG(LOADING_MAX_ID > 7,
4336 			 "New kernel_load_data_id introduced; update SELinux!");
4337 
4338 	switch (id) {
4339 	case LOADING_FIRMWARE:
4340 		rc = selinux_kernel_load_from_file(NULL, SYSTEM__FIRMWARE_LOAD);
4341 		break;
4342 	case LOADING_MODULE:
4343 		rc = selinux_kernel_load_from_file(NULL, SYSTEM__MODULE_LOAD);
4344 		break;
4345 	case LOADING_KEXEC_IMAGE:
4346 		rc = selinux_kernel_load_from_file(NULL,
4347 						   SYSTEM__KEXEC_IMAGE_LOAD);
4348 		break;
4349 	case LOADING_KEXEC_INITRAMFS:
4350 		rc = selinux_kernel_load_from_file(NULL,
4351 						SYSTEM__KEXEC_INITRAMFS_LOAD);
4352 		break;
4353 	case LOADING_POLICY:
4354 		rc = selinux_kernel_load_from_file(NULL,
4355 						   SYSTEM__POLICY_LOAD);
4356 		break;
4357 	case LOADING_X509_CERTIFICATE:
4358 		rc = selinux_kernel_load_from_file(NULL,
4359 						SYSTEM__X509_CERTIFICATE_LOAD);
4360 		break;
4361 	default:
4362 		break;
4363 	}
4364 
4365 	return rc;
4366 }
4367 
4368 static int selinux_task_setpgid(struct task_struct *p, pid_t pgid)
4369 {
4370 	return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4371 			    PROCESS__SETPGID, NULL);
4372 }
4373 
4374 static int selinux_task_getpgid(struct task_struct *p)
4375 {
4376 	return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4377 			    PROCESS__GETPGID, NULL);
4378 }
4379 
4380 static int selinux_task_getsid(struct task_struct *p)
4381 {
4382 	return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4383 			    PROCESS__GETSESSION, NULL);
4384 }
4385 
4386 static void selinux_current_getlsmprop_subj(struct lsm_prop *prop)
4387 {
4388 	prop->selinux.secid = current_sid();
4389 }
4390 
4391 static void selinux_task_getlsmprop_obj(struct task_struct *p,
4392 					struct lsm_prop *prop)
4393 {
4394 	prop->selinux.secid = task_sid_obj(p);
4395 }
4396 
4397 static int selinux_task_setnice(struct task_struct *p, int nice)
4398 {
4399 	return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4400 			    PROCESS__SETSCHED, NULL);
4401 }
4402 
4403 static int selinux_task_setioprio(struct task_struct *p, int ioprio)
4404 {
4405 	return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4406 			    PROCESS__SETSCHED, NULL);
4407 }
4408 
4409 static int selinux_task_getioprio(struct task_struct *p)
4410 {
4411 	return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4412 			    PROCESS__GETSCHED, NULL);
4413 }
4414 
4415 static int selinux_task_prlimit(const struct cred *cred, const struct cred *tcred,
4416 				unsigned int flags)
4417 {
4418 	u32 av = 0;
4419 
4420 	if (!flags)
4421 		return 0;
4422 	if (flags & LSM_PRLIMIT_WRITE)
4423 		av |= PROCESS__SETRLIMIT;
4424 	if (flags & LSM_PRLIMIT_READ)
4425 		av |= PROCESS__GETRLIMIT;
4426 	return avc_has_perm(cred_sid(cred), cred_sid(tcred),
4427 			    SECCLASS_PROCESS, av, NULL);
4428 }
4429 
4430 static int selinux_task_setrlimit(struct task_struct *p, unsigned int resource,
4431 		struct rlimit *new_rlim)
4432 {
4433 	struct rlimit *old_rlim = p->signal->rlim + resource;
4434 
4435 	/* Control the ability to change the hard limit (whether
4436 	   lowering or raising it), so that the hard limit can
4437 	   later be used as a safe reset point for the soft limit
4438 	   upon context transitions.  See selinux_bprm_committing_creds. */
4439 	if (old_rlim->rlim_max != new_rlim->rlim_max)
4440 		return avc_has_perm(current_sid(), task_sid_obj(p),
4441 				    SECCLASS_PROCESS, PROCESS__SETRLIMIT, NULL);
4442 
4443 	return 0;
4444 }
4445 
4446 static int selinux_task_setscheduler(struct task_struct *p)
4447 {
4448 	return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4449 			    PROCESS__SETSCHED, NULL);
4450 }
4451 
4452 static int selinux_task_getscheduler(struct task_struct *p)
4453 {
4454 	return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4455 			    PROCESS__GETSCHED, NULL);
4456 }
4457 
4458 static int selinux_task_movememory(struct task_struct *p)
4459 {
4460 	return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4461 			    PROCESS__SETSCHED, NULL);
4462 }
4463 
4464 static int selinux_task_kill(struct task_struct *p, struct kernel_siginfo *info,
4465 				int sig, const struct cred *cred)
4466 {
4467 	u32 secid;
4468 	u32 perm;
4469 
4470 	if (!sig)
4471 		perm = PROCESS__SIGNULL; /* null signal; existence test */
4472 	else
4473 		perm = signal_to_av(sig);
4474 	if (!cred)
4475 		secid = current_sid();
4476 	else
4477 		secid = cred_sid(cred);
4478 	return avc_has_perm(secid, task_sid_obj(p), SECCLASS_PROCESS, perm, NULL);
4479 }
4480 
4481 static void selinux_task_to_inode(struct task_struct *p,
4482 				  struct inode *inode)
4483 {
4484 	struct inode_security_struct *isec = selinux_inode(inode);
4485 	u32 sid = task_sid_obj(p);
4486 
4487 	spin_lock(&isec->lock);
4488 	isec->sclass = inode_mode_to_security_class(inode->i_mode);
4489 	isec->sid = sid;
4490 	isec->initialized = LABEL_INITIALIZED;
4491 	spin_unlock(&isec->lock);
4492 }
4493 
4494 static int selinux_userns_create(const struct cred *cred)
4495 {
4496 	u32 sid = current_sid();
4497 
4498 	return avc_has_perm(sid, sid, SECCLASS_USER_NAMESPACE,
4499 			USER_NAMESPACE__CREATE, NULL);
4500 }
4501 
4502 /* Returns error only if unable to parse addresses */
4503 static int selinux_parse_skb_ipv4(struct sk_buff *skb,
4504 			struct common_audit_data *ad, u8 *proto)
4505 {
4506 	int offset, ihlen, ret = -EINVAL;
4507 	struct iphdr _iph, *ih;
4508 
4509 	offset = skb_network_offset(skb);
4510 	ih = skb_header_pointer(skb, offset, sizeof(_iph), &_iph);
4511 	if (ih == NULL)
4512 		goto out;
4513 
4514 	ihlen = ih->ihl * 4;
4515 	if (ihlen < sizeof(_iph))
4516 		goto out;
4517 
4518 	ad->u.net->v4info.saddr = ih->saddr;
4519 	ad->u.net->v4info.daddr = ih->daddr;
4520 	ret = 0;
4521 
4522 	if (proto)
4523 		*proto = ih->protocol;
4524 
4525 	switch (ih->protocol) {
4526 	case IPPROTO_TCP: {
4527 		struct tcphdr _tcph, *th;
4528 
4529 		if (ntohs(ih->frag_off) & IP_OFFSET)
4530 			break;
4531 
4532 		offset += ihlen;
4533 		th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
4534 		if (th == NULL)
4535 			break;
4536 
4537 		ad->u.net->sport = th->source;
4538 		ad->u.net->dport = th->dest;
4539 		break;
4540 	}
4541 
4542 	case IPPROTO_UDP: {
4543 		struct udphdr _udph, *uh;
4544 
4545 		if (ntohs(ih->frag_off) & IP_OFFSET)
4546 			break;
4547 
4548 		offset += ihlen;
4549 		uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
4550 		if (uh == NULL)
4551 			break;
4552 
4553 		ad->u.net->sport = uh->source;
4554 		ad->u.net->dport = uh->dest;
4555 		break;
4556 	}
4557 
4558 #if IS_ENABLED(CONFIG_IP_SCTP)
4559 	case IPPROTO_SCTP: {
4560 		struct sctphdr _sctph, *sh;
4561 
4562 		if (ntohs(ih->frag_off) & IP_OFFSET)
4563 			break;
4564 
4565 		offset += ihlen;
4566 		sh = skb_header_pointer(skb, offset, sizeof(_sctph), &_sctph);
4567 		if (sh == NULL)
4568 			break;
4569 
4570 		ad->u.net->sport = sh->source;
4571 		ad->u.net->dport = sh->dest;
4572 		break;
4573 	}
4574 #endif
4575 	default:
4576 		break;
4577 	}
4578 out:
4579 	return ret;
4580 }
4581 
4582 #if IS_ENABLED(CONFIG_IPV6)
4583 
4584 /* Returns error only if unable to parse addresses */
4585 static int selinux_parse_skb_ipv6(struct sk_buff *skb,
4586 			struct common_audit_data *ad, u8 *proto)
4587 {
4588 	u8 nexthdr;
4589 	int ret = -EINVAL, offset;
4590 	struct ipv6hdr _ipv6h, *ip6;
4591 	__be16 frag_off;
4592 
4593 	offset = skb_network_offset(skb);
4594 	ip6 = skb_header_pointer(skb, offset, sizeof(_ipv6h), &_ipv6h);
4595 	if (ip6 == NULL)
4596 		goto out;
4597 
4598 	ad->u.net->v6info.saddr = ip6->saddr;
4599 	ad->u.net->v6info.daddr = ip6->daddr;
4600 	ret = 0;
4601 
4602 	nexthdr = ip6->nexthdr;
4603 	offset += sizeof(_ipv6h);
4604 	offset = ipv6_skip_exthdr(skb, offset, &nexthdr, &frag_off);
4605 	if (offset < 0)
4606 		goto out;
4607 
4608 	if (proto)
4609 		*proto = nexthdr;
4610 
4611 	switch (nexthdr) {
4612 	case IPPROTO_TCP: {
4613 		struct tcphdr _tcph, *th;
4614 
4615 		th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
4616 		if (th == NULL)
4617 			break;
4618 
4619 		ad->u.net->sport = th->source;
4620 		ad->u.net->dport = th->dest;
4621 		break;
4622 	}
4623 
4624 	case IPPROTO_UDP: {
4625 		struct udphdr _udph, *uh;
4626 
4627 		uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
4628 		if (uh == NULL)
4629 			break;
4630 
4631 		ad->u.net->sport = uh->source;
4632 		ad->u.net->dport = uh->dest;
4633 		break;
4634 	}
4635 
4636 #if IS_ENABLED(CONFIG_IP_SCTP)
4637 	case IPPROTO_SCTP: {
4638 		struct sctphdr _sctph, *sh;
4639 
4640 		sh = skb_header_pointer(skb, offset, sizeof(_sctph), &_sctph);
4641 		if (sh == NULL)
4642 			break;
4643 
4644 		ad->u.net->sport = sh->source;
4645 		ad->u.net->dport = sh->dest;
4646 		break;
4647 	}
4648 #endif
4649 	/* includes fragments */
4650 	default:
4651 		break;
4652 	}
4653 out:
4654 	return ret;
4655 }
4656 
4657 #endif /* IPV6 */
4658 
4659 static int selinux_parse_skb(struct sk_buff *skb, struct common_audit_data *ad,
4660 			     char **_addrp, int src, u8 *proto)
4661 {
4662 	char *addrp;
4663 	int ret;
4664 
4665 	switch (ad->u.net->family) {
4666 	case PF_INET:
4667 		ret = selinux_parse_skb_ipv4(skb, ad, proto);
4668 		if (ret)
4669 			goto parse_error;
4670 		addrp = (char *)(src ? &ad->u.net->v4info.saddr :
4671 				       &ad->u.net->v4info.daddr);
4672 		goto okay;
4673 
4674 #if IS_ENABLED(CONFIG_IPV6)
4675 	case PF_INET6:
4676 		ret = selinux_parse_skb_ipv6(skb, ad, proto);
4677 		if (ret)
4678 			goto parse_error;
4679 		addrp = (char *)(src ? &ad->u.net->v6info.saddr :
4680 				       &ad->u.net->v6info.daddr);
4681 		goto okay;
4682 #endif	/* IPV6 */
4683 	default:
4684 		addrp = NULL;
4685 		goto okay;
4686 	}
4687 
4688 parse_error:
4689 	pr_warn(
4690 	       "SELinux: failure in selinux_parse_skb(),"
4691 	       " unable to parse packet\n");
4692 	return ret;
4693 
4694 okay:
4695 	if (_addrp)
4696 		*_addrp = addrp;
4697 	return 0;
4698 }
4699 
4700 /**
4701  * selinux_skb_peerlbl_sid - Determine the peer label of a packet
4702  * @skb: the packet
4703  * @family: protocol family
4704  * @sid: the packet's peer label SID
4705  *
4706  * Description:
4707  * Check the various different forms of network peer labeling and determine
4708  * the peer label/SID for the packet; most of the magic actually occurs in
4709  * the security server function security_net_peersid_cmp().  The function
4710  * returns zero if the value in @sid is valid (although it may be SECSID_NULL)
4711  * or -EACCES if @sid is invalid due to inconsistencies with the different
4712  * peer labels.
4713  *
4714  */
4715 static int selinux_skb_peerlbl_sid(struct sk_buff *skb, u16 family, u32 *sid)
4716 {
4717 	int err;
4718 	u32 xfrm_sid;
4719 	u32 nlbl_sid;
4720 	u32 nlbl_type;
4721 
4722 	err = selinux_xfrm_skb_sid(skb, &xfrm_sid);
4723 	if (unlikely(err))
4724 		return -EACCES;
4725 	err = selinux_netlbl_skbuff_getsid(skb, family, &nlbl_type, &nlbl_sid);
4726 	if (unlikely(err))
4727 		return -EACCES;
4728 
4729 	err = security_net_peersid_resolve(nlbl_sid,
4730 					   nlbl_type, xfrm_sid, sid);
4731 	if (unlikely(err)) {
4732 		pr_warn(
4733 		       "SELinux: failure in selinux_skb_peerlbl_sid(),"
4734 		       " unable to determine packet's peer label\n");
4735 		return -EACCES;
4736 	}
4737 
4738 	return 0;
4739 }
4740 
4741 /**
4742  * selinux_conn_sid - Determine the child socket label for a connection
4743  * @sk_sid: the parent socket's SID
4744  * @skb_sid: the packet's SID
4745  * @conn_sid: the resulting connection SID
4746  *
4747  * If @skb_sid is valid then the user:role:type information from @sk_sid is
4748  * combined with the MLS information from @skb_sid in order to create
4749  * @conn_sid.  If @skb_sid is not valid then @conn_sid is simply a copy
4750  * of @sk_sid.  Returns zero on success, negative values on failure.
4751  *
4752  */
4753 static int selinux_conn_sid(u32 sk_sid, u32 skb_sid, u32 *conn_sid)
4754 {
4755 	int err = 0;
4756 
4757 	if (skb_sid != SECSID_NULL)
4758 		err = security_sid_mls_copy(sk_sid, skb_sid,
4759 					    conn_sid);
4760 	else
4761 		*conn_sid = sk_sid;
4762 
4763 	return err;
4764 }
4765 
4766 /* socket security operations */
4767 
4768 static int socket_sockcreate_sid(const struct cred_security_struct *crsec,
4769 				 u16 secclass, u32 *socksid)
4770 {
4771 	if (crsec->sockcreate_sid > SECSID_NULL) {
4772 		*socksid = crsec->sockcreate_sid;
4773 		return 0;
4774 	}
4775 
4776 	return security_transition_sid(crsec->sid, crsec->sid,
4777 				       secclass, NULL, socksid);
4778 }
4779 
4780 static bool sock_skip_has_perm(u32 sid)
4781 {
4782 	if (sid == SECINITSID_KERNEL)
4783 		return true;
4784 
4785 	/*
4786 	 * Before POLICYDB_CAP_USERSPACE_INITIAL_CONTEXT, sockets that
4787 	 * inherited the kernel context from early boot used to be skipped
4788 	 * here, so preserve that behavior unless the capability is set.
4789 	 *
4790 	 * By setting the capability the policy signals that it is ready
4791 	 * for this quirk to be fixed. Note that sockets created by a kernel
4792 	 * thread or a usermode helper executed without a transition will
4793 	 * still be skipped in this check regardless of the policycap
4794 	 * setting.
4795 	 */
4796 	if (!selinux_policycap_userspace_initial_context() &&
4797 	    sid == SECINITSID_INIT)
4798 		return true;
4799 	return false;
4800 }
4801 
4802 
4803 static int sock_has_perm(struct sock *sk, u32 perms)
4804 {
4805 	struct sk_security_struct *sksec = sk->sk_security;
4806 	struct common_audit_data ad;
4807 	struct lsm_network_audit net;
4808 
4809 	if (sock_skip_has_perm(sksec->sid))
4810 		return 0;
4811 
4812 	ad_net_init_from_sk(&ad, &net, sk);
4813 
4814 	return avc_has_perm(current_sid(), sksec->sid, sksec->sclass, perms,
4815 			    &ad);
4816 }
4817 
4818 static int selinux_socket_create(int family, int type,
4819 				 int protocol, int kern)
4820 {
4821 	const struct cred_security_struct *crsec = selinux_cred(current_cred());
4822 	u32 newsid;
4823 	u16 secclass;
4824 	int rc;
4825 
4826 	if (kern)
4827 		return 0;
4828 
4829 	secclass = socket_type_to_security_class(family, type, protocol);
4830 	rc = socket_sockcreate_sid(crsec, secclass, &newsid);
4831 	if (rc)
4832 		return rc;
4833 
4834 	return avc_has_perm(crsec->sid, newsid, secclass, SOCKET__CREATE, NULL);
4835 }
4836 
4837 static int selinux_socket_post_create(struct socket *sock, int family,
4838 				      int type, int protocol, int kern)
4839 {
4840 	const struct cred_security_struct *crsec = selinux_cred(current_cred());
4841 	struct inode_security_struct *isec = inode_security_novalidate(SOCK_INODE(sock));
4842 	struct sk_security_struct *sksec;
4843 	u16 sclass = socket_type_to_security_class(family, type, protocol);
4844 	u32 sid = SECINITSID_KERNEL;
4845 	int err = 0;
4846 
4847 	if (!kern) {
4848 		err = socket_sockcreate_sid(crsec, sclass, &sid);
4849 		if (err)
4850 			return err;
4851 	}
4852 
4853 	isec->sclass = sclass;
4854 	isec->sid = sid;
4855 	isec->initialized = LABEL_INITIALIZED;
4856 
4857 	if (sock->sk) {
4858 		sksec = selinux_sock(sock->sk);
4859 		sksec->sclass = sclass;
4860 		sksec->sid = sid;
4861 		/* Allows detection of the first association on this socket */
4862 		if (sksec->sclass == SECCLASS_SCTP_SOCKET)
4863 			sksec->sctp_assoc_state = SCTP_ASSOC_UNSET;
4864 
4865 		err = selinux_netlbl_socket_post_create(sock->sk, family);
4866 	}
4867 
4868 	return err;
4869 }
4870 
4871 static int selinux_socket_socketpair(struct socket *socka,
4872 				     struct socket *sockb)
4873 {
4874 	struct sk_security_struct *sksec_a = selinux_sock(socka->sk);
4875 	struct sk_security_struct *sksec_b = selinux_sock(sockb->sk);
4876 
4877 	sksec_a->peer_sid = sksec_b->sid;
4878 	sksec_b->peer_sid = sksec_a->sid;
4879 
4880 	return 0;
4881 }
4882 
4883 /* Range of port numbers used to automatically bind.
4884    Need to determine whether we should perform a name_bind
4885    permission check between the socket and the port number. */
4886 
4887 static int selinux_socket_bind(struct socket *sock, struct sockaddr *address, int addrlen)
4888 {
4889 	struct sock *sk = sock->sk;
4890 	struct sk_security_struct *sksec = selinux_sock(sk);
4891 	u16 family;
4892 	int err;
4893 
4894 	err = sock_has_perm(sk, SOCKET__BIND);
4895 	if (err)
4896 		goto out;
4897 
4898 	/* If PF_INET or PF_INET6, check name_bind permission for the port. */
4899 	family = sk->sk_family;
4900 	if (family == PF_INET || family == PF_INET6) {
4901 		char *addrp;
4902 		struct common_audit_data ad;
4903 		struct lsm_network_audit net = {0,};
4904 		struct sockaddr_in *addr4 = NULL;
4905 		struct sockaddr_in6 *addr6 = NULL;
4906 		u16 family_sa;
4907 		unsigned short snum;
4908 		u32 sid, node_perm;
4909 
4910 		/*
4911 		 * sctp_bindx(3) calls via selinux_sctp_bind_connect()
4912 		 * that validates multiple binding addresses. Because of this
4913 		 * need to check address->sa_family as it is possible to have
4914 		 * sk->sk_family = PF_INET6 with addr->sa_family = AF_INET.
4915 		 */
4916 		if (addrlen < offsetofend(struct sockaddr, sa_family))
4917 			return -EINVAL;
4918 		family_sa = address->sa_family;
4919 		switch (family_sa) {
4920 		case AF_UNSPEC:
4921 		case AF_INET:
4922 			if (addrlen < sizeof(struct sockaddr_in))
4923 				return -EINVAL;
4924 			addr4 = (struct sockaddr_in *)address;
4925 			if (family_sa == AF_UNSPEC) {
4926 				if (family == PF_INET6) {
4927 					/* Length check from inet6_bind_sk() */
4928 					if (addrlen < SIN6_LEN_RFC2133)
4929 						return -EINVAL;
4930 					/* Family check from __inet6_bind() */
4931 					goto err_af;
4932 				}
4933 				/* see __inet_bind(), we only want to allow
4934 				 * AF_UNSPEC if the address is INADDR_ANY
4935 				 */
4936 				if (addr4->sin_addr.s_addr != htonl(INADDR_ANY))
4937 					goto err_af;
4938 				family_sa = AF_INET;
4939 			}
4940 			snum = ntohs(addr4->sin_port);
4941 			addrp = (char *)&addr4->sin_addr.s_addr;
4942 			break;
4943 		case AF_INET6:
4944 			if (addrlen < SIN6_LEN_RFC2133)
4945 				return -EINVAL;
4946 			addr6 = (struct sockaddr_in6 *)address;
4947 			snum = ntohs(addr6->sin6_port);
4948 			addrp = (char *)&addr6->sin6_addr.s6_addr;
4949 			break;
4950 		default:
4951 			goto err_af;
4952 		}
4953 
4954 		ad.type = LSM_AUDIT_DATA_NET;
4955 		ad.u.net = &net;
4956 		ad.u.net->sport = htons(snum);
4957 		ad.u.net->family = family_sa;
4958 
4959 		if (snum) {
4960 			int low, high;
4961 
4962 			inet_get_local_port_range(sock_net(sk), &low, &high);
4963 
4964 			if (inet_port_requires_bind_service(sock_net(sk), snum) ||
4965 			    snum < low || snum > high) {
4966 				err = sel_netport_sid(sk->sk_protocol,
4967 						      snum, &sid);
4968 				if (err)
4969 					goto out;
4970 				err = avc_has_perm(sksec->sid, sid,
4971 						   sksec->sclass,
4972 						   SOCKET__NAME_BIND, &ad);
4973 				if (err)
4974 					goto out;
4975 			}
4976 		}
4977 
4978 		switch (sksec->sclass) {
4979 		case SECCLASS_TCP_SOCKET:
4980 			node_perm = TCP_SOCKET__NODE_BIND;
4981 			break;
4982 
4983 		case SECCLASS_UDP_SOCKET:
4984 			node_perm = UDP_SOCKET__NODE_BIND;
4985 			break;
4986 
4987 		case SECCLASS_SCTP_SOCKET:
4988 			node_perm = SCTP_SOCKET__NODE_BIND;
4989 			break;
4990 
4991 		default:
4992 			node_perm = RAWIP_SOCKET__NODE_BIND;
4993 			break;
4994 		}
4995 
4996 		err = sel_netnode_sid(addrp, family_sa, &sid);
4997 		if (err)
4998 			goto out;
4999 
5000 		if (family_sa == AF_INET)
5001 			ad.u.net->v4info.saddr = addr4->sin_addr.s_addr;
5002 		else
5003 			ad.u.net->v6info.saddr = addr6->sin6_addr;
5004 
5005 		err = avc_has_perm(sksec->sid, sid,
5006 				   sksec->sclass, node_perm, &ad);
5007 		if (err)
5008 			goto out;
5009 	}
5010 out:
5011 	return err;
5012 err_af:
5013 	/* Note that SCTP services expect -EINVAL, others -EAFNOSUPPORT. */
5014 	if (sk->sk_protocol == IPPROTO_SCTP)
5015 		return -EINVAL;
5016 	return -EAFNOSUPPORT;
5017 }
5018 
5019 /* This supports connect(2) and SCTP connect services such as sctp_connectx(3)
5020  * and sctp_sendmsg(3) as described in Documentation/security/SCTP.rst
5021  */
5022 static int selinux_socket_connect_helper(struct socket *sock,
5023 					 struct sockaddr *address, int addrlen)
5024 {
5025 	struct sock *sk = sock->sk;
5026 	struct sk_security_struct *sksec = selinux_sock(sk);
5027 	int err;
5028 
5029 	err = sock_has_perm(sk, SOCKET__CONNECT);
5030 	if (err)
5031 		return err;
5032 	if (addrlen < offsetofend(struct sockaddr, sa_family))
5033 		return -EINVAL;
5034 
5035 	/* connect(AF_UNSPEC) has special handling, as it is a documented
5036 	 * way to disconnect the socket
5037 	 */
5038 	if (address->sa_family == AF_UNSPEC)
5039 		return 0;
5040 
5041 	/*
5042 	 * If a TCP or SCTP socket, check name_connect permission
5043 	 * for the port.
5044 	 */
5045 	if (sksec->sclass == SECCLASS_TCP_SOCKET ||
5046 	    sksec->sclass == SECCLASS_SCTP_SOCKET) {
5047 		struct common_audit_data ad;
5048 		struct lsm_network_audit net = {0,};
5049 		struct sockaddr_in *addr4 = NULL;
5050 		struct sockaddr_in6 *addr6 = NULL;
5051 		unsigned short snum;
5052 		u32 sid, perm;
5053 
5054 		/* sctp_connectx(3) calls via selinux_sctp_bind_connect()
5055 		 * that validates multiple connect addresses. Because of this
5056 		 * need to check address->sa_family as it is possible to have
5057 		 * sk->sk_family = PF_INET6 with addr->sa_family = AF_INET.
5058 		 */
5059 		switch (address->sa_family) {
5060 		case AF_INET:
5061 			addr4 = (struct sockaddr_in *)address;
5062 			if (addrlen < sizeof(struct sockaddr_in))
5063 				return -EINVAL;
5064 			snum = ntohs(addr4->sin_port);
5065 			break;
5066 		case AF_INET6:
5067 			addr6 = (struct sockaddr_in6 *)address;
5068 			if (addrlen < SIN6_LEN_RFC2133)
5069 				return -EINVAL;
5070 			snum = ntohs(addr6->sin6_port);
5071 			break;
5072 		default:
5073 			/* Note that SCTP services expect -EINVAL, whereas
5074 			 * others expect -EAFNOSUPPORT.
5075 			 */
5076 			if (sksec->sclass == SECCLASS_SCTP_SOCKET)
5077 				return -EINVAL;
5078 			else
5079 				return -EAFNOSUPPORT;
5080 		}
5081 
5082 		err = sel_netport_sid(sk->sk_protocol, snum, &sid);
5083 		if (err)
5084 			return err;
5085 
5086 		switch (sksec->sclass) {
5087 		case SECCLASS_TCP_SOCKET:
5088 			perm = TCP_SOCKET__NAME_CONNECT;
5089 			break;
5090 		case SECCLASS_SCTP_SOCKET:
5091 			perm = SCTP_SOCKET__NAME_CONNECT;
5092 			break;
5093 		}
5094 
5095 		ad.type = LSM_AUDIT_DATA_NET;
5096 		ad.u.net = &net;
5097 		ad.u.net->dport = htons(snum);
5098 		ad.u.net->family = address->sa_family;
5099 		err = avc_has_perm(sksec->sid, sid, sksec->sclass, perm, &ad);
5100 		if (err)
5101 			return err;
5102 	}
5103 
5104 	return 0;
5105 }
5106 
5107 /* Supports connect(2), see comments in selinux_socket_connect_helper() */
5108 static int selinux_socket_connect(struct socket *sock,
5109 				  struct sockaddr *address, int addrlen)
5110 {
5111 	int err;
5112 	struct sock *sk = sock->sk;
5113 
5114 	err = selinux_socket_connect_helper(sock, address, addrlen);
5115 	if (err)
5116 		return err;
5117 
5118 	return selinux_netlbl_socket_connect(sk, address);
5119 }
5120 
5121 static int selinux_socket_listen(struct socket *sock, int backlog)
5122 {
5123 	return sock_has_perm(sock->sk, SOCKET__LISTEN);
5124 }
5125 
5126 static int selinux_socket_accept(struct socket *sock, struct socket *newsock)
5127 {
5128 	int err;
5129 	struct inode_security_struct *isec;
5130 	struct inode_security_struct *newisec;
5131 	u16 sclass;
5132 	u32 sid;
5133 
5134 	err = sock_has_perm(sock->sk, SOCKET__ACCEPT);
5135 	if (err)
5136 		return err;
5137 
5138 	isec = inode_security_novalidate(SOCK_INODE(sock));
5139 	spin_lock(&isec->lock);
5140 	sclass = isec->sclass;
5141 	sid = isec->sid;
5142 	spin_unlock(&isec->lock);
5143 
5144 	newisec = inode_security_novalidate(SOCK_INODE(newsock));
5145 	newisec->sclass = sclass;
5146 	newisec->sid = sid;
5147 	newisec->initialized = LABEL_INITIALIZED;
5148 
5149 	return 0;
5150 }
5151 
5152 static int selinux_socket_sendmsg(struct socket *sock, struct msghdr *msg,
5153 				  int size)
5154 {
5155 	return sock_has_perm(sock->sk, SOCKET__WRITE);
5156 }
5157 
5158 static int selinux_socket_recvmsg(struct socket *sock, struct msghdr *msg,
5159 				  int size, int flags)
5160 {
5161 	return sock_has_perm(sock->sk, SOCKET__READ);
5162 }
5163 
5164 static int selinux_socket_getsockname(struct socket *sock)
5165 {
5166 	return sock_has_perm(sock->sk, SOCKET__GETATTR);
5167 }
5168 
5169 static int selinux_socket_getpeername(struct socket *sock)
5170 {
5171 	return sock_has_perm(sock->sk, SOCKET__GETATTR);
5172 }
5173 
5174 static int selinux_socket_setsockopt(struct socket *sock, int level, int optname)
5175 {
5176 	int err;
5177 
5178 	err = sock_has_perm(sock->sk, SOCKET__SETOPT);
5179 	if (err)
5180 		return err;
5181 
5182 	return selinux_netlbl_socket_setsockopt(sock, level, optname);
5183 }
5184 
5185 static int selinux_socket_getsockopt(struct socket *sock, int level,
5186 				     int optname)
5187 {
5188 	return sock_has_perm(sock->sk, SOCKET__GETOPT);
5189 }
5190 
5191 static int selinux_socket_shutdown(struct socket *sock, int how)
5192 {
5193 	return sock_has_perm(sock->sk, SOCKET__SHUTDOWN);
5194 }
5195 
5196 static int selinux_socket_unix_stream_connect(struct sock *sock,
5197 					      struct sock *other,
5198 					      struct sock *newsk)
5199 {
5200 	struct sk_security_struct *sksec_sock = selinux_sock(sock);
5201 	struct sk_security_struct *sksec_other = selinux_sock(other);
5202 	struct sk_security_struct *sksec_new = selinux_sock(newsk);
5203 	struct common_audit_data ad;
5204 	struct lsm_network_audit net;
5205 	int err;
5206 
5207 	ad_net_init_from_sk(&ad, &net, other);
5208 
5209 	err = avc_has_perm(sksec_sock->sid, sksec_other->sid,
5210 			   sksec_other->sclass,
5211 			   UNIX_STREAM_SOCKET__CONNECTTO, &ad);
5212 	if (err)
5213 		return err;
5214 
5215 	/* server child socket */
5216 	sksec_new->peer_sid = sksec_sock->sid;
5217 	err = security_sid_mls_copy(sksec_other->sid,
5218 				    sksec_sock->sid, &sksec_new->sid);
5219 	if (err)
5220 		return err;
5221 
5222 	/* connecting socket */
5223 	sksec_sock->peer_sid = sksec_new->sid;
5224 
5225 	return 0;
5226 }
5227 
5228 static int selinux_socket_unix_may_send(struct socket *sock,
5229 					struct socket *other)
5230 {
5231 	struct sk_security_struct *ssec = selinux_sock(sock->sk);
5232 	struct sk_security_struct *osec = selinux_sock(other->sk);
5233 	struct common_audit_data ad;
5234 	struct lsm_network_audit net;
5235 
5236 	ad_net_init_from_sk(&ad, &net, other->sk);
5237 
5238 	return avc_has_perm(ssec->sid, osec->sid, osec->sclass, SOCKET__SENDTO,
5239 			    &ad);
5240 }
5241 
5242 static int selinux_inet_sys_rcv_skb(struct net *ns, int ifindex,
5243 				    char *addrp, u16 family, u32 peer_sid,
5244 				    struct common_audit_data *ad)
5245 {
5246 	int err;
5247 	u32 if_sid;
5248 	u32 node_sid;
5249 
5250 	err = sel_netif_sid(ns, ifindex, &if_sid);
5251 	if (err)
5252 		return err;
5253 	err = avc_has_perm(peer_sid, if_sid,
5254 			   SECCLASS_NETIF, NETIF__INGRESS, ad);
5255 	if (err)
5256 		return err;
5257 
5258 	err = sel_netnode_sid(addrp, family, &node_sid);
5259 	if (err)
5260 		return err;
5261 	return avc_has_perm(peer_sid, node_sid,
5262 			    SECCLASS_NODE, NODE__RECVFROM, ad);
5263 }
5264 
5265 static int selinux_sock_rcv_skb_compat(struct sock *sk, struct sk_buff *skb,
5266 				       u16 family)
5267 {
5268 	int err = 0;
5269 	struct sk_security_struct *sksec = selinux_sock(sk);
5270 	u32 sk_sid = sksec->sid;
5271 	struct common_audit_data ad;
5272 	struct lsm_network_audit net;
5273 	char *addrp;
5274 
5275 	ad_net_init_from_iif(&ad, &net, skb->skb_iif, family);
5276 	err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
5277 	if (err)
5278 		return err;
5279 
5280 	if (selinux_secmark_enabled()) {
5281 		err = avc_has_perm(sk_sid, skb->secmark, SECCLASS_PACKET,
5282 				   PACKET__RECV, &ad);
5283 		if (err)
5284 			return err;
5285 	}
5286 
5287 	err = selinux_netlbl_sock_rcv_skb(sksec, skb, family, &ad);
5288 	if (err)
5289 		return err;
5290 	err = selinux_xfrm_sock_rcv_skb(sksec->sid, skb, &ad);
5291 
5292 	return err;
5293 }
5294 
5295 static int selinux_socket_sock_rcv_skb(struct sock *sk, struct sk_buff *skb)
5296 {
5297 	int err, peerlbl_active, secmark_active;
5298 	struct sk_security_struct *sksec = selinux_sock(sk);
5299 	u16 family = sk->sk_family;
5300 	u32 sk_sid = sksec->sid;
5301 	struct common_audit_data ad;
5302 	struct lsm_network_audit net;
5303 	char *addrp;
5304 
5305 	if (family != PF_INET && family != PF_INET6)
5306 		return 0;
5307 
5308 	/* Handle mapped IPv4 packets arriving via IPv6 sockets */
5309 	if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
5310 		family = PF_INET;
5311 
5312 	/* If any sort of compatibility mode is enabled then handoff processing
5313 	 * to the selinux_sock_rcv_skb_compat() function to deal with the
5314 	 * special handling.  We do this in an attempt to keep this function
5315 	 * as fast and as clean as possible. */
5316 	if (!selinux_policycap_netpeer())
5317 		return selinux_sock_rcv_skb_compat(sk, skb, family);
5318 
5319 	secmark_active = selinux_secmark_enabled();
5320 	peerlbl_active = selinux_peerlbl_enabled();
5321 	if (!secmark_active && !peerlbl_active)
5322 		return 0;
5323 
5324 	ad_net_init_from_iif(&ad, &net, skb->skb_iif, family);
5325 	err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
5326 	if (err)
5327 		return err;
5328 
5329 	if (peerlbl_active) {
5330 		u32 peer_sid;
5331 
5332 		err = selinux_skb_peerlbl_sid(skb, family, &peer_sid);
5333 		if (err)
5334 			return err;
5335 		err = selinux_inet_sys_rcv_skb(sock_net(sk), skb->skb_iif,
5336 					       addrp, family, peer_sid, &ad);
5337 		if (err) {
5338 			selinux_netlbl_err(skb, family, err, 0);
5339 			return err;
5340 		}
5341 		err = avc_has_perm(sk_sid, peer_sid, SECCLASS_PEER,
5342 				   PEER__RECV, &ad);
5343 		if (err) {
5344 			selinux_netlbl_err(skb, family, err, 0);
5345 			return err;
5346 		}
5347 	}
5348 
5349 	if (secmark_active) {
5350 		err = avc_has_perm(sk_sid, skb->secmark, SECCLASS_PACKET,
5351 				   PACKET__RECV, &ad);
5352 		if (err)
5353 			return err;
5354 	}
5355 
5356 	return err;
5357 }
5358 
5359 static int selinux_socket_getpeersec_stream(struct socket *sock,
5360 					    sockptr_t optval, sockptr_t optlen,
5361 					    unsigned int len)
5362 {
5363 	int err = 0;
5364 	char *scontext = NULL;
5365 	u32 scontext_len;
5366 	struct sk_security_struct *sksec = selinux_sock(sock->sk);
5367 	u32 peer_sid = SECSID_NULL;
5368 
5369 	if (sksec->sclass == SECCLASS_UNIX_STREAM_SOCKET ||
5370 	    sksec->sclass == SECCLASS_TCP_SOCKET ||
5371 	    sksec->sclass == SECCLASS_SCTP_SOCKET)
5372 		peer_sid = sksec->peer_sid;
5373 	if (peer_sid == SECSID_NULL)
5374 		return -ENOPROTOOPT;
5375 
5376 	err = security_sid_to_context(peer_sid, &scontext,
5377 				      &scontext_len);
5378 	if (err)
5379 		return err;
5380 	if (scontext_len > len) {
5381 		err = -ERANGE;
5382 		goto out_len;
5383 	}
5384 
5385 	if (copy_to_sockptr(optval, scontext, scontext_len))
5386 		err = -EFAULT;
5387 out_len:
5388 	if (copy_to_sockptr(optlen, &scontext_len, sizeof(scontext_len)))
5389 		err = -EFAULT;
5390 	kfree(scontext);
5391 	return err;
5392 }
5393 
5394 static int selinux_socket_getpeersec_dgram(struct socket *sock,
5395 					   struct sk_buff *skb, u32 *secid)
5396 {
5397 	u32 peer_secid = SECSID_NULL;
5398 	u16 family;
5399 
5400 	if (skb && skb->protocol == htons(ETH_P_IP))
5401 		family = PF_INET;
5402 	else if (skb && skb->protocol == htons(ETH_P_IPV6))
5403 		family = PF_INET6;
5404 	else if (sock)
5405 		family = sock->sk->sk_family;
5406 	else {
5407 		*secid = SECSID_NULL;
5408 		return -EINVAL;
5409 	}
5410 
5411 	if (sock && family == PF_UNIX) {
5412 		struct inode_security_struct *isec;
5413 		isec = inode_security_novalidate(SOCK_INODE(sock));
5414 		peer_secid = isec->sid;
5415 	} else if (skb)
5416 		selinux_skb_peerlbl_sid(skb, family, &peer_secid);
5417 
5418 	*secid = peer_secid;
5419 	if (peer_secid == SECSID_NULL)
5420 		return -ENOPROTOOPT;
5421 	return 0;
5422 }
5423 
5424 static int selinux_sk_alloc_security(struct sock *sk, int family, gfp_t priority)
5425 {
5426 	struct sk_security_struct *sksec = selinux_sock(sk);
5427 
5428 	sksec->peer_sid = SECINITSID_UNLABELED;
5429 	sksec->sid = SECINITSID_UNLABELED;
5430 	sksec->sclass = SECCLASS_SOCKET;
5431 	selinux_netlbl_sk_security_reset(sksec);
5432 
5433 	return 0;
5434 }
5435 
5436 static void selinux_sk_free_security(struct sock *sk)
5437 {
5438 	struct sk_security_struct *sksec = selinux_sock(sk);
5439 
5440 	selinux_netlbl_sk_security_free(sksec);
5441 }
5442 
5443 static void selinux_sk_clone_security(const struct sock *sk, struct sock *newsk)
5444 {
5445 	struct sk_security_struct *sksec = selinux_sock(sk);
5446 	struct sk_security_struct *newsksec = selinux_sock(newsk);
5447 
5448 	newsksec->sid = sksec->sid;
5449 	newsksec->peer_sid = sksec->peer_sid;
5450 	newsksec->sclass = sksec->sclass;
5451 
5452 	selinux_netlbl_sk_security_reset(newsksec);
5453 }
5454 
5455 static void selinux_sk_getsecid(const struct sock *sk, u32 *secid)
5456 {
5457 	if (!sk)
5458 		*secid = SECINITSID_ANY_SOCKET;
5459 	else {
5460 		const struct sk_security_struct *sksec = selinux_sock(sk);
5461 
5462 		*secid = sksec->sid;
5463 	}
5464 }
5465 
5466 static void selinux_sock_graft(struct sock *sk, struct socket *parent)
5467 {
5468 	struct inode_security_struct *isec =
5469 		inode_security_novalidate(SOCK_INODE(parent));
5470 	struct sk_security_struct *sksec = selinux_sock(sk);
5471 
5472 	if (sk->sk_family == PF_INET || sk->sk_family == PF_INET6 ||
5473 	    sk->sk_family == PF_UNIX)
5474 		isec->sid = sksec->sid;
5475 	sksec->sclass = isec->sclass;
5476 }
5477 
5478 /*
5479  * Determines peer_secid for the asoc and updates socket's peer label
5480  * if it's the first association on the socket.
5481  */
5482 static int selinux_sctp_process_new_assoc(struct sctp_association *asoc,
5483 					  struct sk_buff *skb)
5484 {
5485 	struct sock *sk = asoc->base.sk;
5486 	u16 family = sk->sk_family;
5487 	struct sk_security_struct *sksec = selinux_sock(sk);
5488 	struct common_audit_data ad;
5489 	struct lsm_network_audit net;
5490 	int err;
5491 
5492 	/* handle mapped IPv4 packets arriving via IPv6 sockets */
5493 	if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
5494 		family = PF_INET;
5495 
5496 	if (selinux_peerlbl_enabled()) {
5497 		asoc->peer_secid = SECSID_NULL;
5498 
5499 		/* This will return peer_sid = SECSID_NULL if there are
5500 		 * no peer labels, see security_net_peersid_resolve().
5501 		 */
5502 		err = selinux_skb_peerlbl_sid(skb, family, &asoc->peer_secid);
5503 		if (err)
5504 			return err;
5505 
5506 		if (asoc->peer_secid == SECSID_NULL)
5507 			asoc->peer_secid = SECINITSID_UNLABELED;
5508 	} else {
5509 		asoc->peer_secid = SECINITSID_UNLABELED;
5510 	}
5511 
5512 	if (sksec->sctp_assoc_state == SCTP_ASSOC_UNSET) {
5513 		sksec->sctp_assoc_state = SCTP_ASSOC_SET;
5514 
5515 		/* Here as first association on socket. As the peer SID
5516 		 * was allowed by peer recv (and the netif/node checks),
5517 		 * then it is approved by policy and used as the primary
5518 		 * peer SID for getpeercon(3).
5519 		 */
5520 		sksec->peer_sid = asoc->peer_secid;
5521 	} else if (sksec->peer_sid != asoc->peer_secid) {
5522 		/* Other association peer SIDs are checked to enforce
5523 		 * consistency among the peer SIDs.
5524 		 */
5525 		ad_net_init_from_sk(&ad, &net, asoc->base.sk);
5526 		err = avc_has_perm(sksec->peer_sid, asoc->peer_secid,
5527 				   sksec->sclass, SCTP_SOCKET__ASSOCIATION,
5528 				   &ad);
5529 		if (err)
5530 			return err;
5531 	}
5532 	return 0;
5533 }
5534 
5535 /* Called whenever SCTP receives an INIT or COOKIE ECHO chunk. This
5536  * happens on an incoming connect(2), sctp_connectx(3) or
5537  * sctp_sendmsg(3) (with no association already present).
5538  */
5539 static int selinux_sctp_assoc_request(struct sctp_association *asoc,
5540 				      struct sk_buff *skb)
5541 {
5542 	struct sk_security_struct *sksec = selinux_sock(asoc->base.sk);
5543 	u32 conn_sid;
5544 	int err;
5545 
5546 	if (!selinux_policycap_extsockclass())
5547 		return 0;
5548 
5549 	err = selinux_sctp_process_new_assoc(asoc, skb);
5550 	if (err)
5551 		return err;
5552 
5553 	/* Compute the MLS component for the connection and store
5554 	 * the information in asoc. This will be used by SCTP TCP type
5555 	 * sockets and peeled off connections as they cause a new
5556 	 * socket to be generated. selinux_sctp_sk_clone() will then
5557 	 * plug this into the new socket.
5558 	 */
5559 	err = selinux_conn_sid(sksec->sid, asoc->peer_secid, &conn_sid);
5560 	if (err)
5561 		return err;
5562 
5563 	asoc->secid = conn_sid;
5564 
5565 	/* Set any NetLabel labels including CIPSO/CALIPSO options. */
5566 	return selinux_netlbl_sctp_assoc_request(asoc, skb);
5567 }
5568 
5569 /* Called when SCTP receives a COOKIE ACK chunk as the final
5570  * response to an association request (initited by us).
5571  */
5572 static int selinux_sctp_assoc_established(struct sctp_association *asoc,
5573 					  struct sk_buff *skb)
5574 {
5575 	struct sk_security_struct *sksec = selinux_sock(asoc->base.sk);
5576 
5577 	if (!selinux_policycap_extsockclass())
5578 		return 0;
5579 
5580 	/* Inherit secid from the parent socket - this will be picked up
5581 	 * by selinux_sctp_sk_clone() if the association gets peeled off
5582 	 * into a new socket.
5583 	 */
5584 	asoc->secid = sksec->sid;
5585 
5586 	return selinux_sctp_process_new_assoc(asoc, skb);
5587 }
5588 
5589 /* Check if sctp IPv4/IPv6 addresses are valid for binding or connecting
5590  * based on their @optname.
5591  */
5592 static int selinux_sctp_bind_connect(struct sock *sk, int optname,
5593 				     struct sockaddr *address,
5594 				     int addrlen)
5595 {
5596 	int len, err = 0, walk_size = 0;
5597 	void *addr_buf;
5598 	struct sockaddr *addr;
5599 	struct socket *sock;
5600 
5601 	if (!selinux_policycap_extsockclass())
5602 		return 0;
5603 
5604 	/* Process one or more addresses that may be IPv4 or IPv6 */
5605 	sock = sk->sk_socket;
5606 	addr_buf = address;
5607 
5608 	while (walk_size < addrlen) {
5609 		if (walk_size + sizeof(sa_family_t) > addrlen)
5610 			return -EINVAL;
5611 
5612 		addr = addr_buf;
5613 		switch (addr->sa_family) {
5614 		case AF_UNSPEC:
5615 		case AF_INET:
5616 			len = sizeof(struct sockaddr_in);
5617 			break;
5618 		case AF_INET6:
5619 			len = sizeof(struct sockaddr_in6);
5620 			break;
5621 		default:
5622 			return -EINVAL;
5623 		}
5624 
5625 		if (walk_size + len > addrlen)
5626 			return -EINVAL;
5627 
5628 		err = -EINVAL;
5629 		switch (optname) {
5630 		/* Bind checks */
5631 		case SCTP_PRIMARY_ADDR:
5632 		case SCTP_SET_PEER_PRIMARY_ADDR:
5633 		case SCTP_SOCKOPT_BINDX_ADD:
5634 			err = selinux_socket_bind(sock, addr, len);
5635 			break;
5636 		/* Connect checks */
5637 		case SCTP_SOCKOPT_CONNECTX:
5638 		case SCTP_PARAM_SET_PRIMARY:
5639 		case SCTP_PARAM_ADD_IP:
5640 		case SCTP_SENDMSG_CONNECT:
5641 			err = selinux_socket_connect_helper(sock, addr, len);
5642 			if (err)
5643 				return err;
5644 
5645 			/* As selinux_sctp_bind_connect() is called by the
5646 			 * SCTP protocol layer, the socket is already locked,
5647 			 * therefore selinux_netlbl_socket_connect_locked()
5648 			 * is called here. The situations handled are:
5649 			 * sctp_connectx(3), sctp_sendmsg(3), sendmsg(2),
5650 			 * whenever a new IP address is added or when a new
5651 			 * primary address is selected.
5652 			 * Note that an SCTP connect(2) call happens before
5653 			 * the SCTP protocol layer and is handled via
5654 			 * selinux_socket_connect().
5655 			 */
5656 			err = selinux_netlbl_socket_connect_locked(sk, addr);
5657 			break;
5658 		}
5659 
5660 		if (err)
5661 			return err;
5662 
5663 		addr_buf += len;
5664 		walk_size += len;
5665 	}
5666 
5667 	return 0;
5668 }
5669 
5670 /* Called whenever a new socket is created by accept(2) or sctp_peeloff(3). */
5671 static void selinux_sctp_sk_clone(struct sctp_association *asoc, struct sock *sk,
5672 				  struct sock *newsk)
5673 {
5674 	struct sk_security_struct *sksec = selinux_sock(sk);
5675 	struct sk_security_struct *newsksec = selinux_sock(newsk);
5676 
5677 	/* If policy does not support SECCLASS_SCTP_SOCKET then call
5678 	 * the non-sctp clone version.
5679 	 */
5680 	if (!selinux_policycap_extsockclass())
5681 		return selinux_sk_clone_security(sk, newsk);
5682 
5683 	newsksec->sid = asoc->secid;
5684 	newsksec->peer_sid = asoc->peer_secid;
5685 	newsksec->sclass = sksec->sclass;
5686 	selinux_netlbl_sctp_sk_clone(sk, newsk);
5687 }
5688 
5689 static int selinux_mptcp_add_subflow(struct sock *sk, struct sock *ssk)
5690 {
5691 	struct sk_security_struct *ssksec = selinux_sock(ssk);
5692 	struct sk_security_struct *sksec = selinux_sock(sk);
5693 
5694 	ssksec->sclass = sksec->sclass;
5695 	ssksec->sid = sksec->sid;
5696 
5697 	/* replace the existing subflow label deleting the existing one
5698 	 * and re-recreating a new label using the updated context
5699 	 */
5700 	selinux_netlbl_sk_security_free(ssksec);
5701 	return selinux_netlbl_socket_post_create(ssk, ssk->sk_family);
5702 }
5703 
5704 static int selinux_inet_conn_request(const struct sock *sk, struct sk_buff *skb,
5705 				     struct request_sock *req)
5706 {
5707 	struct sk_security_struct *sksec = selinux_sock(sk);
5708 	int err;
5709 	u16 family = req->rsk_ops->family;
5710 	u32 connsid;
5711 	u32 peersid;
5712 
5713 	err = selinux_skb_peerlbl_sid(skb, family, &peersid);
5714 	if (err)
5715 		return err;
5716 	err = selinux_conn_sid(sksec->sid, peersid, &connsid);
5717 	if (err)
5718 		return err;
5719 	req->secid = connsid;
5720 	req->peer_secid = peersid;
5721 
5722 	return selinux_netlbl_inet_conn_request(req, family);
5723 }
5724 
5725 static void selinux_inet_csk_clone(struct sock *newsk,
5726 				   const struct request_sock *req)
5727 {
5728 	struct sk_security_struct *newsksec = selinux_sock(newsk);
5729 
5730 	newsksec->sid = req->secid;
5731 	newsksec->peer_sid = req->peer_secid;
5732 	/* NOTE: Ideally, we should also get the isec->sid for the
5733 	   new socket in sync, but we don't have the isec available yet.
5734 	   So we will wait until sock_graft to do it, by which
5735 	   time it will have been created and available. */
5736 
5737 	/* We don't need to take any sort of lock here as we are the only
5738 	 * thread with access to newsksec */
5739 	selinux_netlbl_inet_csk_clone(newsk, req->rsk_ops->family);
5740 }
5741 
5742 static void selinux_inet_conn_established(struct sock *sk, struct sk_buff *skb)
5743 {
5744 	u16 family = sk->sk_family;
5745 	struct sk_security_struct *sksec = selinux_sock(sk);
5746 
5747 	/* handle mapped IPv4 packets arriving via IPv6 sockets */
5748 	if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
5749 		family = PF_INET;
5750 
5751 	selinux_skb_peerlbl_sid(skb, family, &sksec->peer_sid);
5752 }
5753 
5754 static int selinux_secmark_relabel_packet(u32 sid)
5755 {
5756 	return avc_has_perm(current_sid(), sid, SECCLASS_PACKET, PACKET__RELABELTO,
5757 			    NULL);
5758 }
5759 
5760 static void selinux_secmark_refcount_inc(void)
5761 {
5762 	atomic_inc(&selinux_secmark_refcount);
5763 }
5764 
5765 static void selinux_secmark_refcount_dec(void)
5766 {
5767 	atomic_dec(&selinux_secmark_refcount);
5768 }
5769 
5770 static void selinux_req_classify_flow(const struct request_sock *req,
5771 				      struct flowi_common *flic)
5772 {
5773 	flic->flowic_secid = req->secid;
5774 }
5775 
5776 static int selinux_tun_dev_alloc_security(void *security)
5777 {
5778 	struct tun_security_struct *tunsec = selinux_tun_dev(security);
5779 
5780 	tunsec->sid = current_sid();
5781 	return 0;
5782 }
5783 
5784 static int selinux_tun_dev_create(void)
5785 {
5786 	u32 sid = current_sid();
5787 
5788 	/* we aren't taking into account the "sockcreate" SID since the socket
5789 	 * that is being created here is not a socket in the traditional sense,
5790 	 * instead it is a private sock, accessible only to the kernel, and
5791 	 * representing a wide range of network traffic spanning multiple
5792 	 * connections unlike traditional sockets - check the TUN driver to
5793 	 * get a better understanding of why this socket is special */
5794 
5795 	return avc_has_perm(sid, sid, SECCLASS_TUN_SOCKET, TUN_SOCKET__CREATE,
5796 			    NULL);
5797 }
5798 
5799 static int selinux_tun_dev_attach_queue(void *security)
5800 {
5801 	struct tun_security_struct *tunsec = selinux_tun_dev(security);
5802 
5803 	return avc_has_perm(current_sid(), tunsec->sid, SECCLASS_TUN_SOCKET,
5804 			    TUN_SOCKET__ATTACH_QUEUE, NULL);
5805 }
5806 
5807 static int selinux_tun_dev_attach(struct sock *sk, void *security)
5808 {
5809 	struct tun_security_struct *tunsec = selinux_tun_dev(security);
5810 	struct sk_security_struct *sksec = selinux_sock(sk);
5811 
5812 	/* we don't currently perform any NetLabel based labeling here and it
5813 	 * isn't clear that we would want to do so anyway; while we could apply
5814 	 * labeling without the support of the TUN user the resulting labeled
5815 	 * traffic from the other end of the connection would almost certainly
5816 	 * cause confusion to the TUN user that had no idea network labeling
5817 	 * protocols were being used */
5818 
5819 	sksec->sid = tunsec->sid;
5820 	sksec->sclass = SECCLASS_TUN_SOCKET;
5821 
5822 	return 0;
5823 }
5824 
5825 static int selinux_tun_dev_open(void *security)
5826 {
5827 	struct tun_security_struct *tunsec = selinux_tun_dev(security);
5828 	u32 sid = current_sid();
5829 	int err;
5830 
5831 	err = avc_has_perm(sid, tunsec->sid, SECCLASS_TUN_SOCKET,
5832 			   TUN_SOCKET__RELABELFROM, NULL);
5833 	if (err)
5834 		return err;
5835 	err = avc_has_perm(sid, sid, SECCLASS_TUN_SOCKET,
5836 			   TUN_SOCKET__RELABELTO, NULL);
5837 	if (err)
5838 		return err;
5839 	tunsec->sid = sid;
5840 
5841 	return 0;
5842 }
5843 
5844 #ifdef CONFIG_NETFILTER
5845 
5846 static unsigned int selinux_ip_forward(void *priv, struct sk_buff *skb,
5847 				       const struct nf_hook_state *state)
5848 {
5849 	int ifindex;
5850 	u16 family;
5851 	char *addrp;
5852 	u32 peer_sid;
5853 	struct common_audit_data ad;
5854 	struct lsm_network_audit net;
5855 	int secmark_active, peerlbl_active;
5856 
5857 	if (!selinux_policycap_netpeer())
5858 		return NF_ACCEPT;
5859 
5860 	secmark_active = selinux_secmark_enabled();
5861 	peerlbl_active = selinux_peerlbl_enabled();
5862 	if (!secmark_active && !peerlbl_active)
5863 		return NF_ACCEPT;
5864 
5865 	family = state->pf;
5866 	if (selinux_skb_peerlbl_sid(skb, family, &peer_sid) != 0)
5867 		return NF_DROP;
5868 
5869 	ifindex = state->in->ifindex;
5870 	ad_net_init_from_iif(&ad, &net, ifindex, family);
5871 	if (selinux_parse_skb(skb, &ad, &addrp, 1, NULL) != 0)
5872 		return NF_DROP;
5873 
5874 	if (peerlbl_active) {
5875 		int err;
5876 
5877 		err = selinux_inet_sys_rcv_skb(state->net, ifindex,
5878 					       addrp, family, peer_sid, &ad);
5879 		if (err) {
5880 			selinux_netlbl_err(skb, family, err, 1);
5881 			return NF_DROP;
5882 		}
5883 	}
5884 
5885 	if (secmark_active)
5886 		if (avc_has_perm(peer_sid, skb->secmark,
5887 				 SECCLASS_PACKET, PACKET__FORWARD_IN, &ad))
5888 			return NF_DROP;
5889 
5890 	if (netlbl_enabled())
5891 		/* we do this in the FORWARD path and not the POST_ROUTING
5892 		 * path because we want to make sure we apply the necessary
5893 		 * labeling before IPsec is applied so we can leverage AH
5894 		 * protection */
5895 		if (selinux_netlbl_skbuff_setsid(skb, family, peer_sid) != 0)
5896 			return NF_DROP;
5897 
5898 	return NF_ACCEPT;
5899 }
5900 
5901 static unsigned int selinux_ip_output(void *priv, struct sk_buff *skb,
5902 				      const struct nf_hook_state *state)
5903 {
5904 	struct sock *sk;
5905 	u32 sid;
5906 
5907 	if (!netlbl_enabled())
5908 		return NF_ACCEPT;
5909 
5910 	/* we do this in the LOCAL_OUT path and not the POST_ROUTING path
5911 	 * because we want to make sure we apply the necessary labeling
5912 	 * before IPsec is applied so we can leverage AH protection */
5913 	sk = skb_to_full_sk(skb);
5914 	if (sk) {
5915 		struct sk_security_struct *sksec;
5916 
5917 		if (sk_listener(sk))
5918 			/* if the socket is the listening state then this
5919 			 * packet is a SYN-ACK packet which means it needs to
5920 			 * be labeled based on the connection/request_sock and
5921 			 * not the parent socket.  unfortunately, we can't
5922 			 * lookup the request_sock yet as it isn't queued on
5923 			 * the parent socket until after the SYN-ACK is sent.
5924 			 * the "solution" is to simply pass the packet as-is
5925 			 * as any IP option based labeling should be copied
5926 			 * from the initial connection request (in the IP
5927 			 * layer).  it is far from ideal, but until we get a
5928 			 * security label in the packet itself this is the
5929 			 * best we can do. */
5930 			return NF_ACCEPT;
5931 
5932 		/* standard practice, label using the parent socket */
5933 		sksec = selinux_sock(sk);
5934 		sid = sksec->sid;
5935 	} else
5936 		sid = SECINITSID_KERNEL;
5937 	if (selinux_netlbl_skbuff_setsid(skb, state->pf, sid) != 0)
5938 		return NF_DROP;
5939 
5940 	return NF_ACCEPT;
5941 }
5942 
5943 
5944 static unsigned int selinux_ip_postroute_compat(struct sk_buff *skb,
5945 					const struct nf_hook_state *state)
5946 {
5947 	struct sock *sk;
5948 	struct sk_security_struct *sksec;
5949 	struct common_audit_data ad;
5950 	struct lsm_network_audit net;
5951 	u8 proto = 0;
5952 
5953 	sk = skb_to_full_sk(skb);
5954 	if (sk == NULL)
5955 		return NF_ACCEPT;
5956 	sksec = selinux_sock(sk);
5957 
5958 	ad_net_init_from_iif(&ad, &net, state->out->ifindex, state->pf);
5959 	if (selinux_parse_skb(skb, &ad, NULL, 0, &proto))
5960 		return NF_DROP;
5961 
5962 	if (selinux_secmark_enabled())
5963 		if (avc_has_perm(sksec->sid, skb->secmark,
5964 				 SECCLASS_PACKET, PACKET__SEND, &ad))
5965 			return NF_DROP_ERR(-ECONNREFUSED);
5966 
5967 	if (selinux_xfrm_postroute_last(sksec->sid, skb, &ad, proto))
5968 		return NF_DROP_ERR(-ECONNREFUSED);
5969 
5970 	return NF_ACCEPT;
5971 }
5972 
5973 static unsigned int selinux_ip_postroute(void *priv,
5974 					 struct sk_buff *skb,
5975 					 const struct nf_hook_state *state)
5976 {
5977 	u16 family;
5978 	u32 secmark_perm;
5979 	u32 peer_sid;
5980 	int ifindex;
5981 	struct sock *sk;
5982 	struct common_audit_data ad;
5983 	struct lsm_network_audit net;
5984 	char *addrp;
5985 	int secmark_active, peerlbl_active;
5986 
5987 	/* If any sort of compatibility mode is enabled then handoff processing
5988 	 * to the selinux_ip_postroute_compat() function to deal with the
5989 	 * special handling.  We do this in an attempt to keep this function
5990 	 * as fast and as clean as possible. */
5991 	if (!selinux_policycap_netpeer())
5992 		return selinux_ip_postroute_compat(skb, state);
5993 
5994 	secmark_active = selinux_secmark_enabled();
5995 	peerlbl_active = selinux_peerlbl_enabled();
5996 	if (!secmark_active && !peerlbl_active)
5997 		return NF_ACCEPT;
5998 
5999 	sk = skb_to_full_sk(skb);
6000 
6001 #ifdef CONFIG_XFRM
6002 	/* If skb->dst->xfrm is non-NULL then the packet is undergoing an IPsec
6003 	 * packet transformation so allow the packet to pass without any checks
6004 	 * since we'll have another chance to perform access control checks
6005 	 * when the packet is on it's final way out.
6006 	 * NOTE: there appear to be some IPv6 multicast cases where skb->dst
6007 	 *       is NULL, in this case go ahead and apply access control.
6008 	 * NOTE: if this is a local socket (skb->sk != NULL) that is in the
6009 	 *       TCP listening state we cannot wait until the XFRM processing
6010 	 *       is done as we will miss out on the SA label if we do;
6011 	 *       unfortunately, this means more work, but it is only once per
6012 	 *       connection. */
6013 	if (skb_dst(skb) != NULL && skb_dst(skb)->xfrm != NULL &&
6014 	    !(sk && sk_listener(sk)))
6015 		return NF_ACCEPT;
6016 #endif
6017 
6018 	family = state->pf;
6019 	if (sk == NULL) {
6020 		/* Without an associated socket the packet is either coming
6021 		 * from the kernel or it is being forwarded; check the packet
6022 		 * to determine which and if the packet is being forwarded
6023 		 * query the packet directly to determine the security label. */
6024 		if (skb->skb_iif) {
6025 			secmark_perm = PACKET__FORWARD_OUT;
6026 			if (selinux_skb_peerlbl_sid(skb, family, &peer_sid))
6027 				return NF_DROP;
6028 		} else {
6029 			secmark_perm = PACKET__SEND;
6030 			peer_sid = SECINITSID_KERNEL;
6031 		}
6032 	} else if (sk_listener(sk)) {
6033 		/* Locally generated packet but the associated socket is in the
6034 		 * listening state which means this is a SYN-ACK packet.  In
6035 		 * this particular case the correct security label is assigned
6036 		 * to the connection/request_sock but unfortunately we can't
6037 		 * query the request_sock as it isn't queued on the parent
6038 		 * socket until after the SYN-ACK packet is sent; the only
6039 		 * viable choice is to regenerate the label like we do in
6040 		 * selinux_inet_conn_request().  See also selinux_ip_output()
6041 		 * for similar problems. */
6042 		u32 skb_sid;
6043 		struct sk_security_struct *sksec;
6044 
6045 		sksec = selinux_sock(sk);
6046 		if (selinux_skb_peerlbl_sid(skb, family, &skb_sid))
6047 			return NF_DROP;
6048 		/* At this point, if the returned skb peerlbl is SECSID_NULL
6049 		 * and the packet has been through at least one XFRM
6050 		 * transformation then we must be dealing with the "final"
6051 		 * form of labeled IPsec packet; since we've already applied
6052 		 * all of our access controls on this packet we can safely
6053 		 * pass the packet. */
6054 		if (skb_sid == SECSID_NULL) {
6055 			switch (family) {
6056 			case PF_INET:
6057 				if (IPCB(skb)->flags & IPSKB_XFRM_TRANSFORMED)
6058 					return NF_ACCEPT;
6059 				break;
6060 			case PF_INET6:
6061 				if (IP6CB(skb)->flags & IP6SKB_XFRM_TRANSFORMED)
6062 					return NF_ACCEPT;
6063 				break;
6064 			default:
6065 				return NF_DROP_ERR(-ECONNREFUSED);
6066 			}
6067 		}
6068 		if (selinux_conn_sid(sksec->sid, skb_sid, &peer_sid))
6069 			return NF_DROP;
6070 		secmark_perm = PACKET__SEND;
6071 	} else {
6072 		/* Locally generated packet, fetch the security label from the
6073 		 * associated socket. */
6074 		struct sk_security_struct *sksec = selinux_sock(sk);
6075 		peer_sid = sksec->sid;
6076 		secmark_perm = PACKET__SEND;
6077 	}
6078 
6079 	ifindex = state->out->ifindex;
6080 	ad_net_init_from_iif(&ad, &net, ifindex, family);
6081 	if (selinux_parse_skb(skb, &ad, &addrp, 0, NULL))
6082 		return NF_DROP;
6083 
6084 	if (secmark_active)
6085 		if (avc_has_perm(peer_sid, skb->secmark,
6086 				 SECCLASS_PACKET, secmark_perm, &ad))
6087 			return NF_DROP_ERR(-ECONNREFUSED);
6088 
6089 	if (peerlbl_active) {
6090 		u32 if_sid;
6091 		u32 node_sid;
6092 
6093 		if (sel_netif_sid(state->net, ifindex, &if_sid))
6094 			return NF_DROP;
6095 		if (avc_has_perm(peer_sid, if_sid,
6096 				 SECCLASS_NETIF, NETIF__EGRESS, &ad))
6097 			return NF_DROP_ERR(-ECONNREFUSED);
6098 
6099 		if (sel_netnode_sid(addrp, family, &node_sid))
6100 			return NF_DROP;
6101 		if (avc_has_perm(peer_sid, node_sid,
6102 				 SECCLASS_NODE, NODE__SENDTO, &ad))
6103 			return NF_DROP_ERR(-ECONNREFUSED);
6104 	}
6105 
6106 	return NF_ACCEPT;
6107 }
6108 #endif	/* CONFIG_NETFILTER */
6109 
6110 static int nlmsg_sock_has_extended_perms(struct sock *sk, u32 perms, u16 nlmsg_type)
6111 {
6112 	struct sk_security_struct *sksec = sk->sk_security;
6113 	struct common_audit_data ad;
6114 	u8 driver;
6115 	u8 xperm;
6116 
6117 	if (sock_skip_has_perm(sksec->sid))
6118 		return 0;
6119 
6120 	ad.type = LSM_AUDIT_DATA_NLMSGTYPE;
6121 	ad.u.nlmsg_type = nlmsg_type;
6122 
6123 	driver = nlmsg_type >> 8;
6124 	xperm = nlmsg_type & 0xff;
6125 
6126 	return avc_has_extended_perms(current_sid(), sksec->sid, sksec->sclass,
6127 				      perms, driver, AVC_EXT_NLMSG, xperm, &ad);
6128 }
6129 
6130 static int selinux_netlink_send(struct sock *sk, struct sk_buff *skb)
6131 {
6132 	int rc = 0;
6133 	unsigned int msg_len;
6134 	unsigned int data_len = skb->len;
6135 	unsigned char *data = skb->data;
6136 	struct nlmsghdr *nlh;
6137 	struct sk_security_struct *sksec = selinux_sock(sk);
6138 	u16 sclass = sksec->sclass;
6139 	u32 perm;
6140 
6141 	while (data_len >= nlmsg_total_size(0)) {
6142 		nlh = (struct nlmsghdr *)data;
6143 
6144 		/* NOTE: the nlmsg_len field isn't reliably set by some netlink
6145 		 *       users which means we can't reject skb's with bogus
6146 		 *       length fields; our solution is to follow what
6147 		 *       netlink_rcv_skb() does and simply skip processing at
6148 		 *       messages with length fields that are clearly junk
6149 		 */
6150 		if (nlh->nlmsg_len < NLMSG_HDRLEN || nlh->nlmsg_len > data_len)
6151 			return 0;
6152 
6153 		rc = selinux_nlmsg_lookup(sclass, nlh->nlmsg_type, &perm);
6154 		if (rc == 0) {
6155 			if (selinux_policycap_netlink_xperm()) {
6156 				rc = nlmsg_sock_has_extended_perms(
6157 					sk, perm, nlh->nlmsg_type);
6158 			} else {
6159 				rc = sock_has_perm(sk, perm);
6160 			}
6161 			if (rc)
6162 				return rc;
6163 		} else if (rc == -EINVAL) {
6164 			/* -EINVAL is a missing msg/perm mapping */
6165 			pr_warn_ratelimited("SELinux: unrecognized netlink"
6166 				" message: protocol=%hu nlmsg_type=%hu sclass=%s"
6167 				" pid=%d comm=%s\n",
6168 				sk->sk_protocol, nlh->nlmsg_type,
6169 				secclass_map[sclass - 1].name,
6170 				task_pid_nr(current), current->comm);
6171 			if (enforcing_enabled() &&
6172 			    !security_get_allow_unknown())
6173 				return rc;
6174 			rc = 0;
6175 		} else if (rc == -ENOENT) {
6176 			/* -ENOENT is a missing socket/class mapping, ignore */
6177 			rc = 0;
6178 		} else {
6179 			return rc;
6180 		}
6181 
6182 		/* move to the next message after applying netlink padding */
6183 		msg_len = NLMSG_ALIGN(nlh->nlmsg_len);
6184 		if (msg_len >= data_len)
6185 			return 0;
6186 		data_len -= msg_len;
6187 		data += msg_len;
6188 	}
6189 
6190 	return rc;
6191 }
6192 
6193 static void ipc_init_security(struct ipc_security_struct *isec, u16 sclass)
6194 {
6195 	isec->sclass = sclass;
6196 	isec->sid = current_sid();
6197 }
6198 
6199 static int ipc_has_perm(struct kern_ipc_perm *ipc_perms,
6200 			u32 perms)
6201 {
6202 	struct ipc_security_struct *isec;
6203 	struct common_audit_data ad;
6204 	u32 sid = current_sid();
6205 
6206 	isec = selinux_ipc(ipc_perms);
6207 
6208 	ad.type = LSM_AUDIT_DATA_IPC;
6209 	ad.u.ipc_id = ipc_perms->key;
6210 
6211 	return avc_has_perm(sid, isec->sid, isec->sclass, perms, &ad);
6212 }
6213 
6214 static int selinux_msg_msg_alloc_security(struct msg_msg *msg)
6215 {
6216 	struct msg_security_struct *msec;
6217 
6218 	msec = selinux_msg_msg(msg);
6219 	msec->sid = SECINITSID_UNLABELED;
6220 
6221 	return 0;
6222 }
6223 
6224 /* message queue security operations */
6225 static int selinux_msg_queue_alloc_security(struct kern_ipc_perm *msq)
6226 {
6227 	struct ipc_security_struct *isec;
6228 	struct common_audit_data ad;
6229 	u32 sid = current_sid();
6230 
6231 	isec = selinux_ipc(msq);
6232 	ipc_init_security(isec, SECCLASS_MSGQ);
6233 
6234 	ad.type = LSM_AUDIT_DATA_IPC;
6235 	ad.u.ipc_id = msq->key;
6236 
6237 	return avc_has_perm(sid, isec->sid, SECCLASS_MSGQ,
6238 			    MSGQ__CREATE, &ad);
6239 }
6240 
6241 static int selinux_msg_queue_associate(struct kern_ipc_perm *msq, int msqflg)
6242 {
6243 	struct ipc_security_struct *isec;
6244 	struct common_audit_data ad;
6245 	u32 sid = current_sid();
6246 
6247 	isec = selinux_ipc(msq);
6248 
6249 	ad.type = LSM_AUDIT_DATA_IPC;
6250 	ad.u.ipc_id = msq->key;
6251 
6252 	return avc_has_perm(sid, isec->sid, SECCLASS_MSGQ,
6253 			    MSGQ__ASSOCIATE, &ad);
6254 }
6255 
6256 static int selinux_msg_queue_msgctl(struct kern_ipc_perm *msq, int cmd)
6257 {
6258 	u32 perms;
6259 
6260 	switch (cmd) {
6261 	case IPC_INFO:
6262 	case MSG_INFO:
6263 		/* No specific object, just general system-wide information. */
6264 		return avc_has_perm(current_sid(), SECINITSID_KERNEL,
6265 				    SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
6266 	case IPC_STAT:
6267 	case MSG_STAT:
6268 	case MSG_STAT_ANY:
6269 		perms = MSGQ__GETATTR | MSGQ__ASSOCIATE;
6270 		break;
6271 	case IPC_SET:
6272 		perms = MSGQ__SETATTR;
6273 		break;
6274 	case IPC_RMID:
6275 		perms = MSGQ__DESTROY;
6276 		break;
6277 	default:
6278 		return 0;
6279 	}
6280 
6281 	return ipc_has_perm(msq, perms);
6282 }
6283 
6284 static int selinux_msg_queue_msgsnd(struct kern_ipc_perm *msq, struct msg_msg *msg, int msqflg)
6285 {
6286 	struct ipc_security_struct *isec;
6287 	struct msg_security_struct *msec;
6288 	struct common_audit_data ad;
6289 	u32 sid = current_sid();
6290 	int rc;
6291 
6292 	isec = selinux_ipc(msq);
6293 	msec = selinux_msg_msg(msg);
6294 
6295 	/*
6296 	 * First time through, need to assign label to the message
6297 	 */
6298 	if (msec->sid == SECINITSID_UNLABELED) {
6299 		/*
6300 		 * Compute new sid based on current process and
6301 		 * message queue this message will be stored in
6302 		 */
6303 		rc = security_transition_sid(sid, isec->sid,
6304 					     SECCLASS_MSG, NULL, &msec->sid);
6305 		if (rc)
6306 			return rc;
6307 	}
6308 
6309 	ad.type = LSM_AUDIT_DATA_IPC;
6310 	ad.u.ipc_id = msq->key;
6311 
6312 	/* Can this process write to the queue? */
6313 	rc = avc_has_perm(sid, isec->sid, SECCLASS_MSGQ,
6314 			  MSGQ__WRITE, &ad);
6315 	if (!rc)
6316 		/* Can this process send the message */
6317 		rc = avc_has_perm(sid, msec->sid, SECCLASS_MSG,
6318 				  MSG__SEND, &ad);
6319 	if (!rc)
6320 		/* Can the message be put in the queue? */
6321 		rc = avc_has_perm(msec->sid, isec->sid, SECCLASS_MSGQ,
6322 				  MSGQ__ENQUEUE, &ad);
6323 
6324 	return rc;
6325 }
6326 
6327 static int selinux_msg_queue_msgrcv(struct kern_ipc_perm *msq, struct msg_msg *msg,
6328 				    struct task_struct *target,
6329 				    long type, int mode)
6330 {
6331 	struct ipc_security_struct *isec;
6332 	struct msg_security_struct *msec;
6333 	struct common_audit_data ad;
6334 	u32 sid = task_sid_obj(target);
6335 	int rc;
6336 
6337 	isec = selinux_ipc(msq);
6338 	msec = selinux_msg_msg(msg);
6339 
6340 	ad.type = LSM_AUDIT_DATA_IPC;
6341 	ad.u.ipc_id = msq->key;
6342 
6343 	rc = avc_has_perm(sid, isec->sid,
6344 			  SECCLASS_MSGQ, MSGQ__READ, &ad);
6345 	if (!rc)
6346 		rc = avc_has_perm(sid, msec->sid,
6347 				  SECCLASS_MSG, MSG__RECEIVE, &ad);
6348 	return rc;
6349 }
6350 
6351 /* Shared Memory security operations */
6352 static int selinux_shm_alloc_security(struct kern_ipc_perm *shp)
6353 {
6354 	struct ipc_security_struct *isec;
6355 	struct common_audit_data ad;
6356 	u32 sid = current_sid();
6357 
6358 	isec = selinux_ipc(shp);
6359 	ipc_init_security(isec, SECCLASS_SHM);
6360 
6361 	ad.type = LSM_AUDIT_DATA_IPC;
6362 	ad.u.ipc_id = shp->key;
6363 
6364 	return avc_has_perm(sid, isec->sid, SECCLASS_SHM,
6365 			    SHM__CREATE, &ad);
6366 }
6367 
6368 static int selinux_shm_associate(struct kern_ipc_perm *shp, int shmflg)
6369 {
6370 	struct ipc_security_struct *isec;
6371 	struct common_audit_data ad;
6372 	u32 sid = current_sid();
6373 
6374 	isec = selinux_ipc(shp);
6375 
6376 	ad.type = LSM_AUDIT_DATA_IPC;
6377 	ad.u.ipc_id = shp->key;
6378 
6379 	return avc_has_perm(sid, isec->sid, SECCLASS_SHM,
6380 			    SHM__ASSOCIATE, &ad);
6381 }
6382 
6383 /* Note, at this point, shp is locked down */
6384 static int selinux_shm_shmctl(struct kern_ipc_perm *shp, int cmd)
6385 {
6386 	u32 perms;
6387 
6388 	switch (cmd) {
6389 	case IPC_INFO:
6390 	case SHM_INFO:
6391 		/* No specific object, just general system-wide information. */
6392 		return avc_has_perm(current_sid(), SECINITSID_KERNEL,
6393 				    SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
6394 	case IPC_STAT:
6395 	case SHM_STAT:
6396 	case SHM_STAT_ANY:
6397 		perms = SHM__GETATTR | SHM__ASSOCIATE;
6398 		break;
6399 	case IPC_SET:
6400 		perms = SHM__SETATTR;
6401 		break;
6402 	case SHM_LOCK:
6403 	case SHM_UNLOCK:
6404 		perms = SHM__LOCK;
6405 		break;
6406 	case IPC_RMID:
6407 		perms = SHM__DESTROY;
6408 		break;
6409 	default:
6410 		return 0;
6411 	}
6412 
6413 	return ipc_has_perm(shp, perms);
6414 }
6415 
6416 static int selinux_shm_shmat(struct kern_ipc_perm *shp,
6417 			     char __user *shmaddr, int shmflg)
6418 {
6419 	u32 perms;
6420 
6421 	if (shmflg & SHM_RDONLY)
6422 		perms = SHM__READ;
6423 	else
6424 		perms = SHM__READ | SHM__WRITE;
6425 
6426 	return ipc_has_perm(shp, perms);
6427 }
6428 
6429 /* Semaphore security operations */
6430 static int selinux_sem_alloc_security(struct kern_ipc_perm *sma)
6431 {
6432 	struct ipc_security_struct *isec;
6433 	struct common_audit_data ad;
6434 	u32 sid = current_sid();
6435 
6436 	isec = selinux_ipc(sma);
6437 	ipc_init_security(isec, SECCLASS_SEM);
6438 
6439 	ad.type = LSM_AUDIT_DATA_IPC;
6440 	ad.u.ipc_id = sma->key;
6441 
6442 	return avc_has_perm(sid, isec->sid, SECCLASS_SEM,
6443 			    SEM__CREATE, &ad);
6444 }
6445 
6446 static int selinux_sem_associate(struct kern_ipc_perm *sma, int semflg)
6447 {
6448 	struct ipc_security_struct *isec;
6449 	struct common_audit_data ad;
6450 	u32 sid = current_sid();
6451 
6452 	isec = selinux_ipc(sma);
6453 
6454 	ad.type = LSM_AUDIT_DATA_IPC;
6455 	ad.u.ipc_id = sma->key;
6456 
6457 	return avc_has_perm(sid, isec->sid, SECCLASS_SEM,
6458 			    SEM__ASSOCIATE, &ad);
6459 }
6460 
6461 /* Note, at this point, sma is locked down */
6462 static int selinux_sem_semctl(struct kern_ipc_perm *sma, int cmd)
6463 {
6464 	int err;
6465 	u32 perms;
6466 
6467 	switch (cmd) {
6468 	case IPC_INFO:
6469 	case SEM_INFO:
6470 		/* No specific object, just general system-wide information. */
6471 		return avc_has_perm(current_sid(), SECINITSID_KERNEL,
6472 				    SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
6473 	case GETPID:
6474 	case GETNCNT:
6475 	case GETZCNT:
6476 		perms = SEM__GETATTR;
6477 		break;
6478 	case GETVAL:
6479 	case GETALL:
6480 		perms = SEM__READ;
6481 		break;
6482 	case SETVAL:
6483 	case SETALL:
6484 		perms = SEM__WRITE;
6485 		break;
6486 	case IPC_RMID:
6487 		perms = SEM__DESTROY;
6488 		break;
6489 	case IPC_SET:
6490 		perms = SEM__SETATTR;
6491 		break;
6492 	case IPC_STAT:
6493 	case SEM_STAT:
6494 	case SEM_STAT_ANY:
6495 		perms = SEM__GETATTR | SEM__ASSOCIATE;
6496 		break;
6497 	default:
6498 		return 0;
6499 	}
6500 
6501 	err = ipc_has_perm(sma, perms);
6502 	return err;
6503 }
6504 
6505 static int selinux_sem_semop(struct kern_ipc_perm *sma,
6506 			     struct sembuf *sops, unsigned nsops, int alter)
6507 {
6508 	u32 perms;
6509 
6510 	if (alter)
6511 		perms = SEM__READ | SEM__WRITE;
6512 	else
6513 		perms = SEM__READ;
6514 
6515 	return ipc_has_perm(sma, perms);
6516 }
6517 
6518 static int selinux_ipc_permission(struct kern_ipc_perm *ipcp, short flag)
6519 {
6520 	u32 av = 0;
6521 
6522 	av = 0;
6523 	if (flag & S_IRUGO)
6524 		av |= IPC__UNIX_READ;
6525 	if (flag & S_IWUGO)
6526 		av |= IPC__UNIX_WRITE;
6527 
6528 	if (av == 0)
6529 		return 0;
6530 
6531 	return ipc_has_perm(ipcp, av);
6532 }
6533 
6534 static void selinux_ipc_getlsmprop(struct kern_ipc_perm *ipcp,
6535 				   struct lsm_prop *prop)
6536 {
6537 	struct ipc_security_struct *isec = selinux_ipc(ipcp);
6538 	prop->selinux.secid = isec->sid;
6539 }
6540 
6541 static void selinux_d_instantiate(struct dentry *dentry, struct inode *inode)
6542 {
6543 	if (inode)
6544 		inode_doinit_with_dentry(inode, dentry);
6545 }
6546 
6547 static int selinux_lsm_getattr(unsigned int attr, struct task_struct *p,
6548 			       char **value)
6549 {
6550 	const struct cred_security_struct *crsec;
6551 	int error;
6552 	u32 sid;
6553 	u32 len;
6554 
6555 	rcu_read_lock();
6556 	crsec = selinux_cred(__task_cred(p));
6557 	if (p != current) {
6558 		error = avc_has_perm(current_sid(), crsec->sid,
6559 				     SECCLASS_PROCESS, PROCESS__GETATTR, NULL);
6560 		if (error)
6561 			goto err_unlock;
6562 	}
6563 	switch (attr) {
6564 	case LSM_ATTR_CURRENT:
6565 		sid = crsec->sid;
6566 		break;
6567 	case LSM_ATTR_PREV:
6568 		sid = crsec->osid;
6569 		break;
6570 	case LSM_ATTR_EXEC:
6571 		sid = crsec->exec_sid;
6572 		break;
6573 	case LSM_ATTR_FSCREATE:
6574 		sid = crsec->create_sid;
6575 		break;
6576 	case LSM_ATTR_KEYCREATE:
6577 		sid = crsec->keycreate_sid;
6578 		break;
6579 	case LSM_ATTR_SOCKCREATE:
6580 		sid = crsec->sockcreate_sid;
6581 		break;
6582 	default:
6583 		error = -EOPNOTSUPP;
6584 		goto err_unlock;
6585 	}
6586 	rcu_read_unlock();
6587 
6588 	if (sid == SECSID_NULL) {
6589 		*value = NULL;
6590 		return 0;
6591 	}
6592 
6593 	error = security_sid_to_context(sid, value, &len);
6594 	if (error)
6595 		return error;
6596 	return len;
6597 
6598 err_unlock:
6599 	rcu_read_unlock();
6600 	return error;
6601 }
6602 
6603 static int selinux_lsm_setattr(u64 attr, void *value, size_t size)
6604 {
6605 	struct cred_security_struct *crsec;
6606 	struct cred *new;
6607 	u32 mysid = current_sid(), sid = 0, ptsid;
6608 	int error;
6609 	char *str = value;
6610 
6611 	/*
6612 	 * Basic control over ability to set these attributes at all.
6613 	 */
6614 	switch (attr) {
6615 	case LSM_ATTR_EXEC:
6616 		error = avc_has_perm(mysid, mysid, SECCLASS_PROCESS,
6617 				     PROCESS__SETEXEC, NULL);
6618 		break;
6619 	case LSM_ATTR_FSCREATE:
6620 		error = avc_has_perm(mysid, mysid, SECCLASS_PROCESS,
6621 				     PROCESS__SETFSCREATE, NULL);
6622 		break;
6623 	case LSM_ATTR_KEYCREATE:
6624 		error = avc_has_perm(mysid, mysid, SECCLASS_PROCESS,
6625 				     PROCESS__SETKEYCREATE, NULL);
6626 		break;
6627 	case LSM_ATTR_SOCKCREATE:
6628 		error = avc_has_perm(mysid, mysid, SECCLASS_PROCESS,
6629 				     PROCESS__SETSOCKCREATE, NULL);
6630 		break;
6631 	case LSM_ATTR_CURRENT:
6632 		error = avc_has_perm(mysid, mysid, SECCLASS_PROCESS,
6633 				     PROCESS__SETCURRENT, NULL);
6634 		break;
6635 	default:
6636 		error = -EOPNOTSUPP;
6637 		break;
6638 	}
6639 	if (error)
6640 		return error;
6641 
6642 	/* Obtain a SID for the context, if one was specified. */
6643 	if (size && str[0] && str[0] != '\n') {
6644 		if (str[size-1] == '\n') {
6645 			str[size-1] = 0;
6646 			size--;
6647 		}
6648 		error = security_context_to_sid(value, size,
6649 						&sid, GFP_KERNEL);
6650 		if (error == -EINVAL && attr == LSM_ATTR_FSCREATE) {
6651 			if (!has_cap_mac_admin(true)) {
6652 				struct audit_buffer *ab;
6653 				size_t audit_size;
6654 
6655 				/* We strip a nul only if it is at the end,
6656 				 * otherwise the context contains a nul and
6657 				 * we should audit that */
6658 				if (str[size - 1] == '\0')
6659 					audit_size = size - 1;
6660 				else
6661 					audit_size = size;
6662 				ab = audit_log_start(audit_context(),
6663 						     GFP_ATOMIC,
6664 						     AUDIT_SELINUX_ERR);
6665 				if (!ab)
6666 					return error;
6667 				audit_log_format(ab, "op=fscreate invalid_context=");
6668 				audit_log_n_untrustedstring(ab, value,
6669 							    audit_size);
6670 				audit_log_end(ab);
6671 
6672 				return error;
6673 			}
6674 			error = security_context_to_sid_force(value, size,
6675 							&sid);
6676 		}
6677 		if (error)
6678 			return error;
6679 	}
6680 
6681 	new = prepare_creds();
6682 	if (!new)
6683 		return -ENOMEM;
6684 
6685 	/* Permission checking based on the specified context is
6686 	   performed during the actual operation (execve,
6687 	   open/mkdir/...), when we know the full context of the
6688 	   operation.  See selinux_bprm_creds_for_exec for the execve
6689 	   checks and may_create for the file creation checks. The
6690 	   operation will then fail if the context is not permitted. */
6691 	crsec = selinux_cred(new);
6692 	if (attr == LSM_ATTR_EXEC) {
6693 		crsec->exec_sid = sid;
6694 	} else if (attr == LSM_ATTR_FSCREATE) {
6695 		crsec->create_sid = sid;
6696 	} else if (attr == LSM_ATTR_KEYCREATE) {
6697 		if (sid) {
6698 			error = avc_has_perm(mysid, sid,
6699 					     SECCLASS_KEY, KEY__CREATE, NULL);
6700 			if (error)
6701 				goto abort_change;
6702 		}
6703 		crsec->keycreate_sid = sid;
6704 	} else if (attr == LSM_ATTR_SOCKCREATE) {
6705 		crsec->sockcreate_sid = sid;
6706 	} else if (attr == LSM_ATTR_CURRENT) {
6707 		error = -EINVAL;
6708 		if (sid == 0)
6709 			goto abort_change;
6710 
6711 		if (!current_is_single_threaded()) {
6712 			error = security_bounded_transition(crsec->sid, sid);
6713 			if (error)
6714 				goto abort_change;
6715 		}
6716 
6717 		/* Check permissions for the transition. */
6718 		error = avc_has_perm(crsec->sid, sid, SECCLASS_PROCESS,
6719 				     PROCESS__DYNTRANSITION, NULL);
6720 		if (error)
6721 			goto abort_change;
6722 
6723 		/* Check for ptracing, and update the task SID if ok.
6724 		   Otherwise, leave SID unchanged and fail. */
6725 		ptsid = ptrace_parent_sid();
6726 		if (ptsid != 0) {
6727 			error = avc_has_perm(ptsid, sid, SECCLASS_PROCESS,
6728 					     PROCESS__PTRACE, NULL);
6729 			if (error)
6730 				goto abort_change;
6731 		}
6732 
6733 		crsec->sid = sid;
6734 	} else {
6735 		error = -EINVAL;
6736 		goto abort_change;
6737 	}
6738 
6739 	commit_creds(new);
6740 	return size;
6741 
6742 abort_change:
6743 	abort_creds(new);
6744 	return error;
6745 }
6746 
6747 /**
6748  * selinux_getselfattr - Get SELinux current task attributes
6749  * @attr: the requested attribute
6750  * @ctx: buffer to receive the result
6751  * @size: buffer size (input), buffer size used (output)
6752  * @flags: unused
6753  *
6754  * Fill the passed user space @ctx with the details of the requested
6755  * attribute.
6756  *
6757  * Returns the number of attributes on success, an error code otherwise.
6758  * There will only ever be one attribute.
6759  */
6760 static int selinux_getselfattr(unsigned int attr, struct lsm_ctx __user *ctx,
6761 			       u32 *size, u32 flags)
6762 {
6763 	int rc;
6764 	char *val = NULL;
6765 	int val_len;
6766 
6767 	val_len = selinux_lsm_getattr(attr, current, &val);
6768 	if (val_len < 0)
6769 		return val_len;
6770 	rc = lsm_fill_user_ctx(ctx, size, val, val_len, LSM_ID_SELINUX, 0);
6771 	kfree(val);
6772 	return (!rc ? 1 : rc);
6773 }
6774 
6775 static int selinux_setselfattr(unsigned int attr, struct lsm_ctx *ctx,
6776 			       u32 size, u32 flags)
6777 {
6778 	int rc;
6779 
6780 	rc = selinux_lsm_setattr(attr, ctx->ctx, ctx->ctx_len);
6781 	if (rc > 0)
6782 		return 0;
6783 	return rc;
6784 }
6785 
6786 static int selinux_getprocattr(struct task_struct *p,
6787 			       const char *name, char **value)
6788 {
6789 	unsigned int attr = lsm_name_to_attr(name);
6790 	int rc;
6791 
6792 	if (attr) {
6793 		rc = selinux_lsm_getattr(attr, p, value);
6794 		if (rc != -EOPNOTSUPP)
6795 			return rc;
6796 	}
6797 
6798 	return -EINVAL;
6799 }
6800 
6801 static int selinux_setprocattr(const char *name, void *value, size_t size)
6802 {
6803 	int attr = lsm_name_to_attr(name);
6804 
6805 	if (attr)
6806 		return selinux_lsm_setattr(attr, value, size);
6807 	return -EINVAL;
6808 }
6809 
6810 static int selinux_ismaclabel(const char *name)
6811 {
6812 	return (strcmp(name, XATTR_SELINUX_SUFFIX) == 0);
6813 }
6814 
6815 static int selinux_secid_to_secctx(u32 secid, struct lsm_context *cp)
6816 {
6817 	u32 seclen;
6818 	int ret;
6819 
6820 	if (cp) {
6821 		cp->id = LSM_ID_SELINUX;
6822 		ret = security_sid_to_context(secid, &cp->context, &cp->len);
6823 		if (ret < 0)
6824 			return ret;
6825 		return cp->len;
6826 	}
6827 	ret = security_sid_to_context(secid, NULL, &seclen);
6828 	if (ret < 0)
6829 		return ret;
6830 	return seclen;
6831 }
6832 
6833 static int selinux_lsmprop_to_secctx(struct lsm_prop *prop,
6834 				     struct lsm_context *cp)
6835 {
6836 	return selinux_secid_to_secctx(prop->selinux.secid, cp);
6837 }
6838 
6839 static int selinux_secctx_to_secid(const char *secdata, u32 seclen, u32 *secid)
6840 {
6841 	return security_context_to_sid(secdata, seclen,
6842 				       secid, GFP_KERNEL);
6843 }
6844 
6845 static void selinux_release_secctx(struct lsm_context *cp)
6846 {
6847 	if (cp->id == LSM_ID_SELINUX) {
6848 		kfree(cp->context);
6849 		cp->context = NULL;
6850 		cp->id = LSM_ID_UNDEF;
6851 	}
6852 }
6853 
6854 static void selinux_inode_invalidate_secctx(struct inode *inode)
6855 {
6856 	struct inode_security_struct *isec = selinux_inode(inode);
6857 
6858 	spin_lock(&isec->lock);
6859 	isec->initialized = LABEL_INVALID;
6860 	spin_unlock(&isec->lock);
6861 }
6862 
6863 /*
6864  *	called with inode->i_mutex locked
6865  */
6866 static int selinux_inode_notifysecctx(struct inode *inode, void *ctx, u32 ctxlen)
6867 {
6868 	int rc = selinux_inode_setsecurity(inode, XATTR_SELINUX_SUFFIX,
6869 					   ctx, ctxlen, 0);
6870 	/* Do not return error when suppressing label (SBLABEL_MNT not set). */
6871 	return rc == -EOPNOTSUPP ? 0 : rc;
6872 }
6873 
6874 /*
6875  *	called with inode->i_mutex locked
6876  */
6877 static int selinux_inode_setsecctx(struct dentry *dentry, void *ctx, u32 ctxlen)
6878 {
6879 	return __vfs_setxattr_locked(&nop_mnt_idmap, dentry, XATTR_NAME_SELINUX,
6880 				     ctx, ctxlen, 0, NULL);
6881 }
6882 
6883 static int selinux_inode_getsecctx(struct inode *inode, struct lsm_context *cp)
6884 {
6885 	int len;
6886 	len = selinux_inode_getsecurity(&nop_mnt_idmap, inode,
6887 					XATTR_SELINUX_SUFFIX,
6888 					(void **)&cp->context, true);
6889 	if (len < 0)
6890 		return len;
6891 	cp->len = len;
6892 	cp->id = LSM_ID_SELINUX;
6893 	return 0;
6894 }
6895 #ifdef CONFIG_KEYS
6896 
6897 static int selinux_key_alloc(struct key *k, const struct cred *cred,
6898 			     unsigned long flags)
6899 {
6900 	const struct cred_security_struct *crsec;
6901 	struct key_security_struct *ksec = selinux_key(k);
6902 
6903 	crsec = selinux_cred(cred);
6904 	if (crsec->keycreate_sid)
6905 		ksec->sid = crsec->keycreate_sid;
6906 	else
6907 		ksec->sid = crsec->sid;
6908 
6909 	return 0;
6910 }
6911 
6912 static int selinux_key_permission(key_ref_t key_ref,
6913 				  const struct cred *cred,
6914 				  enum key_need_perm need_perm)
6915 {
6916 	struct key *key;
6917 	struct key_security_struct *ksec;
6918 	u32 perm, sid;
6919 
6920 	switch (need_perm) {
6921 	case KEY_NEED_VIEW:
6922 		perm = KEY__VIEW;
6923 		break;
6924 	case KEY_NEED_READ:
6925 		perm = KEY__READ;
6926 		break;
6927 	case KEY_NEED_WRITE:
6928 		perm = KEY__WRITE;
6929 		break;
6930 	case KEY_NEED_SEARCH:
6931 		perm = KEY__SEARCH;
6932 		break;
6933 	case KEY_NEED_LINK:
6934 		perm = KEY__LINK;
6935 		break;
6936 	case KEY_NEED_SETATTR:
6937 		perm = KEY__SETATTR;
6938 		break;
6939 	case KEY_NEED_UNLINK:
6940 	case KEY_SYSADMIN_OVERRIDE:
6941 	case KEY_AUTHTOKEN_OVERRIDE:
6942 	case KEY_DEFER_PERM_CHECK:
6943 		return 0;
6944 	default:
6945 		WARN_ON(1);
6946 		return -EPERM;
6947 
6948 	}
6949 
6950 	sid = cred_sid(cred);
6951 	key = key_ref_to_ptr(key_ref);
6952 	ksec = selinux_key(key);
6953 
6954 	return avc_has_perm(sid, ksec->sid, SECCLASS_KEY, perm, NULL);
6955 }
6956 
6957 static int selinux_key_getsecurity(struct key *key, char **_buffer)
6958 {
6959 	struct key_security_struct *ksec = selinux_key(key);
6960 	char *context = NULL;
6961 	unsigned len;
6962 	int rc;
6963 
6964 	rc = security_sid_to_context(ksec->sid,
6965 				     &context, &len);
6966 	if (!rc)
6967 		rc = len;
6968 	*_buffer = context;
6969 	return rc;
6970 }
6971 
6972 #ifdef CONFIG_KEY_NOTIFICATIONS
6973 static int selinux_watch_key(struct key *key)
6974 {
6975 	struct key_security_struct *ksec = selinux_key(key);
6976 	u32 sid = current_sid();
6977 
6978 	return avc_has_perm(sid, ksec->sid, SECCLASS_KEY, KEY__VIEW, NULL);
6979 }
6980 #endif
6981 #endif
6982 
6983 #ifdef CONFIG_SECURITY_INFINIBAND
6984 static int selinux_ib_pkey_access(void *ib_sec, u64 subnet_prefix, u16 pkey_val)
6985 {
6986 	struct common_audit_data ad;
6987 	int err;
6988 	u32 sid = 0;
6989 	struct ib_security_struct *sec = ib_sec;
6990 	struct lsm_ibpkey_audit ibpkey;
6991 
6992 	err = sel_ib_pkey_sid(subnet_prefix, pkey_val, &sid);
6993 	if (err)
6994 		return err;
6995 
6996 	ad.type = LSM_AUDIT_DATA_IBPKEY;
6997 	ibpkey.subnet_prefix = subnet_prefix;
6998 	ibpkey.pkey = pkey_val;
6999 	ad.u.ibpkey = &ibpkey;
7000 	return avc_has_perm(sec->sid, sid,
7001 			    SECCLASS_INFINIBAND_PKEY,
7002 			    INFINIBAND_PKEY__ACCESS, &ad);
7003 }
7004 
7005 static int selinux_ib_endport_manage_subnet(void *ib_sec, const char *dev_name,
7006 					    u8 port_num)
7007 {
7008 	struct common_audit_data ad;
7009 	int err;
7010 	u32 sid = 0;
7011 	struct ib_security_struct *sec = ib_sec;
7012 	struct lsm_ibendport_audit ibendport;
7013 
7014 	err = security_ib_endport_sid(dev_name, port_num,
7015 				      &sid);
7016 
7017 	if (err)
7018 		return err;
7019 
7020 	ad.type = LSM_AUDIT_DATA_IBENDPORT;
7021 	ibendport.dev_name = dev_name;
7022 	ibendport.port = port_num;
7023 	ad.u.ibendport = &ibendport;
7024 	return avc_has_perm(sec->sid, sid,
7025 			    SECCLASS_INFINIBAND_ENDPORT,
7026 			    INFINIBAND_ENDPORT__MANAGE_SUBNET, &ad);
7027 }
7028 
7029 static int selinux_ib_alloc_security(void *ib_sec)
7030 {
7031 	struct ib_security_struct *sec = selinux_ib(ib_sec);
7032 
7033 	sec->sid = current_sid();
7034 	return 0;
7035 }
7036 #endif
7037 
7038 #ifdef CONFIG_BPF_SYSCALL
7039 static int selinux_bpf(int cmd, union bpf_attr *attr,
7040 		       unsigned int size, bool kernel)
7041 {
7042 	u32 sid = current_sid();
7043 	int ret;
7044 
7045 	switch (cmd) {
7046 	case BPF_MAP_CREATE:
7047 		ret = avc_has_perm(sid, sid, SECCLASS_BPF, BPF__MAP_CREATE,
7048 				   NULL);
7049 		break;
7050 	case BPF_PROG_LOAD:
7051 		ret = avc_has_perm(sid, sid, SECCLASS_BPF, BPF__PROG_LOAD,
7052 				   NULL);
7053 		break;
7054 	default:
7055 		ret = 0;
7056 		break;
7057 	}
7058 
7059 	return ret;
7060 }
7061 
7062 static u32 bpf_map_fmode_to_av(fmode_t fmode)
7063 {
7064 	u32 av = 0;
7065 
7066 	if (fmode & FMODE_READ)
7067 		av |= BPF__MAP_READ;
7068 	if (fmode & FMODE_WRITE)
7069 		av |= BPF__MAP_WRITE;
7070 	return av;
7071 }
7072 
7073 /* This function will check the file pass through unix socket or binder to see
7074  * if it is a bpf related object. And apply corresponding checks on the bpf
7075  * object based on the type. The bpf maps and programs, not like other files and
7076  * socket, are using a shared anonymous inode inside the kernel as their inode.
7077  * So checking that inode cannot identify if the process have privilege to
7078  * access the bpf object and that's why we have to add this additional check in
7079  * selinux_file_receive and selinux_binder_transfer_files.
7080  */
7081 static int bpf_fd_pass(const struct file *file, u32 sid)
7082 {
7083 	struct bpf_security_struct *bpfsec;
7084 	struct bpf_prog *prog;
7085 	struct bpf_map *map;
7086 	int ret;
7087 
7088 	if (file->f_op == &bpf_map_fops) {
7089 		map = file->private_data;
7090 		bpfsec = selinux_bpf_map_security(map);
7091 		ret = avc_has_perm(sid, bpfsec->sid, SECCLASS_BPF,
7092 				   bpf_map_fmode_to_av(file->f_mode), NULL);
7093 		if (ret)
7094 			return ret;
7095 	} else if (file->f_op == &bpf_prog_fops) {
7096 		prog = file->private_data;
7097 		bpfsec = selinux_bpf_prog_security(prog);
7098 		ret = avc_has_perm(sid, bpfsec->sid, SECCLASS_BPF,
7099 				   BPF__PROG_RUN, NULL);
7100 		if (ret)
7101 			return ret;
7102 	}
7103 	return 0;
7104 }
7105 
7106 static int selinux_bpf_map(struct bpf_map *map, fmode_t fmode)
7107 {
7108 	u32 sid = current_sid();
7109 	struct bpf_security_struct *bpfsec;
7110 
7111 	bpfsec = selinux_bpf_map_security(map);
7112 	return avc_has_perm(sid, bpfsec->sid, SECCLASS_BPF,
7113 			    bpf_map_fmode_to_av(fmode), NULL);
7114 }
7115 
7116 static int selinux_bpf_prog(struct bpf_prog *prog)
7117 {
7118 	u32 sid = current_sid();
7119 	struct bpf_security_struct *bpfsec;
7120 
7121 	bpfsec = selinux_bpf_prog_security(prog);
7122 	return avc_has_perm(sid, bpfsec->sid, SECCLASS_BPF,
7123 			    BPF__PROG_RUN, NULL);
7124 }
7125 
7126 static int selinux_bpf_map_create(struct bpf_map *map, union bpf_attr *attr,
7127 				  struct bpf_token *token, bool kernel)
7128 {
7129 	struct bpf_security_struct *bpfsec;
7130 
7131 	bpfsec = selinux_bpf_map_security(map);
7132 	bpfsec->sid = current_sid();
7133 
7134 	return 0;
7135 }
7136 
7137 static int selinux_bpf_prog_load(struct bpf_prog *prog, union bpf_attr *attr,
7138 				 struct bpf_token *token, bool kernel)
7139 {
7140 	struct bpf_security_struct *bpfsec;
7141 
7142 	bpfsec = selinux_bpf_prog_security(prog);
7143 	bpfsec->sid = current_sid();
7144 
7145 	return 0;
7146 }
7147 
7148 static int selinux_bpf_token_create(struct bpf_token *token, union bpf_attr *attr,
7149 				    const struct path *path)
7150 {
7151 	struct bpf_security_struct *bpfsec;
7152 
7153 	bpfsec = selinux_bpf_token_security(token);
7154 	bpfsec->sid = current_sid();
7155 
7156 	return 0;
7157 }
7158 #endif
7159 
7160 struct lsm_blob_sizes selinux_blob_sizes __ro_after_init = {
7161 	.lbs_cred = sizeof(struct cred_security_struct),
7162 	.lbs_task = sizeof(struct task_security_struct),
7163 	.lbs_file = sizeof(struct file_security_struct),
7164 	.lbs_inode = sizeof(struct inode_security_struct),
7165 	.lbs_ipc = sizeof(struct ipc_security_struct),
7166 	.lbs_key = sizeof(struct key_security_struct),
7167 	.lbs_msg_msg = sizeof(struct msg_security_struct),
7168 #ifdef CONFIG_PERF_EVENTS
7169 	.lbs_perf_event = sizeof(struct perf_event_security_struct),
7170 #endif
7171 	.lbs_sock = sizeof(struct sk_security_struct),
7172 	.lbs_superblock = sizeof(struct superblock_security_struct),
7173 	.lbs_xattr_count = SELINUX_INODE_INIT_XATTRS,
7174 	.lbs_tun_dev = sizeof(struct tun_security_struct),
7175 	.lbs_ib = sizeof(struct ib_security_struct),
7176 	.lbs_bpf_map = sizeof(struct bpf_security_struct),
7177 	.lbs_bpf_prog = sizeof(struct bpf_security_struct),
7178 	.lbs_bpf_token = sizeof(struct bpf_security_struct),
7179 };
7180 
7181 #ifdef CONFIG_PERF_EVENTS
7182 static int selinux_perf_event_open(int type)
7183 {
7184 	u32 requested, sid = current_sid();
7185 
7186 	if (type == PERF_SECURITY_OPEN)
7187 		requested = PERF_EVENT__OPEN;
7188 	else if (type == PERF_SECURITY_CPU)
7189 		requested = PERF_EVENT__CPU;
7190 	else if (type == PERF_SECURITY_KERNEL)
7191 		requested = PERF_EVENT__KERNEL;
7192 	else if (type == PERF_SECURITY_TRACEPOINT)
7193 		requested = PERF_EVENT__TRACEPOINT;
7194 	else
7195 		return -EINVAL;
7196 
7197 	return avc_has_perm(sid, sid, SECCLASS_PERF_EVENT,
7198 			    requested, NULL);
7199 }
7200 
7201 static int selinux_perf_event_alloc(struct perf_event *event)
7202 {
7203 	struct perf_event_security_struct *perfsec;
7204 
7205 	perfsec = selinux_perf_event(event->security);
7206 	perfsec->sid = current_sid();
7207 
7208 	return 0;
7209 }
7210 
7211 static int selinux_perf_event_read(struct perf_event *event)
7212 {
7213 	struct perf_event_security_struct *perfsec = event->security;
7214 	u32 sid = current_sid();
7215 
7216 	return avc_has_perm(sid, perfsec->sid,
7217 			    SECCLASS_PERF_EVENT, PERF_EVENT__READ, NULL);
7218 }
7219 
7220 static int selinux_perf_event_write(struct perf_event *event)
7221 {
7222 	struct perf_event_security_struct *perfsec = event->security;
7223 	u32 sid = current_sid();
7224 
7225 	return avc_has_perm(sid, perfsec->sid,
7226 			    SECCLASS_PERF_EVENT, PERF_EVENT__WRITE, NULL);
7227 }
7228 #endif
7229 
7230 #ifdef CONFIG_IO_URING
7231 /**
7232  * selinux_uring_override_creds - check the requested cred override
7233  * @new: the target creds
7234  *
7235  * Check to see if the current task is allowed to override it's credentials
7236  * to service an io_uring operation.
7237  */
7238 static int selinux_uring_override_creds(const struct cred *new)
7239 {
7240 	return avc_has_perm(current_sid(), cred_sid(new),
7241 			    SECCLASS_IO_URING, IO_URING__OVERRIDE_CREDS, NULL);
7242 }
7243 
7244 /**
7245  * selinux_uring_sqpoll - check if a io_uring polling thread can be created
7246  *
7247  * Check to see if the current task is allowed to create a new io_uring
7248  * kernel polling thread.
7249  */
7250 static int selinux_uring_sqpoll(void)
7251 {
7252 	u32 sid = current_sid();
7253 
7254 	return avc_has_perm(sid, sid,
7255 			    SECCLASS_IO_URING, IO_URING__SQPOLL, NULL);
7256 }
7257 
7258 /**
7259  * selinux_uring_cmd - check if IORING_OP_URING_CMD is allowed
7260  * @ioucmd: the io_uring command structure
7261  *
7262  * Check to see if the current domain is allowed to execute an
7263  * IORING_OP_URING_CMD against the device/file specified in @ioucmd.
7264  *
7265  */
7266 static int selinux_uring_cmd(struct io_uring_cmd *ioucmd)
7267 {
7268 	struct file *file = ioucmd->file;
7269 	struct inode *inode = file_inode(file);
7270 	struct inode_security_struct *isec = selinux_inode(inode);
7271 	struct common_audit_data ad;
7272 
7273 	ad.type = LSM_AUDIT_DATA_FILE;
7274 	ad.u.file = file;
7275 
7276 	return avc_has_perm(current_sid(), isec->sid,
7277 			    SECCLASS_IO_URING, IO_URING__CMD, &ad);
7278 }
7279 
7280 /**
7281  * selinux_uring_allowed - check if io_uring_setup() can be called
7282  *
7283  * Check to see if the current task is allowed to call io_uring_setup().
7284  */
7285 static int selinux_uring_allowed(void)
7286 {
7287 	u32 sid = current_sid();
7288 
7289 	return avc_has_perm(sid, sid, SECCLASS_IO_URING, IO_URING__ALLOWED,
7290 			    NULL);
7291 }
7292 #endif /* CONFIG_IO_URING */
7293 
7294 static const struct lsm_id selinux_lsmid = {
7295 	.name = "selinux",
7296 	.id = LSM_ID_SELINUX,
7297 };
7298 
7299 /*
7300  * IMPORTANT NOTE: When adding new hooks, please be careful to keep this order:
7301  * 1. any hooks that don't belong to (2.) or (3.) below,
7302  * 2. hooks that both access structures allocated by other hooks, and allocate
7303  *    structures that can be later accessed by other hooks (mostly "cloning"
7304  *    hooks),
7305  * 3. hooks that only allocate structures that can be later accessed by other
7306  *    hooks ("allocating" hooks).
7307  *
7308  * Please follow block comment delimiters in the list to keep this order.
7309  */
7310 static struct security_hook_list selinux_hooks[] __ro_after_init = {
7311 	LSM_HOOK_INIT(binder_set_context_mgr, selinux_binder_set_context_mgr),
7312 	LSM_HOOK_INIT(binder_transaction, selinux_binder_transaction),
7313 	LSM_HOOK_INIT(binder_transfer_binder, selinux_binder_transfer_binder),
7314 	LSM_HOOK_INIT(binder_transfer_file, selinux_binder_transfer_file),
7315 
7316 	LSM_HOOK_INIT(ptrace_access_check, selinux_ptrace_access_check),
7317 	LSM_HOOK_INIT(ptrace_traceme, selinux_ptrace_traceme),
7318 	LSM_HOOK_INIT(capget, selinux_capget),
7319 	LSM_HOOK_INIT(capset, selinux_capset),
7320 	LSM_HOOK_INIT(capable, selinux_capable),
7321 	LSM_HOOK_INIT(quotactl, selinux_quotactl),
7322 	LSM_HOOK_INIT(quota_on, selinux_quota_on),
7323 	LSM_HOOK_INIT(syslog, selinux_syslog),
7324 	LSM_HOOK_INIT(vm_enough_memory, selinux_vm_enough_memory),
7325 
7326 	LSM_HOOK_INIT(netlink_send, selinux_netlink_send),
7327 
7328 	LSM_HOOK_INIT(bprm_creds_for_exec, selinux_bprm_creds_for_exec),
7329 	LSM_HOOK_INIT(bprm_committing_creds, selinux_bprm_committing_creds),
7330 	LSM_HOOK_INIT(bprm_committed_creds, selinux_bprm_committed_creds),
7331 
7332 	LSM_HOOK_INIT(sb_free_mnt_opts, selinux_free_mnt_opts),
7333 	LSM_HOOK_INIT(sb_mnt_opts_compat, selinux_sb_mnt_opts_compat),
7334 	LSM_HOOK_INIT(sb_remount, selinux_sb_remount),
7335 	LSM_HOOK_INIT(sb_kern_mount, selinux_sb_kern_mount),
7336 	LSM_HOOK_INIT(sb_show_options, selinux_sb_show_options),
7337 	LSM_HOOK_INIT(sb_statfs, selinux_sb_statfs),
7338 	LSM_HOOK_INIT(sb_mount, selinux_mount),
7339 	LSM_HOOK_INIT(sb_umount, selinux_umount),
7340 	LSM_HOOK_INIT(sb_set_mnt_opts, selinux_set_mnt_opts),
7341 	LSM_HOOK_INIT(sb_clone_mnt_opts, selinux_sb_clone_mnt_opts),
7342 
7343 	LSM_HOOK_INIT(move_mount, selinux_move_mount),
7344 
7345 	LSM_HOOK_INIT(dentry_init_security, selinux_dentry_init_security),
7346 	LSM_HOOK_INIT(dentry_create_files_as, selinux_dentry_create_files_as),
7347 
7348 	LSM_HOOK_INIT(inode_free_security, selinux_inode_free_security),
7349 	LSM_HOOK_INIT(inode_init_security, selinux_inode_init_security),
7350 	LSM_HOOK_INIT(inode_init_security_anon, selinux_inode_init_security_anon),
7351 	LSM_HOOK_INIT(inode_create, selinux_inode_create),
7352 	LSM_HOOK_INIT(inode_link, selinux_inode_link),
7353 	LSM_HOOK_INIT(inode_unlink, selinux_inode_unlink),
7354 	LSM_HOOK_INIT(inode_symlink, selinux_inode_symlink),
7355 	LSM_HOOK_INIT(inode_mkdir, selinux_inode_mkdir),
7356 	LSM_HOOK_INIT(inode_rmdir, selinux_inode_rmdir),
7357 	LSM_HOOK_INIT(inode_mknod, selinux_inode_mknod),
7358 	LSM_HOOK_INIT(inode_rename, selinux_inode_rename),
7359 	LSM_HOOK_INIT(inode_readlink, selinux_inode_readlink),
7360 	LSM_HOOK_INIT(inode_follow_link, selinux_inode_follow_link),
7361 	LSM_HOOK_INIT(inode_permission, selinux_inode_permission),
7362 	LSM_HOOK_INIT(inode_setattr, selinux_inode_setattr),
7363 	LSM_HOOK_INIT(inode_getattr, selinux_inode_getattr),
7364 	LSM_HOOK_INIT(inode_xattr_skipcap, selinux_inode_xattr_skipcap),
7365 	LSM_HOOK_INIT(inode_setxattr, selinux_inode_setxattr),
7366 	LSM_HOOK_INIT(inode_post_setxattr, selinux_inode_post_setxattr),
7367 	LSM_HOOK_INIT(inode_getxattr, selinux_inode_getxattr),
7368 	LSM_HOOK_INIT(inode_listxattr, selinux_inode_listxattr),
7369 	LSM_HOOK_INIT(inode_removexattr, selinux_inode_removexattr),
7370 	LSM_HOOK_INIT(inode_file_getattr, selinux_inode_file_getattr),
7371 	LSM_HOOK_INIT(inode_file_setattr, selinux_inode_file_setattr),
7372 	LSM_HOOK_INIT(inode_set_acl, selinux_inode_set_acl),
7373 	LSM_HOOK_INIT(inode_get_acl, selinux_inode_get_acl),
7374 	LSM_HOOK_INIT(inode_remove_acl, selinux_inode_remove_acl),
7375 	LSM_HOOK_INIT(inode_getsecurity, selinux_inode_getsecurity),
7376 	LSM_HOOK_INIT(inode_setsecurity, selinux_inode_setsecurity),
7377 	LSM_HOOK_INIT(inode_listsecurity, selinux_inode_listsecurity),
7378 	LSM_HOOK_INIT(inode_getlsmprop, selinux_inode_getlsmprop),
7379 	LSM_HOOK_INIT(inode_copy_up, selinux_inode_copy_up),
7380 	LSM_HOOK_INIT(inode_copy_up_xattr, selinux_inode_copy_up_xattr),
7381 	LSM_HOOK_INIT(path_notify, selinux_path_notify),
7382 
7383 	LSM_HOOK_INIT(kernfs_init_security, selinux_kernfs_init_security),
7384 
7385 	LSM_HOOK_INIT(file_permission, selinux_file_permission),
7386 	LSM_HOOK_INIT(file_alloc_security, selinux_file_alloc_security),
7387 	LSM_HOOK_INIT(file_ioctl, selinux_file_ioctl),
7388 	LSM_HOOK_INIT(file_ioctl_compat, selinux_file_ioctl_compat),
7389 	LSM_HOOK_INIT(mmap_file, selinux_mmap_file),
7390 	LSM_HOOK_INIT(mmap_addr, selinux_mmap_addr),
7391 	LSM_HOOK_INIT(file_mprotect, selinux_file_mprotect),
7392 	LSM_HOOK_INIT(file_lock, selinux_file_lock),
7393 	LSM_HOOK_INIT(file_fcntl, selinux_file_fcntl),
7394 	LSM_HOOK_INIT(file_set_fowner, selinux_file_set_fowner),
7395 	LSM_HOOK_INIT(file_send_sigiotask, selinux_file_send_sigiotask),
7396 	LSM_HOOK_INIT(file_receive, selinux_file_receive),
7397 
7398 	LSM_HOOK_INIT(file_open, selinux_file_open),
7399 
7400 	LSM_HOOK_INIT(task_alloc, selinux_task_alloc),
7401 	LSM_HOOK_INIT(cred_prepare, selinux_cred_prepare),
7402 	LSM_HOOK_INIT(cred_transfer, selinux_cred_transfer),
7403 	LSM_HOOK_INIT(cred_getsecid, selinux_cred_getsecid),
7404 	LSM_HOOK_INIT(cred_getlsmprop, selinux_cred_getlsmprop),
7405 	LSM_HOOK_INIT(kernel_act_as, selinux_kernel_act_as),
7406 	LSM_HOOK_INIT(kernel_create_files_as, selinux_kernel_create_files_as),
7407 	LSM_HOOK_INIT(kernel_module_request, selinux_kernel_module_request),
7408 	LSM_HOOK_INIT(kernel_load_data, selinux_kernel_load_data),
7409 	LSM_HOOK_INIT(kernel_read_file, selinux_kernel_read_file),
7410 	LSM_HOOK_INIT(task_setpgid, selinux_task_setpgid),
7411 	LSM_HOOK_INIT(task_getpgid, selinux_task_getpgid),
7412 	LSM_HOOK_INIT(task_getsid, selinux_task_getsid),
7413 	LSM_HOOK_INIT(current_getlsmprop_subj, selinux_current_getlsmprop_subj),
7414 	LSM_HOOK_INIT(task_getlsmprop_obj, selinux_task_getlsmprop_obj),
7415 	LSM_HOOK_INIT(task_setnice, selinux_task_setnice),
7416 	LSM_HOOK_INIT(task_setioprio, selinux_task_setioprio),
7417 	LSM_HOOK_INIT(task_getioprio, selinux_task_getioprio),
7418 	LSM_HOOK_INIT(task_prlimit, selinux_task_prlimit),
7419 	LSM_HOOK_INIT(task_setrlimit, selinux_task_setrlimit),
7420 	LSM_HOOK_INIT(task_setscheduler, selinux_task_setscheduler),
7421 	LSM_HOOK_INIT(task_getscheduler, selinux_task_getscheduler),
7422 	LSM_HOOK_INIT(task_movememory, selinux_task_movememory),
7423 	LSM_HOOK_INIT(task_kill, selinux_task_kill),
7424 	LSM_HOOK_INIT(task_to_inode, selinux_task_to_inode),
7425 	LSM_HOOK_INIT(userns_create, selinux_userns_create),
7426 
7427 	LSM_HOOK_INIT(ipc_permission, selinux_ipc_permission),
7428 	LSM_HOOK_INIT(ipc_getlsmprop, selinux_ipc_getlsmprop),
7429 
7430 	LSM_HOOK_INIT(msg_queue_associate, selinux_msg_queue_associate),
7431 	LSM_HOOK_INIT(msg_queue_msgctl, selinux_msg_queue_msgctl),
7432 	LSM_HOOK_INIT(msg_queue_msgsnd, selinux_msg_queue_msgsnd),
7433 	LSM_HOOK_INIT(msg_queue_msgrcv, selinux_msg_queue_msgrcv),
7434 
7435 	LSM_HOOK_INIT(shm_associate, selinux_shm_associate),
7436 	LSM_HOOK_INIT(shm_shmctl, selinux_shm_shmctl),
7437 	LSM_HOOK_INIT(shm_shmat, selinux_shm_shmat),
7438 
7439 	LSM_HOOK_INIT(sem_associate, selinux_sem_associate),
7440 	LSM_HOOK_INIT(sem_semctl, selinux_sem_semctl),
7441 	LSM_HOOK_INIT(sem_semop, selinux_sem_semop),
7442 
7443 	LSM_HOOK_INIT(d_instantiate, selinux_d_instantiate),
7444 
7445 	LSM_HOOK_INIT(getselfattr, selinux_getselfattr),
7446 	LSM_HOOK_INIT(setselfattr, selinux_setselfattr),
7447 	LSM_HOOK_INIT(getprocattr, selinux_getprocattr),
7448 	LSM_HOOK_INIT(setprocattr, selinux_setprocattr),
7449 
7450 	LSM_HOOK_INIT(ismaclabel, selinux_ismaclabel),
7451 	LSM_HOOK_INIT(secctx_to_secid, selinux_secctx_to_secid),
7452 	LSM_HOOK_INIT(release_secctx, selinux_release_secctx),
7453 	LSM_HOOK_INIT(inode_invalidate_secctx, selinux_inode_invalidate_secctx),
7454 	LSM_HOOK_INIT(inode_notifysecctx, selinux_inode_notifysecctx),
7455 	LSM_HOOK_INIT(inode_setsecctx, selinux_inode_setsecctx),
7456 
7457 	LSM_HOOK_INIT(unix_stream_connect, selinux_socket_unix_stream_connect),
7458 	LSM_HOOK_INIT(unix_may_send, selinux_socket_unix_may_send),
7459 
7460 	LSM_HOOK_INIT(socket_create, selinux_socket_create),
7461 	LSM_HOOK_INIT(socket_post_create, selinux_socket_post_create),
7462 	LSM_HOOK_INIT(socket_socketpair, selinux_socket_socketpair),
7463 	LSM_HOOK_INIT(socket_bind, selinux_socket_bind),
7464 	LSM_HOOK_INIT(socket_connect, selinux_socket_connect),
7465 	LSM_HOOK_INIT(socket_listen, selinux_socket_listen),
7466 	LSM_HOOK_INIT(socket_accept, selinux_socket_accept),
7467 	LSM_HOOK_INIT(socket_sendmsg, selinux_socket_sendmsg),
7468 	LSM_HOOK_INIT(socket_recvmsg, selinux_socket_recvmsg),
7469 	LSM_HOOK_INIT(socket_getsockname, selinux_socket_getsockname),
7470 	LSM_HOOK_INIT(socket_getpeername, selinux_socket_getpeername),
7471 	LSM_HOOK_INIT(socket_getsockopt, selinux_socket_getsockopt),
7472 	LSM_HOOK_INIT(socket_setsockopt, selinux_socket_setsockopt),
7473 	LSM_HOOK_INIT(socket_shutdown, selinux_socket_shutdown),
7474 	LSM_HOOK_INIT(socket_sock_rcv_skb, selinux_socket_sock_rcv_skb),
7475 	LSM_HOOK_INIT(socket_getpeersec_stream,
7476 			selinux_socket_getpeersec_stream),
7477 	LSM_HOOK_INIT(socket_getpeersec_dgram, selinux_socket_getpeersec_dgram),
7478 	LSM_HOOK_INIT(sk_free_security, selinux_sk_free_security),
7479 	LSM_HOOK_INIT(sk_clone_security, selinux_sk_clone_security),
7480 	LSM_HOOK_INIT(sk_getsecid, selinux_sk_getsecid),
7481 	LSM_HOOK_INIT(sock_graft, selinux_sock_graft),
7482 	LSM_HOOK_INIT(sctp_assoc_request, selinux_sctp_assoc_request),
7483 	LSM_HOOK_INIT(sctp_sk_clone, selinux_sctp_sk_clone),
7484 	LSM_HOOK_INIT(sctp_bind_connect, selinux_sctp_bind_connect),
7485 	LSM_HOOK_INIT(sctp_assoc_established, selinux_sctp_assoc_established),
7486 	LSM_HOOK_INIT(mptcp_add_subflow, selinux_mptcp_add_subflow),
7487 	LSM_HOOK_INIT(inet_conn_request, selinux_inet_conn_request),
7488 	LSM_HOOK_INIT(inet_csk_clone, selinux_inet_csk_clone),
7489 	LSM_HOOK_INIT(inet_conn_established, selinux_inet_conn_established),
7490 	LSM_HOOK_INIT(secmark_relabel_packet, selinux_secmark_relabel_packet),
7491 	LSM_HOOK_INIT(secmark_refcount_inc, selinux_secmark_refcount_inc),
7492 	LSM_HOOK_INIT(secmark_refcount_dec, selinux_secmark_refcount_dec),
7493 	LSM_HOOK_INIT(req_classify_flow, selinux_req_classify_flow),
7494 	LSM_HOOK_INIT(tun_dev_create, selinux_tun_dev_create),
7495 	LSM_HOOK_INIT(tun_dev_attach_queue, selinux_tun_dev_attach_queue),
7496 	LSM_HOOK_INIT(tun_dev_attach, selinux_tun_dev_attach),
7497 	LSM_HOOK_INIT(tun_dev_open, selinux_tun_dev_open),
7498 #ifdef CONFIG_SECURITY_INFINIBAND
7499 	LSM_HOOK_INIT(ib_pkey_access, selinux_ib_pkey_access),
7500 	LSM_HOOK_INIT(ib_endport_manage_subnet,
7501 		      selinux_ib_endport_manage_subnet),
7502 #endif
7503 #ifdef CONFIG_SECURITY_NETWORK_XFRM
7504 	LSM_HOOK_INIT(xfrm_policy_free_security, selinux_xfrm_policy_free),
7505 	LSM_HOOK_INIT(xfrm_policy_delete_security, selinux_xfrm_policy_delete),
7506 	LSM_HOOK_INIT(xfrm_state_free_security, selinux_xfrm_state_free),
7507 	LSM_HOOK_INIT(xfrm_state_delete_security, selinux_xfrm_state_delete),
7508 	LSM_HOOK_INIT(xfrm_policy_lookup, selinux_xfrm_policy_lookup),
7509 	LSM_HOOK_INIT(xfrm_state_pol_flow_match,
7510 			selinux_xfrm_state_pol_flow_match),
7511 	LSM_HOOK_INIT(xfrm_decode_session, selinux_xfrm_decode_session),
7512 #endif
7513 
7514 #ifdef CONFIG_KEYS
7515 	LSM_HOOK_INIT(key_permission, selinux_key_permission),
7516 	LSM_HOOK_INIT(key_getsecurity, selinux_key_getsecurity),
7517 #ifdef CONFIG_KEY_NOTIFICATIONS
7518 	LSM_HOOK_INIT(watch_key, selinux_watch_key),
7519 #endif
7520 #endif
7521 
7522 #ifdef CONFIG_AUDIT
7523 	LSM_HOOK_INIT(audit_rule_known, selinux_audit_rule_known),
7524 	LSM_HOOK_INIT(audit_rule_match, selinux_audit_rule_match),
7525 	LSM_HOOK_INIT(audit_rule_free, selinux_audit_rule_free),
7526 #endif
7527 
7528 #ifdef CONFIG_BPF_SYSCALL
7529 	LSM_HOOK_INIT(bpf, selinux_bpf),
7530 	LSM_HOOK_INIT(bpf_map, selinux_bpf_map),
7531 	LSM_HOOK_INIT(bpf_prog, selinux_bpf_prog),
7532 #endif
7533 
7534 #ifdef CONFIG_PERF_EVENTS
7535 	LSM_HOOK_INIT(perf_event_open, selinux_perf_event_open),
7536 	LSM_HOOK_INIT(perf_event_read, selinux_perf_event_read),
7537 	LSM_HOOK_INIT(perf_event_write, selinux_perf_event_write),
7538 #endif
7539 
7540 #ifdef CONFIG_IO_URING
7541 	LSM_HOOK_INIT(uring_override_creds, selinux_uring_override_creds),
7542 	LSM_HOOK_INIT(uring_sqpoll, selinux_uring_sqpoll),
7543 	LSM_HOOK_INIT(uring_cmd, selinux_uring_cmd),
7544 	LSM_HOOK_INIT(uring_allowed, selinux_uring_allowed),
7545 #endif
7546 
7547 	/*
7548 	 * PUT "CLONING" (ACCESSING + ALLOCATING) HOOKS HERE
7549 	 */
7550 	LSM_HOOK_INIT(fs_context_submount, selinux_fs_context_submount),
7551 	LSM_HOOK_INIT(fs_context_dup, selinux_fs_context_dup),
7552 	LSM_HOOK_INIT(fs_context_parse_param, selinux_fs_context_parse_param),
7553 	LSM_HOOK_INIT(sb_eat_lsm_opts, selinux_sb_eat_lsm_opts),
7554 #ifdef CONFIG_SECURITY_NETWORK_XFRM
7555 	LSM_HOOK_INIT(xfrm_policy_clone_security, selinux_xfrm_policy_clone),
7556 #endif
7557 
7558 	/*
7559 	 * PUT "ALLOCATING" HOOKS HERE
7560 	 */
7561 	LSM_HOOK_INIT(msg_msg_alloc_security, selinux_msg_msg_alloc_security),
7562 	LSM_HOOK_INIT(msg_queue_alloc_security,
7563 		      selinux_msg_queue_alloc_security),
7564 	LSM_HOOK_INIT(shm_alloc_security, selinux_shm_alloc_security),
7565 	LSM_HOOK_INIT(sb_alloc_security, selinux_sb_alloc_security),
7566 	LSM_HOOK_INIT(inode_alloc_security, selinux_inode_alloc_security),
7567 	LSM_HOOK_INIT(sem_alloc_security, selinux_sem_alloc_security),
7568 	LSM_HOOK_INIT(secid_to_secctx, selinux_secid_to_secctx),
7569 	LSM_HOOK_INIT(lsmprop_to_secctx, selinux_lsmprop_to_secctx),
7570 	LSM_HOOK_INIT(inode_getsecctx, selinux_inode_getsecctx),
7571 	LSM_HOOK_INIT(sk_alloc_security, selinux_sk_alloc_security),
7572 	LSM_HOOK_INIT(tun_dev_alloc_security, selinux_tun_dev_alloc_security),
7573 #ifdef CONFIG_SECURITY_INFINIBAND
7574 	LSM_HOOK_INIT(ib_alloc_security, selinux_ib_alloc_security),
7575 #endif
7576 #ifdef CONFIG_SECURITY_NETWORK_XFRM
7577 	LSM_HOOK_INIT(xfrm_policy_alloc_security, selinux_xfrm_policy_alloc),
7578 	LSM_HOOK_INIT(xfrm_state_alloc, selinux_xfrm_state_alloc),
7579 	LSM_HOOK_INIT(xfrm_state_alloc_acquire,
7580 		      selinux_xfrm_state_alloc_acquire),
7581 #endif
7582 #ifdef CONFIG_KEYS
7583 	LSM_HOOK_INIT(key_alloc, selinux_key_alloc),
7584 #endif
7585 #ifdef CONFIG_AUDIT
7586 	LSM_HOOK_INIT(audit_rule_init, selinux_audit_rule_init),
7587 #endif
7588 #ifdef CONFIG_BPF_SYSCALL
7589 	LSM_HOOK_INIT(bpf_map_create, selinux_bpf_map_create),
7590 	LSM_HOOK_INIT(bpf_prog_load, selinux_bpf_prog_load),
7591 	LSM_HOOK_INIT(bpf_token_create, selinux_bpf_token_create),
7592 #endif
7593 #ifdef CONFIG_PERF_EVENTS
7594 	LSM_HOOK_INIT(perf_event_alloc, selinux_perf_event_alloc),
7595 #endif
7596 };
7597 
7598 static __init int selinux_init(void)
7599 {
7600 	pr_info("SELinux:  Initializing.\n");
7601 
7602 	memset(&selinux_state, 0, sizeof(selinux_state));
7603 	enforcing_set(selinux_enforcing_boot);
7604 	selinux_avc_init();
7605 	mutex_init(&selinux_state.status_lock);
7606 	mutex_init(&selinux_state.policy_mutex);
7607 
7608 	/* Set the security state for the initial task. */
7609 	cred_init_security();
7610 
7611 	/* Inform the audit system that secctx is used */
7612 	audit_cfg_lsm(&selinux_lsmid,
7613 		      AUDIT_CFG_LSM_SECCTX_SUBJECT |
7614 		      AUDIT_CFG_LSM_SECCTX_OBJECT);
7615 
7616 	default_noexec = !(VM_DATA_DEFAULT_FLAGS & VM_EXEC);
7617 	if (!default_noexec)
7618 		pr_notice("SELinux:  virtual memory is executable by default\n");
7619 
7620 	avc_init();
7621 
7622 	avtab_cache_init();
7623 
7624 	ebitmap_cache_init();
7625 
7626 	hashtab_cache_init();
7627 
7628 	security_add_hooks(selinux_hooks, ARRAY_SIZE(selinux_hooks),
7629 			   &selinux_lsmid);
7630 
7631 	if (avc_add_callback(selinux_netcache_avc_callback, AVC_CALLBACK_RESET))
7632 		panic("SELinux: Unable to register AVC netcache callback\n");
7633 
7634 	if (avc_add_callback(selinux_lsm_notifier_avc_callback, AVC_CALLBACK_RESET))
7635 		panic("SELinux: Unable to register AVC LSM notifier callback\n");
7636 
7637 	if (avc_add_callback(selinux_audit_rule_avc_callback,
7638 			     AVC_CALLBACK_RESET))
7639 		panic("SELinux: Unable to register AVC audit callback\n");
7640 
7641 	if (selinux_enforcing_boot)
7642 		pr_debug("SELinux:  Starting in enforcing mode\n");
7643 	else
7644 		pr_debug("SELinux:  Starting in permissive mode\n");
7645 
7646 	fs_validate_description("selinux", selinux_fs_parameters);
7647 
7648 	return 0;
7649 }
7650 
7651 static void delayed_superblock_init(struct super_block *sb, void *unused)
7652 {
7653 	selinux_set_mnt_opts(sb, NULL, 0, NULL);
7654 }
7655 
7656 void selinux_complete_init(void)
7657 {
7658 	pr_debug("SELinux:  Completing initialization.\n");
7659 
7660 	/* Set up any superblocks initialized prior to the policy load. */
7661 	pr_debug("SELinux:  Setting up existing superblocks.\n");
7662 	iterate_supers(delayed_superblock_init, NULL);
7663 }
7664 
7665 /* SELinux requires early initialization in order to label
7666    all processes and objects when they are created. */
7667 DEFINE_LSM(selinux) = {
7668 	.id = &selinux_lsmid,
7669 	.flags = LSM_FLAG_LEGACY_MAJOR | LSM_FLAG_EXCLUSIVE,
7670 	.enabled = &selinux_enabled_boot,
7671 	.blobs = &selinux_blob_sizes,
7672 	.init = selinux_init,
7673 	.initcall_device = selinux_initcall,
7674 };
7675 
7676 #if defined(CONFIG_NETFILTER)
7677 static const struct nf_hook_ops selinux_nf_ops[] = {
7678 	{
7679 		.hook =		selinux_ip_postroute,
7680 		.pf =		NFPROTO_IPV4,
7681 		.hooknum =	NF_INET_POST_ROUTING,
7682 		.priority =	NF_IP_PRI_SELINUX_LAST,
7683 	},
7684 	{
7685 		.hook =		selinux_ip_forward,
7686 		.pf =		NFPROTO_IPV4,
7687 		.hooknum =	NF_INET_FORWARD,
7688 		.priority =	NF_IP_PRI_SELINUX_FIRST,
7689 	},
7690 	{
7691 		.hook =		selinux_ip_output,
7692 		.pf =		NFPROTO_IPV4,
7693 		.hooknum =	NF_INET_LOCAL_OUT,
7694 		.priority =	NF_IP_PRI_SELINUX_FIRST,
7695 	},
7696 #if IS_ENABLED(CONFIG_IPV6)
7697 	{
7698 		.hook =		selinux_ip_postroute,
7699 		.pf =		NFPROTO_IPV6,
7700 		.hooknum =	NF_INET_POST_ROUTING,
7701 		.priority =	NF_IP6_PRI_SELINUX_LAST,
7702 	},
7703 	{
7704 		.hook =		selinux_ip_forward,
7705 		.pf =		NFPROTO_IPV6,
7706 		.hooknum =	NF_INET_FORWARD,
7707 		.priority =	NF_IP6_PRI_SELINUX_FIRST,
7708 	},
7709 	{
7710 		.hook =		selinux_ip_output,
7711 		.pf =		NFPROTO_IPV6,
7712 		.hooknum =	NF_INET_LOCAL_OUT,
7713 		.priority =	NF_IP6_PRI_SELINUX_FIRST,
7714 	},
7715 #endif	/* IPV6 */
7716 };
7717 
7718 static int __net_init selinux_nf_register(struct net *net)
7719 {
7720 	return nf_register_net_hooks(net, selinux_nf_ops,
7721 				     ARRAY_SIZE(selinux_nf_ops));
7722 }
7723 
7724 static void __net_exit selinux_nf_unregister(struct net *net)
7725 {
7726 	nf_unregister_net_hooks(net, selinux_nf_ops,
7727 				ARRAY_SIZE(selinux_nf_ops));
7728 }
7729 
7730 static struct pernet_operations selinux_net_ops = {
7731 	.init = selinux_nf_register,
7732 	.exit = selinux_nf_unregister,
7733 };
7734 
7735 int __init selinux_nf_ip_init(void)
7736 {
7737 	int err;
7738 
7739 	if (!selinux_enabled_boot)
7740 		return 0;
7741 
7742 	pr_debug("SELinux:  Registering netfilter hooks\n");
7743 
7744 	err = register_pernet_subsys(&selinux_net_ops);
7745 	if (err)
7746 		panic("SELinux: register_pernet_subsys: error %d\n", err);
7747 
7748 	return 0;
7749 }
7750 #endif /* CONFIG_NETFILTER */
7751