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