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