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