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