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