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