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