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