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