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