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