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