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