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