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