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