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