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