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