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