xref: /linux/security/selinux/hooks.c (revision fafb66e5903c2bcfc7b7e259042a8282f18a6faa)
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;
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 	xattr = lsm_get_xattr_slot(xattrs, xattr_count);
2996 	if (xattr) {
2997 		rc = security_sid_to_context_force(newsid,
2998 						   &context, &clen);
2999 		if (rc)
3000 			return rc;
3001 		xattr->value = context;
3002 		xattr->value_len = clen;
3003 		xattr->name = XATTR_SELINUX_SUFFIX;
3004 	}
3005 
3006 	return 0;
3007 }
3008 
3009 static int selinux_inode_init_security_anon(struct inode *inode,
3010 					    const struct qstr *name,
3011 					    const struct inode *context_inode)
3012 {
3013 	u32 sid = current_sid();
3014 	struct common_audit_data ad;
3015 	struct inode_security_struct *isec;
3016 	int rc;
3017 	bool is_memfd = false;
3018 
3019 	if (unlikely(!selinux_initialized()))
3020 		return 0;
3021 
3022 	if (name != NULL && name->name != NULL &&
3023 	    !strcmp(name->name, MEMFD_ANON_NAME)) {
3024 		if (!selinux_policycap_memfd_class())
3025 			return 0;
3026 		is_memfd = true;
3027 	}
3028 
3029 	isec = selinux_inode(inode);
3030 
3031 	/*
3032 	 * We only get here once per ephemeral inode.  The inode has
3033 	 * been initialized via inode_alloc_security but is otherwise
3034 	 * untouched.
3035 	 */
3036 
3037 	if (context_inode) {
3038 		struct inode_security_struct *context_isec =
3039 			selinux_inode(context_inode);
3040 		if (context_isec->initialized != LABEL_INITIALIZED) {
3041 			pr_err("SELinux:  context_inode is not initialized\n");
3042 			return -EACCES;
3043 		}
3044 
3045 		isec->sclass = context_isec->sclass;
3046 		isec->sid = context_isec->sid;
3047 	} else {
3048 		if (is_memfd)
3049 			isec->sclass = SECCLASS_MEMFD_FILE;
3050 		else
3051 			isec->sclass = SECCLASS_ANON_INODE;
3052 		rc = security_transition_sid(
3053 			sid, sid,
3054 			isec->sclass, name, &isec->sid);
3055 		if (rc)
3056 			return rc;
3057 	}
3058 
3059 	isec->initialized = LABEL_INITIALIZED;
3060 	/*
3061 	 * Now that we've initialized security, check whether we're
3062 	 * allowed to actually create this type of anonymous inode.
3063 	 */
3064 
3065 	ad.type = LSM_AUDIT_DATA_ANONINODE;
3066 	ad.u.anonclass = name ? (const char *)name->name : "?";
3067 
3068 	return avc_has_perm(sid,
3069 			    isec->sid,
3070 			    isec->sclass,
3071 			    FILE__CREATE,
3072 			    &ad);
3073 }
3074 
3075 static int selinux_inode_create(struct inode *dir, struct dentry *dentry, umode_t mode)
3076 {
3077 	return may_create(dir, dentry, SECCLASS_FILE);
3078 }
3079 
3080 static int selinux_inode_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry)
3081 {
3082 	return may_link(dir, old_dentry, MAY_LINK);
3083 }
3084 
3085 static int selinux_inode_unlink(struct inode *dir, struct dentry *dentry)
3086 {
3087 	return may_link(dir, dentry, MAY_UNLINK);
3088 }
3089 
3090 static int selinux_inode_symlink(struct inode *dir, struct dentry *dentry, const char *name)
3091 {
3092 	return may_create(dir, dentry, SECCLASS_LNK_FILE);
3093 }
3094 
3095 static int selinux_inode_mkdir(struct inode *dir, struct dentry *dentry, umode_t mask)
3096 {
3097 	return may_create(dir, dentry, SECCLASS_DIR);
3098 }
3099 
3100 static int selinux_inode_rmdir(struct inode *dir, struct dentry *dentry)
3101 {
3102 	return may_link(dir, dentry, MAY_RMDIR);
3103 }
3104 
3105 static int selinux_inode_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
3106 {
3107 	return may_create(dir, dentry, inode_mode_to_security_class(mode));
3108 }
3109 
3110 static int selinux_inode_rename(struct inode *old_inode, struct dentry *old_dentry,
3111 				struct inode *new_inode, struct dentry *new_dentry)
3112 {
3113 	return may_rename(old_inode, old_dentry, new_inode, new_dentry);
3114 }
3115 
3116 static int selinux_inode_readlink(struct dentry *dentry)
3117 {
3118 	const struct cred *cred = current_cred();
3119 
3120 	return dentry_has_perm(cred, dentry, FILE__READ);
3121 }
3122 
3123 static int selinux_inode_follow_link(struct dentry *dentry, struct inode *inode,
3124 				     bool rcu)
3125 {
3126 	struct common_audit_data ad;
3127 	struct inode_security_struct *isec;
3128 	u32 sid = current_sid();
3129 
3130 	ad.type = LSM_AUDIT_DATA_DENTRY;
3131 	ad.u.dentry = dentry;
3132 	isec = inode_security_rcu(inode, rcu);
3133 	if (IS_ERR(isec))
3134 		return PTR_ERR(isec);
3135 
3136 	return avc_has_perm(sid, isec->sid, isec->sclass, FILE__READ, &ad);
3137 }
3138 
3139 static noinline int audit_inode_permission(struct inode *inode,
3140 					   u32 perms, u32 audited, u32 denied,
3141 					   int result)
3142 {
3143 	struct common_audit_data ad;
3144 	struct inode_security_struct *isec = selinux_inode(inode);
3145 
3146 	ad.type = LSM_AUDIT_DATA_INODE;
3147 	ad.u.inode = inode;
3148 
3149 	return slow_avc_audit(current_sid(), isec->sid, isec->sclass, perms,
3150 			    audited, denied, result, &ad);
3151 }
3152 
3153 /**
3154  * task_avdcache_reset - Reset the task's AVD cache
3155  * @tsec: the task's security state
3156  *
3157  * Clear the task's AVD cache in @tsec and reset it to the current policy's
3158  * and task's info.
3159  */
3160 static inline void task_avdcache_reset(struct task_security_struct *tsec)
3161 {
3162 	memset(&tsec->avdcache.dir, 0, sizeof(tsec->avdcache.dir));
3163 	tsec->avdcache.sid = current_sid();
3164 	tsec->avdcache.seqno = avc_policy_seqno();
3165 	tsec->avdcache.dir_spot = TSEC_AVDC_DIR_SIZE - 1;
3166 }
3167 
3168 /**
3169  * task_avdcache_search - Search the task's AVD cache
3170  * @tsec: the task's security state
3171  * @isec: the inode to search for in the cache
3172  * @avdc: matching avd cache entry returned to the caller
3173  *
3174  * Search @tsec for a AVD cache entry that matches @isec and return it to the
3175  * caller via @avdc.  Returns 0 if a match is found, negative values otherwise.
3176  */
3177 static inline int task_avdcache_search(struct task_security_struct *tsec,
3178 				       struct inode_security_struct *isec,
3179 				       struct avdc_entry **avdc)
3180 {
3181 	int orig, iter;
3182 
3183 	/* focused on path walk optimization, only cache directories */
3184 	if (isec->sclass != SECCLASS_DIR)
3185 		return -ENOENT;
3186 
3187 	if (unlikely(current_sid() != tsec->avdcache.sid ||
3188 		     tsec->avdcache.seqno != avc_policy_seqno())) {
3189 		task_avdcache_reset(tsec);
3190 		return -ENOENT;
3191 	}
3192 
3193 	orig = iter = tsec->avdcache.dir_spot;
3194 	do {
3195 		if (tsec->avdcache.dir[iter].isid == isec->sid) {
3196 			/* cache hit */
3197 			tsec->avdcache.dir_spot = iter;
3198 			*avdc = &tsec->avdcache.dir[iter];
3199 			return 0;
3200 		}
3201 		iter = (iter - 1) & (TSEC_AVDC_DIR_SIZE - 1);
3202 	} while (iter != orig);
3203 
3204 	return -ENOENT;
3205 }
3206 
3207 /**
3208  * task_avdcache_update - Update the task's AVD cache
3209  * @tsec: the task's security state
3210  * @isec: the inode associated with the cache entry
3211  * @avd: the AVD to cache
3212  *
3213  * Update the AVD cache in @tsec with the @avd 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 {
3220 	int spot;
3221 
3222 	/* focused on path walk optimization, only cache directories */
3223 	if (isec->sclass != SECCLASS_DIR)
3224 		return;
3225 
3226 	/* update cache */
3227 	spot = (tsec->avdcache.dir_spot + 1) & (TSEC_AVDC_DIR_SIZE - 1);
3228 	tsec->avdcache.dir_spot = spot;
3229 	tsec->avdcache.dir[spot].isid = isec->sid;
3230 	tsec->avdcache.dir[spot].avd = *avd;
3231 	tsec->avdcache.permissive_neveraudit =
3232 		(avd->flags == (AVD_FLAGS_PERMISSIVE|AVD_FLAGS_NEVERAUDIT));
3233 }
3234 
3235 /**
3236  * selinux_inode_permission - Check if the current task can access an inode
3237  * @inode: the inode that is being accessed
3238  * @requested: the accesses being requested
3239  *
3240  * Check if the current task is allowed to access @inode according to
3241  * @requested.  Returns 0 if allowed, negative values otherwise.
3242  */
3243 static int selinux_inode_permission(struct inode *inode, int requested)
3244 {
3245 	int mask;
3246 	u32 perms;
3247 	u32 sid = current_sid();
3248 	struct task_security_struct *tsec;
3249 	struct inode_security_struct *isec;
3250 	struct avdc_entry *avdc;
3251 	struct av_decision avd, *avdp = &avd;
3252 	int rc, rc2;
3253 	u32 audited, denied;
3254 
3255 	mask = requested & (MAY_READ|MAY_WRITE|MAY_EXEC|MAY_APPEND);
3256 
3257 	/* No permission to check.  Existence test. */
3258 	if (!mask)
3259 		return 0;
3260 
3261 	tsec = selinux_task(current);
3262 	if (task_avdcache_permnoaudit(tsec, sid))
3263 		return 0;
3264 
3265 	isec = inode_security_rcu(inode, requested & MAY_NOT_BLOCK);
3266 	if (IS_ERR(isec))
3267 		return PTR_ERR(isec);
3268 	perms = file_mask_to_av(inode->i_mode, mask);
3269 
3270 	rc = task_avdcache_search(tsec, isec, &avdc);
3271 	if (likely(!rc)) {
3272 		/* Cache hit. */
3273 		avdp = &avdc->avd;
3274 		denied = perms & ~avdp->allowed;
3275 		if (unlikely(denied) && enforcing_enabled() &&
3276 			!(avdp->flags & AVD_FLAGS_PERMISSIVE))
3277 			rc = -EACCES;
3278 	} else {
3279 		/* Cache miss. */
3280 		rc = avc_has_perm_noaudit(sid, isec->sid, isec->sclass,
3281 					  perms, 0, avdp);
3282 		task_avdcache_update(tsec, isec, avdp);
3283 	}
3284 
3285 	audited = avc_audit_required(perms, avdp, rc,
3286 				     (requested & MAY_ACCESS) ?
3287 				     FILE__AUDIT_ACCESS : 0, &denied);
3288 	if (likely(!audited))
3289 		return rc;
3290 
3291 	rc2 = audit_inode_permission(inode, perms, audited, denied, rc);
3292 	if (rc2)
3293 		return rc2;
3294 
3295 	return rc;
3296 }
3297 
3298 static int selinux_inode_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
3299 				 struct iattr *iattr)
3300 {
3301 	const struct cred *cred = current_cred();
3302 	struct inode *inode = d_backing_inode(dentry);
3303 	unsigned int ia_valid = iattr->ia_valid;
3304 	u32 av = FILE__WRITE;
3305 
3306 	/* ATTR_FORCE is just used for ATTR_KILL_S[UG]ID. */
3307 	if (ia_valid & ATTR_FORCE) {
3308 		ia_valid &= ~(ATTR_KILL_SUID | ATTR_KILL_SGID | ATTR_MODE |
3309 			      ATTR_FORCE);
3310 		if (!ia_valid)
3311 			return 0;
3312 	}
3313 
3314 	if (ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID |
3315 			ATTR_ATIME_SET | ATTR_MTIME_SET | ATTR_TIMES_SET))
3316 		return dentry_has_perm(cred, dentry, FILE__SETATTR);
3317 
3318 	if (selinux_policycap_openperm() &&
3319 	    inode->i_sb->s_magic != SOCKFS_MAGIC &&
3320 	    (ia_valid & ATTR_SIZE) &&
3321 	    !(ia_valid & ATTR_FILE))
3322 		av |= FILE__OPEN;
3323 
3324 	return dentry_has_perm(cred, dentry, av);
3325 }
3326 
3327 static int selinux_inode_getattr(const struct path *path)
3328 {
3329 	struct task_security_struct *tsec;
3330 
3331 	tsec = selinux_task(current);
3332 
3333 	if (task_avdcache_permnoaudit(tsec, current_sid()))
3334 		return 0;
3335 
3336 	return path_has_perm(current_cred(), path, FILE__GETATTR);
3337 }
3338 
3339 static bool has_cap_mac_admin(bool audit)
3340 {
3341 	const struct cred *cred = current_cred();
3342 	unsigned int opts = audit ? CAP_OPT_NONE : CAP_OPT_NOAUDIT;
3343 
3344 	if (cap_capable(cred, &init_user_ns, CAP_MAC_ADMIN, opts))
3345 		return false;
3346 	if (cred_has_capability(cred, CAP_MAC_ADMIN, opts, true))
3347 		return false;
3348 	return true;
3349 }
3350 
3351 /**
3352  * selinux_inode_xattr_skipcap - Skip the xattr capability checks?
3353  * @name: name of the xattr
3354  *
3355  * Returns 1 to indicate that SELinux "owns" the access control rights to xattrs
3356  * named @name; the LSM layer should avoid enforcing any traditional
3357  * capability based access controls on this xattr.  Returns 0 to indicate that
3358  * SELinux does not "own" the access control rights to xattrs named @name and is
3359  * deferring to the LSM layer for further access controls, including capability
3360  * based controls.
3361  */
3362 static int selinux_inode_xattr_skipcap(const char *name)
3363 {
3364 	/* require capability check if not a selinux xattr */
3365 	return !strcmp(name, XATTR_NAME_SELINUX);
3366 }
3367 
3368 static int selinux_inode_setxattr(struct mnt_idmap *idmap,
3369 				  struct dentry *dentry, const char *name,
3370 				  const void *value, size_t size, int flags)
3371 {
3372 	struct inode *inode = d_backing_inode(dentry);
3373 	struct inode_security_struct *isec;
3374 	struct superblock_security_struct *sbsec;
3375 	struct common_audit_data ad;
3376 	u32 newsid, sid = current_sid();
3377 	int rc = 0;
3378 
3379 	/* if not a selinux xattr, only check the ordinary setattr perm */
3380 	if (strcmp(name, XATTR_NAME_SELINUX))
3381 		return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3382 
3383 	if (!selinux_initialized())
3384 		return (inode_owner_or_capable(idmap, inode) ? 0 : -EPERM);
3385 
3386 	sbsec = selinux_superblock(inode->i_sb);
3387 	if (!(sbsec->flags & SBLABEL_MNT))
3388 		return -EOPNOTSUPP;
3389 
3390 	if (!inode_owner_or_capable(idmap, inode))
3391 		return -EPERM;
3392 
3393 	ad.type = LSM_AUDIT_DATA_DENTRY;
3394 	ad.u.dentry = dentry;
3395 
3396 	isec = backing_inode_security(dentry);
3397 	rc = avc_has_perm(sid, isec->sid, isec->sclass,
3398 			  FILE__RELABELFROM, &ad);
3399 	if (rc)
3400 		return rc;
3401 
3402 	rc = security_context_to_sid(value, size, &newsid,
3403 				     GFP_KERNEL);
3404 	if (rc == -EINVAL) {
3405 		if (!has_cap_mac_admin(true)) {
3406 			struct audit_buffer *ab;
3407 			size_t audit_size;
3408 
3409 			/* We strip a nul only if it is at the end, otherwise the
3410 			 * context contains a nul and we should audit that */
3411 			if (value) {
3412 				const char *str = value;
3413 
3414 				if (str[size - 1] == '\0')
3415 					audit_size = size - 1;
3416 				else
3417 					audit_size = size;
3418 			} else {
3419 				audit_size = 0;
3420 			}
3421 			ab = audit_log_start(audit_context(),
3422 					     GFP_ATOMIC, AUDIT_SELINUX_ERR);
3423 			if (!ab)
3424 				return rc;
3425 			audit_log_format(ab, "op=setxattr invalid_context=");
3426 			audit_log_n_untrustedstring(ab, value, audit_size);
3427 			audit_log_end(ab);
3428 
3429 			return rc;
3430 		}
3431 		rc = security_context_to_sid_force(value,
3432 						   size, &newsid);
3433 	}
3434 	if (rc)
3435 		return rc;
3436 
3437 	rc = avc_has_perm(sid, newsid, isec->sclass,
3438 			  FILE__RELABELTO, &ad);
3439 	if (rc)
3440 		return rc;
3441 
3442 	rc = security_validate_transition(isec->sid, newsid,
3443 					  sid, isec->sclass);
3444 	if (rc)
3445 		return rc;
3446 
3447 	return avc_has_perm(newsid,
3448 			    sbsec->sid,
3449 			    SECCLASS_FILESYSTEM,
3450 			    FILESYSTEM__ASSOCIATE,
3451 			    &ad);
3452 }
3453 
3454 static int selinux_inode_set_acl(struct mnt_idmap *idmap,
3455 				 struct dentry *dentry, const char *acl_name,
3456 				 struct posix_acl *kacl)
3457 {
3458 	return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3459 }
3460 
3461 static int selinux_inode_get_acl(struct mnt_idmap *idmap,
3462 				 struct dentry *dentry, const char *acl_name)
3463 {
3464 	return dentry_has_perm(current_cred(), dentry, FILE__GETATTR);
3465 }
3466 
3467 static int selinux_inode_remove_acl(struct mnt_idmap *idmap,
3468 				    struct dentry *dentry, const char *acl_name)
3469 {
3470 	return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3471 }
3472 
3473 static void selinux_inode_post_setxattr(struct dentry *dentry, const char *name,
3474 					const void *value, size_t size,
3475 					int flags)
3476 {
3477 	struct inode *inode = d_backing_inode(dentry);
3478 	struct inode_security_struct *isec;
3479 	u32 newsid;
3480 	int rc;
3481 
3482 	if (strcmp(name, XATTR_NAME_SELINUX)) {
3483 		/* Not an attribute we recognize, so nothing to do. */
3484 		return;
3485 	}
3486 
3487 	if (!selinux_initialized()) {
3488 		/* If we haven't even been initialized, then we can't validate
3489 		 * against a policy, so leave the label as invalid. It may
3490 		 * resolve to a valid label on the next revalidation try if
3491 		 * we've since initialized.
3492 		 */
3493 		return;
3494 	}
3495 
3496 	rc = security_context_to_sid_force(value, size,
3497 					   &newsid);
3498 	if (rc) {
3499 		pr_err("SELinux:  unable to map context to SID"
3500 		       "for (%s, %llu), rc=%d\n",
3501 		       inode->i_sb->s_id, inode->i_ino, -rc);
3502 		return;
3503 	}
3504 
3505 	isec = backing_inode_security(dentry);
3506 	spin_lock(&isec->lock);
3507 	isec->sclass = inode_mode_to_security_class(inode->i_mode);
3508 	isec->sid = newsid;
3509 	isec->initialized = LABEL_INITIALIZED;
3510 	spin_unlock(&isec->lock);
3511 }
3512 
3513 static int selinux_inode_getxattr(struct dentry *dentry, const char *name)
3514 {
3515 	const struct cred *cred = current_cred();
3516 
3517 	return dentry_has_perm(cred, dentry, FILE__GETATTR);
3518 }
3519 
3520 static int selinux_inode_listxattr(struct dentry *dentry)
3521 {
3522 	const struct cred *cred = current_cred();
3523 
3524 	return dentry_has_perm(cred, dentry, FILE__GETATTR);
3525 }
3526 
3527 static int selinux_inode_removexattr(struct mnt_idmap *idmap,
3528 				     struct dentry *dentry, const char *name)
3529 {
3530 	/* if not a selinux xattr, only check the ordinary setattr perm */
3531 	if (strcmp(name, XATTR_NAME_SELINUX))
3532 		return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3533 
3534 	if (!selinux_initialized())
3535 		return 0;
3536 
3537 	/* No one is allowed to remove a SELinux security label.
3538 	   You can change the label, but all data must be labeled. */
3539 	return -EACCES;
3540 }
3541 
3542 static int selinux_inode_file_setattr(struct dentry *dentry,
3543 				      struct file_kattr *fa)
3544 {
3545 	return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3546 }
3547 
3548 static int selinux_inode_file_getattr(struct dentry *dentry,
3549 				      struct file_kattr *fa)
3550 {
3551 	return dentry_has_perm(current_cred(), dentry, FILE__GETATTR);
3552 }
3553 
3554 static int selinux_path_notify(const struct path *path, u64 mask,
3555 						unsigned int obj_type)
3556 {
3557 	int ret;
3558 	u32 perm;
3559 
3560 	struct common_audit_data ad;
3561 
3562 	ad.type = LSM_AUDIT_DATA_PATH;
3563 	ad.u.path = *path;
3564 
3565 	/*
3566 	 * Set permission needed based on the type of mark being set.
3567 	 * Performs an additional check for sb watches.
3568 	 */
3569 	switch (obj_type) {
3570 	case FSNOTIFY_OBJ_TYPE_VFSMOUNT:
3571 		perm = FILE__WATCH_MOUNT;
3572 		break;
3573 	case FSNOTIFY_OBJ_TYPE_SB:
3574 		perm = FILE__WATCH_SB;
3575 		ret = superblock_has_perm(current_cred(), path->dentry->d_sb,
3576 						FILESYSTEM__WATCH, &ad);
3577 		if (ret)
3578 			return ret;
3579 		break;
3580 	case FSNOTIFY_OBJ_TYPE_INODE:
3581 		perm = FILE__WATCH;
3582 		break;
3583 	case FSNOTIFY_OBJ_TYPE_MNTNS:
3584 		perm = FILE__WATCH_MOUNTNS;
3585 		break;
3586 	default:
3587 		return -EINVAL;
3588 	}
3589 
3590 	/* blocking watches require the file:watch_with_perm permission */
3591 	if (mask & (ALL_FSNOTIFY_PERM_EVENTS))
3592 		perm |= FILE__WATCH_WITH_PERM;
3593 
3594 	/* watches on read-like events need the file:watch_reads permission */
3595 	if (mask & (FS_ACCESS | FS_ACCESS_PERM | FS_PRE_ACCESS |
3596 		    FS_CLOSE_NOWRITE))
3597 		perm |= FILE__WATCH_READS;
3598 
3599 	return path_has_perm(current_cred(), path, perm);
3600 }
3601 
3602 /*
3603  * Copy the inode security context value to the user.
3604  *
3605  * Permission check is handled by selinux_inode_getxattr hook.
3606  */
3607 static int selinux_inode_getsecurity(struct mnt_idmap *idmap,
3608 				     struct inode *inode, const char *name,
3609 				     void **buffer, bool alloc)
3610 {
3611 	u32 size;
3612 	int error;
3613 	char *context = NULL;
3614 	struct inode_security_struct *isec;
3615 
3616 	/*
3617 	 * If we're not initialized yet, then we can't validate contexts, so
3618 	 * just let vfs_getxattr fall back to using the on-disk xattr.
3619 	 */
3620 	if (!selinux_initialized() ||
3621 	    strcmp(name, XATTR_SELINUX_SUFFIX))
3622 		return -EOPNOTSUPP;
3623 
3624 	/*
3625 	 * If the caller has CAP_MAC_ADMIN, then get the raw context
3626 	 * value even if it is not defined by current policy; otherwise,
3627 	 * use the in-core value under current policy.
3628 	 * Use the non-auditing forms of the permission checks since
3629 	 * getxattr may be called by unprivileged processes commonly
3630 	 * and lack of permission just means that we fall back to the
3631 	 * in-core context value, not a denial.
3632 	 */
3633 	isec = inode_security(inode);
3634 	if (has_cap_mac_admin(false))
3635 		error = security_sid_to_context_force(isec->sid, &context,
3636 						      &size);
3637 	else
3638 		error = security_sid_to_context(isec->sid,
3639 						&context, &size);
3640 	if (error)
3641 		return error;
3642 	error = size;
3643 	if (alloc) {
3644 		*buffer = context;
3645 		goto out_nofree;
3646 	}
3647 	kfree(context);
3648 out_nofree:
3649 	return error;
3650 }
3651 
3652 static int selinux_inode_setsecurity(struct inode *inode, const char *name,
3653 				     const void *value, size_t size, int flags)
3654 {
3655 	struct inode_security_struct *isec = inode_security_novalidate(inode);
3656 	struct superblock_security_struct *sbsec;
3657 	u32 newsid;
3658 	int rc;
3659 
3660 	if (strcmp(name, XATTR_SELINUX_SUFFIX))
3661 		return -EOPNOTSUPP;
3662 
3663 	sbsec = selinux_superblock(inode->i_sb);
3664 	if (!(sbsec->flags & SBLABEL_MNT))
3665 		return -EOPNOTSUPP;
3666 
3667 	if (!value || !size)
3668 		return -EACCES;
3669 
3670 	rc = security_context_to_sid(value, size, &newsid,
3671 				     GFP_KERNEL);
3672 	if (rc)
3673 		return rc;
3674 
3675 	spin_lock(&isec->lock);
3676 	isec->sclass = inode_mode_to_security_class(inode->i_mode);
3677 	isec->sid = newsid;
3678 	isec->initialized = LABEL_INITIALIZED;
3679 	spin_unlock(&isec->lock);
3680 	return 0;
3681 }
3682 
3683 static int selinux_inode_listsecurity(struct inode *inode, char **buffer,
3684 				ssize_t *remaining_size)
3685 {
3686 	if (!selinux_initialized())
3687 		return 0;
3688 	return xattr_list_one(buffer, remaining_size, XATTR_NAME_SELINUX);
3689 }
3690 
3691 static void selinux_inode_getlsmprop(struct inode *inode, struct lsm_prop *prop)
3692 {
3693 	struct inode_security_struct *isec = inode_security_novalidate(inode);
3694 
3695 	prop->selinux.secid = isec->sid;
3696 }
3697 
3698 static int selinux_inode_copy_up(struct dentry *src, struct cred **new)
3699 {
3700 	struct lsm_prop prop;
3701 	struct cred_security_struct *crsec;
3702 	struct cred *new_creds = *new;
3703 
3704 	if (new_creds == NULL) {
3705 		new_creds = prepare_creds();
3706 		if (!new_creds)
3707 			return -ENOMEM;
3708 	}
3709 
3710 	crsec = selinux_cred(new_creds);
3711 	/* Get label from overlay inode and set it in create_sid */
3712 	selinux_inode_getlsmprop(d_inode(src), &prop);
3713 	crsec->create_sid = prop.selinux.secid;
3714 	*new = new_creds;
3715 	return 0;
3716 }
3717 
3718 static int selinux_inode_copy_up_xattr(struct dentry *dentry, const char *name)
3719 {
3720 	/* The copy_up hook above sets the initial context on an inode, but we
3721 	 * don't then want to overwrite it by blindly copying all the lower
3722 	 * xattrs up.  Instead, filter out SELinux-related xattrs following
3723 	 * policy load.
3724 	 */
3725 	if (selinux_initialized() && !strcmp(name, XATTR_NAME_SELINUX))
3726 		return -ECANCELED; /* Discard */
3727 	/*
3728 	 * Any other attribute apart from SELINUX is not claimed, supported
3729 	 * by selinux.
3730 	 */
3731 	return -EOPNOTSUPP;
3732 }
3733 
3734 /* kernfs node operations */
3735 
3736 static int selinux_kernfs_init_security(struct kernfs_node *kn_dir,
3737 					struct kernfs_node *kn)
3738 {
3739 	const struct cred_security_struct *crsec = selinux_cred(current_cred());
3740 	u32 parent_sid, newsid, clen;
3741 	int rc;
3742 	char *context;
3743 
3744 	rc = kernfs_xattr_get(kn_dir, XATTR_NAME_SELINUX, NULL, 0);
3745 	if (rc == -ENODATA)
3746 		return 0;
3747 	else if (rc < 0)
3748 		return rc;
3749 
3750 	clen = (u32)rc;
3751 	context = kmalloc(clen, GFP_KERNEL);
3752 	if (!context)
3753 		return -ENOMEM;
3754 
3755 	rc = kernfs_xattr_get(kn_dir, XATTR_NAME_SELINUX, context, clen);
3756 	if (rc < 0) {
3757 		kfree(context);
3758 		return rc;
3759 	}
3760 
3761 	rc = security_context_to_sid(context, clen, &parent_sid,
3762 				     GFP_KERNEL);
3763 	kfree(context);
3764 	if (rc)
3765 		return rc;
3766 
3767 	if (crsec->create_sid) {
3768 		newsid = crsec->create_sid;
3769 	} else {
3770 		u16 secclass = inode_mode_to_security_class(kn->mode);
3771 		const char *kn_name;
3772 		struct qstr q;
3773 
3774 		/* kn is fresh, can't be renamed, name goes not away */
3775 		kn_name = rcu_dereference_check(kn->name, true);
3776 		q.name = kn_name;
3777 		q.hash_len = hashlen_string(kn_dir, kn_name);
3778 
3779 		rc = security_transition_sid(crsec->sid,
3780 					     parent_sid, secclass, &q,
3781 					     &newsid);
3782 		if (rc)
3783 			return rc;
3784 	}
3785 
3786 	rc = security_sid_to_context_force(newsid,
3787 					   &context, &clen);
3788 	if (rc)
3789 		return rc;
3790 
3791 	rc = kernfs_xattr_set(kn, XATTR_NAME_SELINUX, context, clen,
3792 			      XATTR_CREATE);
3793 	kfree(context);
3794 	return rc;
3795 }
3796 
3797 
3798 /* file security operations */
3799 
3800 static int selinux_revalidate_file_permission(struct file *file, int mask)
3801 {
3802 	const struct cred *cred = current_cred();
3803 	struct inode *inode = file_inode(file);
3804 
3805 	/* file_mask_to_av won't add FILE__WRITE if MAY_APPEND is set */
3806 	if ((file->f_flags & O_APPEND) && (mask & MAY_WRITE))
3807 		mask |= MAY_APPEND;
3808 
3809 	return file_has_perm(cred, file,
3810 			     file_mask_to_av(inode->i_mode, mask));
3811 }
3812 
3813 static int selinux_file_permission(struct file *file, int mask)
3814 {
3815 	struct inode *inode = file_inode(file);
3816 	struct file_security_struct *fsec = selinux_file(file);
3817 	struct inode_security_struct *isec;
3818 	u32 sid = current_sid();
3819 
3820 	if (!mask)
3821 		/* No permission to check.  Existence test. */
3822 		return 0;
3823 
3824 	isec = inode_security(inode);
3825 	if (sid == fsec->sid && fsec->isid == isec->sid &&
3826 	    fsec->pseqno == avc_policy_seqno())
3827 		/* No change since file_open check. */
3828 		return 0;
3829 
3830 	return selinux_revalidate_file_permission(file, mask);
3831 }
3832 
3833 static int selinux_file_alloc_security(struct file *file)
3834 {
3835 	struct file_security_struct *fsec = selinux_file(file);
3836 	u32 sid = current_sid();
3837 
3838 	fsec->sid = sid;
3839 	fsec->fown_sid = sid;
3840 
3841 	return 0;
3842 }
3843 
3844 static int selinux_backing_file_alloc(struct file *backing_file,
3845 				      const struct file *user_file)
3846 {
3847 	struct backing_file_security_struct *bfsec;
3848 
3849 	bfsec = selinux_backing_file(backing_file);
3850 	bfsec->uf_sid = selinux_file(user_file)->sid;
3851 
3852 	return 0;
3853 }
3854 
3855 /*
3856  * Check whether a task has the ioctl permission and cmd
3857  * operation to an inode.
3858  */
3859 static int ioctl_has_perm(const struct cred *cred, struct file *file,
3860 		u32 requested, u16 cmd)
3861 {
3862 	struct common_audit_data ad;
3863 	struct file_security_struct *fsec = selinux_file(file);
3864 	struct inode *inode = file_inode(file);
3865 	struct inode_security_struct *isec;
3866 	struct lsm_ioctlop_audit ioctl;
3867 	u32 ssid = cred_sid(cred);
3868 	int rc;
3869 	u8 driver = cmd >> 8;
3870 	u8 xperm = cmd & 0xff;
3871 
3872 	ad.type = LSM_AUDIT_DATA_IOCTL_OP;
3873 	ad.u.op = &ioctl;
3874 	ad.u.op->cmd = cmd;
3875 	ad.u.op->path = file->f_path;
3876 
3877 	if (ssid != fsec->sid) {
3878 		rc = avc_has_perm(ssid, fsec->sid,
3879 				SECCLASS_FD,
3880 				FD__USE,
3881 				&ad);
3882 		if (rc)
3883 			goto out;
3884 	}
3885 
3886 	if (unlikely(IS_PRIVATE(inode)))
3887 		return 0;
3888 
3889 	isec = inode_security(inode);
3890 	rc = avc_has_extended_perms(ssid, isec->sid, isec->sclass, requested,
3891 				    driver, AVC_EXT_IOCTL, xperm, &ad);
3892 out:
3893 	return rc;
3894 }
3895 
3896 static int selinux_file_ioctl(struct file *file, unsigned int cmd,
3897 			      unsigned long arg)
3898 {
3899 	const struct cred *cred = current_cred();
3900 	int error = 0;
3901 
3902 	switch (cmd) {
3903 	case FIONREAD:
3904 	case FIBMAP:
3905 	case FIGETBSZ:
3906 	case FS_IOC_GETFLAGS:
3907 	case FS_IOC_GETVERSION:
3908 		error = file_has_perm(cred, file, FILE__GETATTR);
3909 		break;
3910 
3911 	case FS_IOC_SETFLAGS:
3912 	case FS_IOC_SETVERSION:
3913 		error = file_has_perm(cred, file, FILE__SETATTR);
3914 		break;
3915 
3916 	/* sys_ioctl() checks */
3917 	case FIONBIO:
3918 	case FIOASYNC:
3919 		error = file_has_perm(cred, file, 0);
3920 		break;
3921 
3922 	case KDSKBENT:
3923 	case KDSKBSENT:
3924 		error = cred_has_capability(cred, CAP_SYS_TTY_CONFIG,
3925 					    CAP_OPT_NONE, true);
3926 		break;
3927 
3928 	case FIOCLEX:
3929 	case FIONCLEX:
3930 		if (!selinux_policycap_ioctl_skip_cloexec())
3931 			error = ioctl_has_perm(cred, file, FILE__IOCTL, (u16) cmd);
3932 		break;
3933 
3934 	/* default case assumes that the command will go
3935 	 * to the file's ioctl() function.
3936 	 */
3937 	default:
3938 		error = ioctl_has_perm(cred, file, FILE__IOCTL, (u16) cmd);
3939 	}
3940 	return error;
3941 }
3942 
3943 static int selinux_file_ioctl_compat(struct file *file, unsigned int cmd,
3944 			      unsigned long arg)
3945 {
3946 	/*
3947 	 * If we are in a 64-bit kernel running 32-bit userspace, we need to
3948 	 * make sure we don't compare 32-bit flags to 64-bit flags.
3949 	 */
3950 	switch (cmd) {
3951 	case FS_IOC32_GETFLAGS:
3952 		cmd = FS_IOC_GETFLAGS;
3953 		break;
3954 	case FS_IOC32_SETFLAGS:
3955 		cmd = FS_IOC_SETFLAGS;
3956 		break;
3957 	case FS_IOC32_GETVERSION:
3958 		cmd = FS_IOC_GETVERSION;
3959 		break;
3960 	case FS_IOC32_SETVERSION:
3961 		cmd = FS_IOC_SETVERSION;
3962 		break;
3963 	default:
3964 		break;
3965 	}
3966 
3967 	return selinux_file_ioctl(file, cmd, arg);
3968 }
3969 
3970 static int default_noexec __ro_after_init;
3971 
3972 static int __file_map_prot_check(const struct file *file, unsigned long prot,
3973 				 bool shared, bool mounter_check,
3974 				 bool bf_user_file)
3975 {
3976 	struct inode *inode = NULL;
3977 	bool prot_exec = prot & PROT_EXEC;
3978 	bool prot_write = prot & PROT_WRITE;
3979 
3980 	if (file) {
3981 		if (bf_user_file)
3982 			inode = d_inode(backing_file_user_path(file)->dentry);
3983 		else
3984 			inode = file_inode(file);
3985 	}
3986 
3987 	if (!mounter_check && default_noexec && prot_exec &&
3988 	    (!file || IS_PRIVATE(inode) || (!shared && prot_write))) {
3989 		int rc;
3990 		u32 sid = current_sid();
3991 
3992 		/*
3993 		 * We are making executable an anonymous mapping or a private
3994 		 * file mapping that will also be writable.
3995 		 */
3996 		rc = avc_has_perm(sid, sid, SECCLASS_PROCESS, PROCESS__EXECMEM,
3997 				  NULL);
3998 		if (rc)
3999 			return rc;
4000 	}
4001 
4002 	if (file) {
4003 		const struct cred *cred = mounter_check ?
4004 				file->f_cred : current_cred();
4005 		/* "read" always possible, "write" only if shared */
4006 		u32 av = FILE__READ;
4007 		if (shared && prot_write)
4008 			av |= FILE__WRITE;
4009 		if (prot_exec)
4010 			av |= FILE__EXECUTE;
4011 
4012 		return __file_has_perm(cred, file, av, bf_user_file);
4013 	}
4014 
4015 	return 0;
4016 }
4017 
4018 static inline int file_map_prot_check(const struct file *file,
4019 				      unsigned long prot, bool shared,
4020 				      bool mounter_check)
4021 {
4022 	return __file_map_prot_check(file, prot, shared, mounter_check, false);
4023 }
4024 
4025 static int selinux_mmap_addr(unsigned long addr)
4026 {
4027 	int rc = 0;
4028 
4029 	if (addr < CONFIG_LSM_MMAP_MIN_ADDR) {
4030 		u32 sid = current_sid();
4031 		rc = avc_has_perm(sid, sid, SECCLASS_MEMPROTECT,
4032 				  MEMPROTECT__MMAP_ZERO, NULL);
4033 	}
4034 
4035 	return rc;
4036 }
4037 
4038 static int selinux_mmap_file_common(struct file *file, unsigned long prot,
4039 				    bool shared, bool mounter_check)
4040 {
4041 	if (file) {
4042 		int rc;
4043 		struct common_audit_data ad;
4044 		const struct cred *cred = mounter_check ?
4045 				file->f_cred : current_cred();
4046 
4047 		ad.type = LSM_AUDIT_DATA_FILE;
4048 		ad.u.file = file;
4049 		rc = inode_has_perm(cred, file_inode(file), FILE__MAP, &ad);
4050 		if (rc)
4051 			return rc;
4052 	}
4053 
4054 	return file_map_prot_check(file, prot, shared, mounter_check);
4055 }
4056 
4057 static int selinux_mmap_file(struct file *file,
4058 			     unsigned long reqprot __always_unused,
4059 			     unsigned long prot, unsigned long flags)
4060 {
4061 	return selinux_mmap_file_common(file, prot,
4062 					(flags & MAP_TYPE) == MAP_SHARED,
4063 					false);
4064 }
4065 
4066 /**
4067  * selinux_mmap_backing_file - Check mmap permissions on a backing file
4068  * @vma: memory region
4069  * @backing_file: stacked filesystem backing file
4070  * @user_file: user visible file
4071  *
4072  * This is called after selinux_mmap_file() on stacked filesystems, and it
4073  * is this function's responsibility to verify access to @backing_file and
4074  * setup the SELinux state for possible later use in the mprotect() code path.
4075  *
4076  * By the time this function is called, mmap() access to @user_file has already
4077  * been authorized and @vma->vm_file has been set to point to @backing_file.
4078  *
4079  * Return zero on success, negative values otherwise.
4080  */
4081 static int selinux_mmap_backing_file(struct vm_area_struct *vma,
4082 				     struct file *backing_file,
4083 				     struct file *user_file __always_unused)
4084 {
4085 	unsigned long prot = 0;
4086 
4087 	/* translate vma->vm_flags perms into PROT perms */
4088 	if (vma->vm_flags & VM_READ)
4089 		prot |= PROT_READ;
4090 	if (vma->vm_flags & VM_WRITE)
4091 		prot |= PROT_WRITE;
4092 	if (vma->vm_flags & VM_EXEC)
4093 		prot |= PROT_EXEC;
4094 
4095 	return selinux_mmap_file_common(backing_file, prot,
4096 					vma->vm_flags & VM_SHARED,
4097 					true);
4098 }
4099 
4100 static int selinux_file_mprotect(struct vm_area_struct *vma,
4101 				 unsigned long reqprot __always_unused,
4102 				 unsigned long prot)
4103 {
4104 	int rc;
4105 	const struct cred *cred = current_cred();
4106 	u32 sid = cred_sid(cred);
4107 	const struct file *file = vma->vm_file;
4108 	bool backing_file;
4109 	bool shared = vma->vm_flags & VM_SHARED;
4110 
4111 	/* check if we need to trigger the "backing files are awful" mode */
4112 	backing_file = file && (file->f_mode & FMODE_BACKING);
4113 
4114 	if (default_noexec &&
4115 	    (prot & PROT_EXEC) && !(vma->vm_flags & VM_EXEC)) {
4116 		/*
4117 		 * We don't use the vma_is_initial_heap() helper as it has
4118 		 * a history of problems and is currently broken on systems
4119 		 * where there is no heap, e.g. brk == start_brk.  Before
4120 		 * replacing the conditional below with vma_is_initial_heap(),
4121 		 * or something similar, please ensure that the logic is the
4122 		 * same as what we have below or you have tested every possible
4123 		 * corner case you can think to test.
4124 		 */
4125 		if (vma->vm_start >= vma->vm_mm->start_brk &&
4126 		    vma->vm_end <= vma->vm_mm->brk) {
4127 			rc = avc_has_perm(sid, sid, SECCLASS_PROCESS,
4128 					  PROCESS__EXECHEAP, NULL);
4129 			if (rc)
4130 				return rc;
4131 		} else if (!file && (vma_is_initial_stack(vma) ||
4132 			    vma_is_stack_for_current(vma))) {
4133 			rc = avc_has_perm(sid, sid, SECCLASS_PROCESS,
4134 					  PROCESS__EXECSTACK, NULL);
4135 			if (rc)
4136 				return rc;
4137 		} else if (file && vma->anon_vma) {
4138 			/*
4139 			 * We are making executable a file mapping that has
4140 			 * had some COW done. Since pages might have been
4141 			 * written, check ability to execute the possibly
4142 			 * modified content.  This typically should only
4143 			 * occur for text relocations.
4144 			 */
4145 			rc = __file_has_perm(cred, file, FILE__EXECMOD,
4146 					     backing_file);
4147 			if (rc)
4148 				return rc;
4149 			if (backing_file) {
4150 				rc = file_has_perm(file->f_cred, file,
4151 						   FILE__EXECMOD);
4152 				if (rc)
4153 					return rc;
4154 			}
4155 		}
4156 	}
4157 
4158 	rc = __file_map_prot_check(file, prot, shared, false, backing_file);
4159 	if (rc)
4160 		return rc;
4161 	if (backing_file) {
4162 		rc = file_map_prot_check(file, prot, shared, true);
4163 		if (rc)
4164 			return rc;
4165 	}
4166 
4167 	return 0;
4168 }
4169 
4170 static int selinux_file_lock(struct file *file, unsigned int cmd)
4171 {
4172 	const struct cred *cred = current_cred();
4173 
4174 	return file_has_perm(cred, file, FILE__LOCK);
4175 }
4176 
4177 static int selinux_file_fcntl(struct file *file, unsigned int cmd,
4178 			      unsigned long arg)
4179 {
4180 	const struct cred *cred = current_cred();
4181 	int err = 0;
4182 
4183 	switch (cmd) {
4184 	case F_SETFL:
4185 		if ((file->f_flags & O_APPEND) && !(arg & O_APPEND)) {
4186 			err = file_has_perm(cred, file, FILE__WRITE);
4187 			break;
4188 		}
4189 		fallthrough;
4190 	case F_SETOWN:
4191 	case F_SETSIG:
4192 	case F_GETFL:
4193 	case F_GETOWN:
4194 	case F_GETSIG:
4195 	case F_GETOWNER_UIDS:
4196 		/* Just check FD__USE permission */
4197 		err = file_has_perm(cred, file, 0);
4198 		break;
4199 	case F_GETLK:
4200 	case F_SETLK:
4201 	case F_SETLKW:
4202 	case F_OFD_GETLK:
4203 	case F_OFD_SETLK:
4204 	case F_OFD_SETLKW:
4205 #if BITS_PER_LONG == 32
4206 	case F_GETLK64:
4207 	case F_SETLK64:
4208 	case F_SETLKW64:
4209 #endif
4210 		err = file_has_perm(cred, file, FILE__LOCK);
4211 		break;
4212 	}
4213 
4214 	return err;
4215 }
4216 
4217 static void selinux_file_set_fowner(struct file *file)
4218 {
4219 	struct file_security_struct *fsec;
4220 
4221 	fsec = selinux_file(file);
4222 	fsec->fown_sid = current_sid();
4223 }
4224 
4225 static int selinux_file_send_sigiotask(struct task_struct *tsk,
4226 				       struct fown_struct *fown, int signum)
4227 {
4228 	struct file *file;
4229 	u32 sid = task_sid_obj(tsk);
4230 	u32 perm;
4231 	struct file_security_struct *fsec;
4232 
4233 	/* struct fown_struct is never outside the context of a struct file */
4234 	file = fown->file;
4235 
4236 	fsec = selinux_file(file);
4237 
4238 	if (!signum)
4239 		perm = signal_to_av(SIGIO); /* as per send_sigio_to_task */
4240 	else
4241 		perm = signal_to_av(signum);
4242 
4243 	return avc_has_perm(fsec->fown_sid, sid,
4244 			    SECCLASS_PROCESS, perm, NULL);
4245 }
4246 
4247 static int selinux_file_receive(struct file *file)
4248 {
4249 	const struct cred *cred = current_cred();
4250 
4251 	return file_has_perm(cred, file, file_to_av(file));
4252 }
4253 
4254 static int selinux_file_open(struct file *file)
4255 {
4256 	struct file_security_struct *fsec;
4257 	struct inode_security_struct *isec;
4258 
4259 	fsec = selinux_file(file);
4260 	isec = inode_security(file_inode(file));
4261 	/*
4262 	 * Save inode label and policy sequence number
4263 	 * at open-time so that selinux_file_permission
4264 	 * can determine whether revalidation is necessary.
4265 	 * Task label is already saved in the file security
4266 	 * struct as its SID.
4267 	 */
4268 	fsec->isid = isec->sid;
4269 	fsec->pseqno = avc_policy_seqno();
4270 	/*
4271 	 * Since the inode label or policy seqno may have changed
4272 	 * between the selinux_inode_permission check and the saving
4273 	 * of state above, recheck that access is still permitted.
4274 	 * Otherwise, access might never be revalidated against the
4275 	 * new inode label or new policy.
4276 	 * This check is not redundant - do not remove.
4277 	 */
4278 	return file_path_has_perm(file->f_cred, file, open_file_to_av(file));
4279 }
4280 
4281 /* task security operations */
4282 
4283 static int selinux_task_alloc(struct task_struct *task,
4284 			      u64 clone_flags)
4285 {
4286 	u32 sid = current_sid();
4287 	struct task_security_struct *old_tsec = selinux_task(current);
4288 	struct task_security_struct *new_tsec = selinux_task(task);
4289 
4290 	*new_tsec = *old_tsec;
4291 	return avc_has_perm(sid, sid, SECCLASS_PROCESS, PROCESS__FORK, NULL);
4292 }
4293 
4294 /*
4295  * prepare a new set of credentials for modification
4296  */
4297 static int selinux_cred_prepare(struct cred *new, const struct cred *old,
4298 				gfp_t gfp)
4299 {
4300 	const struct cred_security_struct *old_crsec = selinux_cred(old);
4301 	struct cred_security_struct *crsec = selinux_cred(new);
4302 
4303 	*crsec = *old_crsec;
4304 	return 0;
4305 }
4306 
4307 /*
4308  * transfer the SELinux data to a blank set of creds
4309  */
4310 static void selinux_cred_transfer(struct cred *new, const struct cred *old)
4311 {
4312 	const struct cred_security_struct *old_crsec = selinux_cred(old);
4313 	struct cred_security_struct *crsec = selinux_cred(new);
4314 
4315 	*crsec = *old_crsec;
4316 }
4317 
4318 static void selinux_cred_getsecid(const struct cred *c, u32 *secid)
4319 {
4320 	*secid = cred_sid(c);
4321 }
4322 
4323 static void selinux_cred_getlsmprop(const struct cred *c, struct lsm_prop *prop)
4324 {
4325 	prop->selinux.secid = cred_sid(c);
4326 }
4327 
4328 /*
4329  * set the security data for a kernel service
4330  * - all the creation contexts are set to unlabelled
4331  */
4332 static int selinux_kernel_act_as(struct cred *new, u32 secid)
4333 {
4334 	struct cred_security_struct *crsec = selinux_cred(new);
4335 	u32 sid = current_sid();
4336 	int ret;
4337 
4338 	ret = avc_has_perm(sid, secid,
4339 			   SECCLASS_KERNEL_SERVICE,
4340 			   KERNEL_SERVICE__USE_AS_OVERRIDE,
4341 			   NULL);
4342 	if (ret == 0) {
4343 		crsec->sid = secid;
4344 		crsec->create_sid = 0;
4345 		crsec->keycreate_sid = 0;
4346 		crsec->sockcreate_sid = 0;
4347 	}
4348 	return ret;
4349 }
4350 
4351 /*
4352  * set the file creation context in a security record to the same as the
4353  * objective context of the specified inode
4354  */
4355 static int selinux_kernel_create_files_as(struct cred *new, struct inode *inode)
4356 {
4357 	struct inode_security_struct *isec = inode_security(inode);
4358 	struct cred_security_struct *crsec = selinux_cred(new);
4359 	u32 sid = current_sid();
4360 	int ret;
4361 
4362 	ret = avc_has_perm(sid, isec->sid,
4363 			   SECCLASS_KERNEL_SERVICE,
4364 			   KERNEL_SERVICE__CREATE_FILES_AS,
4365 			   NULL);
4366 
4367 	if (ret == 0)
4368 		crsec->create_sid = isec->sid;
4369 	return ret;
4370 }
4371 
4372 static int selinux_kernel_module_request(char *kmod_name)
4373 {
4374 	struct common_audit_data ad;
4375 
4376 	ad.type = LSM_AUDIT_DATA_KMOD;
4377 	ad.u.kmod_name = kmod_name;
4378 
4379 	return avc_has_perm(current_sid(), SECINITSID_KERNEL, SECCLASS_SYSTEM,
4380 			    SYSTEM__MODULE_REQUEST, &ad);
4381 }
4382 
4383 static int selinux_kernel_load_from_file(struct file *file, u32 requested)
4384 {
4385 	struct common_audit_data ad;
4386 	struct inode_security_struct *isec;
4387 	struct file_security_struct *fsec;
4388 	u32 sid = current_sid();
4389 	int rc;
4390 
4391 	if (file == NULL)
4392 		return avc_has_perm(sid, sid, SECCLASS_SYSTEM, requested, NULL);
4393 
4394 	ad.type = LSM_AUDIT_DATA_FILE;
4395 	ad.u.file = file;
4396 
4397 	fsec = selinux_file(file);
4398 	if (sid != fsec->sid) {
4399 		rc = avc_has_perm(sid, fsec->sid, SECCLASS_FD, FD__USE, &ad);
4400 		if (rc)
4401 			return rc;
4402 	}
4403 
4404 	isec = inode_security(file_inode(file));
4405 	return avc_has_perm(sid, isec->sid, SECCLASS_SYSTEM, requested, &ad);
4406 }
4407 
4408 static int selinux_kernel_read_file(struct file *file,
4409 				    enum kernel_read_file_id id,
4410 				    bool contents)
4411 {
4412 	int rc = 0;
4413 
4414 	BUILD_BUG_ON_MSG(READING_MAX_ID > 8,
4415 			 "New kernel_read_file_id introduced; update SELinux!");
4416 
4417 	switch (id) {
4418 	case READING_FIRMWARE:
4419 		rc = selinux_kernel_load_from_file(file, SYSTEM__FIRMWARE_LOAD);
4420 		break;
4421 	case READING_MODULE:
4422 	case READING_MODULE_COMPRESSED:
4423 		rc = selinux_kernel_load_from_file(file, SYSTEM__MODULE_LOAD);
4424 		break;
4425 	case READING_KEXEC_IMAGE:
4426 		rc = selinux_kernel_load_from_file(file,
4427 						   SYSTEM__KEXEC_IMAGE_LOAD);
4428 		break;
4429 	case READING_KEXEC_INITRAMFS:
4430 		rc = selinux_kernel_load_from_file(file,
4431 						SYSTEM__KEXEC_INITRAMFS_LOAD);
4432 		break;
4433 	case READING_POLICY:
4434 		rc = selinux_kernel_load_from_file(file, SYSTEM__POLICY_LOAD);
4435 		break;
4436 	case READING_X509_CERTIFICATE:
4437 		rc = selinux_kernel_load_from_file(file,
4438 						SYSTEM__X509_CERTIFICATE_LOAD);
4439 		break;
4440 	default:
4441 		break;
4442 	}
4443 
4444 	return rc;
4445 }
4446 
4447 static int selinux_kernel_load_data(enum kernel_load_data_id id, bool contents)
4448 {
4449 	int rc = 0;
4450 
4451 	BUILD_BUG_ON_MSG(LOADING_MAX_ID > 8,
4452 			 "New kernel_load_data_id introduced; update SELinux!");
4453 
4454 	switch (id) {
4455 	case LOADING_FIRMWARE:
4456 		rc = selinux_kernel_load_from_file(NULL, SYSTEM__FIRMWARE_LOAD);
4457 		break;
4458 	case LOADING_MODULE:
4459 		rc = selinux_kernel_load_from_file(NULL, SYSTEM__MODULE_LOAD);
4460 		break;
4461 	case LOADING_KEXEC_IMAGE:
4462 		rc = selinux_kernel_load_from_file(NULL,
4463 						   SYSTEM__KEXEC_IMAGE_LOAD);
4464 		break;
4465 	case LOADING_KEXEC_INITRAMFS:
4466 		rc = selinux_kernel_load_from_file(NULL,
4467 						SYSTEM__KEXEC_INITRAMFS_LOAD);
4468 		break;
4469 	case LOADING_POLICY:
4470 		rc = selinux_kernel_load_from_file(NULL,
4471 						   SYSTEM__POLICY_LOAD);
4472 		break;
4473 	case LOADING_X509_CERTIFICATE:
4474 		rc = selinux_kernel_load_from_file(NULL,
4475 						SYSTEM__X509_CERTIFICATE_LOAD);
4476 		break;
4477 	default:
4478 		break;
4479 	}
4480 
4481 	return rc;
4482 }
4483 
4484 static int selinux_task_setpgid(struct task_struct *p, pid_t pgid)
4485 {
4486 	return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4487 			    PROCESS__SETPGID, NULL);
4488 }
4489 
4490 static int selinux_task_getpgid(struct task_struct *p)
4491 {
4492 	return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4493 			    PROCESS__GETPGID, NULL);
4494 }
4495 
4496 static int selinux_task_getsid(struct task_struct *p)
4497 {
4498 	return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4499 			    PROCESS__GETSESSION, NULL);
4500 }
4501 
4502 static void selinux_current_getlsmprop_subj(struct lsm_prop *prop)
4503 {
4504 	prop->selinux.secid = current_sid();
4505 }
4506 
4507 static void selinux_task_getlsmprop_obj(struct task_struct *p,
4508 					struct lsm_prop *prop)
4509 {
4510 	prop->selinux.secid = task_sid_obj(p);
4511 }
4512 
4513 static int selinux_task_setnice(struct task_struct *p, int nice)
4514 {
4515 	return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4516 			    PROCESS__SETSCHED, NULL);
4517 }
4518 
4519 static int selinux_task_setioprio(struct task_struct *p, int ioprio)
4520 {
4521 	return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4522 			    PROCESS__SETSCHED, NULL);
4523 }
4524 
4525 static int selinux_task_getioprio(struct task_struct *p)
4526 {
4527 	return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4528 			    PROCESS__GETSCHED, NULL);
4529 }
4530 
4531 static int selinux_task_prlimit(const struct cred *cred, const struct cred *tcred,
4532 				unsigned int flags)
4533 {
4534 	u32 av = 0;
4535 
4536 	if (!flags)
4537 		return 0;
4538 	if (flags & LSM_PRLIMIT_WRITE)
4539 		av |= PROCESS__SETRLIMIT;
4540 	if (flags & LSM_PRLIMIT_READ)
4541 		av |= PROCESS__GETRLIMIT;
4542 	return avc_has_perm(cred_sid(cred), cred_sid(tcred),
4543 			    SECCLASS_PROCESS, av, NULL);
4544 }
4545 
4546 static int selinux_task_setrlimit(struct task_struct *p, unsigned int resource,
4547 		struct rlimit *new_rlim)
4548 {
4549 	struct rlimit *old_rlim = p->signal->rlim + resource;
4550 
4551 	/* Control the ability to change the hard limit (whether
4552 	   lowering or raising it), so that the hard limit can
4553 	   later be used as a safe reset point for the soft limit
4554 	   upon context transitions.  See selinux_bprm_committing_creds. */
4555 	if (old_rlim->rlim_max != new_rlim->rlim_max)
4556 		return avc_has_perm(current_sid(), task_sid_obj(p),
4557 				    SECCLASS_PROCESS, PROCESS__SETRLIMIT, NULL);
4558 
4559 	return 0;
4560 }
4561 
4562 static int selinux_task_setscheduler(struct task_struct *p)
4563 {
4564 	return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4565 			    PROCESS__SETSCHED, NULL);
4566 }
4567 
4568 static int selinux_task_getscheduler(struct task_struct *p)
4569 {
4570 	return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4571 			    PROCESS__GETSCHED, NULL);
4572 }
4573 
4574 static int selinux_task_movememory(struct task_struct *p)
4575 {
4576 	return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4577 			    PROCESS__SETSCHED, NULL);
4578 }
4579 
4580 static int selinux_task_kill(struct task_struct *p, struct kernel_siginfo *info,
4581 				int sig, const struct cred *cred)
4582 {
4583 	u32 secid;
4584 	u32 perm;
4585 
4586 	if (!sig)
4587 		perm = PROCESS__SIGNULL; /* null signal; existence test */
4588 	else
4589 		perm = signal_to_av(sig);
4590 	if (!cred)
4591 		secid = current_sid();
4592 	else
4593 		secid = cred_sid(cred);
4594 	return avc_has_perm(secid, task_sid_obj(p), SECCLASS_PROCESS, perm, NULL);
4595 }
4596 
4597 static void selinux_task_to_inode(struct task_struct *p,
4598 				  struct inode *inode)
4599 {
4600 	struct inode_security_struct *isec = selinux_inode(inode);
4601 	u32 sid = task_sid_obj(p);
4602 
4603 	spin_lock(&isec->lock);
4604 	isec->sclass = inode_mode_to_security_class(inode->i_mode);
4605 	isec->sid = sid;
4606 	isec->initialized = LABEL_INITIALIZED;
4607 	spin_unlock(&isec->lock);
4608 }
4609 
4610 static int selinux_userns_create(const struct cred *cred)
4611 {
4612 	u32 sid = current_sid();
4613 
4614 	return avc_has_perm(sid, sid, SECCLASS_USER_NAMESPACE,
4615 			USER_NAMESPACE__CREATE, NULL);
4616 }
4617 
4618 /* Returns error only if unable to parse addresses */
4619 static int selinux_parse_skb_ipv4(struct sk_buff *skb,
4620 			struct common_audit_data *ad, u8 *proto)
4621 {
4622 	int offset, ihlen, ret = -EINVAL;
4623 	struct iphdr _iph, *ih;
4624 
4625 	offset = skb_network_offset(skb);
4626 	ih = skb_header_pointer(skb, offset, sizeof(_iph), &_iph);
4627 	if (ih == NULL)
4628 		goto out;
4629 
4630 	ihlen = ih->ihl * 4;
4631 	if (ihlen < sizeof(_iph))
4632 		goto out;
4633 
4634 	ad->u.net->v4info.saddr = ih->saddr;
4635 	ad->u.net->v4info.daddr = ih->daddr;
4636 	ret = 0;
4637 
4638 	if (proto)
4639 		*proto = ih->protocol;
4640 
4641 	switch (ih->protocol) {
4642 	case IPPROTO_TCP: {
4643 		struct tcphdr _tcph, *th;
4644 
4645 		if (ntohs(ih->frag_off) & IP_OFFSET)
4646 			break;
4647 
4648 		offset += ihlen;
4649 		th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
4650 		if (th == NULL)
4651 			break;
4652 
4653 		ad->u.net->sport = th->source;
4654 		ad->u.net->dport = th->dest;
4655 		break;
4656 	}
4657 
4658 	case IPPROTO_UDP: {
4659 		struct udphdr _udph, *uh;
4660 
4661 		if (ntohs(ih->frag_off) & IP_OFFSET)
4662 			break;
4663 
4664 		offset += ihlen;
4665 		uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
4666 		if (uh == NULL)
4667 			break;
4668 
4669 		ad->u.net->sport = uh->source;
4670 		ad->u.net->dport = uh->dest;
4671 		break;
4672 	}
4673 
4674 #if IS_ENABLED(CONFIG_IP_SCTP)
4675 	case IPPROTO_SCTP: {
4676 		struct sctphdr _sctph, *sh;
4677 
4678 		if (ntohs(ih->frag_off) & IP_OFFSET)
4679 			break;
4680 
4681 		offset += ihlen;
4682 		sh = skb_header_pointer(skb, offset, sizeof(_sctph), &_sctph);
4683 		if (sh == NULL)
4684 			break;
4685 
4686 		ad->u.net->sport = sh->source;
4687 		ad->u.net->dport = sh->dest;
4688 		break;
4689 	}
4690 #endif
4691 	default:
4692 		break;
4693 	}
4694 out:
4695 	return ret;
4696 }
4697 
4698 #if IS_ENABLED(CONFIG_IPV6)
4699 
4700 /* Returns error only if unable to parse addresses */
4701 static int selinux_parse_skb_ipv6(struct sk_buff *skb,
4702 			struct common_audit_data *ad, u8 *proto)
4703 {
4704 	u8 nexthdr;
4705 	int ret = -EINVAL, offset;
4706 	struct ipv6hdr _ipv6h, *ip6;
4707 	__be16 frag_off;
4708 
4709 	offset = skb_network_offset(skb);
4710 	ip6 = skb_header_pointer(skb, offset, sizeof(_ipv6h), &_ipv6h);
4711 	if (ip6 == NULL)
4712 		goto out;
4713 
4714 	ad->u.net->v6info.saddr = ip6->saddr;
4715 	ad->u.net->v6info.daddr = ip6->daddr;
4716 	ret = 0;
4717 
4718 	nexthdr = ip6->nexthdr;
4719 	offset += sizeof(_ipv6h);
4720 	offset = ipv6_skip_exthdr(skb, offset, &nexthdr, &frag_off);
4721 	if (offset < 0)
4722 		goto out;
4723 
4724 	if (proto)
4725 		*proto = nexthdr;
4726 
4727 	switch (nexthdr) {
4728 	case IPPROTO_TCP: {
4729 		struct tcphdr _tcph, *th;
4730 
4731 		th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
4732 		if (th == NULL)
4733 			break;
4734 
4735 		ad->u.net->sport = th->source;
4736 		ad->u.net->dport = th->dest;
4737 		break;
4738 	}
4739 
4740 	case IPPROTO_UDP: {
4741 		struct udphdr _udph, *uh;
4742 
4743 		uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
4744 		if (uh == NULL)
4745 			break;
4746 
4747 		ad->u.net->sport = uh->source;
4748 		ad->u.net->dport = uh->dest;
4749 		break;
4750 	}
4751 
4752 #if IS_ENABLED(CONFIG_IP_SCTP)
4753 	case IPPROTO_SCTP: {
4754 		struct sctphdr _sctph, *sh;
4755 
4756 		sh = skb_header_pointer(skb, offset, sizeof(_sctph), &_sctph);
4757 		if (sh == NULL)
4758 			break;
4759 
4760 		ad->u.net->sport = sh->source;
4761 		ad->u.net->dport = sh->dest;
4762 		break;
4763 	}
4764 #endif
4765 	/* includes fragments */
4766 	default:
4767 		break;
4768 	}
4769 out:
4770 	return ret;
4771 }
4772 
4773 #endif /* IPV6 */
4774 
4775 static int selinux_parse_skb(struct sk_buff *skb, struct common_audit_data *ad,
4776 			     char **_addrp, int src, u8 *proto)
4777 {
4778 	char *addrp;
4779 	int ret;
4780 
4781 	switch (ad->u.net->family) {
4782 	case PF_INET:
4783 		ret = selinux_parse_skb_ipv4(skb, ad, proto);
4784 		if (ret)
4785 			goto parse_error;
4786 		addrp = (char *)(src ? &ad->u.net->v4info.saddr :
4787 				       &ad->u.net->v4info.daddr);
4788 		goto okay;
4789 
4790 #if IS_ENABLED(CONFIG_IPV6)
4791 	case PF_INET6:
4792 		ret = selinux_parse_skb_ipv6(skb, ad, proto);
4793 		if (ret)
4794 			goto parse_error;
4795 		addrp = (char *)(src ? &ad->u.net->v6info.saddr :
4796 				       &ad->u.net->v6info.daddr);
4797 		goto okay;
4798 #endif	/* IPV6 */
4799 	default:
4800 		addrp = NULL;
4801 		goto okay;
4802 	}
4803 
4804 parse_error:
4805 	pr_warn(
4806 	       "SELinux: failure in selinux_parse_skb(),"
4807 	       " unable to parse packet\n");
4808 	return ret;
4809 
4810 okay:
4811 	if (_addrp)
4812 		*_addrp = addrp;
4813 	return 0;
4814 }
4815 
4816 /**
4817  * selinux_skb_peerlbl_sid - Determine the peer label of a packet
4818  * @skb: the packet
4819  * @family: protocol family
4820  * @sid: the packet's peer label SID
4821  *
4822  * Description:
4823  * Check the various different forms of network peer labeling and determine
4824  * the peer label/SID for the packet; most of the magic actually occurs in
4825  * the security server function security_net_peersid_cmp().  The function
4826  * returns zero if the value in @sid is valid (although it may be SECSID_NULL)
4827  * or -EACCES if @sid is invalid due to inconsistencies with the different
4828  * peer labels.
4829  *
4830  */
4831 static int selinux_skb_peerlbl_sid(struct sk_buff *skb, u16 family, u32 *sid)
4832 {
4833 	int err;
4834 	u32 xfrm_sid;
4835 	u32 nlbl_sid;
4836 	u32 nlbl_type;
4837 
4838 	err = selinux_xfrm_skb_sid(skb, &xfrm_sid);
4839 	if (unlikely(err))
4840 		return -EACCES;
4841 	err = selinux_netlbl_skbuff_getsid(skb, family, &nlbl_type, &nlbl_sid);
4842 	if (unlikely(err))
4843 		return -EACCES;
4844 
4845 	err = security_net_peersid_resolve(nlbl_sid,
4846 					   nlbl_type, xfrm_sid, sid);
4847 	if (unlikely(err)) {
4848 		pr_warn(
4849 		       "SELinux: failure in selinux_skb_peerlbl_sid(),"
4850 		       " unable to determine packet's peer label\n");
4851 		return -EACCES;
4852 	}
4853 
4854 	return 0;
4855 }
4856 
4857 /**
4858  * selinux_conn_sid - Determine the child socket label for a connection
4859  * @sk_sid: the parent socket's SID
4860  * @skb_sid: the packet's SID
4861  * @conn_sid: the resulting connection SID
4862  *
4863  * If @skb_sid is valid then the user:role:type information from @sk_sid is
4864  * combined with the MLS information from @skb_sid in order to create
4865  * @conn_sid.  If @skb_sid is not valid then @conn_sid is simply a copy
4866  * of @sk_sid.  Returns zero on success, negative values on failure.
4867  *
4868  */
4869 static int selinux_conn_sid(u32 sk_sid, u32 skb_sid, u32 *conn_sid)
4870 {
4871 	int err = 0;
4872 
4873 	if (skb_sid != SECSID_NULL)
4874 		err = security_sid_mls_copy(sk_sid, skb_sid,
4875 					    conn_sid);
4876 	else
4877 		*conn_sid = sk_sid;
4878 
4879 	return err;
4880 }
4881 
4882 /* socket security operations */
4883 
4884 static int socket_sockcreate_sid(const struct cred_security_struct *crsec,
4885 				 u16 secclass, u32 *socksid)
4886 {
4887 	if (crsec->sockcreate_sid > SECSID_NULL) {
4888 		*socksid = crsec->sockcreate_sid;
4889 		return 0;
4890 	}
4891 
4892 	return security_transition_sid(crsec->sid, crsec->sid,
4893 				       secclass, NULL, socksid);
4894 }
4895 
4896 static bool sock_skip_has_perm(u32 sid)
4897 {
4898 	if (sid == SECINITSID_KERNEL)
4899 		return true;
4900 
4901 	/*
4902 	 * Before POLICYDB_CAP_USERSPACE_INITIAL_CONTEXT, sockets that
4903 	 * inherited the kernel context from early boot used to be skipped
4904 	 * here, so preserve that behavior unless the capability is set.
4905 	 *
4906 	 * By setting the capability the policy signals that it is ready
4907 	 * for this quirk to be fixed. Note that sockets created by a kernel
4908 	 * thread or a usermode helper executed without a transition will
4909 	 * still be skipped in this check regardless of the policycap
4910 	 * setting.
4911 	 */
4912 	if (!selinux_policycap_userspace_initial_context() &&
4913 	    sid == SECINITSID_INIT)
4914 		return true;
4915 	return false;
4916 }
4917 
4918 
4919 static int sock_has_perm(struct sock *sk, u32 perms)
4920 {
4921 	struct sk_security_struct *sksec = selinux_sock(sk);
4922 	struct common_audit_data ad;
4923 	struct lsm_network_audit net;
4924 
4925 	if (sock_skip_has_perm(sksec->sid))
4926 		return 0;
4927 
4928 	ad_net_init_from_sk(&ad, &net, sk);
4929 
4930 	return avc_has_perm(current_sid(), sksec->sid, sksec->sclass, perms,
4931 			    &ad);
4932 }
4933 
4934 static int selinux_socket_create(int family, int type,
4935 				 int protocol, int kern)
4936 {
4937 	const struct cred_security_struct *crsec = selinux_cred(current_cred());
4938 	u32 newsid;
4939 	u16 secclass;
4940 	int rc;
4941 
4942 	if (kern)
4943 		return 0;
4944 
4945 	secclass = socket_type_to_security_class(family, type, protocol);
4946 	rc = socket_sockcreate_sid(crsec, secclass, &newsid);
4947 	if (rc)
4948 		return rc;
4949 
4950 	return avc_has_perm(crsec->sid, newsid, secclass, SOCKET__CREATE, NULL);
4951 }
4952 
4953 static int selinux_socket_post_create(struct socket *sock, int family,
4954 				      int type, int protocol, int kern)
4955 {
4956 	const struct cred_security_struct *crsec = selinux_cred(current_cred());
4957 	struct inode_security_struct *isec = inode_security_novalidate(SOCK_INODE(sock));
4958 	struct sk_security_struct *sksec;
4959 	u16 sclass = socket_type_to_security_class(family, type, protocol);
4960 	u32 sid = SECINITSID_KERNEL;
4961 	int err = 0;
4962 
4963 	if (!kern) {
4964 		err = socket_sockcreate_sid(crsec, sclass, &sid);
4965 		if (err)
4966 			return err;
4967 	}
4968 
4969 	isec->sclass = sclass;
4970 	isec->sid = sid;
4971 	isec->initialized = LABEL_INITIALIZED;
4972 
4973 	if (sock->sk) {
4974 		sksec = selinux_sock(sock->sk);
4975 		sksec->sclass = sclass;
4976 		sksec->sid = sid;
4977 		/* Allows detection of the first association on this socket */
4978 		if (sksec->sclass == SECCLASS_SCTP_SOCKET)
4979 			sksec->sctp_assoc_state = SCTP_ASSOC_UNSET;
4980 
4981 		err = selinux_netlbl_socket_post_create(sock->sk, family);
4982 	}
4983 
4984 	return err;
4985 }
4986 
4987 static int selinux_socket_socketpair(struct socket *socka,
4988 				     struct socket *sockb)
4989 {
4990 	struct sk_security_struct *sksec_a = selinux_sock(socka->sk);
4991 	struct sk_security_struct *sksec_b = selinux_sock(sockb->sk);
4992 
4993 	sksec_a->peer_sid = sksec_b->sid;
4994 	sksec_b->peer_sid = sksec_a->sid;
4995 
4996 	return 0;
4997 }
4998 
4999 /* Range of port numbers used to automatically bind.
5000    Need to determine whether we should perform a name_bind
5001    permission check between the socket and the port number. */
5002 
5003 static int __selinux_socket_bind(struct sock *sk, struct sockaddr *address, int addrlen)
5004 {
5005 	struct sk_security_struct *sksec = selinux_sock(sk);
5006 	u16 family;
5007 	int err;
5008 
5009 	err = sock_has_perm(sk, SOCKET__BIND);
5010 	if (err)
5011 		goto out;
5012 
5013 	/* If PF_INET or PF_INET6, check name_bind permission for the port. */
5014 	family = sk->sk_family;
5015 	if (family == PF_INET || family == PF_INET6) {
5016 		char *addrp;
5017 		struct common_audit_data ad;
5018 		struct lsm_network_audit net = {0,};
5019 		struct sockaddr_in *addr4 = NULL;
5020 		struct sockaddr_in6 *addr6 = NULL;
5021 		u16 family_sa;
5022 		unsigned short snum;
5023 		u32 sid, node_perm;
5024 
5025 		/*
5026 		 * sctp_bindx(3) calls via selinux_sctp_bind_connect()
5027 		 * that validates multiple binding addresses. Because of this
5028 		 * need to check address->sa_family as it is possible to have
5029 		 * sk->sk_family = PF_INET6 with addr->sa_family = AF_INET.
5030 		 */
5031 		if (addrlen < offsetofend(struct sockaddr, sa_family))
5032 			return -EINVAL;
5033 		family_sa = address->sa_family;
5034 		switch (family_sa) {
5035 		case AF_UNSPEC:
5036 		case AF_INET:
5037 			if (addrlen < sizeof(struct sockaddr_in))
5038 				return -EINVAL;
5039 			addr4 = (struct sockaddr_in *)address;
5040 			if (family_sa == AF_UNSPEC) {
5041 				if (family == PF_INET6) {
5042 					/* Length check from inet6_bind_sk() */
5043 					if (addrlen < SIN6_LEN_RFC2133)
5044 						return -EINVAL;
5045 					/* Family check from __inet6_bind() */
5046 					goto err_af;
5047 				}
5048 				/* see __inet_bind(), we only want to allow
5049 				 * AF_UNSPEC if the address is INADDR_ANY
5050 				 */
5051 				if (addr4->sin_addr.s_addr != htonl(INADDR_ANY))
5052 					goto err_af;
5053 				family_sa = AF_INET;
5054 			}
5055 			snum = ntohs(addr4->sin_port);
5056 			addrp = (char *)&addr4->sin_addr.s_addr;
5057 			break;
5058 		case AF_INET6:
5059 			if (addrlen < SIN6_LEN_RFC2133)
5060 				return -EINVAL;
5061 			addr6 = (struct sockaddr_in6 *)address;
5062 			snum = ntohs(addr6->sin6_port);
5063 			addrp = (char *)&addr6->sin6_addr.s6_addr;
5064 			break;
5065 		default:
5066 			goto err_af;
5067 		}
5068 
5069 		ad.type = LSM_AUDIT_DATA_NET;
5070 		ad.u.net = &net;
5071 		ad.u.net->sport = htons(snum);
5072 		ad.u.net->family = family_sa;
5073 
5074 		if (snum) {
5075 			int low, high;
5076 
5077 			inet_get_local_port_range(sock_net(sk), &low, &high);
5078 
5079 			if (inet_port_requires_bind_service(sock_net(sk), snum) ||
5080 			    snum < low || snum > high) {
5081 				err = sel_netport_sid(sk->sk_protocol,
5082 						      snum, &sid);
5083 				if (err)
5084 					goto out;
5085 				err = avc_has_perm(sksec->sid, sid,
5086 						   sksec->sclass,
5087 						   SOCKET__NAME_BIND, &ad);
5088 				if (err)
5089 					goto out;
5090 			}
5091 		}
5092 
5093 		switch (sksec->sclass) {
5094 		case SECCLASS_TCP_SOCKET:
5095 			node_perm = TCP_SOCKET__NODE_BIND;
5096 			break;
5097 
5098 		case SECCLASS_UDP_SOCKET:
5099 			node_perm = UDP_SOCKET__NODE_BIND;
5100 			break;
5101 
5102 		case SECCLASS_SCTP_SOCKET:
5103 			node_perm = SCTP_SOCKET__NODE_BIND;
5104 			break;
5105 
5106 		default:
5107 			node_perm = RAWIP_SOCKET__NODE_BIND;
5108 			break;
5109 		}
5110 
5111 		err = sel_netnode_sid(addrp, family_sa, &sid);
5112 		if (err)
5113 			goto out;
5114 
5115 		if (family_sa == AF_INET)
5116 			ad.u.net->v4info.saddr = addr4->sin_addr.s_addr;
5117 		else
5118 			ad.u.net->v6info.saddr = addr6->sin6_addr;
5119 
5120 		err = avc_has_perm(sksec->sid, sid,
5121 				   sksec->sclass, node_perm, &ad);
5122 		if (err)
5123 			goto out;
5124 	}
5125 out:
5126 	return err;
5127 err_af:
5128 	/* Note that SCTP services expect -EINVAL, others -EAFNOSUPPORT. */
5129 	if (sk->sk_protocol == IPPROTO_SCTP)
5130 		return -EINVAL;
5131 	return -EAFNOSUPPORT;
5132 }
5133 
5134 static int selinux_socket_bind(struct socket *sock, struct sockaddr *address, int addrlen)
5135 {
5136 	return __selinux_socket_bind(sock->sk, address, addrlen);
5137 }
5138 
5139 /* This supports connect(2) and SCTP connect services such as sctp_connectx(3)
5140  * and sctp_sendmsg(3) as described in Documentation/security/SCTP.rst
5141  */
5142 static int selinux_socket_connect_helper(struct sock *sk,
5143 					 struct sockaddr *address, int addrlen)
5144 {
5145 	struct sk_security_struct *sksec = selinux_sock(sk);
5146 	int err;
5147 
5148 	err = sock_has_perm(sk, SOCKET__CONNECT);
5149 	if (err)
5150 		return err;
5151 	if (addrlen < offsetofend(struct sockaddr, sa_family))
5152 		return -EINVAL;
5153 
5154 	/* connect(AF_UNSPEC) has special handling, as it is a documented
5155 	 * way to disconnect the socket
5156 	 */
5157 	if (address->sa_family == AF_UNSPEC)
5158 		return 0;
5159 
5160 	/*
5161 	 * If a TCP or SCTP socket, check name_connect permission
5162 	 * for the port.
5163 	 */
5164 	if (sksec->sclass == SECCLASS_TCP_SOCKET ||
5165 	    sksec->sclass == SECCLASS_SCTP_SOCKET) {
5166 		struct common_audit_data ad;
5167 		struct lsm_network_audit net = {0,};
5168 		struct sockaddr_in *addr4 = NULL;
5169 		struct sockaddr_in6 *addr6 = NULL;
5170 		unsigned short snum;
5171 		u32 sid, perm;
5172 
5173 		/* sctp_connectx(3) calls via selinux_sctp_bind_connect()
5174 		 * that validates multiple connect addresses. Because of this
5175 		 * need to check address->sa_family as it is possible to have
5176 		 * sk->sk_family = PF_INET6 with addr->sa_family = AF_INET.
5177 		 */
5178 		switch (address->sa_family) {
5179 		case AF_INET:
5180 			addr4 = (struct sockaddr_in *)address;
5181 			if (addrlen < sizeof(struct sockaddr_in))
5182 				return -EINVAL;
5183 			snum = ntohs(addr4->sin_port);
5184 			break;
5185 		case AF_INET6:
5186 			addr6 = (struct sockaddr_in6 *)address;
5187 			if (addrlen < SIN6_LEN_RFC2133)
5188 				return -EINVAL;
5189 			snum = ntohs(addr6->sin6_port);
5190 			break;
5191 		default:
5192 			/* Note that SCTP services expect -EINVAL, whereas
5193 			 * others expect -EAFNOSUPPORT.
5194 			 */
5195 			if (sksec->sclass == SECCLASS_SCTP_SOCKET)
5196 				return -EINVAL;
5197 			else
5198 				return -EAFNOSUPPORT;
5199 		}
5200 
5201 		err = sel_netport_sid(sk->sk_protocol, snum, &sid);
5202 		if (err)
5203 			return err;
5204 
5205 		switch (sksec->sclass) {
5206 		case SECCLASS_TCP_SOCKET:
5207 			perm = TCP_SOCKET__NAME_CONNECT;
5208 			break;
5209 		case SECCLASS_SCTP_SOCKET:
5210 			perm = SCTP_SOCKET__NAME_CONNECT;
5211 			break;
5212 		}
5213 
5214 		ad.type = LSM_AUDIT_DATA_NET;
5215 		ad.u.net = &net;
5216 		ad.u.net->dport = htons(snum);
5217 		ad.u.net->family = address->sa_family;
5218 		err = avc_has_perm(sksec->sid, sid, sksec->sclass, perm, &ad);
5219 		if (err)
5220 			return err;
5221 	}
5222 
5223 	return 0;
5224 }
5225 
5226 /* Supports connect(2), see comments in selinux_socket_connect_helper() */
5227 static int selinux_socket_connect(struct socket *sock,
5228 				  struct sockaddr *address, int addrlen)
5229 {
5230 	int err;
5231 	struct sock *sk = sock->sk;
5232 
5233 	err = selinux_socket_connect_helper(sk, address, addrlen);
5234 	if (err)
5235 		return err;
5236 
5237 	return selinux_netlbl_socket_connect(sk, address);
5238 }
5239 
5240 static int selinux_socket_listen(struct socket *sock, int backlog)
5241 {
5242 	return sock_has_perm(sock->sk, SOCKET__LISTEN);
5243 }
5244 
5245 static int selinux_socket_accept(struct socket *sock, struct socket *newsock)
5246 {
5247 	int err;
5248 	struct inode_security_struct *isec;
5249 	struct inode_security_struct *newisec;
5250 	u16 sclass;
5251 	u32 sid;
5252 
5253 	err = sock_has_perm(sock->sk, SOCKET__ACCEPT);
5254 	if (err)
5255 		return err;
5256 
5257 	isec = inode_security_novalidate(SOCK_INODE(sock));
5258 	spin_lock(&isec->lock);
5259 	sclass = isec->sclass;
5260 	sid = isec->sid;
5261 	spin_unlock(&isec->lock);
5262 
5263 	newisec = inode_security_novalidate(SOCK_INODE(newsock));
5264 	newisec->sclass = sclass;
5265 	newisec->sid = sid;
5266 	newisec->initialized = LABEL_INITIALIZED;
5267 
5268 	return 0;
5269 }
5270 
5271 static int selinux_socket_sendmsg(struct socket *sock, struct msghdr *msg,
5272 				  int size)
5273 {
5274 	int rc;
5275 	struct sockaddr *const addr = msg->msg_name;
5276 	const int addrlen = msg->msg_namelen;
5277 
5278 	rc = sock_has_perm(sock->sk, SOCKET__WRITE);
5279 	if (rc)
5280 		return rc;
5281 
5282 	if (addr && (msg->msg_flags & MSG_FASTOPEN) &&
5283 	    (sk_is_tcp(sock->sk) ||
5284 	     (sk_is_inet(sock->sk) && sock->sk->sk_type == SOCK_STREAM &&
5285 	      sock->sk->sk_protocol == IPPROTO_MPTCP))) {
5286 		rc = selinux_socket_connect(sock, addr, addrlen);
5287 		if (rc)
5288 			return rc;
5289 	}
5290 
5291 	return 0;
5292 }
5293 
5294 static int selinux_socket_recvmsg(struct socket *sock, struct msghdr *msg,
5295 				  int size, int flags)
5296 {
5297 	return sock_has_perm(sock->sk, SOCKET__READ);
5298 }
5299 
5300 static int selinux_socket_getsockname(struct socket *sock)
5301 {
5302 	return sock_has_perm(sock->sk, SOCKET__GETATTR);
5303 }
5304 
5305 static int selinux_socket_getpeername(struct socket *sock)
5306 {
5307 	return sock_has_perm(sock->sk, SOCKET__GETATTR);
5308 }
5309 
5310 static int selinux_socket_setsockopt(struct socket *sock, int level, int optname)
5311 {
5312 	int err;
5313 
5314 	err = sock_has_perm(sock->sk, SOCKET__SETOPT);
5315 	if (err)
5316 		return err;
5317 
5318 	return selinux_netlbl_socket_setsockopt(sock, level, optname);
5319 }
5320 
5321 static int selinux_socket_getsockopt(struct socket *sock, int level,
5322 				     int optname)
5323 {
5324 	return sock_has_perm(sock->sk, SOCKET__GETOPT);
5325 }
5326 
5327 static int selinux_socket_shutdown(struct socket *sock, int how)
5328 {
5329 	return sock_has_perm(sock->sk, SOCKET__SHUTDOWN);
5330 }
5331 
5332 static int selinux_socket_unix_stream_connect(struct sock *sock,
5333 					      struct sock *other,
5334 					      struct sock *newsk)
5335 {
5336 	struct sk_security_struct *sksec_sock = selinux_sock(sock);
5337 	struct sk_security_struct *sksec_other = selinux_sock(other);
5338 	struct sk_security_struct *sksec_new = selinux_sock(newsk);
5339 	struct common_audit_data ad;
5340 	struct lsm_network_audit net;
5341 	int err;
5342 
5343 	ad_net_init_from_sk(&ad, &net, other);
5344 
5345 	err = avc_has_perm(sksec_sock->sid, sksec_other->sid,
5346 			   sksec_other->sclass,
5347 			   UNIX_STREAM_SOCKET__CONNECTTO, &ad);
5348 	if (err)
5349 		return err;
5350 
5351 	/* server child socket */
5352 	sksec_new->peer_sid = sksec_sock->sid;
5353 	err = security_sid_mls_copy(sksec_other->sid,
5354 				    sksec_sock->sid, &sksec_new->sid);
5355 	if (err)
5356 		return err;
5357 
5358 	/* connecting socket */
5359 	sksec_sock->peer_sid = sksec_new->sid;
5360 
5361 	return 0;
5362 }
5363 
5364 static int selinux_socket_unix_may_send(struct socket *sock,
5365 					struct socket *other)
5366 {
5367 	struct sk_security_struct *ssec = selinux_sock(sock->sk);
5368 	struct sk_security_struct *osec = selinux_sock(other->sk);
5369 	struct common_audit_data ad;
5370 	struct lsm_network_audit net;
5371 
5372 	ad_net_init_from_sk(&ad, &net, other->sk);
5373 
5374 	return avc_has_perm(ssec->sid, osec->sid, osec->sclass, SOCKET__SENDTO,
5375 			    &ad);
5376 }
5377 
5378 static int selinux_inet_sys_rcv_skb(struct net *ns, int ifindex,
5379 				    char *addrp, u16 family, u32 peer_sid,
5380 				    struct common_audit_data *ad)
5381 {
5382 	int err;
5383 	u32 if_sid;
5384 	u32 node_sid;
5385 
5386 	err = sel_netif_sid(ns, ifindex, &if_sid);
5387 	if (err)
5388 		return err;
5389 	err = avc_has_perm(peer_sid, if_sid,
5390 			   SECCLASS_NETIF, NETIF__INGRESS, ad);
5391 	if (err)
5392 		return err;
5393 
5394 	err = sel_netnode_sid(addrp, family, &node_sid);
5395 	if (err)
5396 		return err;
5397 	return avc_has_perm(peer_sid, node_sid,
5398 			    SECCLASS_NODE, NODE__RECVFROM, ad);
5399 }
5400 
5401 static int selinux_sock_rcv_skb_compat(struct sock *sk, struct sk_buff *skb,
5402 				       u16 family)
5403 {
5404 	int err = 0;
5405 	struct sk_security_struct *sksec = selinux_sock(sk);
5406 	u32 sk_sid = sksec->sid;
5407 	struct common_audit_data ad;
5408 	struct lsm_network_audit net;
5409 	char *addrp;
5410 
5411 	ad_net_init_from_iif(&ad, &net, skb->skb_iif, family);
5412 	err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
5413 	if (err)
5414 		return err;
5415 
5416 	if (selinux_secmark_enabled()) {
5417 		err = avc_has_perm(sk_sid, skb->secmark, SECCLASS_PACKET,
5418 				   PACKET__RECV, &ad);
5419 		if (err)
5420 			return err;
5421 	}
5422 
5423 	err = selinux_netlbl_sock_rcv_skb(sksec, skb, family, &ad);
5424 	if (err)
5425 		return err;
5426 	err = selinux_xfrm_sock_rcv_skb(sksec->sid, skb, &ad);
5427 
5428 	return err;
5429 }
5430 
5431 static int selinux_socket_sock_rcv_skb(struct sock *sk, struct sk_buff *skb)
5432 {
5433 	int err, peerlbl_active, secmark_active;
5434 	struct sk_security_struct *sksec = selinux_sock(sk);
5435 	u16 family = sk->sk_family;
5436 	u32 sk_sid = sksec->sid;
5437 	struct common_audit_data ad;
5438 	struct lsm_network_audit net;
5439 	char *addrp;
5440 
5441 	if (family != PF_INET && family != PF_INET6)
5442 		return 0;
5443 
5444 	/* Handle mapped IPv4 packets arriving via IPv6 sockets */
5445 	if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
5446 		family = PF_INET;
5447 
5448 	/* If any sort of compatibility mode is enabled then handoff processing
5449 	 * to the selinux_sock_rcv_skb_compat() function to deal with the
5450 	 * special handling.  We do this in an attempt to keep this function
5451 	 * as fast and as clean as possible. */
5452 	if (!selinux_policycap_netpeer())
5453 		return selinux_sock_rcv_skb_compat(sk, skb, family);
5454 
5455 	secmark_active = selinux_secmark_enabled();
5456 	peerlbl_active = selinux_peerlbl_enabled();
5457 	if (!secmark_active && !peerlbl_active)
5458 		return 0;
5459 
5460 	ad_net_init_from_iif(&ad, &net, skb->skb_iif, family);
5461 	err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
5462 	if (err)
5463 		return err;
5464 
5465 	if (peerlbl_active) {
5466 		u32 peer_sid;
5467 
5468 		err = selinux_skb_peerlbl_sid(skb, family, &peer_sid);
5469 		if (err)
5470 			return err;
5471 		err = selinux_inet_sys_rcv_skb(sock_net(sk), skb->skb_iif,
5472 					       addrp, family, peer_sid, &ad);
5473 		if (err) {
5474 			selinux_netlbl_err(skb, family, err, 0);
5475 			return err;
5476 		}
5477 		err = avc_has_perm(sk_sid, peer_sid, SECCLASS_PEER,
5478 				   PEER__RECV, &ad);
5479 		if (err) {
5480 			selinux_netlbl_err(skb, family, err, 0);
5481 			return err;
5482 		}
5483 	}
5484 
5485 	if (secmark_active) {
5486 		err = avc_has_perm(sk_sid, skb->secmark, SECCLASS_PACKET,
5487 				   PACKET__RECV, &ad);
5488 		if (err)
5489 			return err;
5490 	}
5491 
5492 	return err;
5493 }
5494 
5495 static int selinux_socket_getpeersec_stream(struct socket *sock,
5496 					    sockptr_t optval, sockptr_t optlen,
5497 					    unsigned int len)
5498 {
5499 	int err = 0;
5500 	char *scontext = NULL;
5501 	u32 scontext_len;
5502 	struct sk_security_struct *sksec = selinux_sock(sock->sk);
5503 	u32 peer_sid = SECSID_NULL;
5504 
5505 	if (sksec->sclass == SECCLASS_UNIX_STREAM_SOCKET ||
5506 	    sksec->sclass == SECCLASS_TCP_SOCKET ||
5507 	    sksec->sclass == SECCLASS_SCTP_SOCKET)
5508 		peer_sid = sksec->peer_sid;
5509 	if (peer_sid == SECSID_NULL)
5510 		return -ENOPROTOOPT;
5511 
5512 	err = security_sid_to_context(peer_sid, &scontext,
5513 				      &scontext_len);
5514 	if (err)
5515 		return err;
5516 	if (scontext_len > len) {
5517 		err = -ERANGE;
5518 		goto out_len;
5519 	}
5520 
5521 	if (copy_to_sockptr(optval, scontext, scontext_len))
5522 		err = -EFAULT;
5523 out_len:
5524 	if (copy_to_sockptr(optlen, &scontext_len, sizeof(scontext_len)))
5525 		err = -EFAULT;
5526 	kfree(scontext);
5527 	return err;
5528 }
5529 
5530 static int selinux_socket_getpeersec_dgram(struct socket *sock,
5531 					   struct sk_buff *skb, u32 *secid)
5532 {
5533 	u32 peer_secid = SECSID_NULL;
5534 	u16 family;
5535 
5536 	if (skb && skb->protocol == htons(ETH_P_IP))
5537 		family = PF_INET;
5538 	else if (skb && skb->protocol == htons(ETH_P_IPV6))
5539 		family = PF_INET6;
5540 	else if (sock)
5541 		family = sock->sk->sk_family;
5542 	else {
5543 		*secid = SECSID_NULL;
5544 		return -EINVAL;
5545 	}
5546 
5547 	if (sock && family == PF_UNIX) {
5548 		struct inode_security_struct *isec;
5549 		isec = inode_security_novalidate(SOCK_INODE(sock));
5550 		peer_secid = isec->sid;
5551 	} else if (skb)
5552 		selinux_skb_peerlbl_sid(skb, family, &peer_secid);
5553 
5554 	*secid = peer_secid;
5555 	if (peer_secid == SECSID_NULL)
5556 		return -ENOPROTOOPT;
5557 	return 0;
5558 }
5559 
5560 static int selinux_sk_alloc_security(struct sock *sk, int family, gfp_t priority)
5561 {
5562 	struct sk_security_struct *sksec = selinux_sock(sk);
5563 
5564 	sksec->peer_sid = SECINITSID_UNLABELED;
5565 	sksec->sid = SECINITSID_UNLABELED;
5566 	sksec->sclass = SECCLASS_SOCKET;
5567 	selinux_netlbl_sk_security_reset(sksec);
5568 
5569 	return 0;
5570 }
5571 
5572 static void selinux_sk_free_security(struct sock *sk)
5573 {
5574 	struct sk_security_struct *sksec = selinux_sock(sk);
5575 
5576 	selinux_netlbl_sk_security_free(sksec);
5577 }
5578 
5579 static void selinux_sk_clone_security(const struct sock *sk, struct sock *newsk)
5580 {
5581 	struct sk_security_struct *sksec = selinux_sock(sk);
5582 	struct sk_security_struct *newsksec = selinux_sock(newsk);
5583 
5584 	newsksec->sid = sksec->sid;
5585 	newsksec->peer_sid = sksec->peer_sid;
5586 	newsksec->sclass = sksec->sclass;
5587 
5588 	selinux_netlbl_sk_security_reset(newsksec);
5589 }
5590 
5591 static void selinux_sk_getsecid(const struct sock *sk, u32 *secid)
5592 {
5593 	if (!sk)
5594 		*secid = SECINITSID_ANY_SOCKET;
5595 	else {
5596 		const struct sk_security_struct *sksec = selinux_sock(sk);
5597 
5598 		*secid = sksec->sid;
5599 	}
5600 }
5601 
5602 static void selinux_sock_graft(struct sock *sk, struct socket *parent)
5603 {
5604 	struct inode_security_struct *isec =
5605 		inode_security_novalidate(SOCK_INODE(parent));
5606 	struct sk_security_struct *sksec = selinux_sock(sk);
5607 
5608 	if (sk->sk_family == PF_INET || sk->sk_family == PF_INET6 ||
5609 	    sk->sk_family == PF_UNIX)
5610 		isec->sid = sksec->sid;
5611 	sksec->sclass = isec->sclass;
5612 }
5613 
5614 /*
5615  * Determines peer_secid for the asoc and updates socket's peer label
5616  * if it's the first association on the socket.
5617  */
5618 static int selinux_sctp_process_new_assoc(struct sctp_association *asoc,
5619 					  struct sk_buff *skb)
5620 {
5621 	struct sock *sk = asoc->base.sk;
5622 	u16 family = sk->sk_family;
5623 	struct sk_security_struct *sksec = selinux_sock(sk);
5624 	struct common_audit_data ad;
5625 	struct lsm_network_audit net;
5626 	int err;
5627 
5628 	/* handle mapped IPv4 packets arriving via IPv6 sockets */
5629 	if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
5630 		family = PF_INET;
5631 
5632 	if (selinux_peerlbl_enabled()) {
5633 		asoc->peer_secid = SECSID_NULL;
5634 
5635 		/* This will return peer_sid = SECSID_NULL if there are
5636 		 * no peer labels, see security_net_peersid_resolve().
5637 		 */
5638 		err = selinux_skb_peerlbl_sid(skb, family, &asoc->peer_secid);
5639 		if (err)
5640 			return err;
5641 
5642 		if (asoc->peer_secid == SECSID_NULL)
5643 			asoc->peer_secid = SECINITSID_UNLABELED;
5644 	} else {
5645 		asoc->peer_secid = SECINITSID_UNLABELED;
5646 	}
5647 
5648 	if (sksec->sctp_assoc_state == SCTP_ASSOC_UNSET) {
5649 		sksec->sctp_assoc_state = SCTP_ASSOC_SET;
5650 
5651 		/* Here as first association on socket. As the peer SID
5652 		 * was allowed by peer recv (and the netif/node checks),
5653 		 * then it is approved by policy and used as the primary
5654 		 * peer SID for getpeercon(3).
5655 		 */
5656 		sksec->peer_sid = asoc->peer_secid;
5657 	} else if (sksec->peer_sid != asoc->peer_secid) {
5658 		/* Other association peer SIDs are checked to enforce
5659 		 * consistency among the peer SIDs.
5660 		 */
5661 		ad_net_init_from_sk(&ad, &net, asoc->base.sk);
5662 		err = avc_has_perm(sksec->peer_sid, asoc->peer_secid,
5663 				   sksec->sclass, SCTP_SOCKET__ASSOCIATION,
5664 				   &ad);
5665 		if (err)
5666 			return err;
5667 	}
5668 	return 0;
5669 }
5670 
5671 /* Called whenever SCTP receives an INIT or COOKIE ECHO chunk. This
5672  * happens on an incoming connect(2), sctp_connectx(3) or
5673  * sctp_sendmsg(3) (with no association already present).
5674  */
5675 static int selinux_sctp_assoc_request(struct sctp_association *asoc,
5676 				      struct sk_buff *skb)
5677 {
5678 	struct sk_security_struct *sksec = selinux_sock(asoc->base.sk);
5679 	u32 conn_sid;
5680 	int err;
5681 
5682 	if (!selinux_policycap_extsockclass())
5683 		return 0;
5684 
5685 	err = selinux_sctp_process_new_assoc(asoc, skb);
5686 	if (err)
5687 		return err;
5688 
5689 	/* Compute the MLS component for the connection and store
5690 	 * the information in asoc. This will be used by SCTP TCP type
5691 	 * sockets and peeled off connections as they cause a new
5692 	 * socket to be generated. selinux_sctp_sk_clone() will then
5693 	 * plug this into the new socket.
5694 	 */
5695 	err = selinux_conn_sid(sksec->sid, asoc->peer_secid, &conn_sid);
5696 	if (err)
5697 		return err;
5698 
5699 	asoc->secid = conn_sid;
5700 
5701 	/* Set any NetLabel labels including CIPSO/CALIPSO options. */
5702 	return selinux_netlbl_sctp_assoc_request(asoc, skb);
5703 }
5704 
5705 /* Called when SCTP receives a COOKIE ACK chunk as the final
5706  * response to an association request (initited by us).
5707  */
5708 static int selinux_sctp_assoc_established(struct sctp_association *asoc,
5709 					  struct sk_buff *skb)
5710 {
5711 	struct sk_security_struct *sksec = selinux_sock(asoc->base.sk);
5712 
5713 	if (!selinux_policycap_extsockclass())
5714 		return 0;
5715 
5716 	/* Inherit secid from the parent socket - this will be picked up
5717 	 * by selinux_sctp_sk_clone() if the association gets peeled off
5718 	 * into a new socket.
5719 	 */
5720 	asoc->secid = sksec->sid;
5721 
5722 	return selinux_sctp_process_new_assoc(asoc, skb);
5723 }
5724 
5725 /* Check if sctp IPv4/IPv6 addresses are valid for binding or connecting
5726  * based on their @optname.
5727  */
5728 static int selinux_sctp_bind_connect(struct sock *sk, int optname,
5729 				     struct sockaddr *address,
5730 				     int addrlen)
5731 {
5732 	int len, err = 0, walk_size = 0;
5733 	void *addr_buf;
5734 	struct sockaddr *addr;
5735 
5736 	if (!selinux_policycap_extsockclass())
5737 		return 0;
5738 
5739 	/* Process one or more addresses that may be IPv4 or IPv6 */
5740 	addr_buf = address;
5741 
5742 	while (walk_size < addrlen) {
5743 		if (walk_size + sizeof(sa_family_t) > addrlen)
5744 			return -EINVAL;
5745 
5746 		addr = addr_buf;
5747 		switch (addr->sa_family) {
5748 		case AF_UNSPEC:
5749 		case AF_INET:
5750 			len = sizeof(struct sockaddr_in);
5751 			break;
5752 		case AF_INET6:
5753 			len = sizeof(struct sockaddr_in6);
5754 			break;
5755 		default:
5756 			return -EINVAL;
5757 		}
5758 
5759 		if (walk_size + len > addrlen)
5760 			return -EINVAL;
5761 
5762 		err = -EINVAL;
5763 		switch (optname) {
5764 		/* Bind checks */
5765 		case SCTP_PRIMARY_ADDR:
5766 		case SCTP_SET_PEER_PRIMARY_ADDR:
5767 		case SCTP_SOCKOPT_BINDX_ADD:
5768 			err = __selinux_socket_bind(sk, addr, len);
5769 			break;
5770 		/* Connect checks */
5771 		case SCTP_SOCKOPT_CONNECTX:
5772 		case SCTP_PARAM_SET_PRIMARY:
5773 		case SCTP_PARAM_ADD_IP:
5774 		case SCTP_SENDMSG_CONNECT:
5775 			err = selinux_socket_connect_helper(sk, addr, len);
5776 			if (err)
5777 				return err;
5778 
5779 			/* As selinux_sctp_bind_connect() is called by the
5780 			 * SCTP protocol layer, the socket is already locked,
5781 			 * therefore selinux_netlbl_socket_connect_locked()
5782 			 * is called here. The situations handled are:
5783 			 * sctp_connectx(3), sctp_sendmsg(3), sendmsg(2),
5784 			 * whenever a new IP address is added or when a new
5785 			 * primary address is selected.
5786 			 * Note that an SCTP connect(2) call happens before
5787 			 * the SCTP protocol layer and is handled via
5788 			 * selinux_socket_connect().
5789 			 */
5790 			err = selinux_netlbl_socket_connect_locked(sk, addr);
5791 			break;
5792 		}
5793 
5794 		if (err)
5795 			return err;
5796 
5797 		addr_buf += len;
5798 		walk_size += len;
5799 	}
5800 
5801 	return 0;
5802 }
5803 
5804 /* Called whenever a new socket is created by accept(2) or sctp_peeloff(3). */
5805 static void selinux_sctp_sk_clone(struct sctp_association *asoc, struct sock *sk,
5806 				  struct sock *newsk)
5807 {
5808 	struct sk_security_struct *sksec = selinux_sock(sk);
5809 	struct sk_security_struct *newsksec = selinux_sock(newsk);
5810 
5811 	/* If policy does not support SECCLASS_SCTP_SOCKET then call
5812 	 * the non-sctp clone version.
5813 	 */
5814 	if (!selinux_policycap_extsockclass())
5815 		return selinux_sk_clone_security(sk, newsk);
5816 
5817 	newsksec->sid = asoc->secid;
5818 	newsksec->peer_sid = asoc->peer_secid;
5819 	newsksec->sclass = sksec->sclass;
5820 	selinux_netlbl_sctp_sk_clone(sk, newsk);
5821 }
5822 
5823 static int selinux_mptcp_add_subflow(struct sock *sk, struct sock *ssk)
5824 {
5825 	struct sk_security_struct *ssksec = selinux_sock(ssk);
5826 	struct sk_security_struct *sksec = selinux_sock(sk);
5827 
5828 	ssksec->sclass = sksec->sclass;
5829 	ssksec->sid = sksec->sid;
5830 
5831 	/* replace the existing subflow label deleting the existing one
5832 	 * and re-recreating a new label using the updated context
5833 	 */
5834 	selinux_netlbl_sk_security_free(ssksec);
5835 	return selinux_netlbl_socket_post_create(ssk, ssk->sk_family);
5836 }
5837 
5838 static int selinux_inet_conn_request(const struct sock *sk, struct sk_buff *skb,
5839 				     struct request_sock *req)
5840 {
5841 	struct sk_security_struct *sksec = selinux_sock(sk);
5842 	int err;
5843 	u16 family = req->rsk_ops->family;
5844 	u32 connsid;
5845 	u32 peersid;
5846 
5847 	err = selinux_skb_peerlbl_sid(skb, family, &peersid);
5848 	if (err)
5849 		return err;
5850 	err = selinux_conn_sid(sksec->sid, peersid, &connsid);
5851 	if (err)
5852 		return err;
5853 	req->secid = connsid;
5854 	req->peer_secid = peersid;
5855 
5856 	return selinux_netlbl_inet_conn_request(req, family);
5857 }
5858 
5859 static void selinux_inet_csk_clone(struct sock *newsk,
5860 				   const struct request_sock *req)
5861 {
5862 	struct sk_security_struct *newsksec = selinux_sock(newsk);
5863 
5864 	newsksec->sid = req->secid;
5865 	newsksec->peer_sid = req->peer_secid;
5866 	/* NOTE: Ideally, we should also get the isec->sid for the
5867 	   new socket in sync, but we don't have the isec available yet.
5868 	   So we will wait until sock_graft to do it, by which
5869 	   time it will have been created and available. */
5870 
5871 	/* We don't need to take any sort of lock here as we are the only
5872 	 * thread with access to newsksec */
5873 	selinux_netlbl_inet_csk_clone(newsk, req->rsk_ops->family);
5874 }
5875 
5876 static void selinux_inet_conn_established(struct sock *sk, struct sk_buff *skb)
5877 {
5878 	u16 family = sk->sk_family;
5879 	struct sk_security_struct *sksec = selinux_sock(sk);
5880 
5881 	/* handle mapped IPv4 packets arriving via IPv6 sockets */
5882 	if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
5883 		family = PF_INET;
5884 
5885 	selinux_skb_peerlbl_sid(skb, family, &sksec->peer_sid);
5886 }
5887 
5888 static int selinux_secmark_relabel_packet(u32 sid)
5889 {
5890 	return avc_has_perm(current_sid(), sid, SECCLASS_PACKET, PACKET__RELABELTO,
5891 			    NULL);
5892 }
5893 
5894 static void selinux_secmark_refcount_inc(void)
5895 {
5896 	atomic_inc(&selinux_secmark_refcount);
5897 }
5898 
5899 static void selinux_secmark_refcount_dec(void)
5900 {
5901 	atomic_dec(&selinux_secmark_refcount);
5902 }
5903 
5904 static void selinux_req_classify_flow(const struct request_sock *req,
5905 				      struct flowi_common *flic)
5906 {
5907 	flic->flowic_secid = req->secid;
5908 }
5909 
5910 static int selinux_tun_dev_alloc_security(void *security)
5911 {
5912 	struct tun_security_struct *tunsec = selinux_tun_dev(security);
5913 
5914 	tunsec->sid = current_sid();
5915 	return 0;
5916 }
5917 
5918 static int selinux_tun_dev_create(void)
5919 {
5920 	u32 sid = current_sid();
5921 
5922 	/* we aren't taking into account the "sockcreate" SID since the socket
5923 	 * that is being created here is not a socket in the traditional sense,
5924 	 * instead it is a private sock, accessible only to the kernel, and
5925 	 * representing a wide range of network traffic spanning multiple
5926 	 * connections unlike traditional sockets - check the TUN driver to
5927 	 * get a better understanding of why this socket is special */
5928 
5929 	return avc_has_perm(sid, sid, SECCLASS_TUN_SOCKET, TUN_SOCKET__CREATE,
5930 			    NULL);
5931 }
5932 
5933 static int selinux_tun_dev_attach_queue(void *security)
5934 {
5935 	struct tun_security_struct *tunsec = selinux_tun_dev(security);
5936 
5937 	return avc_has_perm(current_sid(), tunsec->sid, SECCLASS_TUN_SOCKET,
5938 			    TUN_SOCKET__ATTACH_QUEUE, NULL);
5939 }
5940 
5941 static int selinux_tun_dev_attach(struct sock *sk, void *security)
5942 {
5943 	struct tun_security_struct *tunsec = selinux_tun_dev(security);
5944 	struct sk_security_struct *sksec = selinux_sock(sk);
5945 
5946 	/* we don't currently perform any NetLabel based labeling here and it
5947 	 * isn't clear that we would want to do so anyway; while we could apply
5948 	 * labeling without the support of the TUN user the resulting labeled
5949 	 * traffic from the other end of the connection would almost certainly
5950 	 * cause confusion to the TUN user that had no idea network labeling
5951 	 * protocols were being used */
5952 
5953 	sksec->sid = tunsec->sid;
5954 	sksec->sclass = SECCLASS_TUN_SOCKET;
5955 
5956 	return 0;
5957 }
5958 
5959 static int selinux_tun_dev_open(void *security)
5960 {
5961 	struct tun_security_struct *tunsec = selinux_tun_dev(security);
5962 	u32 sid = current_sid();
5963 	int err;
5964 
5965 	err = avc_has_perm(sid, tunsec->sid, SECCLASS_TUN_SOCKET,
5966 			   TUN_SOCKET__RELABELFROM, NULL);
5967 	if (err)
5968 		return err;
5969 	err = avc_has_perm(sid, sid, SECCLASS_TUN_SOCKET,
5970 			   TUN_SOCKET__RELABELTO, NULL);
5971 	if (err)
5972 		return err;
5973 	tunsec->sid = sid;
5974 
5975 	return 0;
5976 }
5977 
5978 #ifdef CONFIG_NETFILTER
5979 
5980 static unsigned int selinux_ip_forward(void *priv, struct sk_buff *skb,
5981 				       const struct nf_hook_state *state)
5982 {
5983 	int ifindex;
5984 	u16 family;
5985 	char *addrp;
5986 	u32 peer_sid;
5987 	struct common_audit_data ad;
5988 	struct lsm_network_audit net;
5989 	int secmark_active, peerlbl_active;
5990 
5991 	if (!selinux_policycap_netpeer())
5992 		return NF_ACCEPT;
5993 
5994 	secmark_active = selinux_secmark_enabled();
5995 	peerlbl_active = selinux_peerlbl_enabled();
5996 	if (!secmark_active && !peerlbl_active)
5997 		return NF_ACCEPT;
5998 
5999 	family = state->pf;
6000 	if (selinux_skb_peerlbl_sid(skb, family, &peer_sid) != 0)
6001 		return NF_DROP;
6002 
6003 	ifindex = state->in->ifindex;
6004 	ad_net_init_from_iif(&ad, &net, ifindex, family);
6005 	if (selinux_parse_skb(skb, &ad, &addrp, 1, NULL) != 0)
6006 		return NF_DROP;
6007 
6008 	if (peerlbl_active) {
6009 		int err;
6010 
6011 		err = selinux_inet_sys_rcv_skb(state->net, ifindex,
6012 					       addrp, family, peer_sid, &ad);
6013 		if (err) {
6014 			selinux_netlbl_err(skb, family, err, 1);
6015 			return NF_DROP;
6016 		}
6017 	}
6018 
6019 	if (secmark_active)
6020 		if (avc_has_perm(peer_sid, skb->secmark,
6021 				 SECCLASS_PACKET, PACKET__FORWARD_IN, &ad))
6022 			return NF_DROP;
6023 
6024 	if (netlbl_enabled())
6025 		/* we do this in the FORWARD path and not the POST_ROUTING
6026 		 * path because we want to make sure we apply the necessary
6027 		 * labeling before IPsec is applied so we can leverage AH
6028 		 * protection */
6029 		if (selinux_netlbl_skbuff_setsid(skb, family, peer_sid) != 0)
6030 			return NF_DROP;
6031 
6032 	return NF_ACCEPT;
6033 }
6034 
6035 static unsigned int selinux_ip_output(void *priv, struct sk_buff *skb,
6036 				      const struct nf_hook_state *state)
6037 {
6038 	struct sock *sk;
6039 	u32 sid;
6040 
6041 	if (!netlbl_enabled())
6042 		return NF_ACCEPT;
6043 
6044 	/* we do this in the LOCAL_OUT path and not the POST_ROUTING path
6045 	 * because we want to make sure we apply the necessary labeling
6046 	 * before IPsec is applied so we can leverage AH protection */
6047 	sk = skb_to_full_sk(skb);
6048 	if (sk) {
6049 		struct sk_security_struct *sksec;
6050 
6051 		if (sk_listener(sk))
6052 			/* if the socket is the listening state then this
6053 			 * packet is a SYN-ACK packet which means it needs to
6054 			 * be labeled based on the connection/request_sock and
6055 			 * not the parent socket.  unfortunately, we can't
6056 			 * lookup the request_sock yet as it isn't queued on
6057 			 * the parent socket until after the SYN-ACK is sent.
6058 			 * the "solution" is to simply pass the packet as-is
6059 			 * as any IP option based labeling should be copied
6060 			 * from the initial connection request (in the IP
6061 			 * layer).  it is far from ideal, but until we get a
6062 			 * security label in the packet itself this is the
6063 			 * best we can do. */
6064 			return NF_ACCEPT;
6065 
6066 		/* standard practice, label using the parent socket */
6067 		sksec = selinux_sock(sk);
6068 		sid = sksec->sid;
6069 	} else
6070 		sid = SECINITSID_KERNEL;
6071 	if (selinux_netlbl_skbuff_setsid(skb, state->pf, sid) != 0)
6072 		return NF_DROP;
6073 
6074 	return NF_ACCEPT;
6075 }
6076 
6077 
6078 static unsigned int selinux_ip_postroute_compat(struct sk_buff *skb,
6079 					const struct nf_hook_state *state)
6080 {
6081 	struct sock *sk;
6082 	struct sk_security_struct *sksec;
6083 	struct common_audit_data ad;
6084 	struct lsm_network_audit net;
6085 	u8 proto = 0;
6086 
6087 	sk = skb_to_full_sk(skb);
6088 	if (sk == NULL)
6089 		return NF_ACCEPT;
6090 	sksec = selinux_sock(sk);
6091 
6092 	ad_net_init_from_iif(&ad, &net, state->out->ifindex, state->pf);
6093 	if (selinux_parse_skb(skb, &ad, NULL, 0, &proto))
6094 		return NF_DROP;
6095 
6096 	if (selinux_secmark_enabled())
6097 		if (avc_has_perm(sksec->sid, skb->secmark,
6098 				 SECCLASS_PACKET, PACKET__SEND, &ad))
6099 			return NF_DROP_ERR(-ECONNREFUSED);
6100 
6101 	if (selinux_xfrm_postroute_last(sksec->sid, skb, &ad, proto))
6102 		return NF_DROP_ERR(-ECONNREFUSED);
6103 
6104 	return NF_ACCEPT;
6105 }
6106 
6107 static unsigned int selinux_ip_postroute(void *priv,
6108 					 struct sk_buff *skb,
6109 					 const struct nf_hook_state *state)
6110 {
6111 	u16 family;
6112 	u32 secmark_perm;
6113 	u32 peer_sid;
6114 	int ifindex;
6115 	struct sock *sk;
6116 	struct common_audit_data ad;
6117 	struct lsm_network_audit net;
6118 	char *addrp;
6119 	int secmark_active, peerlbl_active;
6120 
6121 	/* If any sort of compatibility mode is enabled then handoff processing
6122 	 * to the selinux_ip_postroute_compat() function to deal with the
6123 	 * special handling.  We do this in an attempt to keep this function
6124 	 * as fast and as clean as possible. */
6125 	if (!selinux_policycap_netpeer())
6126 		return selinux_ip_postroute_compat(skb, state);
6127 
6128 	secmark_active = selinux_secmark_enabled();
6129 	peerlbl_active = selinux_peerlbl_enabled();
6130 	if (!secmark_active && !peerlbl_active)
6131 		return NF_ACCEPT;
6132 
6133 	sk = skb_to_full_sk(skb);
6134 
6135 #ifdef CONFIG_XFRM
6136 	/* If skb->dst->xfrm is non-NULL then the packet is undergoing an IPsec
6137 	 * packet transformation so allow the packet to pass without any checks
6138 	 * since we'll have another chance to perform access control checks
6139 	 * when the packet is on it's final way out.
6140 	 * NOTE: there appear to be some IPv6 multicast cases where skb->dst
6141 	 *       is NULL, in this case go ahead and apply access control.
6142 	 * NOTE: if this is a local socket (skb->sk != NULL) that is in the
6143 	 *       TCP listening state we cannot wait until the XFRM processing
6144 	 *       is done as we will miss out on the SA label if we do;
6145 	 *       unfortunately, this means more work, but it is only once per
6146 	 *       connection. */
6147 	if (skb_dst(skb) != NULL && skb_dst(skb)->xfrm != NULL &&
6148 	    !(sk && sk_listener(sk)))
6149 		return NF_ACCEPT;
6150 #endif
6151 
6152 	family = state->pf;
6153 	if (sk == NULL) {
6154 		/* Without an associated socket the packet is either coming
6155 		 * from the kernel or it is being forwarded; check the packet
6156 		 * to determine which and if the packet is being forwarded
6157 		 * query the packet directly to determine the security label. */
6158 		if (skb->skb_iif) {
6159 			secmark_perm = PACKET__FORWARD_OUT;
6160 			if (selinux_skb_peerlbl_sid(skb, family, &peer_sid))
6161 				return NF_DROP;
6162 		} else {
6163 			secmark_perm = PACKET__SEND;
6164 			peer_sid = SECINITSID_KERNEL;
6165 		}
6166 	} else if (sk_listener(sk)) {
6167 		/* Locally generated packet but the associated socket is in the
6168 		 * listening state which means this is a SYN-ACK packet.  In
6169 		 * this particular case the correct security label is assigned
6170 		 * to the connection/request_sock but unfortunately we can't
6171 		 * query the request_sock as it isn't queued on the parent
6172 		 * socket until after the SYN-ACK packet is sent; the only
6173 		 * viable choice is to regenerate the label like we do in
6174 		 * selinux_inet_conn_request().  See also selinux_ip_output()
6175 		 * for similar problems. */
6176 		u32 skb_sid;
6177 		struct sk_security_struct *sksec;
6178 
6179 		sksec = selinux_sock(sk);
6180 		if (selinux_skb_peerlbl_sid(skb, family, &skb_sid))
6181 			return NF_DROP;
6182 		/* At this point, if the returned skb peerlbl is SECSID_NULL
6183 		 * and the packet has been through at least one XFRM
6184 		 * transformation then we must be dealing with the "final"
6185 		 * form of labeled IPsec packet; since we've already applied
6186 		 * all of our access controls on this packet we can safely
6187 		 * pass the packet. */
6188 		if (skb_sid == SECSID_NULL) {
6189 			switch (family) {
6190 			case PF_INET:
6191 				if (IPCB(skb)->flags & IPSKB_XFRM_TRANSFORMED)
6192 					return NF_ACCEPT;
6193 				break;
6194 			case PF_INET6:
6195 				if (IP6CB(skb)->flags & IP6SKB_XFRM_TRANSFORMED)
6196 					return NF_ACCEPT;
6197 				break;
6198 			default:
6199 				return NF_DROP_ERR(-ECONNREFUSED);
6200 			}
6201 		}
6202 		if (selinux_conn_sid(sksec->sid, skb_sid, &peer_sid))
6203 			return NF_DROP;
6204 		secmark_perm = PACKET__SEND;
6205 	} else {
6206 		/* Locally generated packet, fetch the security label from the
6207 		 * associated socket. */
6208 		struct sk_security_struct *sksec = selinux_sock(sk);
6209 		peer_sid = sksec->sid;
6210 		secmark_perm = PACKET__SEND;
6211 	}
6212 
6213 	ifindex = state->out->ifindex;
6214 	ad_net_init_from_iif(&ad, &net, ifindex, family);
6215 	if (selinux_parse_skb(skb, &ad, &addrp, 0, NULL))
6216 		return NF_DROP;
6217 
6218 	if (secmark_active)
6219 		if (avc_has_perm(peer_sid, skb->secmark,
6220 				 SECCLASS_PACKET, secmark_perm, &ad))
6221 			return NF_DROP_ERR(-ECONNREFUSED);
6222 
6223 	if (peerlbl_active) {
6224 		u32 if_sid;
6225 		u32 node_sid;
6226 
6227 		if (sel_netif_sid(state->net, ifindex, &if_sid))
6228 			return NF_DROP;
6229 		if (avc_has_perm(peer_sid, if_sid,
6230 				 SECCLASS_NETIF, NETIF__EGRESS, &ad))
6231 			return NF_DROP_ERR(-ECONNREFUSED);
6232 
6233 		if (sel_netnode_sid(addrp, family, &node_sid))
6234 			return NF_DROP;
6235 		if (avc_has_perm(peer_sid, node_sid,
6236 				 SECCLASS_NODE, NODE__SENDTO, &ad))
6237 			return NF_DROP_ERR(-ECONNREFUSED);
6238 	}
6239 
6240 	return NF_ACCEPT;
6241 }
6242 #endif	/* CONFIG_NETFILTER */
6243 
6244 static int nlmsg_sock_has_extended_perms(struct sock *sk, u32 perms, u16 nlmsg_type)
6245 {
6246 	struct sk_security_struct *sksec = selinux_sock(sk);
6247 	struct common_audit_data ad;
6248 	u8 driver;
6249 	u8 xperm;
6250 
6251 	if (sock_skip_has_perm(sksec->sid))
6252 		return 0;
6253 
6254 	ad.type = LSM_AUDIT_DATA_NLMSGTYPE;
6255 	ad.u.nlmsg_type = nlmsg_type;
6256 
6257 	driver = nlmsg_type >> 8;
6258 	xperm = nlmsg_type & 0xff;
6259 
6260 	return avc_has_extended_perms(current_sid(), sksec->sid, sksec->sclass,
6261 				      perms, driver, AVC_EXT_NLMSG, xperm, &ad);
6262 }
6263 
6264 static int selinux_netlink_send(struct sock *sk, struct sk_buff *skb)
6265 {
6266 	int rc = 0;
6267 	unsigned int msg_len;
6268 	unsigned int data_len = skb->len;
6269 	unsigned char *data = skb->data;
6270 	struct nlmsghdr *nlh;
6271 	struct sk_security_struct *sksec = selinux_sock(sk);
6272 	u16 sclass = sksec->sclass;
6273 	u32 perm;
6274 
6275 	while (data_len >= nlmsg_total_size(0)) {
6276 		nlh = (struct nlmsghdr *)data;
6277 
6278 		/* NOTE: the nlmsg_len field isn't reliably set by some netlink
6279 		 *       users which means we can't reject skb's with bogus
6280 		 *       length fields; our solution is to follow what
6281 		 *       netlink_rcv_skb() does and simply skip processing at
6282 		 *       messages with length fields that are clearly junk
6283 		 */
6284 		if (nlh->nlmsg_len < NLMSG_HDRLEN || nlh->nlmsg_len > data_len)
6285 			return 0;
6286 
6287 		rc = selinux_nlmsg_lookup(sclass, nlh->nlmsg_type, &perm);
6288 		if (rc == 0) {
6289 			if (selinux_policycap_netlink_xperm()) {
6290 				rc = nlmsg_sock_has_extended_perms(
6291 					sk, perm, nlh->nlmsg_type);
6292 			} else {
6293 				rc = sock_has_perm(sk, perm);
6294 			}
6295 			if (rc)
6296 				return rc;
6297 		} else if (rc == -EINVAL) {
6298 			/* -EINVAL is a missing msg/perm mapping */
6299 			pr_warn_ratelimited("SELinux: unrecognized netlink"
6300 				" message: protocol=%hu nlmsg_type=%hu sclass=%s"
6301 				" pid=%d comm=%s\n",
6302 				sk->sk_protocol, nlh->nlmsg_type,
6303 				secclass_map[sclass - 1].name,
6304 				task_pid_nr(current), current->comm);
6305 			if (enforcing_enabled() &&
6306 			    !security_get_allow_unknown())
6307 				return rc;
6308 			rc = 0;
6309 		} else if (rc == -ENOENT) {
6310 			/* -ENOENT is a missing socket/class mapping, ignore */
6311 			rc = 0;
6312 		} else {
6313 			return rc;
6314 		}
6315 
6316 		/* move to the next message after applying netlink padding */
6317 		msg_len = NLMSG_ALIGN(nlh->nlmsg_len);
6318 		if (msg_len >= data_len)
6319 			return 0;
6320 		data_len -= msg_len;
6321 		data += msg_len;
6322 	}
6323 
6324 	return rc;
6325 }
6326 
6327 static void ipc_init_security(struct ipc_security_struct *isec, u16 sclass)
6328 {
6329 	isec->sclass = sclass;
6330 	isec->sid = current_sid();
6331 }
6332 
6333 static int ipc_has_perm(struct kern_ipc_perm *ipc_perms,
6334 			u32 perms)
6335 {
6336 	struct ipc_security_struct *isec;
6337 	struct common_audit_data ad;
6338 	u32 sid = current_sid();
6339 
6340 	isec = selinux_ipc(ipc_perms);
6341 
6342 	ad.type = LSM_AUDIT_DATA_IPC;
6343 	ad.u.ipc_id = ipc_perms->key;
6344 
6345 	return avc_has_perm(sid, isec->sid, isec->sclass, perms, &ad);
6346 }
6347 
6348 static int selinux_msg_msg_alloc_security(struct msg_msg *msg)
6349 {
6350 	struct msg_security_struct *msec;
6351 
6352 	msec = selinux_msg_msg(msg);
6353 	msec->sid = SECINITSID_UNLABELED;
6354 
6355 	return 0;
6356 }
6357 
6358 /* message queue security operations */
6359 static int selinux_msg_queue_alloc_security(struct kern_ipc_perm *msq)
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 	ipc_init_security(isec, SECCLASS_MSGQ);
6367 
6368 	ad.type = LSM_AUDIT_DATA_IPC;
6369 	ad.u.ipc_id = msq->key;
6370 
6371 	return avc_has_perm(sid, isec->sid, SECCLASS_MSGQ,
6372 			    MSGQ__CREATE, &ad);
6373 }
6374 
6375 static int selinux_msg_queue_associate(struct kern_ipc_perm *msq, int msqflg)
6376 {
6377 	struct ipc_security_struct *isec;
6378 	struct common_audit_data ad;
6379 	u32 sid = current_sid();
6380 
6381 	isec = selinux_ipc(msq);
6382 
6383 	ad.type = LSM_AUDIT_DATA_IPC;
6384 	ad.u.ipc_id = msq->key;
6385 
6386 	return avc_has_perm(sid, isec->sid, SECCLASS_MSGQ,
6387 			    MSGQ__ASSOCIATE, &ad);
6388 }
6389 
6390 static int selinux_msg_queue_msgctl(struct kern_ipc_perm *msq, int cmd)
6391 {
6392 	u32 perms;
6393 
6394 	switch (cmd) {
6395 	case IPC_INFO:
6396 	case MSG_INFO:
6397 		/* No specific object, just general system-wide information. */
6398 		return avc_has_perm(current_sid(), SECINITSID_KERNEL,
6399 				    SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
6400 	case IPC_STAT:
6401 	case MSG_STAT:
6402 	case MSG_STAT_ANY:
6403 		perms = MSGQ__GETATTR | MSGQ__ASSOCIATE;
6404 		break;
6405 	case IPC_SET:
6406 		perms = MSGQ__SETATTR;
6407 		break;
6408 	case IPC_RMID:
6409 		perms = MSGQ__DESTROY;
6410 		break;
6411 	default:
6412 		return 0;
6413 	}
6414 
6415 	return ipc_has_perm(msq, perms);
6416 }
6417 
6418 static int selinux_msg_queue_msgsnd(struct kern_ipc_perm *msq, struct msg_msg *msg, int msqflg)
6419 {
6420 	struct ipc_security_struct *isec;
6421 	struct msg_security_struct *msec;
6422 	struct common_audit_data ad;
6423 	u32 sid = current_sid();
6424 	int rc;
6425 
6426 	isec = selinux_ipc(msq);
6427 	msec = selinux_msg_msg(msg);
6428 
6429 	/*
6430 	 * First time through, need to assign label to the message
6431 	 */
6432 	if (msec->sid == SECINITSID_UNLABELED) {
6433 		/*
6434 		 * Compute new sid based on current process and
6435 		 * message queue this message will be stored in
6436 		 */
6437 		rc = security_transition_sid(sid, isec->sid,
6438 					     SECCLASS_MSG, NULL, &msec->sid);
6439 		if (rc)
6440 			return rc;
6441 	}
6442 
6443 	ad.type = LSM_AUDIT_DATA_IPC;
6444 	ad.u.ipc_id = msq->key;
6445 
6446 	/* Can this process write to the queue? */
6447 	rc = avc_has_perm(sid, isec->sid, SECCLASS_MSGQ,
6448 			  MSGQ__WRITE, &ad);
6449 	if (!rc)
6450 		/* Can this process send the message */
6451 		rc = avc_has_perm(sid, msec->sid, SECCLASS_MSG,
6452 				  MSG__SEND, &ad);
6453 	if (!rc)
6454 		/* Can the message be put in the queue? */
6455 		rc = avc_has_perm(msec->sid, isec->sid, SECCLASS_MSGQ,
6456 				  MSGQ__ENQUEUE, &ad);
6457 
6458 	return rc;
6459 }
6460 
6461 static int selinux_msg_queue_msgrcv(struct kern_ipc_perm *msq, struct msg_msg *msg,
6462 				    struct task_struct *target,
6463 				    long type, int mode)
6464 {
6465 	struct ipc_security_struct *isec;
6466 	struct msg_security_struct *msec;
6467 	struct common_audit_data ad;
6468 	u32 sid = task_sid_obj(target);
6469 	int rc;
6470 
6471 	isec = selinux_ipc(msq);
6472 	msec = selinux_msg_msg(msg);
6473 
6474 	ad.type = LSM_AUDIT_DATA_IPC;
6475 	ad.u.ipc_id = msq->key;
6476 
6477 	rc = avc_has_perm(sid, isec->sid,
6478 			  SECCLASS_MSGQ, MSGQ__READ, &ad);
6479 	if (!rc)
6480 		rc = avc_has_perm(sid, msec->sid,
6481 				  SECCLASS_MSG, MSG__RECEIVE, &ad);
6482 	return rc;
6483 }
6484 
6485 /* Shared Memory security operations */
6486 static int selinux_shm_alloc_security(struct kern_ipc_perm *shp)
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 	ipc_init_security(isec, SECCLASS_SHM);
6494 
6495 	ad.type = LSM_AUDIT_DATA_IPC;
6496 	ad.u.ipc_id = shp->key;
6497 
6498 	return avc_has_perm(sid, isec->sid, SECCLASS_SHM,
6499 			    SHM__CREATE, &ad);
6500 }
6501 
6502 static int selinux_shm_associate(struct kern_ipc_perm *shp, int shmflg)
6503 {
6504 	struct ipc_security_struct *isec;
6505 	struct common_audit_data ad;
6506 	u32 sid = current_sid();
6507 
6508 	isec = selinux_ipc(shp);
6509 
6510 	ad.type = LSM_AUDIT_DATA_IPC;
6511 	ad.u.ipc_id = shp->key;
6512 
6513 	return avc_has_perm(sid, isec->sid, SECCLASS_SHM,
6514 			    SHM__ASSOCIATE, &ad);
6515 }
6516 
6517 /* Note, at this point, shp is locked down */
6518 static int selinux_shm_shmctl(struct kern_ipc_perm *shp, int cmd)
6519 {
6520 	u32 perms;
6521 
6522 	switch (cmd) {
6523 	case IPC_INFO:
6524 	case SHM_INFO:
6525 		/* No specific object, just general system-wide information. */
6526 		return avc_has_perm(current_sid(), SECINITSID_KERNEL,
6527 				    SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
6528 	case IPC_STAT:
6529 	case SHM_STAT:
6530 	case SHM_STAT_ANY:
6531 		perms = SHM__GETATTR | SHM__ASSOCIATE;
6532 		break;
6533 	case IPC_SET:
6534 		perms = SHM__SETATTR;
6535 		break;
6536 	case SHM_LOCK:
6537 	case SHM_UNLOCK:
6538 		perms = SHM__LOCK;
6539 		break;
6540 	case IPC_RMID:
6541 		perms = SHM__DESTROY;
6542 		break;
6543 	default:
6544 		return 0;
6545 	}
6546 
6547 	return ipc_has_perm(shp, perms);
6548 }
6549 
6550 static int selinux_shm_shmat(struct kern_ipc_perm *shp,
6551 			     char __user *shmaddr, int shmflg)
6552 {
6553 	u32 perms;
6554 
6555 	if (shmflg & SHM_RDONLY)
6556 		perms = SHM__READ;
6557 	else
6558 		perms = SHM__READ | SHM__WRITE;
6559 
6560 	return ipc_has_perm(shp, perms);
6561 }
6562 
6563 /* Semaphore security operations */
6564 static int selinux_sem_alloc_security(struct kern_ipc_perm *sma)
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 	ipc_init_security(isec, SECCLASS_SEM);
6572 
6573 	ad.type = LSM_AUDIT_DATA_IPC;
6574 	ad.u.ipc_id = sma->key;
6575 
6576 	return avc_has_perm(sid, isec->sid, SECCLASS_SEM,
6577 			    SEM__CREATE, &ad);
6578 }
6579 
6580 static int selinux_sem_associate(struct kern_ipc_perm *sma, int semflg)
6581 {
6582 	struct ipc_security_struct *isec;
6583 	struct common_audit_data ad;
6584 	u32 sid = current_sid();
6585 
6586 	isec = selinux_ipc(sma);
6587 
6588 	ad.type = LSM_AUDIT_DATA_IPC;
6589 	ad.u.ipc_id = sma->key;
6590 
6591 	return avc_has_perm(sid, isec->sid, SECCLASS_SEM,
6592 			    SEM__ASSOCIATE, &ad);
6593 }
6594 
6595 /* Note, at this point, sma is locked down */
6596 static int selinux_sem_semctl(struct kern_ipc_perm *sma, int cmd)
6597 {
6598 	int err;
6599 	u32 perms;
6600 
6601 	switch (cmd) {
6602 	case IPC_INFO:
6603 	case SEM_INFO:
6604 		/* No specific object, just general system-wide information. */
6605 		return avc_has_perm(current_sid(), SECINITSID_KERNEL,
6606 				    SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
6607 	case GETPID:
6608 	case GETNCNT:
6609 	case GETZCNT:
6610 		perms = SEM__GETATTR;
6611 		break;
6612 	case GETVAL:
6613 	case GETALL:
6614 		perms = SEM__READ;
6615 		break;
6616 	case SETVAL:
6617 	case SETALL:
6618 		perms = SEM__WRITE;
6619 		break;
6620 	case IPC_RMID:
6621 		perms = SEM__DESTROY;
6622 		break;
6623 	case IPC_SET:
6624 		perms = SEM__SETATTR;
6625 		break;
6626 	case IPC_STAT:
6627 	case SEM_STAT:
6628 	case SEM_STAT_ANY:
6629 		perms = SEM__GETATTR | SEM__ASSOCIATE;
6630 		break;
6631 	default:
6632 		return 0;
6633 	}
6634 
6635 	err = ipc_has_perm(sma, perms);
6636 	return err;
6637 }
6638 
6639 static int selinux_sem_semop(struct kern_ipc_perm *sma,
6640 			     struct sembuf *sops, unsigned nsops, int alter)
6641 {
6642 	u32 perms;
6643 
6644 	if (alter)
6645 		perms = SEM__READ | SEM__WRITE;
6646 	else
6647 		perms = SEM__READ;
6648 
6649 	return ipc_has_perm(sma, perms);
6650 }
6651 
6652 static int selinux_ipc_permission(struct kern_ipc_perm *ipcp, short flag)
6653 {
6654 	u32 av = 0;
6655 
6656 	av = 0;
6657 	if (flag & S_IRUGO)
6658 		av |= IPC__UNIX_READ;
6659 	if (flag & S_IWUGO)
6660 		av |= IPC__UNIX_WRITE;
6661 
6662 	if (av == 0)
6663 		return 0;
6664 
6665 	return ipc_has_perm(ipcp, av);
6666 }
6667 
6668 static void selinux_ipc_getlsmprop(struct kern_ipc_perm *ipcp,
6669 				   struct lsm_prop *prop)
6670 {
6671 	struct ipc_security_struct *isec = selinux_ipc(ipcp);
6672 	prop->selinux.secid = isec->sid;
6673 }
6674 
6675 static void selinux_d_instantiate(struct dentry *dentry, struct inode *inode)
6676 {
6677 	if (inode)
6678 		inode_doinit_with_dentry(inode, dentry);
6679 }
6680 
6681 static int selinux_lsm_getattr(unsigned int attr, struct task_struct *p,
6682 			       char **value)
6683 {
6684 	const struct cred_security_struct *crsec;
6685 	int error;
6686 	u32 sid;
6687 	u32 len;
6688 
6689 	rcu_read_lock();
6690 	crsec = selinux_cred(__task_cred(p));
6691 	if (p != current) {
6692 		error = avc_has_perm(current_sid(), crsec->sid,
6693 				     SECCLASS_PROCESS, PROCESS__GETATTR, NULL);
6694 		if (error)
6695 			goto err_unlock;
6696 	}
6697 	switch (attr) {
6698 	case LSM_ATTR_CURRENT:
6699 		sid = crsec->sid;
6700 		break;
6701 	case LSM_ATTR_PREV:
6702 		sid = crsec->osid;
6703 		break;
6704 	case LSM_ATTR_EXEC:
6705 		sid = crsec->exec_sid;
6706 		break;
6707 	case LSM_ATTR_FSCREATE:
6708 		sid = crsec->create_sid;
6709 		break;
6710 	case LSM_ATTR_KEYCREATE:
6711 		sid = crsec->keycreate_sid;
6712 		break;
6713 	case LSM_ATTR_SOCKCREATE:
6714 		sid = crsec->sockcreate_sid;
6715 		break;
6716 	default:
6717 		error = -EOPNOTSUPP;
6718 		goto err_unlock;
6719 	}
6720 	rcu_read_unlock();
6721 
6722 	if (sid == SECSID_NULL) {
6723 		*value = NULL;
6724 		return 0;
6725 	}
6726 
6727 	error = security_sid_to_context(sid, value, &len);
6728 	if (error)
6729 		return error;
6730 	return len;
6731 
6732 err_unlock:
6733 	rcu_read_unlock();
6734 	return error;
6735 }
6736 
6737 static int selinux_lsm_setattr(u64 attr, void *value, size_t size)
6738 {
6739 	struct cred_security_struct *crsec;
6740 	struct cred *new;
6741 	u32 mysid = current_sid(), sid = 0, ptsid;
6742 	int error;
6743 	char *str = value;
6744 
6745 	/*
6746 	 * Basic control over ability to set these attributes at all.
6747 	 */
6748 	switch (attr) {
6749 	case LSM_ATTR_EXEC:
6750 		error = avc_has_perm(mysid, mysid, SECCLASS_PROCESS,
6751 				     PROCESS__SETEXEC, NULL);
6752 		break;
6753 	case LSM_ATTR_FSCREATE:
6754 		error = avc_has_perm(mysid, mysid, SECCLASS_PROCESS,
6755 				     PROCESS__SETFSCREATE, NULL);
6756 		break;
6757 	case LSM_ATTR_KEYCREATE:
6758 		error = avc_has_perm(mysid, mysid, SECCLASS_PROCESS,
6759 				     PROCESS__SETKEYCREATE, NULL);
6760 		break;
6761 	case LSM_ATTR_SOCKCREATE:
6762 		error = avc_has_perm(mysid, mysid, SECCLASS_PROCESS,
6763 				     PROCESS__SETSOCKCREATE, NULL);
6764 		break;
6765 	case LSM_ATTR_CURRENT:
6766 		error = avc_has_perm(mysid, mysid, SECCLASS_PROCESS,
6767 				     PROCESS__SETCURRENT, NULL);
6768 		break;
6769 	default:
6770 		error = -EOPNOTSUPP;
6771 		break;
6772 	}
6773 	if (error)
6774 		return error;
6775 
6776 	/* Obtain a SID for the context, if one was specified. */
6777 	if (size && str[0] && str[0] != '\n') {
6778 		if (str[size-1] == '\n') {
6779 			str[size-1] = 0;
6780 			size--;
6781 		}
6782 		error = security_context_to_sid(value, size,
6783 						&sid, GFP_KERNEL);
6784 		if (error == -EINVAL && attr == LSM_ATTR_FSCREATE) {
6785 			if (!has_cap_mac_admin(true)) {
6786 				struct audit_buffer *ab;
6787 				size_t audit_size;
6788 
6789 				/* We strip a nul only if it is at the end,
6790 				 * otherwise the context contains a nul and
6791 				 * we should audit that */
6792 				if (str[size - 1] == '\0')
6793 					audit_size = size - 1;
6794 				else
6795 					audit_size = size;
6796 				ab = audit_log_start(audit_context(),
6797 						     GFP_ATOMIC,
6798 						     AUDIT_SELINUX_ERR);
6799 				if (!ab)
6800 					return error;
6801 				audit_log_format(ab, "op=fscreate invalid_context=");
6802 				audit_log_n_untrustedstring(ab, value,
6803 							    audit_size);
6804 				audit_log_end(ab);
6805 
6806 				return error;
6807 			}
6808 			error = security_context_to_sid_force(value, size,
6809 							&sid);
6810 		}
6811 		if (error)
6812 			return error;
6813 	}
6814 
6815 	new = prepare_creds();
6816 	if (!new)
6817 		return -ENOMEM;
6818 
6819 	/* Permission checking based on the specified context is
6820 	   performed during the actual operation (execve,
6821 	   open/mkdir/...), when we know the full context of the
6822 	   operation.  See selinux_bprm_creds_for_exec for the execve
6823 	   checks and may_create for the file creation checks. The
6824 	   operation will then fail if the context is not permitted. */
6825 	crsec = selinux_cred(new);
6826 	if (attr == LSM_ATTR_EXEC) {
6827 		crsec->exec_sid = sid;
6828 	} else if (attr == LSM_ATTR_FSCREATE) {
6829 		crsec->create_sid = sid;
6830 	} else if (attr == LSM_ATTR_KEYCREATE) {
6831 		if (sid) {
6832 			error = avc_has_perm(mysid, sid,
6833 					     SECCLASS_KEY, KEY__CREATE, NULL);
6834 			if (error)
6835 				goto abort_change;
6836 		}
6837 		crsec->keycreate_sid = sid;
6838 	} else if (attr == LSM_ATTR_SOCKCREATE) {
6839 		crsec->sockcreate_sid = sid;
6840 	} else if (attr == LSM_ATTR_CURRENT) {
6841 		error = -EINVAL;
6842 		if (sid == 0)
6843 			goto abort_change;
6844 
6845 		if (!current_is_single_threaded()) {
6846 			error = security_bounded_transition(crsec->sid, sid);
6847 			if (error)
6848 				goto abort_change;
6849 		}
6850 
6851 		/* Check permissions for the transition. */
6852 		error = avc_has_perm(crsec->sid, sid, SECCLASS_PROCESS,
6853 				     PROCESS__DYNTRANSITION, NULL);
6854 		if (error)
6855 			goto abort_change;
6856 
6857 		/* Check for ptracing, and update the task SID if ok.
6858 		   Otherwise, leave SID unchanged and fail. */
6859 		ptsid = ptrace_parent_sid();
6860 		if (ptsid != 0) {
6861 			error = avc_has_perm(ptsid, sid, SECCLASS_PROCESS,
6862 					     PROCESS__PTRACE, NULL);
6863 			if (error)
6864 				goto abort_change;
6865 		}
6866 
6867 		crsec->sid = sid;
6868 	} else {
6869 		error = -EINVAL;
6870 		goto abort_change;
6871 	}
6872 
6873 	commit_creds(new);
6874 	return size;
6875 
6876 abort_change:
6877 	abort_creds(new);
6878 	return error;
6879 }
6880 
6881 /**
6882  * selinux_getselfattr - Get SELinux current task attributes
6883  * @attr: the requested attribute
6884  * @ctx: buffer to receive the result
6885  * @size: buffer size (input), buffer size used (output)
6886  * @flags: unused
6887  *
6888  * Fill the passed user space @ctx with the details of the requested
6889  * attribute.
6890  *
6891  * Returns the number of attributes on success, an error code otherwise.
6892  * There will only ever be one attribute.
6893  */
6894 static int selinux_getselfattr(unsigned int attr, struct lsm_ctx __user *ctx,
6895 			       u32 *size, u32 flags)
6896 {
6897 	int rc;
6898 	char *val = NULL;
6899 	int val_len;
6900 
6901 	val_len = selinux_lsm_getattr(attr, current, &val);
6902 	if (val_len < 0)
6903 		return val_len;
6904 	rc = lsm_fill_user_ctx(ctx, size, val, val_len, LSM_ID_SELINUX, 0);
6905 	kfree(val);
6906 	return (!rc ? 1 : rc);
6907 }
6908 
6909 static int selinux_setselfattr(unsigned int attr, struct lsm_ctx *ctx,
6910 			       u32 size, u32 flags)
6911 {
6912 	int rc;
6913 
6914 	rc = selinux_lsm_setattr(attr, ctx->ctx, ctx->ctx_len);
6915 	if (rc > 0)
6916 		return 0;
6917 	return rc;
6918 }
6919 
6920 static int selinux_getprocattr(struct task_struct *p,
6921 			       const char *name, char **value)
6922 {
6923 	unsigned int attr = lsm_name_to_attr(name);
6924 	int rc;
6925 
6926 	if (attr) {
6927 		rc = selinux_lsm_getattr(attr, p, value);
6928 		if (rc != -EOPNOTSUPP)
6929 			return rc;
6930 	}
6931 
6932 	return -EINVAL;
6933 }
6934 
6935 static int selinux_setprocattr(const char *name, void *value, size_t size)
6936 {
6937 	int attr = lsm_name_to_attr(name);
6938 
6939 	if (attr)
6940 		return selinux_lsm_setattr(attr, value, size);
6941 	return -EINVAL;
6942 }
6943 
6944 static int selinux_ismaclabel(const char *name)
6945 {
6946 	return (strcmp(name, XATTR_SELINUX_SUFFIX) == 0);
6947 }
6948 
6949 static int selinux_secid_to_secctx(u32 secid, struct lsm_context *cp)
6950 {
6951 	u32 seclen;
6952 	int ret;
6953 
6954 	if (cp) {
6955 		cp->id = LSM_ID_SELINUX;
6956 		ret = security_sid_to_context(secid, &cp->context, &cp->len);
6957 		if (ret < 0)
6958 			return ret;
6959 		return cp->len;
6960 	}
6961 	ret = security_sid_to_context(secid, NULL, &seclen);
6962 	if (ret < 0)
6963 		return ret;
6964 	return seclen;
6965 }
6966 
6967 static int selinux_lsmprop_to_secctx(struct lsm_prop *prop,
6968 				     struct lsm_context *cp)
6969 {
6970 	return selinux_secid_to_secctx(prop->selinux.secid, cp);
6971 }
6972 
6973 static int selinux_secctx_to_secid(const char *secdata, u32 seclen, u32 *secid)
6974 {
6975 	return security_context_to_sid(secdata, seclen,
6976 				       secid, GFP_KERNEL);
6977 }
6978 
6979 static void selinux_release_secctx(struct lsm_context *cp)
6980 {
6981 	if (cp->id == LSM_ID_SELINUX) {
6982 		kfree(cp->context);
6983 		cp->context = NULL;
6984 		cp->id = LSM_ID_UNDEF;
6985 	}
6986 }
6987 
6988 static void selinux_inode_invalidate_secctx(struct inode *inode)
6989 {
6990 	struct inode_security_struct *isec = selinux_inode(inode);
6991 
6992 	spin_lock(&isec->lock);
6993 	isec->initialized = LABEL_INVALID;
6994 	spin_unlock(&isec->lock);
6995 }
6996 
6997 /*
6998  *	called with inode->i_mutex locked
6999  */
7000 static int selinux_inode_notifysecctx(struct inode *inode, void *ctx, u32 ctxlen)
7001 {
7002 	int rc = selinux_inode_setsecurity(inode, XATTR_SELINUX_SUFFIX,
7003 					   ctx, ctxlen, 0);
7004 	/* Do not return error when suppressing label (SBLABEL_MNT not set). */
7005 	return rc == -EOPNOTSUPP ? 0 : rc;
7006 }
7007 
7008 /*
7009  *	called with inode->i_mutex locked
7010  */
7011 static int selinux_inode_setsecctx(struct dentry *dentry, void *ctx, u32 ctxlen)
7012 {
7013 	return __vfs_setxattr_locked(&nop_mnt_idmap, dentry, XATTR_NAME_SELINUX,
7014 				     ctx, ctxlen, 0, NULL);
7015 }
7016 
7017 static int selinux_inode_getsecctx(struct inode *inode, struct lsm_context *cp)
7018 {
7019 	int len;
7020 	len = selinux_inode_getsecurity(&nop_mnt_idmap, inode,
7021 					XATTR_SELINUX_SUFFIX,
7022 					(void **)&cp->context, true);
7023 	if (len < 0)
7024 		return len;
7025 	cp->len = len;
7026 	cp->id = LSM_ID_SELINUX;
7027 	return 0;
7028 }
7029 #ifdef CONFIG_KEYS
7030 
7031 static int selinux_key_alloc(struct key *k, const struct cred *cred,
7032 			     unsigned long flags)
7033 {
7034 	const struct cred_security_struct *crsec;
7035 	struct key_security_struct *ksec = selinux_key(k);
7036 
7037 	crsec = selinux_cred(cred);
7038 	if (crsec->keycreate_sid)
7039 		ksec->sid = crsec->keycreate_sid;
7040 	else
7041 		ksec->sid = crsec->sid;
7042 
7043 	return 0;
7044 }
7045 
7046 static int selinux_key_permission(key_ref_t key_ref,
7047 				  const struct cred *cred,
7048 				  enum key_need_perm need_perm)
7049 {
7050 	struct key *key;
7051 	struct key_security_struct *ksec;
7052 	u32 perm, sid;
7053 
7054 	switch (need_perm) {
7055 	case KEY_NEED_VIEW:
7056 		perm = KEY__VIEW;
7057 		break;
7058 	case KEY_NEED_READ:
7059 		perm = KEY__READ;
7060 		break;
7061 	case KEY_NEED_WRITE:
7062 		perm = KEY__WRITE;
7063 		break;
7064 	case KEY_NEED_SEARCH:
7065 		perm = KEY__SEARCH;
7066 		break;
7067 	case KEY_NEED_LINK:
7068 		perm = KEY__LINK;
7069 		break;
7070 	case KEY_NEED_SETATTR:
7071 		perm = KEY__SETATTR;
7072 		break;
7073 	case KEY_NEED_UNLINK:
7074 	case KEY_SYSADMIN_OVERRIDE:
7075 	case KEY_AUTHTOKEN_OVERRIDE:
7076 	case KEY_DEFER_PERM_CHECK:
7077 		return 0;
7078 	default:
7079 		WARN_ON(1);
7080 		return -EPERM;
7081 
7082 	}
7083 
7084 	sid = cred_sid(cred);
7085 	key = key_ref_to_ptr(key_ref);
7086 	ksec = selinux_key(key);
7087 
7088 	return avc_has_perm(sid, ksec->sid, SECCLASS_KEY, perm, NULL);
7089 }
7090 
7091 static int selinux_key_getsecurity(struct key *key, char **_buffer)
7092 {
7093 	struct key_security_struct *ksec = selinux_key(key);
7094 	char *context = NULL;
7095 	unsigned len;
7096 	int rc;
7097 
7098 	rc = security_sid_to_context(ksec->sid,
7099 				     &context, &len);
7100 	if (!rc)
7101 		rc = len;
7102 	*_buffer = context;
7103 	return rc;
7104 }
7105 
7106 #ifdef CONFIG_KEY_NOTIFICATIONS
7107 static int selinux_watch_key(struct key *key)
7108 {
7109 	struct key_security_struct *ksec = selinux_key(key);
7110 	u32 sid = current_sid();
7111 
7112 	return avc_has_perm(sid, ksec->sid, SECCLASS_KEY, KEY__VIEW, NULL);
7113 }
7114 #endif
7115 #endif
7116 
7117 #ifdef CONFIG_SECURITY_INFINIBAND
7118 static int selinux_ib_pkey_access(void *ib_sec, u64 subnet_prefix, u16 pkey_val)
7119 {
7120 	struct common_audit_data ad;
7121 	int err;
7122 	u32 sid = 0;
7123 	struct ib_security_struct *sec = ib_sec;
7124 	struct lsm_ibpkey_audit ibpkey;
7125 
7126 	err = sel_ib_pkey_sid(subnet_prefix, pkey_val, &sid);
7127 	if (err)
7128 		return err;
7129 
7130 	ad.type = LSM_AUDIT_DATA_IBPKEY;
7131 	ibpkey.subnet_prefix = subnet_prefix;
7132 	ibpkey.pkey = pkey_val;
7133 	ad.u.ibpkey = &ibpkey;
7134 	return avc_has_perm(sec->sid, sid,
7135 			    SECCLASS_INFINIBAND_PKEY,
7136 			    INFINIBAND_PKEY__ACCESS, &ad);
7137 }
7138 
7139 static int selinux_ib_endport_manage_subnet(void *ib_sec, const char *dev_name,
7140 					    u8 port_num)
7141 {
7142 	struct common_audit_data ad;
7143 	int err;
7144 	u32 sid = 0;
7145 	struct ib_security_struct *sec = ib_sec;
7146 	struct lsm_ibendport_audit ibendport;
7147 
7148 	err = security_ib_endport_sid(dev_name, port_num,
7149 				      &sid);
7150 
7151 	if (err)
7152 		return err;
7153 
7154 	ad.type = LSM_AUDIT_DATA_IBENDPORT;
7155 	ibendport.dev_name = dev_name;
7156 	ibendport.port = port_num;
7157 	ad.u.ibendport = &ibendport;
7158 	return avc_has_perm(sec->sid, sid,
7159 			    SECCLASS_INFINIBAND_ENDPORT,
7160 			    INFINIBAND_ENDPORT__MANAGE_SUBNET, &ad);
7161 }
7162 
7163 static int selinux_ib_alloc_security(void *ib_sec)
7164 {
7165 	struct ib_security_struct *sec = selinux_ib(ib_sec);
7166 
7167 	sec->sid = current_sid();
7168 	return 0;
7169 }
7170 #endif
7171 
7172 #ifdef CONFIG_BPF_SYSCALL
7173 static int selinux_bpf(int cmd, union bpf_attr *attr,
7174 		       unsigned int size, bool kernel)
7175 {
7176 	u32 sid = current_sid();
7177 	int ret;
7178 
7179 	if (selinux_policycap_bpf_token_perms())
7180 		return 0;
7181 
7182 	switch (cmd) {
7183 	case BPF_MAP_CREATE:
7184 		ret = avc_has_perm(sid, sid, SECCLASS_BPF, BPF__MAP_CREATE,
7185 				   NULL);
7186 		break;
7187 	case BPF_PROG_LOAD:
7188 		ret = avc_has_perm(sid, sid, SECCLASS_BPF, BPF__PROG_LOAD,
7189 				   NULL);
7190 		break;
7191 	default:
7192 		ret = 0;
7193 		break;
7194 	}
7195 
7196 	return ret;
7197 }
7198 
7199 static u32 bpf_map_fmode_to_av(fmode_t fmode)
7200 {
7201 	u32 av = 0;
7202 
7203 	if (fmode & FMODE_READ)
7204 		av |= BPF__MAP_READ;
7205 	if (fmode & FMODE_WRITE)
7206 		av |= BPF__MAP_WRITE;
7207 	return av;
7208 }
7209 
7210 /* This function will check the file pass through unix socket or binder to see
7211  * if it is a bpf related object. And apply corresponding checks on the bpf
7212  * object based on the type. The bpf maps and programs, not like other files and
7213  * socket, are using a shared anonymous inode inside the kernel as their inode.
7214  * So checking that inode cannot identify if the process have privilege to
7215  * access the bpf object and that's why we have to add this additional check in
7216  * selinux_file_receive and selinux_binder_transfer_files.
7217  */
7218 static int bpf_fd_pass(const struct file *file, u32 sid)
7219 {
7220 	struct bpf_security_struct *bpfsec;
7221 	struct bpf_prog *prog;
7222 	struct bpf_map *map;
7223 	int ret;
7224 
7225 	if (file->f_op == &bpf_map_fops) {
7226 		map = file->private_data;
7227 		bpfsec = selinux_bpf_map_security(map);
7228 		ret = avc_has_perm(sid, bpfsec->sid, SECCLASS_BPF,
7229 				   bpf_map_fmode_to_av(file->f_mode), NULL);
7230 		if (ret)
7231 			return ret;
7232 	} else if (file->f_op == &bpf_prog_fops) {
7233 		prog = file->private_data;
7234 		bpfsec = selinux_bpf_prog_security(prog);
7235 		ret = avc_has_perm(sid, bpfsec->sid, SECCLASS_BPF,
7236 				   BPF__PROG_RUN, NULL);
7237 		if (ret)
7238 			return ret;
7239 	}
7240 	return 0;
7241 }
7242 
7243 static int selinux_bpf_map(struct bpf_map *map, fmode_t fmode)
7244 {
7245 	u32 sid = current_sid();
7246 	struct bpf_security_struct *bpfsec;
7247 
7248 	bpfsec = selinux_bpf_map_security(map);
7249 	return avc_has_perm(sid, bpfsec->sid, SECCLASS_BPF,
7250 			    bpf_map_fmode_to_av(fmode), NULL);
7251 }
7252 
7253 static int selinux_bpf_prog(struct bpf_prog *prog)
7254 {
7255 	u32 sid = current_sid();
7256 	struct bpf_security_struct *bpfsec;
7257 
7258 	bpfsec = selinux_bpf_prog_security(prog);
7259 	return avc_has_perm(sid, bpfsec->sid, SECCLASS_BPF,
7260 			    BPF__PROG_RUN, NULL);
7261 }
7262 
7263 static u32 selinux_bpffs_creator_sid(u32 fd)
7264 {
7265 	struct path path;
7266 	struct super_block *sb;
7267 	struct superblock_security_struct *sbsec;
7268 
7269 	CLASS(fd, f)(fd);
7270 
7271 	if (fd_empty(f))
7272 		return SECSID_NULL;
7273 
7274 	path = fd_file(f)->f_path;
7275 	sb = path.dentry->d_sb;
7276 	sbsec = selinux_superblock(sb);
7277 
7278 	return sbsec->creator_sid;
7279 }
7280 
7281 static int selinux_bpf_map_create(struct bpf_map *map, union bpf_attr *attr,
7282 				  struct bpf_token *token, bool kernel)
7283 {
7284 	struct bpf_security_struct *bpfsec;
7285 	u32 ssid;
7286 
7287 	bpfsec = selinux_bpf_map_security(map);
7288 	bpfsec->sid = current_sid();
7289 
7290 	if (!token)
7291 		ssid = bpfsec->sid;
7292 	else
7293 		ssid = selinux_bpffs_creator_sid(attr->map_token_fd);
7294 
7295 	return avc_has_perm(ssid, bpfsec->sid, SECCLASS_BPF, BPF__MAP_CREATE,
7296 			    NULL);
7297 }
7298 
7299 static int selinux_bpf_prog_load(struct bpf_prog *prog, union bpf_attr *attr,
7300 				 struct bpf_token *token, bool kernel)
7301 {
7302 	struct bpf_security_struct *bpfsec;
7303 	u32 ssid;
7304 
7305 	bpfsec = selinux_bpf_prog_security(prog);
7306 	bpfsec->sid = current_sid();
7307 
7308 	if (!token)
7309 		ssid = bpfsec->sid;
7310 	else
7311 		ssid = selinux_bpffs_creator_sid(attr->prog_token_fd);
7312 
7313 	return avc_has_perm(ssid, bpfsec->sid, SECCLASS_BPF, BPF__PROG_LOAD,
7314 			    NULL);
7315 }
7316 
7317 #define bpf_token_cmd(T, C) \
7318 	((T)->allowed_cmds & (1ULL << (C)))
7319 
7320 static int selinux_bpf_token_create(struct bpf_token *token,
7321 				    union bpf_attr *attr,
7322 				    const struct path *path)
7323 {
7324 	struct bpf_security_struct *bpfsec;
7325 	u32 sid = selinux_bpffs_creator_sid(attr->token_create.bpffs_fd);
7326 	int err;
7327 
7328 	bpfsec = selinux_bpf_token_security(token);
7329 	bpfsec->sid = current_sid();
7330 	bpfsec->grantor_sid = sid;
7331 
7332 	bpfsec->perms = 0;
7333 	/**
7334 	 * 'token->allowed_cmds' is a bit mask of allowed commands
7335 	 * Convert the BPF command enum to a bitmask representing its position
7336 	 * in the allowed_cmds bitmap.
7337 	 */
7338 	if (bpf_token_cmd(token, BPF_MAP_CREATE)) {
7339 		err = avc_has_perm(bpfsec->sid, sid, SECCLASS_BPF,
7340 				   BPF__MAP_CREATE_AS, NULL);
7341 		if (err)
7342 			return err;
7343 		bpfsec->perms |= BPF__MAP_CREATE;
7344 	}
7345 	if (bpf_token_cmd(token, BPF_PROG_LOAD)) {
7346 		err = avc_has_perm(bpfsec->sid, sid, SECCLASS_BPF,
7347 				   BPF__PROG_LOAD_AS, NULL);
7348 		if (err)
7349 			return err;
7350 		bpfsec->perms |= BPF__PROG_LOAD;
7351 	}
7352 
7353 	return 0;
7354 }
7355 
7356 static int selinux_bpf_token_cmd(const struct bpf_token *token,
7357 				 enum bpf_cmd cmd)
7358 {
7359 	struct bpf_security_struct *bpfsec;
7360 
7361 	bpfsec = token->security;
7362 	switch (cmd) {
7363 	case BPF_MAP_CREATE:
7364 		if (!(bpfsec->perms & BPF__MAP_CREATE))
7365 			return -EACCES;
7366 		break;
7367 	case BPF_PROG_LOAD:
7368 		if (!(bpfsec->perms & BPF__PROG_LOAD))
7369 			return -EACCES;
7370 		break;
7371 	default:
7372 		break;
7373 	}
7374 
7375 	return 0;
7376 }
7377 
7378 static int selinux_bpf_token_capable(const struct bpf_token *token, int cap)
7379 {
7380 	u16 sclass;
7381 	struct bpf_security_struct *bpfsec = token->security;
7382 	bool initns = (token->userns == &init_user_ns);
7383 	u32 av = CAP_TO_MASK(cap);
7384 
7385 	switch (CAP_TO_INDEX(cap)) {
7386 	case 0:
7387 		sclass = initns ? SECCLASS_CAPABILITY : SECCLASS_CAP_USERNS;
7388 		break;
7389 	case 1:
7390 		sclass = initns ? SECCLASS_CAPABILITY2 : SECCLASS_CAP2_USERNS;
7391 		break;
7392 	default:
7393 		pr_err("SELinux:  out of range capability %d\n", cap);
7394 		return -EINVAL;
7395 	}
7396 
7397 	return avc_has_perm(current_sid(), bpfsec->grantor_sid, sclass, av,
7398 			    NULL);
7399 }
7400 #endif
7401 
7402 #ifdef CONFIG_PERF_EVENTS
7403 static int selinux_perf_event_open(int type)
7404 {
7405 	u32 requested, sid = current_sid();
7406 
7407 	if (type == PERF_SECURITY_OPEN)
7408 		requested = PERF_EVENT__OPEN;
7409 	else if (type == PERF_SECURITY_CPU)
7410 		requested = PERF_EVENT__CPU;
7411 	else if (type == PERF_SECURITY_KERNEL)
7412 		requested = PERF_EVENT__KERNEL;
7413 	else if (type == PERF_SECURITY_TRACEPOINT)
7414 		requested = PERF_EVENT__TRACEPOINT;
7415 	else
7416 		return -EINVAL;
7417 
7418 	return avc_has_perm(sid, sid, SECCLASS_PERF_EVENT,
7419 			    requested, NULL);
7420 }
7421 
7422 static int selinux_perf_event_alloc(struct perf_event *event)
7423 {
7424 	struct perf_event_security_struct *perfsec;
7425 
7426 	perfsec = selinux_perf_event(event->security);
7427 	perfsec->sid = current_sid();
7428 
7429 	return 0;
7430 }
7431 
7432 static int selinux_perf_event_read(struct perf_event *event)
7433 {
7434 	struct perf_event_security_struct *perfsec = event->security;
7435 	u32 sid = current_sid();
7436 
7437 	return avc_has_perm(sid, perfsec->sid,
7438 			    SECCLASS_PERF_EVENT, PERF_EVENT__READ, NULL);
7439 }
7440 
7441 static int selinux_perf_event_write(struct perf_event *event)
7442 {
7443 	struct perf_event_security_struct *perfsec = event->security;
7444 	u32 sid = current_sid();
7445 
7446 	return avc_has_perm(sid, perfsec->sid,
7447 			    SECCLASS_PERF_EVENT, PERF_EVENT__WRITE, NULL);
7448 }
7449 #endif
7450 
7451 #ifdef CONFIG_IO_URING
7452 /**
7453  * selinux_uring_override_creds - check the requested cred override
7454  * @new: the target creds
7455  *
7456  * Check to see if the current task is allowed to override it's credentials
7457  * to service an io_uring operation.
7458  */
7459 static int selinux_uring_override_creds(const struct cred *new)
7460 {
7461 	return avc_has_perm(current_sid(), cred_sid(new),
7462 			    SECCLASS_IO_URING, IO_URING__OVERRIDE_CREDS, NULL);
7463 }
7464 
7465 /**
7466  * selinux_uring_sqpoll - check if a io_uring polling thread can be created
7467  *
7468  * Check to see if the current task is allowed to create a new io_uring
7469  * kernel polling thread.
7470  */
7471 static int selinux_uring_sqpoll(void)
7472 {
7473 	u32 sid = current_sid();
7474 
7475 	return avc_has_perm(sid, sid,
7476 			    SECCLASS_IO_URING, IO_URING__SQPOLL, NULL);
7477 }
7478 
7479 /**
7480  * selinux_uring_cmd - check if IORING_OP_URING_CMD is allowed
7481  * @ioucmd: the io_uring command structure
7482  *
7483  * Check to see if the current domain is allowed to execute an
7484  * IORING_OP_URING_CMD against the device/file specified in @ioucmd.
7485  *
7486  */
7487 static int selinux_uring_cmd(struct io_uring_cmd *ioucmd)
7488 {
7489 	struct file *file = ioucmd->file;
7490 	struct inode *inode = file_inode(file);
7491 	struct inode_security_struct *isec = selinux_inode(inode);
7492 	struct common_audit_data ad;
7493 
7494 	ad.type = LSM_AUDIT_DATA_FILE;
7495 	ad.u.file = file;
7496 
7497 	return avc_has_perm(current_sid(), isec->sid,
7498 			    SECCLASS_IO_URING, IO_URING__CMD, &ad);
7499 }
7500 
7501 /**
7502  * selinux_uring_allowed - check if io_uring_setup() can be called
7503  *
7504  * Check to see if the current task is allowed to call io_uring_setup().
7505  */
7506 static int selinux_uring_allowed(void)
7507 {
7508 	u32 sid = current_sid();
7509 
7510 	return avc_has_perm(sid, sid, SECCLASS_IO_URING, IO_URING__ALLOWED,
7511 			    NULL);
7512 }
7513 #endif /* CONFIG_IO_URING */
7514 
7515 static const struct lsm_id selinux_lsmid = {
7516 	.name = "selinux",
7517 	.id = LSM_ID_SELINUX,
7518 };
7519 
7520 struct lsm_blob_sizes selinux_blob_sizes __ro_after_init = {
7521 	.lbs_cred = sizeof(struct cred_security_struct),
7522 	.lbs_task = sizeof(struct task_security_struct),
7523 	.lbs_file = sizeof(struct file_security_struct),
7524 	.lbs_backing_file = sizeof(struct backing_file_security_struct),
7525 	.lbs_inode = sizeof(struct inode_security_struct),
7526 	.lbs_ipc = sizeof(struct ipc_security_struct),
7527 	.lbs_key = sizeof(struct key_security_struct),
7528 	.lbs_msg_msg = sizeof(struct msg_security_struct),
7529 #ifdef CONFIG_PERF_EVENTS
7530 	.lbs_perf_event = sizeof(struct perf_event_security_struct),
7531 #endif
7532 	.lbs_sock = sizeof(struct sk_security_struct),
7533 	.lbs_superblock = sizeof(struct superblock_security_struct),
7534 	.lbs_xattr_count = SELINUX_INODE_INIT_XATTRS,
7535 	.lbs_tun_dev = sizeof(struct tun_security_struct),
7536 	.lbs_ib = sizeof(struct ib_security_struct),
7537 	.lbs_bpf_map = sizeof(struct bpf_security_struct),
7538 	.lbs_bpf_prog = sizeof(struct bpf_security_struct),
7539 	.lbs_bpf_token = sizeof(struct bpf_security_struct),
7540 };
7541 
7542 /*
7543  * IMPORTANT NOTE: When adding new hooks, please be careful to keep this order:
7544  * 1. any hooks that don't belong to (2.) or (3.) below,
7545  * 2. hooks that both access structures allocated by other hooks, and allocate
7546  *    structures that can be later accessed by other hooks (mostly "cloning"
7547  *    hooks),
7548  * 3. hooks that only allocate structures that can be later accessed by other
7549  *    hooks ("allocating" hooks).
7550  *
7551  * Please follow block comment delimiters in the list to keep this order.
7552  */
7553 static struct security_hook_list selinux_hooks[] __ro_after_init = {
7554 	LSM_HOOK_INIT(binder_set_context_mgr, selinux_binder_set_context_mgr),
7555 	LSM_HOOK_INIT(binder_transaction, selinux_binder_transaction),
7556 	LSM_HOOK_INIT(binder_transfer_binder, selinux_binder_transfer_binder),
7557 	LSM_HOOK_INIT(binder_transfer_file, selinux_binder_transfer_file),
7558 
7559 	LSM_HOOK_INIT(ptrace_access_check, selinux_ptrace_access_check),
7560 	LSM_HOOK_INIT(ptrace_traceme, selinux_ptrace_traceme),
7561 	LSM_HOOK_INIT(capget, selinux_capget),
7562 	LSM_HOOK_INIT(capset, selinux_capset),
7563 	LSM_HOOK_INIT(capable, selinux_capable),
7564 	LSM_HOOK_INIT(quotactl, selinux_quotactl),
7565 	LSM_HOOK_INIT(quota_on, selinux_quota_on),
7566 	LSM_HOOK_INIT(syslog, selinux_syslog),
7567 	LSM_HOOK_INIT(vm_enough_memory, selinux_vm_enough_memory),
7568 
7569 	LSM_HOOK_INIT(netlink_send, selinux_netlink_send),
7570 
7571 	LSM_HOOK_INIT(bprm_creds_for_exec, selinux_bprm_creds_for_exec),
7572 	LSM_HOOK_INIT(bprm_committing_creds, selinux_bprm_committing_creds),
7573 	LSM_HOOK_INIT(bprm_committed_creds, selinux_bprm_committed_creds),
7574 
7575 	LSM_HOOK_INIT(sb_free_mnt_opts, selinux_free_mnt_opts),
7576 	LSM_HOOK_INIT(sb_mnt_opts_compat, selinux_sb_mnt_opts_compat),
7577 	LSM_HOOK_INIT(sb_remount, selinux_sb_remount),
7578 	LSM_HOOK_INIT(sb_kern_mount, selinux_sb_kern_mount),
7579 	LSM_HOOK_INIT(sb_show_options, selinux_sb_show_options),
7580 	LSM_HOOK_INIT(sb_statfs, selinux_sb_statfs),
7581 	LSM_HOOK_INIT(sb_mount, selinux_mount),
7582 	LSM_HOOK_INIT(sb_umount, selinux_umount),
7583 	LSM_HOOK_INIT(sb_set_mnt_opts, selinux_set_mnt_opts),
7584 	LSM_HOOK_INIT(sb_clone_mnt_opts, selinux_sb_clone_mnt_opts),
7585 
7586 	LSM_HOOK_INIT(move_mount, selinux_move_mount),
7587 
7588 	LSM_HOOK_INIT(dentry_init_security, selinux_dentry_init_security),
7589 	LSM_HOOK_INIT(dentry_create_files_as, selinux_dentry_create_files_as),
7590 
7591 	LSM_HOOK_INIT(inode_free_security, selinux_inode_free_security),
7592 	LSM_HOOK_INIT(inode_init_security, selinux_inode_init_security),
7593 	LSM_HOOK_INIT(inode_init_security_anon, selinux_inode_init_security_anon),
7594 	LSM_HOOK_INIT(inode_create, selinux_inode_create),
7595 	LSM_HOOK_INIT(inode_link, selinux_inode_link),
7596 	LSM_HOOK_INIT(inode_unlink, selinux_inode_unlink),
7597 	LSM_HOOK_INIT(inode_symlink, selinux_inode_symlink),
7598 	LSM_HOOK_INIT(inode_mkdir, selinux_inode_mkdir),
7599 	LSM_HOOK_INIT(inode_rmdir, selinux_inode_rmdir),
7600 	LSM_HOOK_INIT(inode_mknod, selinux_inode_mknod),
7601 	LSM_HOOK_INIT(inode_rename, selinux_inode_rename),
7602 	LSM_HOOK_INIT(inode_readlink, selinux_inode_readlink),
7603 	LSM_HOOK_INIT(inode_follow_link, selinux_inode_follow_link),
7604 	LSM_HOOK_INIT(inode_permission, selinux_inode_permission),
7605 	LSM_HOOK_INIT(inode_setattr, selinux_inode_setattr),
7606 	LSM_HOOK_INIT(inode_getattr, selinux_inode_getattr),
7607 	LSM_HOOK_INIT(inode_xattr_skipcap, selinux_inode_xattr_skipcap),
7608 	LSM_HOOK_INIT(inode_setxattr, selinux_inode_setxattr),
7609 	LSM_HOOK_INIT(inode_post_setxattr, selinux_inode_post_setxattr),
7610 	LSM_HOOK_INIT(inode_getxattr, selinux_inode_getxattr),
7611 	LSM_HOOK_INIT(inode_listxattr, selinux_inode_listxattr),
7612 	LSM_HOOK_INIT(inode_removexattr, selinux_inode_removexattr),
7613 	LSM_HOOK_INIT(inode_file_getattr, selinux_inode_file_getattr),
7614 	LSM_HOOK_INIT(inode_file_setattr, selinux_inode_file_setattr),
7615 	LSM_HOOK_INIT(inode_set_acl, selinux_inode_set_acl),
7616 	LSM_HOOK_INIT(inode_get_acl, selinux_inode_get_acl),
7617 	LSM_HOOK_INIT(inode_remove_acl, selinux_inode_remove_acl),
7618 	LSM_HOOK_INIT(inode_getsecurity, selinux_inode_getsecurity),
7619 	LSM_HOOK_INIT(inode_setsecurity, selinux_inode_setsecurity),
7620 	LSM_HOOK_INIT(inode_listsecurity, selinux_inode_listsecurity),
7621 	LSM_HOOK_INIT(inode_getlsmprop, selinux_inode_getlsmprop),
7622 	LSM_HOOK_INIT(inode_copy_up, selinux_inode_copy_up),
7623 	LSM_HOOK_INIT(inode_copy_up_xattr, selinux_inode_copy_up_xattr),
7624 	LSM_HOOK_INIT(path_notify, selinux_path_notify),
7625 
7626 	LSM_HOOK_INIT(kernfs_init_security, selinux_kernfs_init_security),
7627 
7628 	LSM_HOOK_INIT(file_permission, selinux_file_permission),
7629 	LSM_HOOK_INIT(file_alloc_security, selinux_file_alloc_security),
7630 	LSM_HOOK_INIT(backing_file_alloc, selinux_backing_file_alloc),
7631 	LSM_HOOK_INIT(file_ioctl, selinux_file_ioctl),
7632 	LSM_HOOK_INIT(file_ioctl_compat, selinux_file_ioctl_compat),
7633 	LSM_HOOK_INIT(mmap_file, selinux_mmap_file),
7634 	LSM_HOOK_INIT(mmap_backing_file, selinux_mmap_backing_file),
7635 	LSM_HOOK_INIT(mmap_addr, selinux_mmap_addr),
7636 	LSM_HOOK_INIT(file_mprotect, selinux_file_mprotect),
7637 	LSM_HOOK_INIT(file_lock, selinux_file_lock),
7638 	LSM_HOOK_INIT(file_fcntl, selinux_file_fcntl),
7639 	LSM_HOOK_INIT(file_set_fowner, selinux_file_set_fowner),
7640 	LSM_HOOK_INIT(file_send_sigiotask, selinux_file_send_sigiotask),
7641 	LSM_HOOK_INIT(file_receive, selinux_file_receive),
7642 
7643 	LSM_HOOK_INIT(file_open, selinux_file_open),
7644 
7645 	LSM_HOOK_INIT(task_alloc, selinux_task_alloc),
7646 	LSM_HOOK_INIT(cred_prepare, selinux_cred_prepare),
7647 	LSM_HOOK_INIT(cred_transfer, selinux_cred_transfer),
7648 	LSM_HOOK_INIT(cred_getsecid, selinux_cred_getsecid),
7649 	LSM_HOOK_INIT(cred_getlsmprop, selinux_cred_getlsmprop),
7650 	LSM_HOOK_INIT(kernel_act_as, selinux_kernel_act_as),
7651 	LSM_HOOK_INIT(kernel_create_files_as, selinux_kernel_create_files_as),
7652 	LSM_HOOK_INIT(kernel_module_request, selinux_kernel_module_request),
7653 	LSM_HOOK_INIT(kernel_load_data, selinux_kernel_load_data),
7654 	LSM_HOOK_INIT(kernel_read_file, selinux_kernel_read_file),
7655 	LSM_HOOK_INIT(task_setpgid, selinux_task_setpgid),
7656 	LSM_HOOK_INIT(task_getpgid, selinux_task_getpgid),
7657 	LSM_HOOK_INIT(task_getsid, selinux_task_getsid),
7658 	LSM_HOOK_INIT(current_getlsmprop_subj, selinux_current_getlsmprop_subj),
7659 	LSM_HOOK_INIT(task_getlsmprop_obj, selinux_task_getlsmprop_obj),
7660 	LSM_HOOK_INIT(task_setnice, selinux_task_setnice),
7661 	LSM_HOOK_INIT(task_setioprio, selinux_task_setioprio),
7662 	LSM_HOOK_INIT(task_getioprio, selinux_task_getioprio),
7663 	LSM_HOOK_INIT(task_prlimit, selinux_task_prlimit),
7664 	LSM_HOOK_INIT(task_setrlimit, selinux_task_setrlimit),
7665 	LSM_HOOK_INIT(task_setscheduler, selinux_task_setscheduler),
7666 	LSM_HOOK_INIT(task_getscheduler, selinux_task_getscheduler),
7667 	LSM_HOOK_INIT(task_movememory, selinux_task_movememory),
7668 	LSM_HOOK_INIT(task_kill, selinux_task_kill),
7669 	LSM_HOOK_INIT(task_to_inode, selinux_task_to_inode),
7670 	LSM_HOOK_INIT(userns_create, selinux_userns_create),
7671 
7672 	LSM_HOOK_INIT(ipc_permission, selinux_ipc_permission),
7673 	LSM_HOOK_INIT(ipc_getlsmprop, selinux_ipc_getlsmprop),
7674 
7675 	LSM_HOOK_INIT(msg_queue_associate, selinux_msg_queue_associate),
7676 	LSM_HOOK_INIT(msg_queue_msgctl, selinux_msg_queue_msgctl),
7677 	LSM_HOOK_INIT(msg_queue_msgsnd, selinux_msg_queue_msgsnd),
7678 	LSM_HOOK_INIT(msg_queue_msgrcv, selinux_msg_queue_msgrcv),
7679 
7680 	LSM_HOOK_INIT(shm_associate, selinux_shm_associate),
7681 	LSM_HOOK_INIT(shm_shmctl, selinux_shm_shmctl),
7682 	LSM_HOOK_INIT(shm_shmat, selinux_shm_shmat),
7683 
7684 	LSM_HOOK_INIT(sem_associate, selinux_sem_associate),
7685 	LSM_HOOK_INIT(sem_semctl, selinux_sem_semctl),
7686 	LSM_HOOK_INIT(sem_semop, selinux_sem_semop),
7687 
7688 	LSM_HOOK_INIT(d_instantiate, selinux_d_instantiate),
7689 
7690 	LSM_HOOK_INIT(getselfattr, selinux_getselfattr),
7691 	LSM_HOOK_INIT(setselfattr, selinux_setselfattr),
7692 	LSM_HOOK_INIT(getprocattr, selinux_getprocattr),
7693 	LSM_HOOK_INIT(setprocattr, selinux_setprocattr),
7694 
7695 	LSM_HOOK_INIT(ismaclabel, selinux_ismaclabel),
7696 	LSM_HOOK_INIT(secctx_to_secid, selinux_secctx_to_secid),
7697 	LSM_HOOK_INIT(release_secctx, selinux_release_secctx),
7698 	LSM_HOOK_INIT(inode_invalidate_secctx, selinux_inode_invalidate_secctx),
7699 	LSM_HOOK_INIT(inode_notifysecctx, selinux_inode_notifysecctx),
7700 	LSM_HOOK_INIT(inode_setsecctx, selinux_inode_setsecctx),
7701 
7702 	LSM_HOOK_INIT(unix_stream_connect, selinux_socket_unix_stream_connect),
7703 	LSM_HOOK_INIT(unix_may_send, selinux_socket_unix_may_send),
7704 
7705 	LSM_HOOK_INIT(socket_create, selinux_socket_create),
7706 	LSM_HOOK_INIT(socket_post_create, selinux_socket_post_create),
7707 	LSM_HOOK_INIT(socket_socketpair, selinux_socket_socketpair),
7708 	LSM_HOOK_INIT(socket_bind, selinux_socket_bind),
7709 	LSM_HOOK_INIT(socket_connect, selinux_socket_connect),
7710 	LSM_HOOK_INIT(socket_listen, selinux_socket_listen),
7711 	LSM_HOOK_INIT(socket_accept, selinux_socket_accept),
7712 	LSM_HOOK_INIT(socket_sendmsg, selinux_socket_sendmsg),
7713 	LSM_HOOK_INIT(socket_recvmsg, selinux_socket_recvmsg),
7714 	LSM_HOOK_INIT(socket_getsockname, selinux_socket_getsockname),
7715 	LSM_HOOK_INIT(socket_getpeername, selinux_socket_getpeername),
7716 	LSM_HOOK_INIT(socket_getsockopt, selinux_socket_getsockopt),
7717 	LSM_HOOK_INIT(socket_setsockopt, selinux_socket_setsockopt),
7718 	LSM_HOOK_INIT(socket_shutdown, selinux_socket_shutdown),
7719 	LSM_HOOK_INIT(socket_sock_rcv_skb, selinux_socket_sock_rcv_skb),
7720 	LSM_HOOK_INIT(socket_getpeersec_stream,
7721 			selinux_socket_getpeersec_stream),
7722 	LSM_HOOK_INIT(socket_getpeersec_dgram, selinux_socket_getpeersec_dgram),
7723 	LSM_HOOK_INIT(sk_free_security, selinux_sk_free_security),
7724 	LSM_HOOK_INIT(sk_clone_security, selinux_sk_clone_security),
7725 	LSM_HOOK_INIT(sk_getsecid, selinux_sk_getsecid),
7726 	LSM_HOOK_INIT(sock_graft, selinux_sock_graft),
7727 	LSM_HOOK_INIT(sctp_assoc_request, selinux_sctp_assoc_request),
7728 	LSM_HOOK_INIT(sctp_sk_clone, selinux_sctp_sk_clone),
7729 	LSM_HOOK_INIT(sctp_bind_connect, selinux_sctp_bind_connect),
7730 	LSM_HOOK_INIT(sctp_assoc_established, selinux_sctp_assoc_established),
7731 	LSM_HOOK_INIT(mptcp_add_subflow, selinux_mptcp_add_subflow),
7732 	LSM_HOOK_INIT(inet_conn_request, selinux_inet_conn_request),
7733 	LSM_HOOK_INIT(inet_csk_clone, selinux_inet_csk_clone),
7734 	LSM_HOOK_INIT(inet_conn_established, selinux_inet_conn_established),
7735 	LSM_HOOK_INIT(secmark_relabel_packet, selinux_secmark_relabel_packet),
7736 	LSM_HOOK_INIT(secmark_refcount_inc, selinux_secmark_refcount_inc),
7737 	LSM_HOOK_INIT(secmark_refcount_dec, selinux_secmark_refcount_dec),
7738 	LSM_HOOK_INIT(req_classify_flow, selinux_req_classify_flow),
7739 	LSM_HOOK_INIT(tun_dev_create, selinux_tun_dev_create),
7740 	LSM_HOOK_INIT(tun_dev_attach_queue, selinux_tun_dev_attach_queue),
7741 	LSM_HOOK_INIT(tun_dev_attach, selinux_tun_dev_attach),
7742 	LSM_HOOK_INIT(tun_dev_open, selinux_tun_dev_open),
7743 #ifdef CONFIG_SECURITY_INFINIBAND
7744 	LSM_HOOK_INIT(ib_pkey_access, selinux_ib_pkey_access),
7745 	LSM_HOOK_INIT(ib_endport_manage_subnet,
7746 		      selinux_ib_endport_manage_subnet),
7747 #endif
7748 #ifdef CONFIG_SECURITY_NETWORK_XFRM
7749 	LSM_HOOK_INIT(xfrm_policy_free_security, selinux_xfrm_policy_free),
7750 	LSM_HOOK_INIT(xfrm_policy_delete_security, selinux_xfrm_policy_delete),
7751 	LSM_HOOK_INIT(xfrm_state_free_security, selinux_xfrm_state_free),
7752 	LSM_HOOK_INIT(xfrm_state_delete_security, selinux_xfrm_state_delete),
7753 	LSM_HOOK_INIT(xfrm_policy_lookup, selinux_xfrm_policy_lookup),
7754 	LSM_HOOK_INIT(xfrm_state_pol_flow_match,
7755 			selinux_xfrm_state_pol_flow_match),
7756 	LSM_HOOK_INIT(xfrm_decode_session, selinux_xfrm_decode_session),
7757 #endif
7758 
7759 #ifdef CONFIG_KEYS
7760 	LSM_HOOK_INIT(key_permission, selinux_key_permission),
7761 	LSM_HOOK_INIT(key_getsecurity, selinux_key_getsecurity),
7762 #ifdef CONFIG_KEY_NOTIFICATIONS
7763 	LSM_HOOK_INIT(watch_key, selinux_watch_key),
7764 #endif
7765 #endif
7766 
7767 #ifdef CONFIG_AUDIT
7768 	LSM_HOOK_INIT(audit_rule_known, selinux_audit_rule_known),
7769 	LSM_HOOK_INIT(audit_rule_match, selinux_audit_rule_match),
7770 	LSM_HOOK_INIT(audit_rule_free, selinux_audit_rule_free),
7771 #endif
7772 
7773 #ifdef CONFIG_BPF_SYSCALL
7774 	LSM_HOOK_INIT(bpf, selinux_bpf),
7775 	LSM_HOOK_INIT(bpf_map, selinux_bpf_map),
7776 	LSM_HOOK_INIT(bpf_prog, selinux_bpf_prog),
7777 #endif
7778 
7779 #ifdef CONFIG_PERF_EVENTS
7780 	LSM_HOOK_INIT(perf_event_open, selinux_perf_event_open),
7781 	LSM_HOOK_INIT(perf_event_read, selinux_perf_event_read),
7782 	LSM_HOOK_INIT(perf_event_write, selinux_perf_event_write),
7783 #endif
7784 
7785 #ifdef CONFIG_IO_URING
7786 	LSM_HOOK_INIT(uring_override_creds, selinux_uring_override_creds),
7787 	LSM_HOOK_INIT(uring_sqpoll, selinux_uring_sqpoll),
7788 	LSM_HOOK_INIT(uring_cmd, selinux_uring_cmd),
7789 	LSM_HOOK_INIT(uring_allowed, selinux_uring_allowed),
7790 #endif
7791 
7792 	/*
7793 	 * PUT "CLONING" (ACCESSING + ALLOCATING) HOOKS HERE
7794 	 */
7795 	LSM_HOOK_INIT(fs_context_submount, selinux_fs_context_submount),
7796 	LSM_HOOK_INIT(fs_context_dup, selinux_fs_context_dup),
7797 	LSM_HOOK_INIT(fs_context_parse_param, selinux_fs_context_parse_param),
7798 	LSM_HOOK_INIT(sb_eat_lsm_opts, selinux_sb_eat_lsm_opts),
7799 #ifdef CONFIG_SECURITY_NETWORK_XFRM
7800 	LSM_HOOK_INIT(xfrm_policy_clone_security, selinux_xfrm_policy_clone),
7801 #endif
7802 
7803 	/*
7804 	 * PUT "ALLOCATING" HOOKS HERE
7805 	 */
7806 	LSM_HOOK_INIT(msg_msg_alloc_security, selinux_msg_msg_alloc_security),
7807 	LSM_HOOK_INIT(msg_queue_alloc_security,
7808 		      selinux_msg_queue_alloc_security),
7809 	LSM_HOOK_INIT(shm_alloc_security, selinux_shm_alloc_security),
7810 	LSM_HOOK_INIT(sb_alloc_security, selinux_sb_alloc_security),
7811 	LSM_HOOK_INIT(inode_alloc_security, selinux_inode_alloc_security),
7812 	LSM_HOOK_INIT(sem_alloc_security, selinux_sem_alloc_security),
7813 	LSM_HOOK_INIT(secid_to_secctx, selinux_secid_to_secctx),
7814 	LSM_HOOK_INIT(lsmprop_to_secctx, selinux_lsmprop_to_secctx),
7815 	LSM_HOOK_INIT(inode_getsecctx, selinux_inode_getsecctx),
7816 	LSM_HOOK_INIT(sk_alloc_security, selinux_sk_alloc_security),
7817 	LSM_HOOK_INIT(tun_dev_alloc_security, selinux_tun_dev_alloc_security),
7818 #ifdef CONFIG_SECURITY_INFINIBAND
7819 	LSM_HOOK_INIT(ib_alloc_security, selinux_ib_alloc_security),
7820 #endif
7821 #ifdef CONFIG_SECURITY_NETWORK_XFRM
7822 	LSM_HOOK_INIT(xfrm_policy_alloc_security, selinux_xfrm_policy_alloc),
7823 	LSM_HOOK_INIT(xfrm_state_alloc, selinux_xfrm_state_alloc),
7824 	LSM_HOOK_INIT(xfrm_state_alloc_acquire,
7825 		      selinux_xfrm_state_alloc_acquire),
7826 #endif
7827 #ifdef CONFIG_KEYS
7828 	LSM_HOOK_INIT(key_alloc, selinux_key_alloc),
7829 #endif
7830 #ifdef CONFIG_AUDIT
7831 	LSM_HOOK_INIT(audit_rule_init, selinux_audit_rule_init),
7832 #endif
7833 #ifdef CONFIG_BPF_SYSCALL
7834 	LSM_HOOK_INIT(bpf_map_create, selinux_bpf_map_create),
7835 	LSM_HOOK_INIT(bpf_prog_load, selinux_bpf_prog_load),
7836 	LSM_HOOK_INIT(bpf_token_create, selinux_bpf_token_create),
7837 	LSM_HOOK_INIT(bpf_token_cmd, selinux_bpf_token_cmd),
7838 	LSM_HOOK_INIT(bpf_token_capable, selinux_bpf_token_capable),
7839 #endif
7840 #ifdef CONFIG_PERF_EVENTS
7841 	LSM_HOOK_INIT(perf_event_alloc, selinux_perf_event_alloc),
7842 #endif
7843 };
7844 
7845 static __init int selinux_init(void)
7846 {
7847 	vma_flags_t data_default_flags = VMA_DATA_DEFAULT_FLAGS;
7848 
7849 	pr_info("SELinux:  Initializing.\n");
7850 
7851 	memset(&selinux_state, 0, sizeof(selinux_state));
7852 	enforcing_set(selinux_enforcing_boot);
7853 	selinux_avc_init();
7854 	mutex_init(&selinux_state.status_lock);
7855 	mutex_init(&selinux_state.policy_mutex);
7856 
7857 	/* Set the security state for the initial task. */
7858 	cred_init_security();
7859 
7860 	/* Inform the audit system that secctx is used */
7861 	audit_cfg_lsm(&selinux_lsmid,
7862 		      AUDIT_CFG_LSM_SECCTX_SUBJECT |
7863 		      AUDIT_CFG_LSM_SECCTX_OBJECT);
7864 
7865 	default_noexec = !vma_flags_test(&data_default_flags, VMA_EXEC_BIT);
7866 	if (!default_noexec)
7867 		pr_notice("SELinux:  virtual memory is executable by default\n");
7868 
7869 	avc_init();
7870 
7871 	avtab_cache_init();
7872 
7873 	ebitmap_cache_init();
7874 
7875 	hashtab_cache_init();
7876 
7877 	security_add_hooks(selinux_hooks, ARRAY_SIZE(selinux_hooks),
7878 			   &selinux_lsmid);
7879 
7880 	if (avc_add_callback(selinux_netcache_avc_callback, AVC_CALLBACK_RESET))
7881 		panic("SELinux: Unable to register AVC netcache callback\n");
7882 
7883 	if (avc_add_callback(selinux_lsm_notifier_avc_callback, AVC_CALLBACK_RESET))
7884 		panic("SELinux: Unable to register AVC LSM notifier callback\n");
7885 
7886 	if (avc_add_callback(selinux_audit_rule_avc_callback,
7887 			     AVC_CALLBACK_RESET))
7888 		panic("SELinux: Unable to register AVC audit callback\n");
7889 
7890 	if (selinux_enforcing_boot)
7891 		pr_debug("SELinux:  Starting in enforcing mode\n");
7892 	else
7893 		pr_debug("SELinux:  Starting in permissive mode\n");
7894 
7895 	fs_validate_description("selinux", selinux_fs_parameters);
7896 
7897 	return 0;
7898 }
7899 
7900 static void delayed_superblock_init(struct super_block *sb, void *unused)
7901 {
7902 	selinux_set_mnt_opts(sb, NULL, 0, NULL);
7903 }
7904 
7905 void selinux_complete_init(void)
7906 {
7907 	pr_debug("SELinux:  Completing initialization.\n");
7908 
7909 	/* Set up any superblocks initialized prior to the policy load. */
7910 	pr_debug("SELinux:  Setting up existing superblocks.\n");
7911 	iterate_supers(delayed_superblock_init, NULL);
7912 }
7913 
7914 /* SELinux requires early initialization in order to label
7915    all processes and objects when they are created. */
7916 DEFINE_LSM(selinux) = {
7917 	.id = &selinux_lsmid,
7918 	.flags = LSM_FLAG_LEGACY_MAJOR | LSM_FLAG_EXCLUSIVE,
7919 	.enabled = &selinux_enabled_boot,
7920 	.blobs = &selinux_blob_sizes,
7921 	.init = selinux_init,
7922 	.initcall_device = selinux_initcall,
7923 };
7924 
7925 #if defined(CONFIG_NETFILTER)
7926 static const struct nf_hook_ops selinux_nf_ops[] = {
7927 	{
7928 		.hook =		selinux_ip_postroute,
7929 		.pf =		NFPROTO_IPV4,
7930 		.hooknum =	NF_INET_POST_ROUTING,
7931 		.priority =	NF_IP_PRI_SELINUX_LAST,
7932 	},
7933 	{
7934 		.hook =		selinux_ip_forward,
7935 		.pf =		NFPROTO_IPV4,
7936 		.hooknum =	NF_INET_FORWARD,
7937 		.priority =	NF_IP_PRI_SELINUX_FIRST,
7938 	},
7939 	{
7940 		.hook =		selinux_ip_output,
7941 		.pf =		NFPROTO_IPV4,
7942 		.hooknum =	NF_INET_LOCAL_OUT,
7943 		.priority =	NF_IP_PRI_SELINUX_FIRST,
7944 	},
7945 #if IS_ENABLED(CONFIG_IPV6)
7946 	{
7947 		.hook =		selinux_ip_postroute,
7948 		.pf =		NFPROTO_IPV6,
7949 		.hooknum =	NF_INET_POST_ROUTING,
7950 		.priority =	NF_IP6_PRI_SELINUX_LAST,
7951 	},
7952 	{
7953 		.hook =		selinux_ip_forward,
7954 		.pf =		NFPROTO_IPV6,
7955 		.hooknum =	NF_INET_FORWARD,
7956 		.priority =	NF_IP6_PRI_SELINUX_FIRST,
7957 	},
7958 	{
7959 		.hook =		selinux_ip_output,
7960 		.pf =		NFPROTO_IPV6,
7961 		.hooknum =	NF_INET_LOCAL_OUT,
7962 		.priority =	NF_IP6_PRI_SELINUX_FIRST,
7963 	},
7964 #endif	/* IPV6 */
7965 };
7966 
7967 static int __net_init selinux_nf_register(struct net *net)
7968 {
7969 	return nf_register_net_hooks(net, selinux_nf_ops,
7970 				     ARRAY_SIZE(selinux_nf_ops));
7971 }
7972 
7973 static void __net_exit selinux_nf_unregister(struct net *net)
7974 {
7975 	nf_unregister_net_hooks(net, selinux_nf_ops,
7976 				ARRAY_SIZE(selinux_nf_ops));
7977 }
7978 
7979 static struct pernet_operations selinux_net_ops = {
7980 	.init = selinux_nf_register,
7981 	.exit = selinux_nf_unregister,
7982 };
7983 
7984 int __init selinux_nf_ip_init(void)
7985 {
7986 	int err;
7987 
7988 	if (!selinux_enabled_boot)
7989 		return 0;
7990 
7991 	pr_debug("SELinux:  Registering netfilter hooks\n");
7992 
7993 	err = register_pernet_subsys(&selinux_net_ops);
7994 	if (err)
7995 		panic("SELinux: register_pernet_subsys: error %d\n", err);
7996 
7997 	return 0;
7998 }
7999 #endif /* CONFIG_NETFILTER */
8000