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