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