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