xref: /linux/security/selinux/selinuxfs.c (revision 231e9d447ea97033ae8b8dff7b910e6269d7c5af)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Updated: Karl MacMillan <kmacmillan@tresys.com>
3  *
4  *	Added conditional policy language extensions
5  *
6  *  Updated: Hewlett-Packard <paul@paul-moore.com>
7  *
8  *	Added support for the policy capability bitmap
9  *
10  * Copyright (C) 2007 Hewlett-Packard Development Company, L.P.
11  * Copyright (C) 2003 - 2004 Tresys Technology, LLC
12  * Copyright (C) 2004 Red Hat, Inc., James Morris <jmorris@redhat.com>
13  */
14 
15 #include <linux/kernel.h>
16 #include <linux/pagemap.h>
17 #include <linux/slab.h>
18 #include <linux/vmalloc.h>
19 #include <linux/fs.h>
20 #include <linux/fs_context.h>
21 #include <linux/hex.h>
22 #include <linux/mount.h>
23 #include <linux/mutex.h>
24 #include <linux/namei.h>
25 #include <linux/init.h>
26 #include <linux/string.h>
27 #include <linux/security.h>
28 #include <linux/major.h>
29 #include <linux/seq_file.h>
30 #include <linux/percpu.h>
31 #include <linux/audit.h>
32 #include <linux/uaccess.h>
33 #include <linux/kobject.h>
34 #include <linux/ctype.h>
35 
36 /* selinuxfs pseudo filesystem for exporting the security policy API.
37    Based on the proc code and the fs/nfsd/nfsctl.c code. */
38 
39 #include "initcalls.h"
40 #include "flask.h"
41 #include "avc.h"
42 #include "avc_ss.h"
43 #include "security.h"
44 #include "objsec.h"
45 #include "conditional.h"
46 #include "ima.h"
47 
48 enum sel_inos {
49 	SEL_ROOT_INO = 2,
50 	SEL_LOAD,	/* load policy */
51 	SEL_ENFORCE,	/* get or set enforcing status */
52 	SEL_CONTEXT,	/* validate context */
53 	SEL_ACCESS,	/* compute access decision */
54 	SEL_CREATE,	/* compute create labeling decision */
55 	SEL_RELABEL,	/* compute relabeling decision */
56 	SEL_USER,	/* compute reachable user contexts */
57 	SEL_POLICYVERS,	/* return policy version for this kernel */
58 	SEL_COMMIT_BOOLS, /* commit new boolean values */
59 	SEL_MLS,	/* return if MLS policy is enabled */
60 	SEL_DISABLE,	/* disable SELinux until next reboot */
61 	SEL_MEMBER,	/* compute polyinstantiation membership decision */
62 	SEL_CHECKREQPROT, /* check requested protection, not kernel-applied one */
63 	SEL_COMPAT_NET,	/* whether to use old compat network packet controls */
64 	SEL_REJECT_UNKNOWN, /* export unknown reject handling to userspace */
65 	SEL_DENY_UNKNOWN, /* export unknown deny handling to userspace */
66 	SEL_STATUS,	/* export current status using mmap() */
67 	SEL_POLICY,	/* allow userspace to read the in kernel policy */
68 	SEL_VALIDATE_TRANS, /* compute validatetrans decision */
69 	SEL_INO_NEXT,	/* The next inode number to use */
70 };
71 
72 struct selinux_fs_info {
73 	struct dentry *bool_dir;
74 	unsigned int bool_num;
75 	char **bool_pending_names;
76 	int *bool_pending_values;
77 	struct dentry *class_dir;
78 	unsigned long last_class_ino;
79 	unsigned long last_ino;
80 	struct super_block *sb;
81 };
82 
83 static int selinux_fs_info_create(struct super_block *sb)
84 {
85 	struct selinux_fs_info *fsi;
86 
87 	fsi = kzalloc_obj(*fsi);
88 	if (!fsi)
89 		return -ENOMEM;
90 
91 	fsi->last_ino = SEL_INO_NEXT - 1;
92 	fsi->sb = sb;
93 	sb->s_fs_info = fsi;
94 	return 0;
95 }
96 
97 static void selinux_fs_info_free(struct selinux_fs_info *fsi)
98 {
99 	unsigned int i;
100 
101 	if (fsi) {
102 		for (i = 0; i < fsi->bool_num; i++)
103 			kfree(fsi->bool_pending_names[i]);
104 		kfree(fsi->bool_pending_names);
105 		kfree(fsi->bool_pending_values);
106 	}
107 	kfree(fsi);
108 }
109 
110 #define SEL_INITCON_INO_OFFSET		0x01000000
111 #define SEL_BOOL_INO_OFFSET		0x02000000
112 #define SEL_CLASS_INO_OFFSET		0x04000000
113 #define SEL_POLICYCAP_INO_OFFSET	0x08000000
114 #define SEL_INO_MASK			0x00ffffff
115 
116 #define BOOL_DIR_NAME "booleans"
117 #define CLASS_DIR_NAME "class"
118 
119 #define TMPBUFLEN	12
120 static ssize_t sel_read_enforce(struct file *filp, char __user *buf,
121 				size_t count, loff_t *ppos)
122 {
123 	char tmpbuf[TMPBUFLEN];
124 	ssize_t length;
125 
126 	length = scnprintf(tmpbuf, TMPBUFLEN, "%d",
127 			   enforcing_enabled());
128 	return simple_read_from_buffer(buf, count, ppos, tmpbuf, length);
129 }
130 
131 #ifdef CONFIG_SECURITY_SELINUX_DEVELOP
132 static ssize_t sel_write_enforce(struct file *file, const char __user *buf,
133 				 size_t count, loff_t *ppos)
134 
135 {
136 	char *page = NULL;
137 	ssize_t length;
138 	int scan_value;
139 	bool old_value, new_value;
140 
141 	if (count >= PAGE_SIZE)
142 		return -ENOMEM;
143 
144 	/* No partial writes. */
145 	if (*ppos != 0)
146 		return -EINVAL;
147 
148 	page = memdup_user_nul(buf, count);
149 	if (IS_ERR(page))
150 		return PTR_ERR(page);
151 
152 	length = -EINVAL;
153 	if (sscanf(page, "%d", &scan_value) != 1)
154 		goto out;
155 
156 	new_value = !!scan_value;
157 
158 	old_value = enforcing_enabled();
159 	if (new_value != old_value) {
160 		length = avc_has_perm(current_sid(), SECINITSID_SECURITY,
161 				      SECCLASS_SECURITY, SECURITY__SETENFORCE,
162 				      NULL);
163 		if (length)
164 			goto out;
165 		audit_log(audit_context(), GFP_KERNEL, AUDIT_MAC_STATUS,
166 			"enforcing=%d old_enforcing=%d auid=%u ses=%u"
167 			" enabled=1 old-enabled=1 lsm=selinux res=1",
168 			new_value, old_value,
169 			from_kuid(&init_user_ns, audit_get_loginuid(current)),
170 			audit_get_sessionid(current));
171 		enforcing_set(new_value);
172 		if (new_value)
173 			avc_ss_reset(0);
174 		selnl_notify_setenforce(new_value);
175 		selinux_status_update_setenforce(new_value);
176 		if (!new_value)
177 			call_blocking_lsm_notifier(LSM_POLICY_CHANGE, NULL);
178 
179 		selinux_ima_measure_state();
180 	}
181 	length = count;
182 out:
183 	kfree(page);
184 	return length;
185 }
186 #else
187 #define sel_write_enforce NULL
188 #endif
189 
190 static const struct file_operations sel_enforce_ops = {
191 	.read		= sel_read_enforce,
192 	.write		= sel_write_enforce,
193 	.llseek		= generic_file_llseek,
194 };
195 
196 static ssize_t sel_read_handle_unknown(struct file *filp, char __user *buf,
197 					size_t count, loff_t *ppos)
198 {
199 	char tmpbuf[TMPBUFLEN];
200 	ssize_t length;
201 	ino_t ino = file_inode(filp)->i_ino;
202 	int handle_unknown = (ino == SEL_REJECT_UNKNOWN) ?
203 		security_get_reject_unknown() :
204 		!security_get_allow_unknown();
205 
206 	length = scnprintf(tmpbuf, TMPBUFLEN, "%d", handle_unknown);
207 	return simple_read_from_buffer(buf, count, ppos, tmpbuf, length);
208 }
209 
210 static const struct file_operations sel_handle_unknown_ops = {
211 	.read		= sel_read_handle_unknown,
212 	.llseek		= generic_file_llseek,
213 };
214 
215 static int sel_open_handle_status(struct inode *inode, struct file *filp)
216 {
217 	struct page    *status = selinux_kernel_status_page();
218 
219 	if (!status)
220 		return -ENOMEM;
221 
222 	filp->private_data = status;
223 
224 	return 0;
225 }
226 
227 static ssize_t sel_read_handle_status(struct file *filp, char __user *buf,
228 				      size_t count, loff_t *ppos)
229 {
230 	struct page    *status = filp->private_data;
231 
232 	BUG_ON(!status);
233 
234 	return simple_read_from_buffer(buf, count, ppos,
235 				       page_address(status),
236 				       sizeof(struct selinux_kernel_status));
237 }
238 
239 static int sel_mmap_handle_status(struct file *filp,
240 				  struct vm_area_struct *vma)
241 {
242 	struct page    *status = filp->private_data;
243 	unsigned long	size = vma->vm_end - vma->vm_start;
244 
245 	BUG_ON(!status);
246 
247 	/* only allows one page from the head */
248 	if (vma->vm_pgoff > 0 || size != PAGE_SIZE)
249 		return -EIO;
250 	/* disallow writable mapping */
251 	if (vma->vm_flags & VM_WRITE)
252 		return -EPERM;
253 	/* disallow mprotect() turns it into writable */
254 	vm_flags_clear(vma, VM_MAYWRITE);
255 
256 	return remap_pfn_range(vma, vma->vm_start,
257 			       page_to_pfn(status),
258 			       size, vma->vm_page_prot);
259 }
260 
261 static const struct file_operations sel_handle_status_ops = {
262 	.open		= sel_open_handle_status,
263 	.read		= sel_read_handle_status,
264 	.mmap		= sel_mmap_handle_status,
265 	.llseek		= generic_file_llseek,
266 };
267 
268 static ssize_t sel_write_disable(struct file *file, const char __user *buf,
269 				 size_t count, loff_t *ppos)
270 
271 {
272 	/*
273 	 * Setting disable is no longer supported, see
274 	 * https://github.com/SELinuxProject/selinux-kernel/wiki/DEPRECATE-runtime-disable
275 	 */
276 	pr_err_once("SELinux: %s (%d) wrote to disable. This is no longer supported.\n",
277 		    current->comm, current->pid);
278 	return count;
279 }
280 
281 static const struct file_operations sel_disable_ops = {
282 	.write		= sel_write_disable,
283 	.llseek		= generic_file_llseek,
284 };
285 
286 static ssize_t sel_read_policyvers(struct file *filp, char __user *buf,
287 				   size_t count, loff_t *ppos)
288 {
289 	char tmpbuf[TMPBUFLEN];
290 	ssize_t length;
291 
292 	length = scnprintf(tmpbuf, TMPBUFLEN, "%u", POLICYDB_VERSION_MAX);
293 	return simple_read_from_buffer(buf, count, ppos, tmpbuf, length);
294 }
295 
296 static const struct file_operations sel_policyvers_ops = {
297 	.read		= sel_read_policyvers,
298 	.llseek		= generic_file_llseek,
299 };
300 
301 /* declaration for sel_write_load */
302 static int sel_make_bools(struct selinux_policy *newpolicy, struct dentry *bool_dir,
303 			  unsigned int *bool_num, char ***bool_pending_names,
304 			  int **bool_pending_values);
305 static int sel_make_classes(struct selinux_policy *newpolicy,
306 			    struct dentry *class_dir,
307 			    unsigned long *last_class_ino);
308 
309 /* declaration for sel_make_class_dirs */
310 static struct dentry *sel_make_dir(struct dentry *dir, const char *name,
311 			unsigned long *ino);
312 
313 /* declaration for sel_make_policy_nodes */
314 static struct dentry *sel_make_swapover_dir(struct super_block *sb,
315 						unsigned long *ino);
316 
317 static ssize_t sel_read_mls(struct file *filp, char __user *buf,
318 				size_t count, loff_t *ppos)
319 {
320 	char tmpbuf[TMPBUFLEN];
321 	ssize_t length;
322 
323 	length = scnprintf(tmpbuf, TMPBUFLEN, "%d",
324 			   security_mls_enabled());
325 	return simple_read_from_buffer(buf, count, ppos, tmpbuf, length);
326 }
327 
328 static const struct file_operations sel_mls_ops = {
329 	.read		= sel_read_mls,
330 	.llseek		= generic_file_llseek,
331 };
332 
333 struct policy_load_memory {
334 	size_t len;
335 	void *data;
336 };
337 
338 static int sel_open_policy(struct inode *inode, struct file *filp)
339 {
340 	struct policy_load_memory *plm = NULL;
341 	int rc;
342 
343 	rc = avc_has_perm(current_sid(), SECINITSID_SECURITY,
344 			  SECCLASS_SECURITY, SECURITY__READ_POLICY, NULL);
345 	if (rc)
346 		return rc;
347 
348 	plm = kzalloc_obj(*plm);
349 	if (!plm)
350 		return -ENOMEM;
351 
352 	mutex_lock(&selinux_state.policy_mutex);
353 	rc = security_read_policy(&plm->data, &plm->len);
354 	if (rc)
355 		goto err;
356 	if ((size_t)i_size_read(inode) != plm->len) {
357 		inode_lock(inode);
358 		i_size_write(inode, plm->len);
359 		inode_unlock(inode);
360 	}
361 	mutex_unlock(&selinux_state.policy_mutex);
362 
363 	filp->private_data = plm;
364 
365 	return 0;
366 err:
367 	mutex_unlock(&selinux_state.policy_mutex);
368 
369 	if (plm)
370 		vfree(plm->data);
371 	kfree(plm);
372 	return rc;
373 }
374 
375 static int sel_release_policy(struct inode *inode, struct file *filp)
376 {
377 	struct policy_load_memory *plm = filp->private_data;
378 
379 	vfree(plm->data);
380 	kfree(plm);
381 
382 	return 0;
383 }
384 
385 static ssize_t sel_read_policy(struct file *filp, char __user *buf,
386 			       size_t count, loff_t *ppos)
387 {
388 	struct policy_load_memory *plm = filp->private_data;
389 	int ret;
390 
391 	ret = avc_has_perm(current_sid(), SECINITSID_SECURITY,
392 			  SECCLASS_SECURITY, SECURITY__READ_POLICY, NULL);
393 	if (ret)
394 		return ret;
395 
396 	return simple_read_from_buffer(buf, count, ppos, plm->data, plm->len);
397 }
398 
399 static vm_fault_t sel_mmap_policy_fault(struct vm_fault *vmf)
400 {
401 	struct policy_load_memory *plm = vmf->vma->vm_file->private_data;
402 	unsigned long offset;
403 	struct page *page;
404 
405 	if (vmf->flags & (FAULT_FLAG_MKWRITE | FAULT_FLAG_WRITE))
406 		return VM_FAULT_SIGBUS;
407 
408 	offset = vmf->pgoff << PAGE_SHIFT;
409 	if (offset >= roundup(plm->len, PAGE_SIZE))
410 		return VM_FAULT_SIGBUS;
411 
412 	page = vmalloc_to_page(plm->data + offset);
413 	get_page(page);
414 
415 	vmf->page = page;
416 
417 	return 0;
418 }
419 
420 static const struct vm_operations_struct sel_mmap_policy_ops = {
421 	.fault = sel_mmap_policy_fault,
422 	.page_mkwrite = sel_mmap_policy_fault,
423 };
424 
425 static int sel_mmap_policy(struct file *filp, struct vm_area_struct *vma)
426 {
427 	if (vma->vm_flags & VM_SHARED) {
428 		/* do not allow mprotect to make mapping writable */
429 		vm_flags_clear(vma, VM_MAYWRITE);
430 
431 		if (vma->vm_flags & VM_WRITE)
432 			return -EACCES;
433 	}
434 
435 	vm_flags_set(vma, VM_DONTEXPAND | VM_DONTDUMP);
436 	vma->vm_ops = &sel_mmap_policy_ops;
437 
438 	return 0;
439 }
440 
441 static const struct file_operations sel_policy_ops = {
442 	.open		= sel_open_policy,
443 	.read		= sel_read_policy,
444 	.mmap		= sel_mmap_policy,
445 	.release	= sel_release_policy,
446 	.llseek		= generic_file_llseek,
447 };
448 
449 static void sel_remove_old_bool_data(unsigned int bool_num, char **bool_names,
450 				     int *bool_values)
451 {
452 	u32 i;
453 
454 	/* bool_dir cleanup */
455 	for (i = 0; i < bool_num; i++)
456 		kfree(bool_names[i]);
457 	kfree(bool_names);
458 	kfree(bool_values);
459 }
460 
461 static int sel_make_policy_nodes(struct selinux_fs_info *fsi,
462 				struct selinux_policy *newpolicy)
463 {
464 	int ret = 0;
465 	struct dentry *tmp_parent, *tmp_bool_dir, *tmp_class_dir;
466 	struct renamedata rd = {};
467 	unsigned int bool_num = 0;
468 	char **bool_names = NULL;
469 	int *bool_values = NULL;
470 	unsigned long tmp_ino = fsi->last_ino; /* Don't increment last_ino in this function */
471 
472 	tmp_parent = sel_make_swapover_dir(fsi->sb, &tmp_ino);
473 	if (IS_ERR(tmp_parent))
474 		return PTR_ERR(tmp_parent);
475 
476 	tmp_ino = fsi->bool_dir->d_inode->i_ino - 1; /* sel_make_dir will increment and set */
477 	tmp_bool_dir = sel_make_dir(tmp_parent, BOOL_DIR_NAME, &tmp_ino);
478 	if (IS_ERR(tmp_bool_dir)) {
479 		ret = PTR_ERR(tmp_bool_dir);
480 		goto out;
481 	}
482 
483 	tmp_ino = fsi->class_dir->d_inode->i_ino - 1; /* sel_make_dir will increment and set */
484 	tmp_class_dir = sel_make_dir(tmp_parent, CLASS_DIR_NAME, &tmp_ino);
485 	if (IS_ERR(tmp_class_dir)) {
486 		ret = PTR_ERR(tmp_class_dir);
487 		goto out;
488 	}
489 
490 	ret = sel_make_bools(newpolicy, tmp_bool_dir, &bool_num,
491 			     &bool_names, &bool_values);
492 	if (ret)
493 		goto out;
494 
495 	ret = sel_make_classes(newpolicy, tmp_class_dir,
496 			       &fsi->last_class_ino);
497 	if (ret)
498 		goto out;
499 
500 	rd.old_parent = tmp_parent;
501 	rd.new_parent = fsi->sb->s_root;
502 
503 	/* booleans */
504 	ret = start_renaming_two_dentries(&rd, tmp_bool_dir, fsi->bool_dir);
505 	if (ret)
506 		goto out;
507 
508 	d_exchange(tmp_bool_dir, fsi->bool_dir);
509 
510 	swap(fsi->bool_num, bool_num);
511 	swap(fsi->bool_pending_names, bool_names);
512 	swap(fsi->bool_pending_values, bool_values);
513 
514 	fsi->bool_dir = tmp_bool_dir;
515 	end_renaming(&rd);
516 
517 	/* classes */
518 	ret = start_renaming_two_dentries(&rd, tmp_class_dir, fsi->class_dir);
519 	if (ret)
520 		goto out;
521 
522 	d_exchange(tmp_class_dir, fsi->class_dir);
523 	fsi->class_dir = tmp_class_dir;
524 
525 	end_renaming(&rd);
526 
527 out:
528 	sel_remove_old_bool_data(bool_num, bool_names, bool_values);
529 	/* Since the other temporary dirs are children of tmp_parent
530 	 * this will handle all the cleanup in the case of a failure before
531 	 * the swapover
532 	 */
533 	simple_recursive_removal(tmp_parent, NULL);
534 
535 	return ret;
536 }
537 
538 static ssize_t sel_write_load(struct file *file, const char __user *buf,
539 			      size_t count, loff_t *ppos)
540 
541 {
542 	struct selinux_fs_info *fsi;
543 	struct selinux_load_state load_state;
544 	ssize_t length;
545 	void *data = NULL;
546 
547 	/* no partial writes */
548 	if (*ppos)
549 		return -EINVAL;
550 	/* no empty policies */
551 	if (!count)
552 		return -EINVAL;
553 
554 	length = avc_has_perm(current_sid(), SECINITSID_SECURITY,
555 			      SECCLASS_SECURITY, SECURITY__LOAD_POLICY, NULL);
556 	if (length)
557 		return length;
558 
559 	data = vmalloc(count);
560 	if (!data)
561 		return -ENOMEM;
562 	if (copy_from_user(data, buf, count) != 0) {
563 		length = -EFAULT;
564 		goto out;
565 	}
566 
567 	mutex_lock(&selinux_state.policy_mutex);
568 	length = security_load_policy(data, count, &load_state);
569 	if (length) {
570 		pr_warn_ratelimited("SELinux: failed to load policy\n");
571 		goto out_unlock;
572 	}
573 	fsi = file_inode(file)->i_sb->s_fs_info;
574 	length = sel_make_policy_nodes(fsi, load_state.policy);
575 	if (length) {
576 		pr_warn_ratelimited("SELinux: failed to initialize selinuxfs\n");
577 		selinux_policy_cancel(&load_state);
578 		goto out_unlock;
579 	}
580 
581 	selinux_policy_commit(&load_state);
582 	length = count;
583 	audit_log(audit_context(), GFP_KERNEL, AUDIT_MAC_POLICY_LOAD,
584 		"auid=%u ses=%u lsm=selinux res=1",
585 		from_kuid(&init_user_ns, audit_get_loginuid(current)),
586 		audit_get_sessionid(current));
587 
588 out_unlock:
589 	mutex_unlock(&selinux_state.policy_mutex);
590 out:
591 	vfree(data);
592 	return length;
593 }
594 
595 static const struct file_operations sel_load_ops = {
596 	.write		= sel_write_load,
597 	.llseek		= generic_file_llseek,
598 };
599 
600 static ssize_t sel_write_context(struct file *file, char *buf, size_t size)
601 {
602 	char *canon = NULL;
603 	u32 sid, len;
604 	ssize_t length;
605 
606 	length = avc_has_perm(current_sid(), SECINITSID_SECURITY,
607 			      SECCLASS_SECURITY, SECURITY__CHECK_CONTEXT, NULL);
608 	if (length)
609 		goto out;
610 
611 	length = security_context_to_sid(buf, size, &sid, GFP_KERNEL);
612 	if (length)
613 		goto out;
614 
615 	length = security_sid_to_context(sid, &canon, &len);
616 	if (length)
617 		goto out;
618 
619 	length = -ERANGE;
620 	if (len > SIMPLE_TRANSACTION_LIMIT) {
621 		pr_err("SELinux: %s:  context size (%u) exceeds "
622 			"payload max\n", __func__, len);
623 		goto out;
624 	}
625 
626 	memcpy(buf, canon, len);
627 	length = len;
628 out:
629 	kfree(canon);
630 	return length;
631 }
632 
633 static ssize_t sel_read_checkreqprot(struct file *filp, char __user *buf,
634 				     size_t count, loff_t *ppos)
635 {
636 	char tmpbuf[TMPBUFLEN];
637 	ssize_t length;
638 
639 	length = scnprintf(tmpbuf, TMPBUFLEN, "%u",
640 			   checkreqprot_get());
641 	return simple_read_from_buffer(buf, count, ppos, tmpbuf, length);
642 }
643 
644 static ssize_t sel_write_checkreqprot(struct file *file, const char __user *buf,
645 				      size_t count, loff_t *ppos)
646 {
647 	/*
648 	 * Setting checkreqprot is no longer supported, see
649 	 * https://github.com/SELinuxProject/selinux-kernel/wiki/DEPRECATE-checkreqprot
650 	 */
651 	pr_err_once("SELinux: %s (%d) wrote to checkreqprot. This is no longer supported.\n",
652 		    current->comm, current->pid);
653 	return count;
654 }
655 static const struct file_operations sel_checkreqprot_ops = {
656 	.read		= sel_read_checkreqprot,
657 	.write		= sel_write_checkreqprot,
658 	.llseek		= generic_file_llseek,
659 };
660 
661 static ssize_t sel_write_validatetrans(struct file *file,
662 					const char __user *buf,
663 					size_t count, loff_t *ppos)
664 {
665 	char *oldcon = NULL, *newcon = NULL, *taskcon = NULL;
666 	char *req = NULL;
667 	u32 osid, nsid, tsid;
668 	u16 tclass;
669 	int rc;
670 
671 	rc = avc_has_perm(current_sid(), SECINITSID_SECURITY,
672 			  SECCLASS_SECURITY, SECURITY__VALIDATE_TRANS, NULL);
673 	if (rc)
674 		goto out;
675 
676 	rc = -ENOMEM;
677 	if (count >= PAGE_SIZE)
678 		goto out;
679 
680 	/* No partial writes. */
681 	rc = -EINVAL;
682 	if (*ppos != 0)
683 		goto out;
684 
685 	req = memdup_user_nul(buf, count);
686 	if (IS_ERR(req)) {
687 		rc = PTR_ERR(req);
688 		req = NULL;
689 		goto out;
690 	}
691 
692 	rc = -ENOMEM;
693 	oldcon = kzalloc(count + 1, GFP_KERNEL);
694 	if (!oldcon)
695 		goto out;
696 
697 	newcon = kzalloc(count + 1, GFP_KERNEL);
698 	if (!newcon)
699 		goto out;
700 
701 	taskcon = kzalloc(count + 1, GFP_KERNEL);
702 	if (!taskcon)
703 		goto out;
704 
705 	rc = -EINVAL;
706 	if (sscanf(req, "%s %s %hu %s", oldcon, newcon, &tclass, taskcon) != 4)
707 		goto out;
708 
709 	rc = security_context_str_to_sid(oldcon, &osid, GFP_KERNEL);
710 	if (rc)
711 		goto out;
712 
713 	rc = security_context_str_to_sid(newcon, &nsid, GFP_KERNEL);
714 	if (rc)
715 		goto out;
716 
717 	rc = security_context_str_to_sid(taskcon, &tsid, GFP_KERNEL);
718 	if (rc)
719 		goto out;
720 
721 	rc = security_validate_transition_user(osid, nsid, tsid, tclass);
722 	if (!rc)
723 		rc = count;
724 out:
725 	kfree(req);
726 	kfree(oldcon);
727 	kfree(newcon);
728 	kfree(taskcon);
729 	return rc;
730 }
731 
732 static const struct file_operations sel_transition_ops = {
733 	.write		= sel_write_validatetrans,
734 	.llseek		= generic_file_llseek,
735 };
736 
737 /*
738  * Remaining nodes use transaction based IO methods like nfsd/nfsctl.c
739  */
740 static ssize_t sel_write_access(struct file *file, char *buf, size_t size);
741 static ssize_t sel_write_create(struct file *file, char *buf, size_t size);
742 static ssize_t sel_write_relabel(struct file *file, char *buf, size_t size);
743 static ssize_t sel_write_user(struct file *file, char *buf, size_t size);
744 static ssize_t sel_write_member(struct file *file, char *buf, size_t size);
745 
746 static ssize_t (*const write_op[])(struct file *, char *, size_t) = {
747 	[SEL_ACCESS] = sel_write_access,
748 	[SEL_CREATE] = sel_write_create,
749 	[SEL_RELABEL] = sel_write_relabel,
750 	[SEL_USER] = sel_write_user,
751 	[SEL_MEMBER] = sel_write_member,
752 	[SEL_CONTEXT] = sel_write_context,
753 };
754 
755 static ssize_t selinux_transaction_write(struct file *file, const char __user *buf, size_t size, loff_t *pos)
756 {
757 	ino_t ino = file_inode(file)->i_ino;
758 	char *data;
759 	ssize_t rv;
760 
761 	if (ino >= ARRAY_SIZE(write_op) || !write_op[ino])
762 		return -EINVAL;
763 
764 	data = simple_transaction_get(file, buf, size);
765 	if (IS_ERR(data))
766 		return PTR_ERR(data);
767 
768 	rv = write_op[ino](file, data, size);
769 	if (rv > 0) {
770 		simple_transaction_set(file, rv);
771 		rv = size;
772 	}
773 	return rv;
774 }
775 
776 static const struct file_operations transaction_ops = {
777 	.write		= selinux_transaction_write,
778 	.read		= simple_transaction_read,
779 	.release	= simple_transaction_release,
780 	.llseek		= generic_file_llseek,
781 };
782 
783 /*
784  * payload - write methods
785  * If the method has a response, the response should be put in buf,
786  * and the length returned.  Otherwise return 0 or -error.
787  */
788 
789 static ssize_t sel_write_access(struct file *file, char *buf, size_t size)
790 {
791 	char *scon = NULL, *tcon = NULL;
792 	u32 ssid, tsid;
793 	u16 tclass;
794 	struct av_decision avd;
795 	ssize_t length;
796 
797 	length = avc_has_perm(current_sid(), SECINITSID_SECURITY,
798 			      SECCLASS_SECURITY, SECURITY__COMPUTE_AV, NULL);
799 	if (length)
800 		goto out;
801 
802 	length = -ENOMEM;
803 	scon = kzalloc(size + 1, GFP_KERNEL);
804 	if (!scon)
805 		goto out;
806 
807 	length = -ENOMEM;
808 	tcon = kzalloc(size + 1, GFP_KERNEL);
809 	if (!tcon)
810 		goto out;
811 
812 	length = -EINVAL;
813 	if (sscanf(buf, "%s %s %hu", scon, tcon, &tclass) != 3)
814 		goto out;
815 
816 	length = security_context_str_to_sid(scon, &ssid, GFP_KERNEL);
817 	if (length)
818 		goto out;
819 
820 	length = security_context_str_to_sid(tcon, &tsid, GFP_KERNEL);
821 	if (length)
822 		goto out;
823 
824 	security_compute_av_user(ssid, tsid, tclass, &avd);
825 
826 	length = scnprintf(buf, SIMPLE_TRANSACTION_LIMIT,
827 			  "%x %x %x %x %u %x",
828 			  avd.allowed, 0xffffffff,
829 			  avd.auditallow, avd.auditdeny,
830 			  avd.seqno, avd.flags);
831 out:
832 	kfree(tcon);
833 	kfree(scon);
834 	return length;
835 }
836 
837 static ssize_t sel_write_create(struct file *file, char *buf, size_t size)
838 {
839 	char *scon = NULL, *tcon = NULL;
840 	char *namebuf = NULL, *objname = NULL;
841 	u32 ssid, tsid, newsid;
842 	u16 tclass;
843 	ssize_t length;
844 	char *newcon = NULL;
845 	u32 len;
846 	int nargs;
847 
848 	length = avc_has_perm(current_sid(), SECINITSID_SECURITY,
849 			      SECCLASS_SECURITY, SECURITY__COMPUTE_CREATE,
850 			      NULL);
851 	if (length)
852 		goto out;
853 
854 	length = -ENOMEM;
855 	scon = kzalloc(size + 1, GFP_KERNEL);
856 	if (!scon)
857 		goto out;
858 
859 	length = -ENOMEM;
860 	tcon = kzalloc(size + 1, GFP_KERNEL);
861 	if (!tcon)
862 		goto out;
863 
864 	length = -ENOMEM;
865 	namebuf = kzalloc(size + 1, GFP_KERNEL);
866 	if (!namebuf)
867 		goto out;
868 
869 	length = -EINVAL;
870 	nargs = sscanf(buf, "%s %s %hu %s", scon, tcon, &tclass, namebuf);
871 	if (nargs < 3 || nargs > 4)
872 		goto out;
873 	if (nargs == 4) {
874 		/*
875 		 * If and when the name of new object to be queried contains
876 		 * either whitespace or multibyte characters, they shall be
877 		 * encoded based on the percentage-encoding rule.
878 		 * If not encoded, the sscanf logic picks up only left-half
879 		 * of the supplied name; split by a whitespace unexpectedly.
880 		 */
881 		char   *r, *w;
882 		int     c1, c2;
883 
884 		r = w = namebuf;
885 		do {
886 			c1 = *r++;
887 			if (c1 == '+')
888 				c1 = ' ';
889 			else if (c1 == '%') {
890 				c1 = hex_to_bin(*r++);
891 				if (c1 < 0)
892 					goto out;
893 				c2 = hex_to_bin(*r++);
894 				if (c2 < 0)
895 					goto out;
896 				c1 = (c1 << 4) | c2;
897 			}
898 			*w++ = c1;
899 		} while (c1 != '\0');
900 
901 		objname = namebuf;
902 	}
903 
904 	length = security_context_str_to_sid(scon, &ssid, GFP_KERNEL);
905 	if (length)
906 		goto out;
907 
908 	length = security_context_str_to_sid(tcon, &tsid, GFP_KERNEL);
909 	if (length)
910 		goto out;
911 
912 	length = security_transition_sid_user(ssid, tsid, tclass,
913 					      objname, &newsid);
914 	if (length)
915 		goto out;
916 
917 	length = security_sid_to_context(newsid, &newcon, &len);
918 	if (length)
919 		goto out;
920 
921 	length = -ERANGE;
922 	if (len > SIMPLE_TRANSACTION_LIMIT) {
923 		pr_err("SELinux: %s:  context size (%u) exceeds "
924 			"payload max\n", __func__, len);
925 		goto out;
926 	}
927 
928 	memcpy(buf, newcon, len);
929 	length = len;
930 out:
931 	kfree(newcon);
932 	kfree(namebuf);
933 	kfree(tcon);
934 	kfree(scon);
935 	return length;
936 }
937 
938 static ssize_t sel_write_relabel(struct file *file, char *buf, size_t size)
939 {
940 	char *scon = NULL, *tcon = NULL;
941 	u32 ssid, tsid, newsid;
942 	u16 tclass;
943 	ssize_t length;
944 	char *newcon = NULL;
945 	u32 len;
946 
947 	length = avc_has_perm(current_sid(), SECINITSID_SECURITY,
948 			      SECCLASS_SECURITY, SECURITY__COMPUTE_RELABEL,
949 			      NULL);
950 	if (length)
951 		goto out;
952 
953 	length = -ENOMEM;
954 	scon = kzalloc(size + 1, GFP_KERNEL);
955 	if (!scon)
956 		goto out;
957 
958 	length = -ENOMEM;
959 	tcon = kzalloc(size + 1, GFP_KERNEL);
960 	if (!tcon)
961 		goto out;
962 
963 	length = -EINVAL;
964 	if (sscanf(buf, "%s %s %hu", scon, tcon, &tclass) != 3)
965 		goto out;
966 
967 	length = security_context_str_to_sid(scon, &ssid, GFP_KERNEL);
968 	if (length)
969 		goto out;
970 
971 	length = security_context_str_to_sid(tcon, &tsid, GFP_KERNEL);
972 	if (length)
973 		goto out;
974 
975 	length = security_change_sid(ssid, tsid, tclass, &newsid);
976 	if (length)
977 		goto out;
978 
979 	length = security_sid_to_context(newsid, &newcon, &len);
980 	if (length)
981 		goto out;
982 
983 	length = -ERANGE;
984 	if (len > SIMPLE_TRANSACTION_LIMIT)
985 		goto out;
986 
987 	memcpy(buf, newcon, len);
988 	length = len;
989 out:
990 	kfree(newcon);
991 	kfree(tcon);
992 	kfree(scon);
993 	return length;
994 }
995 
996 static ssize_t sel_write_user(struct file *file, char *buf, size_t size)
997 {
998 	pr_err_once("SELinux: %s (%d) wrote to user. This is no longer supported.\n",
999 		    current->comm, current->pid);
1000 	buf[0] = '0';
1001 	buf[1] = 0;
1002 	return 2;
1003 }
1004 
1005 static ssize_t sel_write_member(struct file *file, char *buf, size_t size)
1006 {
1007 	char *scon = NULL, *tcon = NULL;
1008 	u32 ssid, tsid, newsid;
1009 	u16 tclass;
1010 	ssize_t length;
1011 	char *newcon = NULL;
1012 	u32 len;
1013 
1014 	length = avc_has_perm(current_sid(), SECINITSID_SECURITY,
1015 			      SECCLASS_SECURITY, SECURITY__COMPUTE_MEMBER,
1016 			      NULL);
1017 	if (length)
1018 		goto out;
1019 
1020 	length = -ENOMEM;
1021 	scon = kzalloc(size + 1, GFP_KERNEL);
1022 	if (!scon)
1023 		goto out;
1024 
1025 	length = -ENOMEM;
1026 	tcon = kzalloc(size + 1, GFP_KERNEL);
1027 	if (!tcon)
1028 		goto out;
1029 
1030 	length = -EINVAL;
1031 	if (sscanf(buf, "%s %s %hu", scon, tcon, &tclass) != 3)
1032 		goto out;
1033 
1034 	length = security_context_str_to_sid(scon, &ssid, GFP_KERNEL);
1035 	if (length)
1036 		goto out;
1037 
1038 	length = security_context_str_to_sid(tcon, &tsid, GFP_KERNEL);
1039 	if (length)
1040 		goto out;
1041 
1042 	length = security_member_sid(ssid, tsid, tclass, &newsid);
1043 	if (length)
1044 		goto out;
1045 
1046 	length = security_sid_to_context(newsid, &newcon, &len);
1047 	if (length)
1048 		goto out;
1049 
1050 	length = -ERANGE;
1051 	if (len > SIMPLE_TRANSACTION_LIMIT) {
1052 		pr_err("SELinux: %s:  context size (%u) exceeds "
1053 			"payload max\n", __func__, len);
1054 		goto out;
1055 	}
1056 
1057 	memcpy(buf, newcon, len);
1058 	length = len;
1059 out:
1060 	kfree(newcon);
1061 	kfree(tcon);
1062 	kfree(scon);
1063 	return length;
1064 }
1065 
1066 static struct inode *sel_make_inode(struct super_block *sb, umode_t mode)
1067 {
1068 	struct inode *ret = new_inode(sb);
1069 
1070 	if (ret) {
1071 		ret->i_mode = mode;
1072 		simple_inode_init_ts(ret);
1073 	}
1074 	return ret;
1075 }
1076 
1077 static struct dentry *sel_attach(struct dentry *parent, const char *name,
1078 				 struct inode *inode)
1079 {
1080 	struct dentry *dentry = d_alloc_name(parent, name);
1081 	if (unlikely(!dentry)) {
1082 		iput(inode);
1083 		return ERR_PTR(-ENOMEM);
1084 	}
1085 	d_make_persistent(dentry, inode);
1086 	dput(dentry);
1087 	return dentry;
1088 }
1089 
1090 static int sel_attach_file(struct dentry *parent, const char *name,
1091 			   struct inode *inode)
1092 {
1093 	struct dentry *dentry = sel_attach(parent, name, inode);
1094 	return PTR_ERR_OR_ZERO(dentry);
1095 }
1096 
1097 static ssize_t sel_read_bool(struct file *filep, char __user *buf,
1098 			     size_t count, loff_t *ppos)
1099 {
1100 	struct selinux_fs_info *fsi = file_inode(filep)->i_sb->s_fs_info;
1101 	char buffer[4];
1102 	ssize_t length;
1103 	ssize_t ret;
1104 	int cur_enforcing;
1105 	unsigned index = file_inode(filep)->i_ino & SEL_INO_MASK;
1106 	const char *name = filep->f_path.dentry->d_name.name;
1107 
1108 	mutex_lock(&selinux_state.policy_mutex);
1109 
1110 	ret = -EINVAL;
1111 	if (index >= fsi->bool_num || strcmp(name,
1112 					     fsi->bool_pending_names[index]))
1113 		goto out_unlock;
1114 
1115 	cur_enforcing = security_get_bool_value(index);
1116 	if (cur_enforcing < 0) {
1117 		ret = cur_enforcing;
1118 		goto out_unlock;
1119 	}
1120 	length = scnprintf(buffer, sizeof(buffer), "%d %d", !!cur_enforcing,
1121 			  !!fsi->bool_pending_values[index]);
1122 	mutex_unlock(&selinux_state.policy_mutex);
1123 	return simple_read_from_buffer(buf, count, ppos, buffer, length);
1124 
1125 out_unlock:
1126 	mutex_unlock(&selinux_state.policy_mutex);
1127 	return ret;
1128 }
1129 
1130 static ssize_t sel_write_bool(struct file *filep, const char __user *buf,
1131 			      size_t count, loff_t *ppos)
1132 {
1133 	struct selinux_fs_info *fsi = file_inode(filep)->i_sb->s_fs_info;
1134 	char *page = NULL;
1135 	ssize_t length;
1136 	int new_value;
1137 	unsigned index = file_inode(filep)->i_ino & SEL_INO_MASK;
1138 	const char *name = filep->f_path.dentry->d_name.name;
1139 
1140 	if (count >= PAGE_SIZE)
1141 		return -ENOMEM;
1142 
1143 	/* No partial writes. */
1144 	if (*ppos != 0)
1145 		return -EINVAL;
1146 
1147 	page = memdup_user_nul(buf, count);
1148 	if (IS_ERR(page))
1149 		return PTR_ERR(page);
1150 
1151 	mutex_lock(&selinux_state.policy_mutex);
1152 
1153 	length = avc_has_perm(current_sid(), SECINITSID_SECURITY,
1154 			      SECCLASS_SECURITY, SECURITY__SETBOOL,
1155 			      NULL);
1156 	if (length)
1157 		goto out;
1158 
1159 	length = -EINVAL;
1160 	if (index >= fsi->bool_num || strcmp(name,
1161 					     fsi->bool_pending_names[index]))
1162 		goto out;
1163 
1164 	length = -EINVAL;
1165 	if (sscanf(page, "%d", &new_value) != 1)
1166 		goto out;
1167 
1168 	if (new_value)
1169 		new_value = 1;
1170 
1171 	fsi->bool_pending_values[index] = new_value;
1172 	length = count;
1173 
1174 out:
1175 	mutex_unlock(&selinux_state.policy_mutex);
1176 	kfree(page);
1177 	return length;
1178 }
1179 
1180 static const struct file_operations sel_bool_ops = {
1181 	.read		= sel_read_bool,
1182 	.write		= sel_write_bool,
1183 	.llseek		= generic_file_llseek,
1184 };
1185 
1186 static ssize_t sel_commit_bools_write(struct file *filep,
1187 				      const char __user *buf,
1188 				      size_t count, loff_t *ppos)
1189 {
1190 	struct selinux_fs_info *fsi = file_inode(filep)->i_sb->s_fs_info;
1191 	char *page = NULL;
1192 	ssize_t length;
1193 	int new_value;
1194 
1195 	if (count >= PAGE_SIZE)
1196 		return -ENOMEM;
1197 
1198 	/* No partial writes. */
1199 	if (*ppos != 0)
1200 		return -EINVAL;
1201 
1202 	page = memdup_user_nul(buf, count);
1203 	if (IS_ERR(page))
1204 		return PTR_ERR(page);
1205 
1206 	mutex_lock(&selinux_state.policy_mutex);
1207 
1208 	length = avc_has_perm(current_sid(), SECINITSID_SECURITY,
1209 			      SECCLASS_SECURITY, SECURITY__SETBOOL,
1210 			      NULL);
1211 	if (length)
1212 		goto out;
1213 
1214 	length = -EINVAL;
1215 	if (sscanf(page, "%d", &new_value) != 1)
1216 		goto out;
1217 
1218 	length = 0;
1219 	if (new_value && fsi->bool_pending_values)
1220 		length = security_set_bools(fsi->bool_num,
1221 					    fsi->bool_pending_values);
1222 
1223 	if (!length)
1224 		length = count;
1225 
1226 out:
1227 	mutex_unlock(&selinux_state.policy_mutex);
1228 	kfree(page);
1229 	return length;
1230 }
1231 
1232 static const struct file_operations sel_commit_bools_ops = {
1233 	.write		= sel_commit_bools_write,
1234 	.llseek		= generic_file_llseek,
1235 };
1236 
1237 static int sel_make_bools(struct selinux_policy *newpolicy, struct dentry *bool_dir,
1238 			  unsigned int *bool_num, char ***bool_pending_names,
1239 			  int **bool_pending_values)
1240 {
1241 	int ret;
1242 	char **names, *page;
1243 	u32 i, num;
1244 
1245 	page = kzalloc(PAGE_SIZE, GFP_KERNEL);
1246 	if (!page)
1247 		return -ENOMEM;
1248 
1249 	ret = security_get_bools(newpolicy, &num, &names, bool_pending_values);
1250 	if (ret)
1251 		goto out;
1252 
1253 	*bool_num = num;
1254 	*bool_pending_names = names;
1255 
1256 	for (i = 0; !ret && i < num; i++) {
1257 		struct inode *inode;
1258 		struct inode_security_struct *isec;
1259 		ssize_t len;
1260 		u32 sid;
1261 
1262 		len = snprintf(page, PAGE_SIZE, "/%s/%s", BOOL_DIR_NAME, names[i]);
1263 		if (len >= PAGE_SIZE) {
1264 			ret = -ENAMETOOLONG;
1265 			break;
1266 		}
1267 
1268 		inode = sel_make_inode(bool_dir->d_sb, S_IFREG | S_IRUGO | S_IWUSR);
1269 		if (!inode) {
1270 			ret = -ENOMEM;
1271 			break;
1272 		}
1273 
1274 		isec = selinux_inode(inode);
1275 		ret = selinux_policy_genfs_sid(newpolicy, "selinuxfs", page,
1276 					 SECCLASS_FILE, &sid);
1277 		if (ret) {
1278 			pr_warn_ratelimited("SELinux: no sid found, defaulting to security isid for %s\n",
1279 					   page);
1280 			sid = SECINITSID_SECURITY;
1281 		}
1282 
1283 		isec->sid = sid;
1284 		isec->initialized = LABEL_INITIALIZED;
1285 		inode->i_fop = &sel_bool_ops;
1286 		inode->i_ino = i|SEL_BOOL_INO_OFFSET;
1287 
1288 		ret = sel_attach_file(bool_dir, names[i], inode);
1289 	}
1290 out:
1291 	kfree(page);
1292 	return ret;
1293 }
1294 
1295 static ssize_t sel_read_avc_cache_threshold(struct file *filp, char __user *buf,
1296 					    size_t count, loff_t *ppos)
1297 {
1298 	char tmpbuf[TMPBUFLEN];
1299 	ssize_t length;
1300 
1301 	length = scnprintf(tmpbuf, TMPBUFLEN, "%u",
1302 			   avc_get_cache_threshold());
1303 	return simple_read_from_buffer(buf, count, ppos, tmpbuf, length);
1304 }
1305 
1306 static ssize_t sel_write_avc_cache_threshold(struct file *file,
1307 					     const char __user *buf,
1308 					     size_t count, loff_t *ppos)
1309 
1310 {
1311 	char *page;
1312 	ssize_t ret;
1313 	unsigned int new_value;
1314 
1315 	ret = avc_has_perm(current_sid(), SECINITSID_SECURITY,
1316 			   SECCLASS_SECURITY, SECURITY__SETSECPARAM,
1317 			   NULL);
1318 	if (ret)
1319 		return ret;
1320 
1321 	if (count >= PAGE_SIZE)
1322 		return -ENOMEM;
1323 
1324 	/* No partial writes. */
1325 	if (*ppos != 0)
1326 		return -EINVAL;
1327 
1328 	page = memdup_user_nul(buf, count);
1329 	if (IS_ERR(page))
1330 		return PTR_ERR(page);
1331 
1332 	ret = -EINVAL;
1333 	if (sscanf(page, "%u", &new_value) != 1)
1334 		goto out;
1335 
1336 	avc_set_cache_threshold(new_value);
1337 
1338 	ret = count;
1339 out:
1340 	kfree(page);
1341 	return ret;
1342 }
1343 
1344 static ssize_t sel_read_avc_hash_stats(struct file *filp, char __user *buf,
1345 				       size_t count, loff_t *ppos)
1346 {
1347 	char *page;
1348 	ssize_t length;
1349 
1350 	page = kmalloc(PAGE_SIZE, GFP_KERNEL);
1351 	if (!page)
1352 		return -ENOMEM;
1353 
1354 	length = avc_get_hash_stats(page);
1355 	if (length >= 0)
1356 		length = simple_read_from_buffer(buf, count, ppos, page, length);
1357 	kfree(page);
1358 
1359 	return length;
1360 }
1361 
1362 static ssize_t sel_read_sidtab_hash_stats(struct file *filp, char __user *buf,
1363 					size_t count, loff_t *ppos)
1364 {
1365 	char *page;
1366 	ssize_t length;
1367 
1368 	page = kmalloc(PAGE_SIZE, GFP_KERNEL);
1369 	if (!page)
1370 		return -ENOMEM;
1371 
1372 	length = security_sidtab_hash_stats(page);
1373 	if (length >= 0)
1374 		length = simple_read_from_buffer(buf, count, ppos, page,
1375 						length);
1376 	kfree(page);
1377 
1378 	return length;
1379 }
1380 
1381 static const struct file_operations sel_sidtab_hash_stats_ops = {
1382 	.read		= sel_read_sidtab_hash_stats,
1383 	.llseek		= generic_file_llseek,
1384 };
1385 
1386 static const struct file_operations sel_avc_cache_threshold_ops = {
1387 	.read		= sel_read_avc_cache_threshold,
1388 	.write		= sel_write_avc_cache_threshold,
1389 	.llseek		= generic_file_llseek,
1390 };
1391 
1392 static const struct file_operations sel_avc_hash_stats_ops = {
1393 	.read		= sel_read_avc_hash_stats,
1394 	.llseek		= generic_file_llseek,
1395 };
1396 
1397 #ifdef CONFIG_SECURITY_SELINUX_AVC_STATS
1398 static struct avc_cache_stats *sel_avc_get_stat_idx(loff_t *idx)
1399 {
1400 	loff_t cpu;
1401 
1402 	for (cpu = *idx; cpu < nr_cpu_ids; ++cpu) {
1403 		if (!cpu_possible(cpu))
1404 			continue;
1405 		*idx = cpu + 1;
1406 		return &per_cpu(avc_cache_stats, cpu);
1407 	}
1408 	(*idx)++;
1409 	return NULL;
1410 }
1411 
1412 static void *sel_avc_stats_seq_start(struct seq_file *seq, loff_t *pos)
1413 {
1414 	loff_t n = *pos - 1;
1415 
1416 	if (*pos == 0)
1417 		return SEQ_START_TOKEN;
1418 
1419 	return sel_avc_get_stat_idx(&n);
1420 }
1421 
1422 static void *sel_avc_stats_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1423 {
1424 	return sel_avc_get_stat_idx(pos);
1425 }
1426 
1427 static int sel_avc_stats_seq_show(struct seq_file *seq, void *v)
1428 {
1429 	struct avc_cache_stats *st = v;
1430 
1431 	if (v == SEQ_START_TOKEN) {
1432 		seq_puts(seq,
1433 			 "lookups hits misses allocations reclaims frees\n");
1434 	} else {
1435 		unsigned int lookups = st->lookups;
1436 		unsigned int misses = st->misses;
1437 		unsigned int hits = lookups - misses;
1438 		seq_printf(seq, "%u %u %u %u %u %u\n", lookups,
1439 			   hits, misses, st->allocations,
1440 			   st->reclaims, st->frees);
1441 	}
1442 	return 0;
1443 }
1444 
1445 static void sel_avc_stats_seq_stop(struct seq_file *seq, void *v)
1446 { }
1447 
1448 static const struct seq_operations sel_avc_cache_stats_seq_ops = {
1449 	.start		= sel_avc_stats_seq_start,
1450 	.next		= sel_avc_stats_seq_next,
1451 	.show		= sel_avc_stats_seq_show,
1452 	.stop		= sel_avc_stats_seq_stop,
1453 };
1454 
1455 static int sel_open_avc_cache_stats(struct inode *inode, struct file *file)
1456 {
1457 	return seq_open(file, &sel_avc_cache_stats_seq_ops);
1458 }
1459 
1460 static const struct file_operations sel_avc_cache_stats_ops = {
1461 	.open		= sel_open_avc_cache_stats,
1462 	.read		= seq_read,
1463 	.llseek		= seq_lseek,
1464 	.release	= seq_release,
1465 };
1466 #endif
1467 
1468 static int sel_make_avc_files(struct dentry *dir)
1469 {
1470 	struct super_block *sb = dir->d_sb;
1471 	struct selinux_fs_info *fsi = sb->s_fs_info;
1472 	unsigned int i;
1473 	int err = 0;
1474 	static const struct tree_descr files[] = {
1475 		{ "cache_threshold",
1476 		  &sel_avc_cache_threshold_ops, S_IRUGO|S_IWUSR },
1477 		{ "hash_stats", &sel_avc_hash_stats_ops, S_IRUGO },
1478 #ifdef CONFIG_SECURITY_SELINUX_AVC_STATS
1479 		{ "cache_stats", &sel_avc_cache_stats_ops, S_IRUGO },
1480 #endif
1481 	};
1482 
1483 	for (i = 0; !err && i < ARRAY_SIZE(files); i++) {
1484 		struct inode *inode;
1485 
1486 		inode = sel_make_inode(dir->d_sb, S_IFREG|files[i].mode);
1487 		if (!inode)
1488 			return -ENOMEM;
1489 
1490 		inode->i_fop = files[i].ops;
1491 		inode->i_ino = ++fsi->last_ino;
1492 
1493 		err = sel_attach_file(dir, files[i].name, inode);
1494 	}
1495 
1496 	return err;
1497 }
1498 
1499 static int sel_make_ss_files(struct dentry *dir)
1500 {
1501 	struct super_block *sb = dir->d_sb;
1502 	struct selinux_fs_info *fsi = sb->s_fs_info;
1503 	unsigned int i;
1504 	int err = 0;
1505 	static const struct tree_descr files[] = {
1506 		{ "sidtab_hash_stats", &sel_sidtab_hash_stats_ops, S_IRUGO },
1507 	};
1508 
1509 	for (i = 0; !err && i < ARRAY_SIZE(files); i++) {
1510 		struct inode *inode;
1511 
1512 		inode = sel_make_inode(dir->d_sb, S_IFREG|files[i].mode);
1513 		if (!inode)
1514 			return -ENOMEM;
1515 
1516 		inode->i_fop = files[i].ops;
1517 		inode->i_ino = ++fsi->last_ino;
1518 
1519 		err = sel_attach_file(dir, files[i].name, inode);
1520 	}
1521 
1522 	return err;
1523 }
1524 
1525 static ssize_t sel_read_initcon(struct file *file, char __user *buf,
1526 				size_t count, loff_t *ppos)
1527 {
1528 	char *con;
1529 	u32 sid, len;
1530 	ssize_t ret;
1531 
1532 	sid = file_inode(file)->i_ino&SEL_INO_MASK;
1533 	ret = security_sid_to_context(sid, &con, &len);
1534 	if (ret)
1535 		return ret;
1536 
1537 	ret = simple_read_from_buffer(buf, count, ppos, con, len);
1538 	kfree(con);
1539 	return ret;
1540 }
1541 
1542 static const struct file_operations sel_initcon_ops = {
1543 	.read		= sel_read_initcon,
1544 	.llseek		= generic_file_llseek,
1545 };
1546 
1547 static int sel_make_initcon_files(struct dentry *dir)
1548 {
1549 	unsigned int i;
1550 	int err = 0;
1551 
1552 	for (i = 1; !err && i <= SECINITSID_NUM; i++) {
1553 		const char *s = security_get_initial_sid_context(i);
1554 		struct inode *inode;
1555 
1556 		if (!s)
1557 			continue;
1558 
1559 		inode = sel_make_inode(dir->d_sb, S_IFREG|S_IRUGO);
1560 		if (!inode)
1561 			return -ENOMEM;
1562 
1563 		inode->i_fop = &sel_initcon_ops;
1564 		inode->i_ino = i|SEL_INITCON_INO_OFFSET;
1565 		err = sel_attach_file(dir, s, inode);
1566 	}
1567 
1568 	return err;
1569 }
1570 
1571 static inline unsigned long sel_class_to_ino(u16 class)
1572 {
1573 	return (class * (SEL_VEC_MAX + 1)) | SEL_CLASS_INO_OFFSET;
1574 }
1575 
1576 static inline u16 sel_ino_to_class(unsigned long ino)
1577 {
1578 	return (ino & SEL_INO_MASK) / (SEL_VEC_MAX + 1);
1579 }
1580 
1581 static inline unsigned long sel_perm_to_ino(u16 class, u32 perm)
1582 {
1583 	return (class * (SEL_VEC_MAX + 1) + perm) | SEL_CLASS_INO_OFFSET;
1584 }
1585 
1586 static inline u32 sel_ino_to_perm(unsigned long ino)
1587 {
1588 	return (ino & SEL_INO_MASK) % (SEL_VEC_MAX + 1);
1589 }
1590 
1591 static ssize_t sel_read_class(struct file *file, char __user *buf,
1592 				size_t count, loff_t *ppos)
1593 {
1594 	unsigned long ino = file_inode(file)->i_ino;
1595 	char res[TMPBUFLEN];
1596 	ssize_t len = scnprintf(res, sizeof(res), "%d", sel_ino_to_class(ino));
1597 	return simple_read_from_buffer(buf, count, ppos, res, len);
1598 }
1599 
1600 static const struct file_operations sel_class_ops = {
1601 	.read		= sel_read_class,
1602 	.llseek		= generic_file_llseek,
1603 };
1604 
1605 static ssize_t sel_read_perm(struct file *file, char __user *buf,
1606 				size_t count, loff_t *ppos)
1607 {
1608 	unsigned long ino = file_inode(file)->i_ino;
1609 	char res[TMPBUFLEN];
1610 	ssize_t len = scnprintf(res, sizeof(res), "%d", sel_ino_to_perm(ino));
1611 	return simple_read_from_buffer(buf, count, ppos, res, len);
1612 }
1613 
1614 static const struct file_operations sel_perm_ops = {
1615 	.read		= sel_read_perm,
1616 	.llseek		= generic_file_llseek,
1617 };
1618 
1619 static ssize_t sel_read_policycap(struct file *file, char __user *buf,
1620 				  size_t count, loff_t *ppos)
1621 {
1622 	int value;
1623 	char tmpbuf[TMPBUFLEN];
1624 	ssize_t length;
1625 	unsigned long i_ino = file_inode(file)->i_ino;
1626 
1627 	value = security_policycap_supported(i_ino & SEL_INO_MASK);
1628 	length = scnprintf(tmpbuf, TMPBUFLEN, "%d", value);
1629 
1630 	return simple_read_from_buffer(buf, count, ppos, tmpbuf, length);
1631 }
1632 
1633 static const struct file_operations sel_policycap_ops = {
1634 	.read		= sel_read_policycap,
1635 	.llseek		= generic_file_llseek,
1636 };
1637 
1638 static int sel_make_perm_files(struct selinux_policy *newpolicy,
1639 			char *objclass, int classvalue,
1640 			struct dentry *dir)
1641 {
1642 	u32 i, nperms;
1643 	int rc;
1644 	char **perms;
1645 
1646 	rc = security_get_permissions(newpolicy, objclass, &perms, &nperms);
1647 	if (rc)
1648 		return rc;
1649 
1650 	for (i = 0; !rc && i < nperms; i++) {
1651 		struct inode *inode;
1652 
1653 		inode = sel_make_inode(dir->d_sb, S_IFREG|S_IRUGO);
1654 		if (!inode) {
1655 			rc = -ENOMEM;
1656 			break;
1657 		}
1658 
1659 		inode->i_fop = &sel_perm_ops;
1660 		/* i+1 since perm values are 1-indexed */
1661 		inode->i_ino = sel_perm_to_ino(classvalue, i + 1);
1662 
1663 		rc = sel_attach_file(dir, perms[i], inode);
1664 	}
1665 	for (i = 0; i < nperms; i++)
1666 		kfree(perms[i]);
1667 	kfree(perms);
1668 	return rc;
1669 }
1670 
1671 static int sel_make_class_dir_entries(struct selinux_policy *newpolicy,
1672 				char *classname, int index,
1673 				struct dentry *dir)
1674 {
1675 	struct super_block *sb = dir->d_sb;
1676 	struct selinux_fs_info *fsi = sb->s_fs_info;
1677 	struct dentry *dentry = NULL;
1678 	struct inode *inode = NULL;
1679 	int err;
1680 
1681 	inode = sel_make_inode(dir->d_sb, S_IFREG|S_IRUGO);
1682 	if (!inode)
1683 		return -ENOMEM;
1684 
1685 	inode->i_fop = &sel_class_ops;
1686 	inode->i_ino = sel_class_to_ino(index);
1687 
1688 	err = sel_attach_file(dir, "index", inode);
1689 	if (err)
1690 		return err;
1691 
1692 	dentry = sel_make_dir(dir, "perms", &fsi->last_class_ino);
1693 	if (IS_ERR(dentry))
1694 		return PTR_ERR(dentry);
1695 
1696 	return sel_make_perm_files(newpolicy, classname, index, dentry);
1697 }
1698 
1699 static int sel_make_classes(struct selinux_policy *newpolicy,
1700 			    struct dentry *class_dir,
1701 			    unsigned long *last_class_ino)
1702 {
1703 	u32 i, nclasses;
1704 	int rc;
1705 	char **classes;
1706 
1707 	rc = security_get_classes(newpolicy, &classes, &nclasses);
1708 	if (rc)
1709 		return rc;
1710 
1711 	/* +2 since classes are 1-indexed */
1712 	*last_class_ino = sel_class_to_ino(nclasses + 2);
1713 
1714 	for (i = 0; i < nclasses; i++) {
1715 		struct dentry *class_name_dir;
1716 
1717 		class_name_dir = sel_make_dir(class_dir, classes[i],
1718 					      last_class_ino);
1719 		if (IS_ERR(class_name_dir)) {
1720 			rc = PTR_ERR(class_name_dir);
1721 			goto out;
1722 		}
1723 
1724 		/* i+1 since class values are 1-indexed */
1725 		rc = sel_make_class_dir_entries(newpolicy, classes[i], i + 1,
1726 				class_name_dir);
1727 		if (rc)
1728 			goto out;
1729 	}
1730 	rc = 0;
1731 out:
1732 	for (i = 0; i < nclasses; i++)
1733 		kfree(classes[i]);
1734 	kfree(classes);
1735 	return rc;
1736 }
1737 
1738 static int sel_make_policycap(struct dentry *dir)
1739 {
1740 	struct super_block *sb = dir->d_sb;
1741 	unsigned int iter;
1742 	struct inode *inode = NULL;
1743 	int err = 0;
1744 
1745 	for (iter = 0; !err && iter <= POLICYDB_CAP_MAX; iter++) {
1746 		const char *name;
1747 
1748 		if (iter < ARRAY_SIZE(selinux_policycap_names))
1749 			name = selinux_policycap_names[iter];
1750 		else
1751 			name = "unknown";
1752 
1753 		inode = sel_make_inode(sb, S_IFREG | 0444);
1754 		if (!inode)
1755 			return -ENOMEM;
1756 
1757 		inode->i_fop = &sel_policycap_ops;
1758 		inode->i_ino = iter | SEL_POLICYCAP_INO_OFFSET;
1759 		err = sel_attach_file(dir, name, inode);
1760 	}
1761 
1762 	return err;
1763 }
1764 
1765 static struct dentry *sel_make_dir(struct dentry *dir, const char *name,
1766 			unsigned long *ino)
1767 {
1768 	struct inode *inode;
1769 
1770 	inode = sel_make_inode(dir->d_sb, S_IFDIR | S_IRUGO | S_IXUGO);
1771 	if (!inode)
1772 		return ERR_PTR(-ENOMEM);
1773 
1774 	inode->i_op = &simple_dir_inode_operations;
1775 	inode->i_fop = &simple_dir_operations;
1776 	inode->i_ino = ++(*ino);
1777 	/* directory inodes start off with i_nlink == 2 (for "." entry) */
1778 	inc_nlink(inode);
1779 	/* bump link count on parent directory, too */
1780 	inc_nlink(d_inode(dir));
1781 
1782 	return sel_attach(dir, name, inode);
1783 }
1784 
1785 static int reject_all(struct mnt_idmap *idmap, struct inode *inode, int mask)
1786 {
1787 	return -EPERM;	// no access for anyone, root or no root.
1788 }
1789 
1790 static const struct inode_operations swapover_dir_inode_operations = {
1791 	.lookup		= simple_lookup,
1792 	.permission	= reject_all,
1793 };
1794 
1795 static struct dentry *sel_make_swapover_dir(struct super_block *sb,
1796 						unsigned long *ino)
1797 {
1798 	struct dentry *dentry;
1799 	struct inode *inode;
1800 
1801 	inode = sel_make_inode(sb, S_IFDIR);
1802 	if (!inode)
1803 		return ERR_PTR(-ENOMEM);
1804 
1805 	dentry = simple_start_creating(sb->s_root, ".swapover");
1806 	if (IS_ERR(dentry)) {
1807 		iput(inode);
1808 		return dentry;
1809 	}
1810 
1811 	inode->i_op = &swapover_dir_inode_operations;
1812 	inode->i_ino = ++(*ino);
1813 	/* directory inodes start off with i_nlink == 2 (for "." entry) */
1814 	inc_nlink(inode);
1815 	d_make_persistent(dentry, inode);
1816 	inc_nlink(sb->s_root->d_inode);
1817 	simple_done_creating(dentry);
1818 	return dentry;	// borrowed
1819 }
1820 
1821 #define NULL_FILE_NAME "null"
1822 
1823 static int sel_fill_super(struct super_block *sb, struct fs_context *fc)
1824 {
1825 	struct selinux_fs_info *fsi;
1826 	int ret;
1827 	struct dentry *dentry;
1828 	struct inode *inode;
1829 	struct inode_security_struct *isec;
1830 
1831 	static const struct tree_descr selinux_files[] = {
1832 		[SEL_LOAD] = {"load", &sel_load_ops, S_IRUSR|S_IWUSR},
1833 		[SEL_ENFORCE] = {"enforce", &sel_enforce_ops, S_IRUGO|S_IWUSR},
1834 		[SEL_CONTEXT] = {"context", &transaction_ops, S_IRUGO|S_IWUGO},
1835 		[SEL_ACCESS] = {"access", &transaction_ops, S_IRUGO|S_IWUGO},
1836 		[SEL_CREATE] = {"create", &transaction_ops, S_IRUGO|S_IWUGO},
1837 		[SEL_RELABEL] = {"relabel", &transaction_ops, S_IRUGO|S_IWUGO},
1838 		[SEL_USER] = {"user", &transaction_ops, S_IRUGO|S_IWUGO},
1839 		[SEL_POLICYVERS] = {"policyvers", &sel_policyvers_ops, S_IRUGO},
1840 		[SEL_COMMIT_BOOLS] = {"commit_pending_bools", &sel_commit_bools_ops, S_IWUSR},
1841 		[SEL_MLS] = {"mls", &sel_mls_ops, S_IRUGO},
1842 		[SEL_DISABLE] = {"disable", &sel_disable_ops, S_IWUSR},
1843 		[SEL_MEMBER] = {"member", &transaction_ops, S_IRUGO|S_IWUGO},
1844 		[SEL_CHECKREQPROT] = {"checkreqprot", &sel_checkreqprot_ops, S_IRUGO|S_IWUSR},
1845 		[SEL_REJECT_UNKNOWN] = {"reject_unknown", &sel_handle_unknown_ops, S_IRUGO},
1846 		[SEL_DENY_UNKNOWN] = {"deny_unknown", &sel_handle_unknown_ops, S_IRUGO},
1847 		[SEL_STATUS] = {"status", &sel_handle_status_ops, S_IRUGO},
1848 		[SEL_POLICY] = {"policy", &sel_policy_ops, S_IRUGO},
1849 		[SEL_VALIDATE_TRANS] = {"validatetrans", &sel_transition_ops,
1850 					S_IWUGO},
1851 		/* last one */ {"", NULL, 0}
1852 	};
1853 
1854 	ret = selinux_fs_info_create(sb);
1855 	if (ret)
1856 		goto err;
1857 
1858 	ret = simple_fill_super(sb, SELINUX_MAGIC, selinux_files);
1859 	if (ret)
1860 		goto err;
1861 
1862 	fsi = sb->s_fs_info;
1863 	fsi->bool_dir = sel_make_dir(sb->s_root, BOOL_DIR_NAME, &fsi->last_ino);
1864 	if (IS_ERR(fsi->bool_dir)) {
1865 		ret = PTR_ERR(fsi->bool_dir);
1866 		fsi->bool_dir = NULL;
1867 		goto err;
1868 	}
1869 
1870 	ret = -ENOMEM;
1871 	inode = sel_make_inode(sb, S_IFCHR | S_IRUGO | S_IWUGO);
1872 	if (!inode)
1873 		goto err;
1874 
1875 	inode->i_ino = ++fsi->last_ino;
1876 	isec = selinux_inode(inode);
1877 	isec->sid = SECINITSID_DEVNULL;
1878 	isec->sclass = SECCLASS_CHR_FILE;
1879 	isec->initialized = LABEL_INITIALIZED;
1880 
1881 	init_special_inode(inode, S_IFCHR | S_IRUGO | S_IWUGO, MKDEV(MEM_MAJOR, 3));
1882 	ret = sel_attach_file(sb->s_root, NULL_FILE_NAME, inode);
1883 	if (ret)
1884 		goto err;
1885 
1886 	dentry = sel_make_dir(sb->s_root, "avc", &fsi->last_ino);
1887 	if (IS_ERR(dentry)) {
1888 		ret = PTR_ERR(dentry);
1889 		goto err;
1890 	}
1891 
1892 	ret = sel_make_avc_files(dentry);
1893 	if (ret)
1894 		goto err;
1895 
1896 	dentry = sel_make_dir(sb->s_root, "ss", &fsi->last_ino);
1897 	if (IS_ERR(dentry)) {
1898 		ret = PTR_ERR(dentry);
1899 		goto err;
1900 	}
1901 
1902 	ret = sel_make_ss_files(dentry);
1903 	if (ret)
1904 		goto err;
1905 
1906 	dentry = sel_make_dir(sb->s_root, "initial_contexts", &fsi->last_ino);
1907 	if (IS_ERR(dentry)) {
1908 		ret = PTR_ERR(dentry);
1909 		goto err;
1910 	}
1911 
1912 	ret = sel_make_initcon_files(dentry);
1913 	if (ret)
1914 		goto err;
1915 
1916 	fsi->class_dir = sel_make_dir(sb->s_root, CLASS_DIR_NAME, &fsi->last_ino);
1917 	if (IS_ERR(fsi->class_dir)) {
1918 		ret = PTR_ERR(fsi->class_dir);
1919 		fsi->class_dir = NULL;
1920 		goto err;
1921 	}
1922 
1923 	dentry = sel_make_dir(sb->s_root, "policy_capabilities", &fsi->last_ino);
1924 	if (IS_ERR(dentry)) {
1925 		ret = PTR_ERR(dentry);
1926 		goto err;
1927 	}
1928 
1929 	ret = sel_make_policycap(dentry);
1930 	if (ret) {
1931 		pr_err("SELinux: failed to load policy capabilities\n");
1932 		goto err;
1933 	}
1934 
1935 	return 0;
1936 err:
1937 	pr_err("SELinux: %s:  failed while creating inodes\n",
1938 		__func__);
1939 
1940 	return ret;
1941 }
1942 
1943 static int sel_get_tree(struct fs_context *fc)
1944 {
1945 	return get_tree_single(fc, sel_fill_super);
1946 }
1947 
1948 static const struct fs_context_operations sel_context_ops = {
1949 	.get_tree	= sel_get_tree,
1950 };
1951 
1952 static int sel_init_fs_context(struct fs_context *fc)
1953 {
1954 	fc->ops = &sel_context_ops;
1955 	return 0;
1956 }
1957 
1958 static void sel_kill_sb(struct super_block *sb)
1959 {
1960 	struct selinux_fs_info *fsi = sb->s_fs_info;
1961 
1962 	kill_anon_super(sb);
1963 	selinux_fs_info_free(fsi);
1964 }
1965 
1966 static struct file_system_type sel_fs_type = {
1967 	.name		= "selinuxfs",
1968 	.init_fs_context = sel_init_fs_context,
1969 	.kill_sb	= sel_kill_sb,
1970 };
1971 
1972 struct path selinux_null __ro_after_init;
1973 
1974 int __init init_sel_fs(void)
1975 {
1976 	struct qstr null_name = QSTR(NULL_FILE_NAME);
1977 	int err;
1978 
1979 	if (!selinux_enabled_boot)
1980 		return 0;
1981 
1982 	err = sysfs_create_mount_point(fs_kobj, "selinux");
1983 	if (err)
1984 		return err;
1985 
1986 	err = register_filesystem(&sel_fs_type);
1987 	if (err) {
1988 		sysfs_remove_mount_point(fs_kobj, "selinux");
1989 		return err;
1990 	}
1991 
1992 	selinux_null.mnt = kern_mount(&sel_fs_type);
1993 	if (IS_ERR(selinux_null.mnt)) {
1994 		pr_err("selinuxfs:  could not mount!\n");
1995 		err = PTR_ERR(selinux_null.mnt);
1996 		selinux_null.mnt = NULL;
1997 		return err;
1998 	}
1999 
2000 	selinux_null.dentry = try_lookup_noperm(&null_name,
2001 						  selinux_null.mnt->mnt_root);
2002 	if (IS_ERR(selinux_null.dentry)) {
2003 		pr_err("selinuxfs:  could not lookup null!\n");
2004 		err = PTR_ERR(selinux_null.dentry);
2005 		selinux_null.dentry = NULL;
2006 		return err;
2007 	}
2008 
2009 	/*
2010 	 * Try to pre-allocate the status page, so the sequence number of the
2011 	 * initial policy load can be stored.
2012 	 */
2013 	(void) selinux_kernel_status_page();
2014 
2015 	return err;
2016 }
2017