xref: /linux/security/apparmor/apparmorfs.c (revision 7965b1f3940ae21209ad095fcf2df46c0a99df2d)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * AppArmor security module
4  *
5  * This file contains AppArmor /sys/kernel/security/apparmor interface functions
6  *
7  * Copyright (C) 1998-2008 Novell/SUSE
8  * Copyright 2009-2010 Canonical Ltd.
9  */
10 
11 #include <linux/ctype.h>
12 #include <linux/slab.h>
13 #include <linux/security.h>
14 #include <linux/vmalloc.h>
15 #include <linux/init.h>
16 #include <linux/seq_file.h>
17 #include <linux/uaccess.h>
18 #include <linux/mount.h>
19 #include <linux/namei.h>
20 #include <linux/capability.h>
21 #include <linux/rcupdate.h>
22 #include <linux/fs.h>
23 #include <linux/fs_context.h>
24 #include <linux/poll.h>
25 #include <linux/zstd.h>
26 #include <linux/string.h>
27 #include <uapi/linux/major.h>
28 #include <uapi/linux/magic.h>
29 
30 #include "include/apparmor.h"
31 #include "include/apparmorfs.h"
32 #include "include/audit.h"
33 #include "include/cred.h"
34 #include "include/crypto.h"
35 #include "include/ipc.h"
36 #include "include/label.h"
37 #include "include/net.h"
38 #include "include/lib.h"
39 #include "include/policy.h"
40 #include "include/policy_ns.h"
41 #include "include/resource.h"
42 #include "include/policy_unpack.h"
43 #include "include/task.h"
44 
45 /*
46  * The apparmor filesystem interface used for policy load and introspection
47  * The interface is split into two main components based on their function
48  * a securityfs component:
49  *   used for static files that are always available, and which allows
50  *   userspace to specify the location of the security filesystem.
51  *
52  *   fns and data are prefixed with
53  *      aa_sfs_
54  *
55  * an apparmorfs component:
56  *   used loaded policy content and introspection. It is not part of  a
57  *   regular mounted filesystem and is available only through the magic
58  *   policy symlink in the root of the securityfs apparmor/ directory.
59  *   Tasks queries will be magically redirected to the correct portion
60  *   of the policy tree based on their confinement.
61  *
62  *   fns and data are prefixed with
63  *      aafs_
64  *
65  * The aa_fs_ prefix is used to indicate the fn is used by both the
66  * securityfs and apparmorfs filesystems.
67  */
68 
69 #define IREF_POISON 101
70 
71 /*
72  * support fns
73  */
74 
75 struct rawdata_f_data {
76 	struct aa_loaddata *loaddata;
77 	DECLARE_FLEX_ARRAY(char, data);
78 };
79 
80 #ifdef CONFIG_SECURITY_APPARMOR_EXPORT_BINARY
81 
82 static void rawdata_f_data_free(struct rawdata_f_data *private)
83 {
84 	if (!private)
85 		return;
86 
87 	aa_put_i_loaddata(private->loaddata);
88 	kvfree(private);
89 }
90 
91 static struct rawdata_f_data *rawdata_f_data_alloc(size_t size)
92 {
93 	struct rawdata_f_data *ret;
94 
95 	if (size > SIZE_MAX - sizeof(*ret))
96 		return ERR_PTR(-EINVAL);
97 
98 	ret = kvzalloc(sizeof(*ret) + size, GFP_KERNEL);
99 	if (!ret)
100 		return ERR_PTR(-ENOMEM);
101 
102 	return ret;
103 }
104 #endif
105 
106 /**
107  * mangle_name - mangle a profile name to std profile layout form
108  * @name: profile name to mangle  (NOT NULL)
109  * @target: buffer to store mangled name, same length as @name (MAYBE NULL)
110  *
111  * Returns: length of mangled name
112  */
113 static int mangle_name(const char *name, char *target)
114 {
115 	char *t = target;
116 
117 	while (*name == '/' || *name == '.')
118 		name++;
119 
120 	if (target) {
121 		for (; *name; name++) {
122 			if (*name == '/')
123 				*(t)++ = '.';
124 			else if (isspace(*name))
125 				*(t)++ = '_';
126 			else if (isalnum(*name) || strchr("._-", *name))
127 				*(t)++ = *name;
128 		}
129 
130 		*t = 0;
131 	} else {
132 		int len = 0;
133 		for (; *name; name++) {
134 			if (isalnum(*name) || isspace(*name) ||
135 			    strchr("/._-", *name))
136 				len++;
137 		}
138 
139 		return len;
140 	}
141 
142 	return t - target;
143 }
144 
145 
146 /*
147  * aafs - core fns and data for the policy tree
148  */
149 
150 #define AAFS_NAME		"apparmorfs"
151 static struct vfsmount *aafs_mnt;
152 static int aafs_count;
153 
154 
155 static int aafs_show_path(struct seq_file *seq, struct dentry *dentry)
156 {
157 	seq_printf(seq, "%s:[%llu]", AAFS_NAME, d_inode(dentry)->i_ino);
158 	return 0;
159 }
160 
161 static struct aa_ns *get_ns_common_ref(struct aa_common_ref *ref)
162 {
163 	if (ref) {
164 		struct aa_label *reflabel = container_of(ref, struct aa_label,
165 							 count);
166 		return aa_get_ns(labels_ns(reflabel));
167 	}
168 
169 	return NULL;
170 }
171 
172 static struct aa_proxy *get_proxy_common_ref(struct aa_common_ref *ref)
173 {
174 	if (ref)
175 		return aa_get_proxy(container_of(ref, struct aa_proxy, count));
176 
177 	return NULL;
178 }
179 
180 #ifdef CONFIG_SECURITY_APPARMOR_EXPORT_BINARY
181 static struct aa_loaddata *get_loaddata_common_ref(struct aa_common_ref *ref)
182 {
183 	if (ref)
184 		return aa_get_i_loaddata(container_of(ref, struct aa_loaddata,
185 						      count));
186 	return NULL;
187 }
188 #endif
189 
190 static void aa_put_common_ref(struct aa_common_ref *ref)
191 {
192 	if (!ref)
193 		return;
194 
195 	switch (ref->reftype) {
196 	case REF_RAWDATA:
197 		aa_put_i_loaddata(container_of(ref, struct aa_loaddata,
198 					       count));
199 		break;
200 	case REF_PROXY:
201 		aa_put_proxy(container_of(ref, struct aa_proxy,
202 					  count));
203 		break;
204 	case REF_NS:
205 		/* ns count is held on its unconfined label */
206 		aa_put_ns(labels_ns(container_of(ref, struct aa_label, count)));
207 		break;
208 	default:
209 		AA_BUG(true, "unknown refcount type");
210 		break;
211 	}
212 }
213 
214 static void aa_get_common_ref(struct aa_common_ref *ref)
215 {
216 	kref_get(&ref->count);
217 }
218 
219 static void aafs_evict(struct inode *inode)
220 {
221 	struct aa_common_ref *ref = inode->i_private;
222 
223 	clear_inode(inode);
224 	aa_put_common_ref(ref);
225 	inode->i_private = (void *) IREF_POISON;
226 }
227 
228 static void aafs_free_inode(struct inode *inode)
229 {
230 	if (S_ISLNK(inode->i_mode))
231 		kfree(inode->i_link);
232 	free_inode_nonrcu(inode);
233 }
234 
235 static const struct super_operations aafs_super_ops = {
236 	.statfs = simple_statfs,
237 	.evict_inode = aafs_evict,
238 	.free_inode = aafs_free_inode,
239 	.show_path = aafs_show_path,
240 };
241 
242 static int apparmorfs_fill_super(struct super_block *sb, struct fs_context *fc)
243 {
244 	static struct tree_descr files[] = { {""} };
245 	int error;
246 
247 	error = simple_fill_super(sb, AAFS_MAGIC, files);
248 	if (error)
249 		return error;
250 	sb->s_op = &aafs_super_ops;
251 
252 	return 0;
253 }
254 
255 static int apparmorfs_get_tree(struct fs_context *fc)
256 {
257 	return get_tree_single(fc, apparmorfs_fill_super);
258 }
259 
260 static const struct fs_context_operations apparmorfs_context_ops = {
261 	.get_tree	= apparmorfs_get_tree,
262 };
263 
264 static int apparmorfs_init_fs_context(struct fs_context *fc)
265 {
266 	fc->ops = &apparmorfs_context_ops;
267 	return 0;
268 }
269 
270 static struct file_system_type aafs_ops = {
271 	.owner = THIS_MODULE,
272 	.name = AAFS_NAME,
273 	.init_fs_context = apparmorfs_init_fs_context,
274 	.kill_sb = kill_anon_super,
275 };
276 
277 /**
278  * __aafs_setup_d_inode - basic inode setup for apparmorfs
279  * @dir: parent directory for the dentry
280  * @dentry: dentry we are setting the inode up for
281  * @mode: permissions the file should have
282  * @data: data to store on inode.i_private, available in open()
283  * @link: if symlink, symlink target string
284  * @fops: struct file_operations that should be used
285  * @iops: struct of inode_operations that should be used
286  */
287 static int __aafs_setup_d_inode(struct inode *dir, struct dentry *dentry,
288 			       umode_t mode, void *data, char *link,
289 			       const struct file_operations *fops,
290 			       const struct inode_operations *iops)
291 {
292 	struct inode *inode = new_inode(dir->i_sb);
293 
294 	AA_BUG(!dir);
295 	AA_BUG(!dentry);
296 
297 	if (!inode)
298 		return -ENOMEM;
299 
300 	inode->i_ino = get_next_ino();
301 	inode->i_mode = mode;
302 	simple_inode_init_ts(inode);
303 	inode->i_private = data;
304 	if (S_ISDIR(mode)) {
305 		inode->i_op = iops ? iops : &simple_dir_inode_operations;
306 		inode->i_fop = &simple_dir_operations;
307 		inc_nlink(inode);
308 		inc_nlink(dir);
309 	} else if (S_ISLNK(mode)) {
310 		inode->i_op = iops ? iops : &simple_symlink_inode_operations;
311 		inode->i_link = link;
312 	} else {
313 		inode->i_fop = fops;
314 	}
315 	d_instantiate(dentry, inode);
316 	dget(dentry);
317 
318 	return 0;
319 }
320 
321 /**
322  * aafs_create - create a dentry in the apparmorfs filesystem
323  *
324  * @name: name of dentry to create
325  * @mode: permissions the file should have
326  * @parent: parent directory for this dentry
327  * @data: data to store on inode.i_private, available in open()
328  * @link: if symlink, symlink target string
329  * @fops: struct file_operations that should be used for
330  * @iops: struct of inode_operations that should be used
331  *
332  * This is the basic "create a xxx" function for apparmorfs.
333  *
334  * Returns a pointer to a dentry if it succeeds, that must be free with
335  * aafs_remove(). Will return ERR_PTR on failure.
336  */
337 static struct dentry *aafs_create(const char *name, umode_t mode,
338 				  struct dentry *parent,
339 				  struct aa_common_ref *data, void *link,
340 				  const struct file_operations *fops,
341 				  const struct inode_operations *iops)
342 {
343 	struct dentry *dentry;
344 	struct inode *dir;
345 	int error;
346 
347 	AA_BUG(!name);
348 	AA_BUG(!parent);
349 
350 	if (!(mode & S_IFMT))
351 		mode = (mode & S_IALLUGO) | S_IFREG;
352 
353 	error = simple_pin_fs(&aafs_ops, &aafs_mnt, &aafs_count);
354 	if (error)
355 		return ERR_PTR(error);
356 
357 	dir = d_inode(parent);
358 
359 	dentry = simple_start_creating(parent, name);
360 	if (IS_ERR(dentry)) {
361 		error = PTR_ERR(dentry);
362 		goto fail;
363 	}
364 
365 	error = __aafs_setup_d_inode(dir, dentry, mode, data, link, fops, iops);
366 	simple_done_creating(dentry);
367 	if (error)
368 		goto fail;
369 
370 	if (data)
371 		aa_get_common_ref(data);
372 
373 	return dentry;
374 
375 fail:
376 	simple_release_fs(&aafs_mnt, &aafs_count);
377 	return ERR_PTR(error);
378 }
379 
380 /**
381  * aafs_create_file - create a file in the apparmorfs filesystem
382  *
383  * @name: name of dentry to create
384  * @mode: permissions the file should have
385  * @parent: parent directory for this dentry
386  * @data: data to store on inode.i_private, available in open()
387  * @fops: struct file_operations that should be used for
388  *
389  * see aafs_create
390  */
391 static struct dentry *aafs_create_file(const char *name, umode_t mode,
392 				       struct dentry *parent,
393 				       struct aa_common_ref *data,
394 				       const struct file_operations *fops)
395 {
396 	return aafs_create(name, mode, parent, data, NULL, fops, NULL);
397 }
398 
399 /**
400  * aafs_create_dir - create a directory in the apparmorfs filesystem
401  *
402  * @name: name of dentry to create
403  * @parent: parent directory for this dentry
404  *
405  * see aafs_create
406  */
407 static struct dentry *aafs_create_dir(const char *name, struct dentry *parent)
408 {
409 	return aafs_create(name, S_IFDIR | 0755, parent, NULL, NULL, NULL,
410 			   NULL);
411 }
412 
413 /**
414  * aafs_remove - removes a file or directory from the apparmorfs filesystem
415  *
416  * @dentry: dentry of the file/directory/symlink to removed.
417  */
418 static void aafs_remove(struct dentry *dentry)
419 {
420 	struct inode *dir;
421 
422 	if (!dentry || IS_ERR(dentry))
423 		return;
424 
425 	/* ->d_parent is stable as rename is not supported */
426 	dir = d_inode(dentry->d_parent);
427 	dentry = start_removing_dentry(dentry->d_parent, dentry);
428 	if (!IS_ERR(dentry) && simple_positive(dentry)) {
429 		if (d_is_dir(dentry)) {
430 			if (!WARN_ON(!simple_empty(dentry))) {
431 				__simple_rmdir(dir, dentry);
432 				dput(dentry);
433 			}
434 		} else {
435 			__simple_unlink(dir, dentry);
436 			dput(dentry);
437 		}
438 		d_delete(dentry);
439 	}
440 	end_removing(dentry);
441 	simple_release_fs(&aafs_mnt, &aafs_count);
442 }
443 
444 
445 /*
446  * aa_fs - policy load/replace/remove
447  */
448 
449 /**
450  * aa_simple_write_to_buffer - common routine for getting policy from user
451  * @userbuf: user buffer to copy data from  (NOT NULL)
452  * @alloc_size: size of user buffer (REQUIRES: @alloc_size >= @copy_size)
453  * @copy_size: size of data to copy from user buffer
454  * @pos: position write is at in the file (NOT NULL)
455  *
456  * Returns: kernel buffer containing copy of user buffer data or an
457  *          ERR_PTR on failure.
458  */
459 static struct aa_loaddata *aa_simple_write_to_buffer(const char __user *userbuf,
460 						     size_t alloc_size,
461 						     size_t copy_size,
462 						     loff_t *pos)
463 {
464 	struct aa_loaddata *data;
465 
466 	AA_BUG(copy_size > alloc_size);
467 
468 	if (*pos != 0)
469 		/* only writes from pos 0, that is complete writes */
470 		return ERR_PTR(-ESPIPE);
471 
472 	/* freed by caller to simple_write_to_buffer */
473 	data = aa_loaddata_alloc(alloc_size);
474 	if (IS_ERR(data))
475 		return data;
476 
477 	data->size = copy_size;
478 	if (copy_from_user(data->data, userbuf, copy_size)) {
479 		/* trigger free - don't need to put pcount */
480 		aa_put_i_loaddata(data);
481 		return ERR_PTR(-EFAULT);
482 	}
483 
484 	return data;
485 }
486 
487 #if defined(CONFIG_SECURITY_APPARMOR_COMPRESSED_POLICY) || \
488     defined(CONFIG_SECURITY_APPARMOR_EXPORT_BINARY)
489 static int decompress_zstd(char *src, size_t slen, char *dst, size_t dlen)
490 {
491 	if (slen < dlen) {
492 		const size_t wksp_len = zstd_dctx_workspace_bound();
493 		zstd_dctx *ctx;
494 		void *wksp;
495 		size_t out_len;
496 		int ret = 0;
497 
498 		wksp = kvzalloc(wksp_len, GFP_KERNEL);
499 		if (!wksp) {
500 			ret = -ENOMEM;
501 			goto cleanup;
502 		}
503 		ctx = zstd_init_dctx(wksp, wksp_len);
504 		if (ctx == NULL) {
505 			ret = -ENOMEM;
506 			goto cleanup;
507 		}
508 		out_len = zstd_decompress_dctx(ctx, dst, dlen, src, slen);
509 		if (zstd_is_error(out_len)) {
510 			ret = -EINVAL;
511 			goto cleanup;
512 		}
513 cleanup:
514 		kvfree(wksp);
515 		return ret;
516 	}
517 
518 	if (dlen < slen)
519 		return -EINVAL;
520 	memcpy(dst, src, slen);
521 	return 0;
522 }
523 #endif
524 
525 
526 #ifdef CONFIG_SECURITY_APPARMOR_COMPRESSED_POLICY
527 /**
528  * aa_get_data_from_compressed - common routine for getting compressed policy
529  * from user and get both compressed and uncompressed version.
530  * @userbuf: user buffer to copy data from  (NOT NULL)
531  * @buffer_size: size of user buffer
532  * @pos: position write is at in the file (NOT NULL)
533  * @compressed_data: Ptr on compressed data. *compressed_data is allocated there
534  *
535  * Returns: kernel buffer containing copy of user buffer data or an
536  *          ERR_PTR on failure.
537  */
538 static struct aa_loaddata *aa_get_data_from_compressed(const char __user *userbuf,
539 						  size_t buffer_size,
540 						  loff_t *pos,
541 						  char **compressed_data)
542 {
543 	struct aa_loaddata *data;
544 	zstd_frame_header header;
545 	int error;
546 
547 	if (!userbuf || !pos)
548 		return ERR_PTR(-EINVAL);
549 	if (*pos)
550 		return ERR_PTR(-ESPIPE);
551 
552 	*compressed_data = kvmalloc(buffer_size, GFP_KERNEL);
553 	if (!*compressed_data)
554 		return ERR_PTR(-ENOMEM);
555 	if (copy_from_user(*compressed_data, userbuf, buffer_size)) {
556 		error = -EFAULT;
557 		goto fail;
558 	}
559 	error = zstd_get_frame_header(&header, *compressed_data, buffer_size);
560 	if (error || header.frameContentSize == ZSTD_CONTENTSIZE_UNKNOWN ||
561 	    header.frameContentSize == ZSTD_CONTENTSIZE_ERROR) {
562 		error = -EINVAL;
563 		goto fail;
564 	}
565 
566 	data = aa_loaddata_alloc(header.frameContentSize);
567 	if (IS_ERR(data)) {
568 		error = PTR_ERR(data);
569 		goto fail;
570 	}
571 
572 	// We then decompress the data
573 	error = decompress_zstd(*compressed_data, buffer_size, data->data,
574 				header.frameContentSize);
575 	if (error)
576 		goto fail_decompress;
577 
578 	data->size = header.frameContentSize;
579 	return data;
580 
581 fail_decompress:
582 	aa_put_i_loaddata(data);
583 fail:
584 	kvfree(*compressed_data);
585 	return ERR_PTR(error);
586 
587 }
588 #else
589 static struct aa_loaddata *aa_get_data_from_compressed(const char __user *userbuf __always_unused,
590 						  size_t buffer_size __always_unused,
591 						  loff_t *pos __always_unused,
592 						  char **compressed_data __always_unused)
593 {
594 	return ERR_PTR(-EINVAL);
595 }
596 #endif /* CONFIG_SECURITY_APPARMOR_COMPRESSED_POLICY */
597 
598 struct aa_user_hdr {
599 	uint8_t version;
600 	uint8_t compress_level;
601 	uint8_t padding[6];	/* force 8-byte alignment */
602 } __packed __aligned(8);
603 
604 #define aa_hdr_magic "\x04\x08\x00\x76\x65\x72\x73\x69\x6f\x6e\x00\x02"
605 #define aa_hdr_magic_size 12
606 
607 static ssize_t policy_update(u32 mask, const char __user *buf, size_t size,
608 			     loff_t *pos, struct aa_ns *ns,
609 			     const struct cred *ocred)
610 {
611 	struct aa_loaddata *data;
612 	struct aa_label *label;
613 	ssize_t error;
614 	char *compressed_data = NULL;
615 	__le32 magic_le;
616 	bool is_compressed;
617 	u8 aahdr[aa_hdr_magic_size];
618 	bool needput;
619 
620 	label = begin_current_label_crit_section(&needput);
621 
622 	/* high level check about policy management - fine grained in
623 	 * below after unpack
624 	 */
625 	error = aa_may_manage_policy(current_cred(), label, ns, ocred, mask);
626 	if (error)
627 		goto end_section;
628 
629 	/* If the policy is userspace compressed we start by decompressing it
630 	 * to make the required checks (computing hash, verifying profile, ...)
631 	 *
632 	 * Getting a userspace-compressed version then decompressing it in the
633 	 * kernel actually makes sense since zstd decompression is ~3.5x faster
634 	 * than compression. This also allow to increase the compression level.
635 	 */
636 
637 	if (size >= sizeof(__le32) &&
638 	    !copy_from_user(&magic_le, buf, sizeof(magic_le)) &&
639 	    le32_to_cpu(magic_le) == ZSTD_MAGICNUMBER) {
640 		is_compressed = true;
641 	} else if (size >= sizeof(struct aa_user_hdr) + sizeof(__le32) &&
642 		   !copy_from_user(&magic_le,
643 				   buf + sizeof(struct aa_user_hdr),
644 				   sizeof(magic_le)) &&
645 		   le32_to_cpu(magic_le) == ZSTD_MAGICNUMBER) {
646 		is_compressed = true;
647 		/* skip the userspace header if present */
648 		buf += sizeof(struct aa_user_hdr);
649 		size -= sizeof(struct aa_user_hdr);
650 	} else if (size >= sizeof(struct aa_user_hdr) +
651 		   aa_hdr_magic_size &&
652 		   !copy_from_user(&aahdr,
653 				   buf + sizeof(struct aa_user_hdr),
654 				   aa_hdr_magic_size) &&
655 		   memcmp(&aahdr, aa_hdr_magic, aa_hdr_magic_size) == 0) {
656 		/* uncompressed blob with user hdr */
657 		buf += sizeof(struct aa_user_hdr);
658 		size -= sizeof(struct aa_user_hdr);
659 		is_compressed = false;
660 	} else {
661 		is_compressed = false;
662 	}
663 	if (is_compressed) {
664 
665 		data = aa_get_data_from_compressed(buf, size, pos, &compressed_data);
666 		error = PTR_ERR(data);
667 	} else {
668 		data = aa_simple_write_to_buffer(buf, size, size, pos);
669 		error = PTR_ERR(data);
670 	}
671 
672 	if (!IS_ERR(data)) {
673 		error = aa_replace_profiles(ns, label, mask, data,
674 					    compressed_data, size);
675 		/* put pcount, which will put count and free if no
676 		 * profiles referencing it.
677 		 */
678 		aa_put_profile_loaddata(data);
679 	}
680 end_section:
681 	end_current_label_crit_section(label, needput);
682 
683 	return error;
684 }
685 
686 /* .load file hook fn to load policy */
687 static ssize_t profile_load(struct file *f, const char __user *buf, size_t size,
688 			    loff_t *pos)
689 {
690 	struct aa_ns *ns = get_ns_common_ref(f->f_inode->i_private);
691 	int error = policy_update(AA_MAY_LOAD_POLICY, buf, size, pos, ns,
692 				  f->f_cred);
693 
694 	aa_put_ns(ns);
695 
696 	return error;
697 }
698 
699 static const struct file_operations aa_fs_profile_load = {
700 	.write = profile_load,
701 	.llseek = default_llseek,
702 };
703 
704 /* .replace file hook fn to load and/or replace policy */
705 static ssize_t profile_replace(struct file *f, const char __user *buf,
706 			       size_t size, loff_t *pos)
707 {
708 	struct aa_ns *ns = get_ns_common_ref(f->f_inode->i_private);
709 	int error = policy_update(AA_MAY_LOAD_POLICY | AA_MAY_REPLACE_POLICY,
710 				  buf, size, pos, ns, f->f_cred);
711 	aa_put_ns(ns);
712 
713 	return error;
714 }
715 
716 static const struct file_operations aa_fs_profile_replace = {
717 	.write = profile_replace,
718 	.llseek = default_llseek,
719 };
720 
721 
722 /* .remove file hook fn to remove loaded policy */
723 static ssize_t profile_remove(struct file *f, const char __user *buf,
724 			      size_t size, loff_t *pos)
725 {
726 	struct aa_loaddata *data;
727 	struct aa_label *label;
728 	ssize_t error;
729 	struct aa_ns *ns = get_ns_common_ref(f->f_inode->i_private);
730 	bool needput;
731 
732 	label = begin_current_label_crit_section(&needput);
733 	/* high level check about policy management - fine grained in
734 	 * below after unpack
735 	 */
736 	error = aa_may_manage_policy(current_cred(), label, ns,
737 				     f->f_cred, AA_MAY_REMOVE_POLICY);
738 	if (error)
739 		goto out;
740 
741 	/*
742 	 * aa_remove_profile needs a null terminated string so 1 extra
743 	 * byte is allocated and the copied data is null terminated.
744 	 */
745 	data = aa_simple_write_to_buffer(buf, size + 1, size, pos);
746 
747 	error = PTR_ERR(data);
748 	if (!IS_ERR(data)) {
749 		data->data[size] = 0;
750 		error = aa_remove_profiles(ns, label, data->data, size);
751 		aa_put_profile_loaddata(data);
752 	}
753  out:
754 	end_current_label_crit_section(label, needput);
755 	aa_put_ns(ns);
756 	return error;
757 }
758 
759 static const struct file_operations aa_fs_profile_remove = {
760 	.write = profile_remove,
761 	.llseek = default_llseek,
762 };
763 
764 struct aa_revision {
765 	struct aa_ns *ns;
766 	long last_read;
767 };
768 
769 /* revision file hook fn for policy loads */
770 static int ns_revision_release(struct inode *inode, struct file *file)
771 {
772 	struct aa_revision *rev = file->private_data;
773 
774 	if (rev) {
775 		aa_put_ns(rev->ns);
776 		kfree(rev);
777 	}
778 
779 	return 0;
780 }
781 
782 static ssize_t ns_revision_read(struct file *file, char __user *buf,
783 				size_t size, loff_t *ppos)
784 {
785 	struct aa_revision *rev = file->private_data;
786 	char buffer[32];
787 	long last_read;
788 	int avail;
789 
790 	mutex_lock_nested(&rev->ns->lock, rev->ns->level);
791 	last_read = rev->last_read;
792 	if (last_read == rev->ns->revision) {
793 		mutex_unlock(&rev->ns->lock);
794 		if (file->f_flags & O_NONBLOCK)
795 			return -EAGAIN;
796 		if (wait_event_interruptible(rev->ns->wait,
797 					     last_read !=
798 					     READ_ONCE(rev->ns->revision)))
799 			return -ERESTARTSYS;
800 		mutex_lock_nested(&rev->ns->lock, rev->ns->level);
801 	}
802 
803 	avail = sprintf(buffer, "%ld\n", rev->ns->revision);
804 	if (*ppos + size > avail) {
805 		rev->last_read = rev->ns->revision;
806 		*ppos = 0;
807 	}
808 	mutex_unlock(&rev->ns->lock);
809 
810 	return simple_read_from_buffer(buf, size, ppos, buffer, avail);
811 }
812 
813 static int ns_revision_open(struct inode *inode, struct file *file)
814 {
815 	struct aa_revision *rev = kzalloc_obj(*rev);
816 
817 	if (!rev)
818 		return -ENOMEM;
819 
820 	rev->ns = get_ns_common_ref(inode->i_private);
821 	if (!rev->ns)
822 		rev->ns = aa_get_current_ns();
823 	file->private_data = rev;
824 
825 	return 0;
826 }
827 
828 static __poll_t ns_revision_poll(struct file *file, poll_table *pt)
829 {
830 	struct aa_revision *rev = file->private_data;
831 	__poll_t mask = 0;
832 
833 	if (rev) {
834 		mutex_lock_nested(&rev->ns->lock, rev->ns->level);
835 		poll_wait(file, &rev->ns->wait, pt);
836 		if (rev->last_read < rev->ns->revision)
837 			mask |= EPOLLIN | EPOLLRDNORM;
838 		mutex_unlock(&rev->ns->lock);
839 	}
840 
841 	return mask;
842 }
843 
844 void __aa_bump_ns_revision(struct aa_ns *ns)
845 {
846 	WRITE_ONCE(ns->revision, READ_ONCE(ns->revision) + 1);
847 	wake_up_interruptible(&ns->wait);
848 }
849 
850 static const struct file_operations aa_fs_ns_revision_fops = {
851 	.owner		= THIS_MODULE,
852 	.open		= ns_revision_open,
853 	.poll		= ns_revision_poll,
854 	.read		= ns_revision_read,
855 	.llseek		= generic_file_llseek,
856 	.release	= ns_revision_release,
857 };
858 
859 static void profile_query_cb(struct aa_profile *profile, struct aa_perms *perms,
860 			     const char *match_str, size_t match_len)
861 {
862 	struct aa_ruleset *rules = profile->label.rules[0];
863 	struct aa_perms tmp = { };
864 	aa_state_t state = DFA_NOMATCH;
865 
866 	if (profile_unconfined(profile))
867 		return;
868 	if (rules->file->dfa && *match_str == AA_CLASS_FILE) {
869 		state = aa_dfa_match_len(rules->file->dfa,
870 					 rules->file->start[AA_CLASS_FILE],
871 					 match_str + 1, match_len - 1);
872 		if (state) {
873 			struct path_cond cond = { };
874 
875 			tmp = *(aa_lookup_condperms(current_fsuid(),
876 						    rules->file, state, &cond));
877 		}
878 	} else if (rules->policy->dfa) {
879 		if (!RULE_MEDIATES(rules, *match_str))
880 			return;	/* no change to current perms */
881 		/* old user space does not correctly detect dbus mediation
882 		 * support so we may get dbus policy and requests when
883 		 * the abi doesn't support it. This can cause mediation
884 		 * regressions, so explicitly test for this situation.
885 		 */
886 		if (*match_str == AA_CLASS_DBUS &&
887 		    !RULE_MEDIATES_v9NET(rules))
888 			return; /* no change to current perms */
889 		state = aa_dfa_match_len(rules->policy->dfa,
890 					 rules->policy->start[0],
891 					 match_str, match_len);
892 		if (state)
893 			tmp = *aa_lookup_perms(rules->policy, state);
894 	}
895 	aa_apply_modes_to_perms(profile, &tmp);
896 	aa_perms_accum_raw(perms, &tmp);
897 }
898 
899 
900 /**
901  * query_data - queries a policy and writes its data to buf
902  * @buf: the resulting data is stored here (NOT NULL)
903  * @buf_len: size of buf
904  * @query: query string used to retrieve data
905  * @query_len: size of query including second NUL byte
906  *
907  * The buffers pointed to by buf and query may overlap. The query buffer is
908  * parsed before buf is written to.
909  *
910  * The query should look like "<LABEL>\0<KEY>\0", where <LABEL> is the name of
911  * the security confinement context and <KEY> is the name of the data to
912  * retrieve. <LABEL> and <KEY> must not be NUL-terminated.
913  *
914  * Don't expect the contents of buf to be preserved on failure.
915  *
916  * Returns: number of characters written to buf or -errno on failure
917  */
918 static ssize_t query_data(char *buf, size_t buf_len,
919 			  char *query, size_t query_len)
920 {
921 	char *out;
922 	const char *key;
923 	struct label_it i;
924 	struct aa_label *label, *curr;
925 	struct aa_profile *profile;
926 	struct aa_data *data;
927 	u32 bytes, blocks;
928 	__le32 outle32;
929 	bool needput;
930 
931 	if (!query_len)
932 		return -EINVAL; /* need a query */
933 
934 	key = query + strnlen(query, query_len) + 1;
935 	if (key + 1 >= query + query_len)
936 		return -EINVAL; /* not enough space for a non-empty key */
937 	if (key + strnlen(key, query + query_len - key) >= query + query_len)
938 		return -EINVAL; /* must end with NUL */
939 
940 	if (buf_len < sizeof(bytes) + sizeof(blocks))
941 		return -EINVAL; /* not enough space */
942 
943 	curr = begin_current_label_crit_section(&needput);
944 	label = aa_label_parse(curr, query, GFP_KERNEL, false, false);
945 	end_current_label_crit_section(curr, needput);
946 	if (IS_ERR(label))
947 		return PTR_ERR(label);
948 
949 	/* We are going to leave space for two numbers. The first is the total
950 	 * number of bytes we are writing after the first number. This is so
951 	 * users can read the full output without reallocation.
952 	 *
953 	 * The second number is the number of data blocks we're writing. An
954 	 * application might be confined by multiple policies having data in
955 	 * the same key.
956 	 */
957 	memset(buf, 0, sizeof(bytes) + sizeof(blocks));
958 	out = buf + sizeof(bytes) + sizeof(blocks);
959 
960 	blocks = 0;
961 	label_for_each_confined(i, label, profile) {
962 		if (!profile->data)
963 			continue;
964 
965 		data = rhashtable_lookup_fast(profile->data, &key,
966 					      profile->data->p);
967 
968 		if (data) {
969 			if (out + sizeof(outle32) + data->size > buf +
970 			    buf_len) {
971 				aa_put_label(label);
972 				return -EINVAL; /* not enough space */
973 			}
974 			outle32 = __cpu_to_le32(data->size);
975 			memcpy(out, &outle32, sizeof(outle32));
976 			out += sizeof(outle32);
977 			memcpy(out, data->data, data->size);
978 			out += data->size;
979 			blocks++;
980 		}
981 	}
982 	aa_put_label(label);
983 
984 	outle32 = __cpu_to_le32(out - buf - sizeof(bytes));
985 	memcpy(buf, &outle32, sizeof(outle32));
986 	outle32 = __cpu_to_le32(blocks);
987 	memcpy(buf + sizeof(bytes), &outle32, sizeof(outle32));
988 
989 	return out - buf;
990 }
991 
992 /**
993  * query_label - queries a label and writes permissions to buf
994  * @buf: the resulting permissions string is stored here (NOT NULL)
995  * @buf_len: size of buf
996  * @query: binary query string to match against the dfa
997  * @query_len: size of query
998  * @view_only: only compute for querier's view
999  *
1000  * The buffers pointed to by buf and query may overlap. The query buffer is
1001  * parsed before buf is written to.
1002  *
1003  * The query should look like "LABEL_NAME\0DFA_STRING" where LABEL_NAME is
1004  * the name of the label, in the current namespace, that is to be queried and
1005  * DFA_STRING is a binary string to match against the label(s)'s DFA.
1006  *
1007  * LABEL_NAME must be NUL terminated. DFA_STRING may contain NUL characters
1008  * but must *not* be NUL terminated.
1009  *
1010  * Returns: number of characters written to buf or -errno on failure
1011  */
1012 static ssize_t query_label(char *buf, size_t buf_len,
1013 			   char *query, size_t query_len, bool view_only)
1014 {
1015 	struct aa_profile *profile;
1016 	struct aa_label *label, *curr;
1017 	char *label_name, *match_str;
1018 	size_t label_name_len, match_len;
1019 	struct aa_perms perms;
1020 	struct label_it i;
1021 	bool needput;
1022 
1023 	if (!query_len)
1024 		return -EINVAL;
1025 
1026 	label_name = query;
1027 	label_name_len = strnlen(query, query_len);
1028 	if (!label_name_len || label_name_len == query_len)
1029 		return -EINVAL;
1030 
1031 	/**
1032 	 * The extra byte is to account for the null byte between the
1033 	 * profile name and dfa string. profile_name_len is greater
1034 	 * than zero and less than query_len, so a byte can be safely
1035 	 * added or subtracted.
1036 	 */
1037 	match_str = label_name + label_name_len + 1;
1038 	match_len = query_len - label_name_len - 1;
1039 
1040 	curr = begin_current_label_crit_section(&needput);
1041 	label = aa_label_parse(curr, label_name, GFP_KERNEL, false, false);
1042 	end_current_label_crit_section(curr, needput);
1043 	if (IS_ERR(label))
1044 		return PTR_ERR(label);
1045 
1046 	perms = allperms;
1047 	if (view_only) {
1048 		label_for_each_in_scope(i, labels_ns(label), label, profile) {
1049 			profile_query_cb(profile, &perms, match_str, match_len);
1050 		}
1051 	} else {
1052 		label_for_each(i, label, profile) {
1053 			profile_query_cb(profile, &perms, match_str, match_len);
1054 		}
1055 	}
1056 	aa_put_label(label);
1057 
1058 	return scnprintf(buf, buf_len,
1059 		      "allow 0x%08x\ndeny 0x%08x\naudit 0x%08x\nquiet 0x%08x\n",
1060 		      perms.allow, perms.deny, perms.audit, perms.quiet);
1061 }
1062 
1063 /*
1064  * Transaction based IO.
1065  * The file expects a write which triggers the transaction, and then
1066  * possibly a read(s) which collects the result - which is stored in a
1067  * file-local buffer. Once a new write is performed, a new set of results
1068  * are stored in the file-local buffer.
1069  */
1070 struct multi_transaction {
1071 	struct kref count;
1072 	ssize_t size;
1073 	char data[];
1074 };
1075 
1076 #define MULTI_TRANSACTION_LIMIT (PAGE_SIZE - sizeof(struct multi_transaction))
1077 
1078 static void multi_transaction_kref(struct kref *kref)
1079 {
1080 	struct multi_transaction *t;
1081 
1082 	t = container_of(kref, struct multi_transaction, count);
1083 	kfree(t);
1084 }
1085 
1086 static struct multi_transaction *
1087 get_multi_transaction(struct multi_transaction *t)
1088 {
1089 	if  (t)
1090 		kref_get(&(t->count));
1091 
1092 	return t;
1093 }
1094 
1095 static void put_multi_transaction(struct multi_transaction *t)
1096 {
1097 	if (t)
1098 		kref_put(&(t->count), multi_transaction_kref);
1099 }
1100 
1101 /* does not increment @new's count */
1102 static void multi_transaction_set(struct file *file,
1103 				  struct multi_transaction *new, size_t n)
1104 {
1105 	struct multi_transaction *old;
1106 
1107 	AA_BUG(n > MULTI_TRANSACTION_LIMIT);
1108 
1109 	new->size = n;
1110 	spin_lock(&file->f_lock);
1111 	old = (struct multi_transaction *) file->private_data;
1112 	file->private_data = new;
1113 	spin_unlock(&file->f_lock);
1114 	put_multi_transaction(old);
1115 }
1116 
1117 static struct multi_transaction *multi_transaction_new(struct file *file,
1118 						       const char __user *buf,
1119 						       size_t size)
1120 {
1121 	struct multi_transaction *t;
1122 
1123 	if (size > MULTI_TRANSACTION_LIMIT - 1)
1124 		return ERR_PTR(-EFBIG);
1125 
1126 	t = kzalloc(PAGE_SIZE, GFP_KERNEL);
1127 	if (!t)
1128 		return ERR_PTR(-ENOMEM);
1129 	kref_init(&t->count);
1130 	if (copy_from_user(t->data, buf, size)) {
1131 		put_multi_transaction(t);
1132 		return ERR_PTR(-EFAULT);
1133 	}
1134 
1135 	return t;
1136 }
1137 
1138 static ssize_t multi_transaction_read(struct file *file, char __user *buf,
1139 				       size_t size, loff_t *pos)
1140 {
1141 	struct multi_transaction *t;
1142 	ssize_t ret;
1143 
1144 	spin_lock(&file->f_lock);
1145 	t = get_multi_transaction(file->private_data);
1146 	spin_unlock(&file->f_lock);
1147 
1148 	if (!t)
1149 		return 0;
1150 
1151 	ret = simple_read_from_buffer(buf, size, pos, t->data, t->size);
1152 	put_multi_transaction(t);
1153 
1154 	return ret;
1155 }
1156 
1157 static int multi_transaction_release(struct inode *inode, struct file *file)
1158 {
1159 	put_multi_transaction(file->private_data);
1160 
1161 	return 0;
1162 }
1163 
1164 #define QUERY_CMD_LABEL		"label\0"
1165 #define QUERY_CMD_LABEL_LEN	6
1166 #define QUERY_CMD_PROFILE	"profile\0"
1167 #define QUERY_CMD_PROFILE_LEN	8
1168 #define QUERY_CMD_LABELALL	"labelall\0"
1169 #define QUERY_CMD_LABELALL_LEN	9
1170 #define QUERY_CMD_DATA		"data\0"
1171 #define QUERY_CMD_DATA_LEN	5
1172 
1173 /**
1174  * aa_write_access - generic permissions and data query
1175  * @file: pointer to open apparmorfs/access file
1176  * @ubuf: user buffer containing the complete query string (NOT NULL)
1177  * @count: size of ubuf
1178  * @ppos: position in the file (MUST BE ZERO)
1179  *
1180  * Allows for one permissions or data query per open(), write(), and read()
1181  * sequence. The only queries currently supported are label-based queries for
1182  * permissions or data.
1183  *
1184  * For permissions queries, ubuf must begin with "label\0", followed by the
1185  * profile query specific format described in the query_label() function
1186  * documentation.
1187  *
1188  * For data queries, ubuf must have the form "data\0<LABEL>\0<KEY>\0", where
1189  * <LABEL> is the name of the security confinement context and <KEY> is the
1190  * name of the data to retrieve.
1191  *
1192  * Returns: number of bytes written or -errno on failure
1193  */
1194 static ssize_t aa_write_access(struct file *file, const char __user *ubuf,
1195 			       size_t count, loff_t *ppos)
1196 {
1197 	struct multi_transaction *t;
1198 	ssize_t len;
1199 
1200 	if (*ppos)
1201 		return -ESPIPE;
1202 
1203 	t = multi_transaction_new(file, ubuf, count);
1204 	if (IS_ERR(t))
1205 		return PTR_ERR(t);
1206 
1207 	if (count > QUERY_CMD_PROFILE_LEN &&
1208 	    !memcmp(t->data, QUERY_CMD_PROFILE, QUERY_CMD_PROFILE_LEN)) {
1209 		len = query_label(t->data, MULTI_TRANSACTION_LIMIT,
1210 				  t->data + QUERY_CMD_PROFILE_LEN,
1211 				  count - QUERY_CMD_PROFILE_LEN, true);
1212 	} else if (count > QUERY_CMD_LABEL_LEN &&
1213 		   !memcmp(t->data, QUERY_CMD_LABEL, QUERY_CMD_LABEL_LEN)) {
1214 		len = query_label(t->data, MULTI_TRANSACTION_LIMIT,
1215 				  t->data + QUERY_CMD_LABEL_LEN,
1216 				  count - QUERY_CMD_LABEL_LEN, true);
1217 	} else if (count > QUERY_CMD_LABELALL_LEN &&
1218 		   !memcmp(t->data, QUERY_CMD_LABELALL,
1219 			   QUERY_CMD_LABELALL_LEN)) {
1220 		len = query_label(t->data, MULTI_TRANSACTION_LIMIT,
1221 				  t->data + QUERY_CMD_LABELALL_LEN,
1222 				  count - QUERY_CMD_LABELALL_LEN, false);
1223 	} else if (count > QUERY_CMD_DATA_LEN &&
1224 		   !memcmp(t->data, QUERY_CMD_DATA, QUERY_CMD_DATA_LEN)) {
1225 		len = query_data(t->data, MULTI_TRANSACTION_LIMIT,
1226 				 t->data + QUERY_CMD_DATA_LEN,
1227 				 count - QUERY_CMD_DATA_LEN);
1228 	} else
1229 		len = -EINVAL;
1230 
1231 	if (len < 0) {
1232 		put_multi_transaction(t);
1233 		return len;
1234 	}
1235 
1236 	multi_transaction_set(file, t, len);
1237 
1238 	return count;
1239 }
1240 
1241 static const struct file_operations aa_sfs_access = {
1242 	.write		= aa_write_access,
1243 	.read		= multi_transaction_read,
1244 	.release	= multi_transaction_release,
1245 	.llseek		= generic_file_llseek,
1246 };
1247 
1248 static int aa_sfs_seq_show(struct seq_file *seq, void *v)
1249 {
1250 	struct aa_sfs_entry *fs_file = seq->private;
1251 
1252 	if (!fs_file)
1253 		return 0;
1254 
1255 	switch (fs_file->v_type) {
1256 	case AA_SFS_TYPE_BOOLEAN:
1257 		seq_printf(seq, "%s\n", str_yes_no(fs_file->v.boolean));
1258 		break;
1259 	case AA_SFS_TYPE_STRING:
1260 		seq_printf(seq, "%s\n", fs_file->v.string);
1261 		break;
1262 	case AA_SFS_TYPE_U64:
1263 		seq_printf(seq, "%#08lx\n", fs_file->v.u64);
1264 		break;
1265 	default:
1266 		/* Ignore unprintable entry types. */
1267 		break;
1268 	}
1269 
1270 	return 0;
1271 }
1272 
1273 static int aa_sfs_seq_open(struct inode *inode, struct file *file)
1274 {
1275 	return single_open(file, aa_sfs_seq_show, inode->i_private);
1276 }
1277 
1278 const struct file_operations aa_sfs_seq_file_ops = {
1279 	.owner		= THIS_MODULE,
1280 	.open		= aa_sfs_seq_open,
1281 	.read		= seq_read,
1282 	.llseek		= seq_lseek,
1283 	.release	= single_release,
1284 };
1285 
1286 /*
1287  * profile based file operations
1288  *     policy/profiles/XXXX/profiles/ *
1289  */
1290 
1291 #define SEQ_PROFILE_FOPS(NAME)						      \
1292 static int seq_profile_ ##NAME ##_open(struct inode *inode, struct file *file)\
1293 {									      \
1294 	return seq_profile_open(inode, file, seq_profile_ ##NAME ##_show);    \
1295 }									      \
1296 									      \
1297 static const struct file_operations seq_profile_ ##NAME ##_fops = {	      \
1298 	.owner		= THIS_MODULE,					      \
1299 	.open		= seq_profile_ ##NAME ##_open,			      \
1300 	.read		= seq_read,					      \
1301 	.llseek		= seq_lseek,					      \
1302 	.release	= seq_profile_release,				      \
1303 }									      \
1304 
1305 static int seq_profile_open(struct inode *inode, struct file *file,
1306 			    int (*show)(struct seq_file *, void *))
1307 {
1308 	struct aa_proxy *proxy = get_proxy_common_ref(inode->i_private);
1309 	int error = single_open(file, show, proxy);
1310 
1311 	if (error) {
1312 		file->private_data = NULL;
1313 		aa_put_proxy(proxy);
1314 	}
1315 
1316 	return error;
1317 }
1318 
1319 static int seq_profile_release(struct inode *inode, struct file *file)
1320 {
1321 	struct seq_file *seq = (struct seq_file *) file->private_data;
1322 	if (seq)
1323 		aa_put_proxy(seq->private);
1324 	return single_release(inode, file);
1325 }
1326 
1327 static int seq_profile_name_show(struct seq_file *seq, void *v)
1328 {
1329 	struct aa_proxy *proxy = seq->private;
1330 	struct aa_label *label = aa_get_label_rcu(&proxy->label);
1331 	struct aa_profile *profile = labels_profile(label);
1332 	seq_printf(seq, "%s\n", profile->base.name);
1333 	aa_put_label(label);
1334 
1335 	return 0;
1336 }
1337 
1338 static int seq_profile_mode_show(struct seq_file *seq, void *v)
1339 {
1340 	struct aa_proxy *proxy = seq->private;
1341 	struct aa_label *label = aa_get_label_rcu(&proxy->label);
1342 	struct aa_profile *profile = labels_profile(label);
1343 	seq_printf(seq, "%s\n", aa_profile_mode_names[profile->mode]);
1344 	aa_put_label(label);
1345 
1346 	return 0;
1347 }
1348 
1349 static int seq_profile_attach_show(struct seq_file *seq, void *v)
1350 {
1351 	struct aa_proxy *proxy = seq->private;
1352 	struct aa_label *label = aa_get_label_rcu(&proxy->label);
1353 	struct aa_profile *profile = labels_profile(label);
1354 	if (profile->attach.xmatch_str)
1355 		seq_printf(seq, "%s\n", profile->attach.xmatch_str);
1356 	else if (profile->attach.xmatch->dfa)
1357 		seq_puts(seq, "<unknown>\n");
1358 	else
1359 		seq_printf(seq, "%s\n", profile->base.name);
1360 	aa_put_label(label);
1361 
1362 	return 0;
1363 }
1364 
1365 static int seq_profile_hash_show(struct seq_file *seq, void *v)
1366 {
1367 	struct aa_proxy *proxy = seq->private;
1368 	struct aa_label *label = aa_get_label_rcu(&proxy->label);
1369 	struct aa_profile *profile = labels_profile(label);
1370 	unsigned int i, size = aa_hash_size();
1371 
1372 	if (profile->hash) {
1373 		for (i = 0; i < size; i++)
1374 			seq_printf(seq, "%.2x", profile->hash[i]);
1375 		seq_putc(seq, '\n');
1376 	}
1377 	aa_put_label(label);
1378 
1379 	return 0;
1380 }
1381 
1382 SEQ_PROFILE_FOPS(name);
1383 SEQ_PROFILE_FOPS(mode);
1384 SEQ_PROFILE_FOPS(attach);
1385 SEQ_PROFILE_FOPS(hash);
1386 
1387 /*
1388  * namespace based files
1389  *     several root files and
1390  *     policy/ *
1391  */
1392 
1393 #define SEQ_NS_FOPS(NAME)						      \
1394 static int seq_ns_ ##NAME ##_open(struct inode *inode, struct file *file)     \
1395 {									      \
1396 	return single_open(file, seq_ns_ ##NAME ##_show, inode->i_private);   \
1397 }									      \
1398 									      \
1399 static const struct file_operations seq_ns_ ##NAME ##_fops = {	      \
1400 	.owner		= THIS_MODULE,					      \
1401 	.open		= seq_ns_ ##NAME ##_open,			      \
1402 	.read		= seq_read,					      \
1403 	.llseek		= seq_lseek,					      \
1404 	.release	= single_release,				      \
1405 }									      \
1406 
1407 static int seq_ns_stacked_show(struct seq_file *seq, void *v)
1408 {
1409 	struct aa_label *label;
1410 	bool needput;
1411 
1412 	label = begin_current_label_crit_section(&needput);
1413 	seq_printf(seq, "%s\n", str_yes_no(label->size > 1));
1414 	end_current_label_crit_section(label, needput);
1415 
1416 	return 0;
1417 }
1418 
1419 static int seq_ns_nsstacked_show(struct seq_file *seq, void *v)
1420 {
1421 	struct aa_label *label;
1422 	struct aa_profile *profile;
1423 	struct label_it it;
1424 	int count = 1;
1425 	bool needput;
1426 
1427 	label = begin_current_label_crit_section(&needput);
1428 
1429 	if (label->size > 1) {
1430 		label_for_each(it, label, profile)
1431 			if (profile->ns != labels_ns(label)) {
1432 				count++;
1433 				break;
1434 			}
1435 	}
1436 
1437 	seq_printf(seq, "%s\n", str_yes_no(count > 1));
1438 	end_current_label_crit_section(label, needput);
1439 
1440 	return 0;
1441 }
1442 
1443 static int seq_ns_level_show(struct seq_file *seq, void *v)
1444 {
1445 	struct aa_label *label;
1446 	bool needput;
1447 
1448 	label = begin_current_label_crit_section(&needput);
1449 	seq_printf(seq, "%d\n", labels_ns(label)->level);
1450 	end_current_label_crit_section(label, needput);
1451 
1452 	return 0;
1453 }
1454 
1455 static int seq_ns_name_show(struct seq_file *seq, void *v)
1456 {
1457 	bool needput;
1458 	struct aa_label *label = begin_current_label_crit_section(&needput);
1459 
1460 	seq_printf(seq, "%s\n", labels_ns(label)->base.name);
1461 	end_current_label_crit_section(label, needput);
1462 
1463 	return 0;
1464 }
1465 
1466 SEQ_NS_FOPS(stacked);
1467 SEQ_NS_FOPS(nsstacked);
1468 SEQ_NS_FOPS(level);
1469 SEQ_NS_FOPS(name);
1470 
1471 #ifdef CONFIG_SECURITY_APPARMOR_EXPORT_BINARY
1472 static int seq_ns_compress_min_show(struct seq_file *seq, void *v)
1473 {
1474 	seq_printf(seq, "%d\n", AA_MIN_CLEVEL);
1475 	return 0;
1476 }
1477 
1478 static int seq_ns_compress_max_show(struct seq_file *seq, void *v)
1479 {
1480 	seq_printf(seq, "%d\n", AA_MAX_CLEVEL);
1481 	return 0;
1482 }
1483 
1484 SEQ_NS_FOPS(compress_min);
1485 SEQ_NS_FOPS(compress_max);
1486 
1487 
1488 /* policy/raw_data/ * file ops */
1489 #define SEQ_RAWDATA_FOPS(NAME)						      \
1490 static int seq_rawdata_ ##NAME ##_open(struct inode *inode, struct file *file)\
1491 {									      \
1492 	return seq_rawdata_open(inode, file, seq_rawdata_ ##NAME ##_show);    \
1493 }									      \
1494 									      \
1495 static const struct file_operations seq_rawdata_ ##NAME ##_fops = {	      \
1496 	.owner		= THIS_MODULE,					      \
1497 	.open		= seq_rawdata_ ##NAME ##_open,			      \
1498 	.read		= seq_read,					      \
1499 	.llseek		= seq_lseek,					      \
1500 	.release	= seq_rawdata_release,				      \
1501 }									      \
1502 
1503 static int seq_rawdata_open(struct inode *inode, struct file *file,
1504 			    int (*show)(struct seq_file *, void *))
1505 {
1506 	struct aa_loaddata *data = get_loaddata_common_ref(inode->i_private);
1507 	int error;
1508 
1509 	if (!data)
1510 		return -ENOENT;
1511 
1512 	error = single_open(file, show, data);
1513 	if (error) {
1514 		AA_BUG(file->private_data &&
1515 		       ((struct seq_file *)file->private_data)->private);
1516 		aa_put_i_loaddata(data);
1517 	}
1518 
1519 	return error;
1520 }
1521 
1522 static int seq_rawdata_release(struct inode *inode, struct file *file)
1523 {
1524 	struct seq_file *seq = (struct seq_file *) file->private_data;
1525 
1526 	if (seq)
1527 		aa_put_i_loaddata(seq->private);
1528 
1529 	return single_release(inode, file);
1530 }
1531 
1532 static int seq_rawdata_abi_show(struct seq_file *seq, void *v)
1533 {
1534 	struct aa_loaddata *data = seq->private;
1535 
1536 	seq_printf(seq, "v%d\n", data->abi);
1537 
1538 	return 0;
1539 }
1540 
1541 static int seq_rawdata_revision_show(struct seq_file *seq, void *v)
1542 {
1543 	struct aa_loaddata *data = seq->private;
1544 
1545 	seq_printf(seq, "%ld\n", data->revision);
1546 
1547 	return 0;
1548 }
1549 
1550 static int seq_rawdata_hash_show(struct seq_file *seq, void *v)
1551 {
1552 	struct aa_loaddata *data = seq->private;
1553 	unsigned int i, size = aa_hash_size();
1554 
1555 	if (data->hash) {
1556 		for (i = 0; i < size; i++)
1557 			seq_printf(seq, "%.2x", data->hash[i]);
1558 		seq_putc(seq, '\n');
1559 	}
1560 
1561 	return 0;
1562 }
1563 
1564 static int seq_rawdata_compressed_size_show(struct seq_file *seq, void *v)
1565 {
1566 	struct aa_loaddata *data = seq->private;
1567 
1568 	seq_printf(seq, "%zu\n", data->compressed_size);
1569 
1570 	return 0;
1571 }
1572 
1573 SEQ_RAWDATA_FOPS(abi);
1574 SEQ_RAWDATA_FOPS(revision);
1575 SEQ_RAWDATA_FOPS(hash);
1576 SEQ_RAWDATA_FOPS(compressed_size);
1577 
1578 static ssize_t rawdata_read(struct file *file, char __user *buf, size_t size,
1579 			    loff_t *ppos)
1580 {
1581 	struct rawdata_f_data *private = file->private_data;
1582 
1583 	return simple_read_from_buffer(buf, size, ppos,
1584 				       private->data,
1585 				       private->loaddata->size);
1586 }
1587 
1588 static int rawdata_release(struct inode *inode, struct file *file)
1589 {
1590 	rawdata_f_data_free(file->private_data);
1591 
1592 	return 0;
1593 }
1594 
1595 static int rawdata_open(struct inode *inode, struct file *file)
1596 {
1597 	int error;
1598 	struct aa_loaddata *loaddata;
1599 	struct rawdata_f_data *private;
1600 
1601 	if (!aa_current_policy_view_capable(NULL))
1602 		return -EACCES;
1603 
1604 	loaddata = get_loaddata_common_ref(inode->i_private);
1605 	if (!loaddata)
1606 		return -ENOENT;
1607 
1608 	private = rawdata_f_data_alloc(loaddata->size);
1609 	if (IS_ERR(private)) {
1610 		error = PTR_ERR(private);
1611 		goto fail_private_alloc;
1612 	}
1613 
1614 	private->loaddata = loaddata;
1615 
1616 	error = decompress_zstd(loaddata->data, loaddata->compressed_size,
1617 				private->data, loaddata->size);
1618 	if (error)
1619 		goto fail_decompress;
1620 
1621 	file->private_data = private;
1622 	return 0;
1623 
1624 fail_decompress:
1625 	rawdata_f_data_free(private);
1626 	return error;
1627 
1628 fail_private_alloc:
1629 	aa_put_i_loaddata(loaddata);
1630 	return error;
1631 }
1632 
1633 static const struct file_operations rawdata_fops = {
1634 	.open = rawdata_open,
1635 	.read = rawdata_read,
1636 	.llseek = generic_file_llseek,
1637 	.release = rawdata_release,
1638 };
1639 
1640 static void remove_rawdata_dents(struct aa_loaddata *rawdata)
1641 {
1642 	int i;
1643 
1644 	for (i = 0; i < AAFS_LOADDATA_NDENTS; i++) {
1645 		if (!IS_ERR_OR_NULL(rawdata->dents[i])) {
1646 			aafs_remove(rawdata->dents[i]);
1647 			rawdata->dents[i] = NULL;
1648 		}
1649 	}
1650 }
1651 
1652 void __aa_fs_remove_rawdata(struct aa_loaddata *rawdata)
1653 {
1654 	AA_BUG(rawdata->ns && !mutex_is_locked(&rawdata->ns->lock));
1655 
1656 	if (rawdata->ns) {
1657 		remove_rawdata_dents(rawdata);
1658 		list_del_init(&rawdata->list);
1659 		aa_put_ns(rawdata->ns);
1660 		rawdata->ns = NULL;
1661 	}
1662 }
1663 
1664 int __aa_fs_create_rawdata(struct aa_ns *ns, struct aa_loaddata *rawdata)
1665 {
1666 	struct dentry *dent, *dir;
1667 
1668 	AA_BUG(!ns);
1669 	AA_BUG(!rawdata);
1670 	AA_BUG(!mutex_is_locked(&ns->lock));
1671 	AA_BUG(!ns_subdata_dir(ns));
1672 
1673 	/*
1674 	 * just use ns revision dir was originally created at. This is
1675 	 * under ns->lock and if load is successful revision will be
1676 	 * bumped and is guaranteed to be unique
1677 	 */
1678 	rawdata->name = kasprintf(GFP_KERNEL, "%ld", ns->revision);
1679 	if (!rawdata->name)
1680 		return -ENOMEM;
1681 
1682 	dir = aafs_create_dir(rawdata->name, ns_subdata_dir(ns));
1683 	if (IS_ERR(dir))
1684 		/* ->name freed when rawdata freed */
1685 		return PTR_ERR(dir);
1686 	rawdata->dents[AAFS_LOADDATA_DIR] = dir;
1687 
1688 	dent = aafs_create_file("abi", S_IFREG | 0444, dir, &rawdata->count,
1689 				      &seq_rawdata_abi_fops);
1690 	if (IS_ERR(dent))
1691 		goto fail;
1692 	rawdata->dents[AAFS_LOADDATA_ABI] = dent;
1693 
1694 	dent = aafs_create_file("revision", S_IFREG | 0444, dir,
1695 				&rawdata->count,
1696 				&seq_rawdata_revision_fops);
1697 	if (IS_ERR(dent))
1698 		goto fail;
1699 	rawdata->dents[AAFS_LOADDATA_REVISION] = dent;
1700 
1701 	if (aa_g_hash_policy) {
1702 		dent = aafs_create_file("sha256", S_IFREG | 0444, dir,
1703 					&rawdata->count,
1704 					&seq_rawdata_hash_fops);
1705 		if (IS_ERR(dent))
1706 			goto fail;
1707 		rawdata->dents[AAFS_LOADDATA_HASH] = dent;
1708 	}
1709 
1710 	dent = aafs_create_file("compressed_size", S_IFREG | 0444, dir,
1711 				&rawdata->count,
1712 				&seq_rawdata_compressed_size_fops);
1713 	if (IS_ERR(dent))
1714 		goto fail;
1715 	rawdata->dents[AAFS_LOADDATA_COMPRESSED_SIZE] = dent;
1716 
1717 	dent = aafs_create_file("raw_data", S_IFREG | 0444, dir,
1718 				&rawdata->count, &rawdata_fops);
1719 	if (IS_ERR(dent))
1720 		goto fail;
1721 	rawdata->dents[AAFS_LOADDATA_DATA] = dent;
1722 	d_inode(dent)->i_size = rawdata->size;
1723 
1724 	rawdata->ns = aa_get_ns(ns);
1725 	list_add(&rawdata->list, &ns->rawdata_list);
1726 
1727 	return 0;
1728 
1729 fail:
1730 	remove_rawdata_dents(rawdata);
1731 	return PTR_ERR(dent);
1732 }
1733 #endif /* CONFIG_SECURITY_APPARMOR_EXPORT_BINARY */
1734 
1735 
1736 /** fns to setup dynamic per profile/namespace files **/
1737 
1738 /*
1739  *
1740  * Requires: @profile->ns->lock held
1741  */
1742 void __aafs_profile_rmdir(struct aa_profile *profile)
1743 {
1744 	struct aa_profile *child;
1745 	int i;
1746 
1747 	if (!profile)
1748 		return;
1749 
1750 	list_for_each_entry(child, &profile->base.profiles, base.list)
1751 		__aafs_profile_rmdir(child);
1752 
1753 	for (i = AAFS_PROF_SIZEOF - 1; i >= 0; --i) {
1754 		if (!profile->dents[i])
1755 			continue;
1756 
1757 		aafs_remove(profile->dents[i]);
1758 		profile->dents[i] = NULL;
1759 	}
1760 }
1761 
1762 /*
1763  *
1764  * Requires: @old->ns->lock held
1765  */
1766 void __aafs_profile_migrate_dents(struct aa_profile *old,
1767 				  struct aa_profile *new)
1768 {
1769 	int i;
1770 
1771 	AA_BUG(!old);
1772 	AA_BUG(!new);
1773 	AA_BUG(!mutex_is_locked(&profiles_ns(old)->lock));
1774 
1775 	for (i = 0; i < AAFS_PROF_SIZEOF; i++) {
1776 		new->dents[i] = old->dents[i];
1777 		if (new->dents[i]) {
1778 			struct inode *inode = d_inode(new->dents[i]);
1779 
1780 			inode_set_mtime_to_ts(inode,
1781 					      inode_set_ctime_current(inode));
1782 		}
1783 		old->dents[i] = NULL;
1784 	}
1785 }
1786 
1787 static struct dentry *create_profile_file(struct dentry *dir, const char *name,
1788 					  struct aa_profile *profile,
1789 					  const struct file_operations *fops)
1790 {
1791 	return aafs_create_file(name, S_IFREG | 0444, dir, &profile->label.proxy->count, fops);
1792 }
1793 
1794 #ifdef CONFIG_SECURITY_APPARMOR_EXPORT_BINARY
1795 static int profile_depth(struct aa_profile *profile)
1796 {
1797 	int depth = 0;
1798 
1799 	rcu_read_lock();
1800 	for (depth = 0; profile; profile = rcu_access_pointer(profile->parent))
1801 		depth++;
1802 	rcu_read_unlock();
1803 
1804 	return depth;
1805 }
1806 
1807 static char *gen_symlink_name(int depth, const char *dirname, const char *fname)
1808 {
1809 	char *buffer, *s;
1810 	int error;
1811 	const char *path = "../../";
1812 	size_t path_len = strlen(path);
1813 	int size;
1814 
1815 	/* Extra 11 bytes: "raw_data" (9) + two slashes "//" (2) */
1816 	size = depth * path_len + strlen(dirname) + strlen(fname) + 11;
1817 	s = buffer = kmalloc(size, GFP_KERNEL);
1818 	if (!buffer)
1819 		return ERR_PTR(-ENOMEM);
1820 
1821 	for (; depth > 0; depth--) {
1822 		memcpy(s, path, path_len);
1823 		s += path_len;
1824 		size -= path_len;
1825 	}
1826 
1827 	error = snprintf(s, size, "raw_data/%s/%s", dirname, fname);
1828 	if (error >= size || error < 0) {
1829 		kfree(buffer);
1830 		return ERR_PTR(-ENAMETOOLONG);
1831 	}
1832 
1833 	return buffer;
1834 }
1835 
1836 static const char *rawdata_get_link_base(struct dentry *dentry,
1837 					 struct inode *inode,
1838 					 struct delayed_call *done,
1839 					 const char *name)
1840 {
1841 	struct aa_common_ref *ref = inode->i_private;
1842 	struct aa_proxy *proxy = container_of(ref, struct aa_proxy, count);
1843 	struct aa_label *label;
1844 	struct aa_profile *profile;
1845 	char *target;
1846 	int depth;
1847 
1848 	if (!dentry)
1849 		return ERR_PTR(-ECHILD);
1850 
1851 	label = aa_get_label_rcu(&proxy->label);
1852 	profile = labels_profile(label);
1853 
1854 	/* rawdata can be null when aa_g_export_binary is unset during
1855 	 * runtime and a profile is replaced
1856 	 */
1857 	if (!profile->rawdata) {
1858 		aa_put_label(label);
1859 		return ERR_PTR(-ENOENT);
1860 	}
1861 
1862 	depth = profile_depth(profile);
1863 	target = gen_symlink_name(depth, profile->rawdata->name, name);
1864 	aa_put_label(label);
1865 
1866 	if (IS_ERR(target))
1867 		return target;
1868 
1869 	set_delayed_call(done, kfree_link, target);
1870 
1871 	return target;
1872 }
1873 
1874 static const char *rawdata_get_link_sha256(struct dentry *dentry,
1875 					 struct inode *inode,
1876 					 struct delayed_call *done)
1877 {
1878 	return rawdata_get_link_base(dentry, inode, done, "sha256");
1879 }
1880 
1881 static const char *rawdata_get_link_abi(struct dentry *dentry,
1882 					struct inode *inode,
1883 					struct delayed_call *done)
1884 {
1885 	return rawdata_get_link_base(dentry, inode, done, "abi");
1886 }
1887 
1888 static const char *rawdata_get_link_data(struct dentry *dentry,
1889 					 struct inode *inode,
1890 					 struct delayed_call *done)
1891 {
1892 	return rawdata_get_link_base(dentry, inode, done, "raw_data");
1893 }
1894 
1895 static const struct inode_operations rawdata_link_sha256_iops = {
1896 	.get_link	= rawdata_get_link_sha256,
1897 };
1898 
1899 static const struct inode_operations rawdata_link_abi_iops = {
1900 	.get_link	= rawdata_get_link_abi,
1901 };
1902 static const struct inode_operations rawdata_link_data_iops = {
1903 	.get_link	= rawdata_get_link_data,
1904 };
1905 
1906 /*
1907  * Requires: @profile->ns->lock held
1908  */
1909 void __aa_remove_rawdata_symlink_dents(struct aa_profile *profile)
1910 {
1911 	aafs_remove(profile->dents[AAFS_PROF_RAW_HASH]);
1912 	profile->dents[AAFS_PROF_RAW_HASH] = NULL;
1913 	aafs_remove(profile->dents[AAFS_PROF_RAW_ABI]);
1914 	profile->dents[AAFS_PROF_RAW_ABI] = NULL;
1915 	aafs_remove(profile->dents[AAFS_PROF_RAW_DATA]);
1916 	profile->dents[AAFS_PROF_RAW_DATA] = NULL;
1917 }
1918 
1919 static inline int create_symlink_dent(struct aa_profile *profile,
1920 				      const char *name,
1921 				      enum aafs_prof_type type,
1922 				      const struct inode_operations *iops)
1923 {
1924 	struct dentry *dent = NULL;
1925 	struct dentry *dir = prof_dir(profile);
1926 
1927 	if (profile->dents[type])
1928 		return 0;
1929 
1930 	dent = aafs_create(name, S_IFLNK | 0444, dir,
1931 			   &profile->label.proxy->count, NULL, NULL, iops);
1932 	if (IS_ERR(dent))
1933 		return PTR_ERR(dent);
1934 
1935 	profile->dents[type] = dent;
1936 	return 0;
1937 }
1938 
1939 /*
1940  * Requires: @profile->ns->lock held
1941  */
1942 int __aa_create_rawdata_symlink_dents(struct aa_profile *profile)
1943 {
1944 	int error;
1945 
1946 	if (!profile ||
1947 	    (profile->dents[AAFS_PROF_RAW_HASH] &&
1948 	     profile->dents[AAFS_PROF_RAW_ABI] &&
1949 	     profile->dents[AAFS_PROF_RAW_DATA]))
1950 		return 0;
1951 
1952 	if (!profile->rawdata)
1953 		return 0;
1954 
1955 	if (aa_g_hash_policy) {
1956 		error = create_symlink_dent(profile, "raw_sha256",
1957 					    AAFS_PROF_RAW_HASH,
1958 					    &rawdata_link_sha256_iops);
1959 		if (error)
1960 			return error;
1961 	}
1962 
1963 	error = create_symlink_dent(profile, "raw_abi",
1964 				    AAFS_PROF_RAW_ABI,
1965 				    &rawdata_link_abi_iops);
1966 	if (error)
1967 		return error;
1968 
1969 
1970 	error = create_symlink_dent(profile, "raw_data",
1971 				    AAFS_PROF_RAW_DATA,
1972 				    &rawdata_link_data_iops);
1973 	if (error)
1974 		return error;
1975 
1976 	return 0;
1977 }
1978 
1979 #endif /* CONFIG_SECURITY_APPARMOR_EXPORT_BINARY */
1980 
1981 /*
1982  * Requires: @profile->ns->lock held
1983  */
1984 int __aafs_profile_mkdir(struct aa_profile *profile, struct dentry *parent)
1985 {
1986 	struct aa_profile *child;
1987 	struct dentry *dent = NULL, *dir;
1988 	int error;
1989 
1990 	AA_BUG(!profile);
1991 	AA_BUG(!mutex_is_locked(&profiles_ns(profile)->lock));
1992 
1993 	if (!parent) {
1994 		struct aa_profile *p;
1995 		p = aa_deref_parent(profile);
1996 		dent = prof_dir(p);
1997 		if (!dent) {
1998 			error = -ENOENT;
1999 			goto fail2;
2000 		}
2001 		/* adding to parent that previously didn't have children */
2002 		dent = aafs_create_dir("profiles", dent);
2003 		if (IS_ERR(dent))
2004 			goto fail;
2005 		prof_child_dir(p) = parent = dent;
2006 	}
2007 
2008 	if (!profile->dirname) {
2009 		int len, id_len;
2010 		len = mangle_name(profile->base.name, NULL);
2011 		id_len = snprintf(NULL, 0, ".%ld", profile->ns->uniq_id);
2012 
2013 		profile->dirname = kmalloc(len + id_len + 1, GFP_KERNEL);
2014 		if (!profile->dirname) {
2015 			error = -ENOMEM;
2016 			goto fail2;
2017 		}
2018 
2019 		mangle_name(profile->base.name, profile->dirname);
2020 		sprintf(profile->dirname + len, ".%ld", profile->ns->uniq_id++);
2021 	}
2022 
2023 	dent = aafs_create_dir(profile->dirname, parent);
2024 	if (IS_ERR(dent))
2025 		goto fail;
2026 	prof_dir(profile) = dir = dent;
2027 
2028 	dent = create_profile_file(dir, "name", profile,
2029 				   &seq_profile_name_fops);
2030 	if (IS_ERR(dent))
2031 		goto fail;
2032 	profile->dents[AAFS_PROF_NAME] = dent;
2033 
2034 	dent = create_profile_file(dir, "mode", profile,
2035 				   &seq_profile_mode_fops);
2036 	if (IS_ERR(dent))
2037 		goto fail;
2038 	profile->dents[AAFS_PROF_MODE] = dent;
2039 
2040 	dent = create_profile_file(dir, "attach", profile,
2041 				   &seq_profile_attach_fops);
2042 	if (IS_ERR(dent))
2043 		goto fail;
2044 	profile->dents[AAFS_PROF_ATTACH] = dent;
2045 
2046 	if (profile->hash) {
2047 		dent = create_profile_file(dir, "sha256", profile,
2048 					   &seq_profile_hash_fops);
2049 		if (IS_ERR(dent))
2050 			goto fail;
2051 		profile->dents[AAFS_PROF_HASH] = dent;
2052 	}
2053 
2054 	error = __aa_create_rawdata_symlink_dents(profile);
2055 	if (error)
2056 		goto fail2;
2057 
2058 	list_for_each_entry(child, &profile->base.profiles, base.list) {
2059 		error = __aafs_profile_mkdir(child, prof_child_dir(profile));
2060 		if (error)
2061 			goto fail2;
2062 	}
2063 
2064 	return 0;
2065 
2066 fail:
2067 	error = PTR_ERR(dent);
2068 
2069 fail2:
2070 	__aafs_profile_rmdir(profile);
2071 
2072 	return error;
2073 }
2074 
2075 static struct dentry *ns_mkdir_op(struct mnt_idmap *idmap, struct inode *dir,
2076 				  struct dentry *dentry, umode_t mode)
2077 {
2078 	struct aa_ns *ns, *parent;
2079 	/* TODO: improve permission check */
2080 	struct aa_label *label;
2081 	int error;
2082 	bool needput;
2083 
2084 	label = begin_current_label_crit_section(&needput);
2085 	error = aa_may_manage_policy(current_cred(), label, NULL, NULL,
2086 				     AA_MAY_LOAD_POLICY);
2087 	end_current_label_crit_section(label, needput);
2088 	if (error)
2089 		return ERR_PTR(error);
2090 
2091 	parent = get_ns_common_ref(dir->i_private);
2092 	AA_BUG(d_inode(ns_subns_dir(parent)) != dir);
2093 
2094 	/* we have to unlock and then relock to get locking order right
2095 	 * for pin_fs
2096 	 */
2097 	inode_unlock(dir);
2098 	error = simple_pin_fs(&aafs_ops, &aafs_mnt, &aafs_count);
2099 	mutex_lock_nested(&parent->lock, parent->level);
2100 	inode_lock_nested(dir, I_MUTEX_PARENT);
2101 	if (error)
2102 		goto out;
2103 
2104 	error = __aafs_setup_d_inode(dir, dentry, mode | S_IFDIR,  NULL,
2105 				     NULL, NULL, NULL);
2106 	if (error)
2107 		goto out_pin;
2108 
2109 	ns = __aa_find_or_create_ns(parent, READ_ONCE(dentry->d_name.name),
2110 				    dentry);
2111 	if (IS_ERR(ns)) {
2112 		error = PTR_ERR(ns);
2113 		ns = NULL;
2114 	}
2115 
2116 	aa_put_ns(ns);		/* list ref remains */
2117 out_pin:
2118 	if (error)
2119 		simple_release_fs(&aafs_mnt, &aafs_count);
2120 out:
2121 	mutex_unlock(&parent->lock);
2122 	aa_put_ns(parent);
2123 
2124 	return error ? ERR_PTR(error) : NULL;
2125 }
2126 
2127 static int ns_rmdir_op(struct inode *dir, struct dentry *dentry)
2128 {
2129 	struct aa_ns *ns, *parent;
2130 	/* TODO: improve permission check */
2131 	struct aa_label *label;
2132 	bool needput;
2133 	int error;
2134 
2135 	label = begin_current_label_crit_section(&needput);
2136 	error = aa_may_manage_policy(current_cred(), label, NULL, NULL,
2137 				     AA_MAY_LOAD_POLICY);
2138 	end_current_label_crit_section(label, needput);
2139 	if (error)
2140 		return error;
2141 
2142 	parent = get_ns_common_ref(dir->i_private);
2143 	/* rmdir calls the generic securityfs functions to remove files
2144 	 * from the apparmor dir. It is up to the apparmor ns locking
2145 	 * to avoid races.
2146 	 */
2147 	inode_unlock(dir);
2148 	inode_unlock(dentry->d_inode);
2149 
2150 	mutex_lock_nested(&parent->lock, parent->level);
2151 	ns = aa_get_ns(__aa_findn_ns(&parent->sub_ns, dentry->d_name.name,
2152 				     dentry->d_name.len));
2153 	if (!ns) {
2154 		error = -ENOENT;
2155 		goto out;
2156 	}
2157 	AA_BUG(ns_dir(ns) != dentry);
2158 
2159 	__aa_remove_ns(ns);
2160 	aa_put_ns(ns);
2161 
2162 out:
2163 	mutex_unlock(&parent->lock);
2164 	inode_lock_nested(dir, I_MUTEX_PARENT);
2165 	inode_lock(dentry->d_inode);
2166 	aa_put_ns(parent);
2167 
2168 	return error;
2169 }
2170 
2171 static const struct inode_operations ns_dir_inode_operations = {
2172 	.lookup		= simple_lookup,
2173 	.mkdir		= ns_mkdir_op,
2174 	.rmdir		= ns_rmdir_op,
2175 };
2176 
2177 static void __aa_fs_list_remove_rawdata(struct aa_ns *ns)
2178 {
2179 	struct aa_loaddata *ent, *tmp;
2180 
2181 	AA_BUG(!mutex_is_locked(&ns->lock));
2182 
2183 	list_for_each_entry_safe(ent, tmp, &ns->rawdata_list, list)
2184 		__aa_fs_remove_rawdata(ent);
2185 }
2186 
2187 /*
2188  *
2189  * Requires: @ns->lock held
2190  */
2191 void __aafs_ns_rmdir(struct aa_ns *ns)
2192 {
2193 	struct aa_ns *sub;
2194 	struct aa_profile *child;
2195 	int i;
2196 
2197 	if (!ns)
2198 		return;
2199 	AA_BUG(!mutex_is_locked(&ns->lock));
2200 
2201 	list_for_each_entry(child, &ns->base.profiles, base.list)
2202 		__aafs_profile_rmdir(child);
2203 
2204 	list_for_each_entry(sub, &ns->sub_ns, base.list) {
2205 		mutex_lock_nested(&sub->lock, sub->level);
2206 		__aafs_ns_rmdir(sub);
2207 		mutex_unlock(&sub->lock);
2208 	}
2209 
2210 	__aa_fs_list_remove_rawdata(ns);
2211 
2212 	for (i = AAFS_NS_SIZEOF - 1; i >= 0; --i) {
2213 		aafs_remove(ns->dents[i]);
2214 		ns->dents[i] = NULL;
2215 	}
2216 }
2217 
2218 /* assumes cleanup in caller */
2219 static int __aafs_ns_mkdir_entries(struct aa_ns *ns, struct dentry *dir)
2220 {
2221 	struct dentry *dent;
2222 
2223 	AA_BUG(!ns);
2224 	AA_BUG(!dir);
2225 
2226 	dent = aafs_create_dir("profiles", dir);
2227 	if (IS_ERR(dent))
2228 		return PTR_ERR(dent);
2229 	ns_subprofs_dir(ns) = dent;
2230 
2231 	dent = aafs_create_dir("raw_data", dir);
2232 	if (IS_ERR(dent))
2233 		return PTR_ERR(dent);
2234 	ns_subdata_dir(ns) = dent;
2235 
2236 	dent = aafs_create_file("revision", 0444, dir,
2237 				&ns->unconfined->label.count,
2238 				&aa_fs_ns_revision_fops);
2239 	if (IS_ERR(dent))
2240 		return PTR_ERR(dent);
2241 	ns_subrevision(ns) = dent;
2242 
2243 	dent = aafs_create_file(".load", 0640, dir,
2244 				&ns->unconfined->label.count,
2245 				&aa_fs_profile_load);
2246 	if (IS_ERR(dent))
2247 		return PTR_ERR(dent);
2248 	ns_subload(ns) = dent;
2249 
2250 	dent = aafs_create_file(".replace", 0640, dir,
2251 				&ns->unconfined->label.count,
2252 				&aa_fs_profile_replace);
2253 	if (IS_ERR(dent))
2254 		return PTR_ERR(dent);
2255 	ns_subreplace(ns) = dent;
2256 
2257 	dent = aafs_create_file(".remove", 0640, dir,
2258 				&ns->unconfined->label.count,
2259 				&aa_fs_profile_remove);
2260 	if (IS_ERR(dent))
2261 		return PTR_ERR(dent);
2262 	ns_subremove(ns) = dent;
2263 
2264 	  /* use create_dentry so we can supply private data */
2265 	dent = aafs_create("namespaces", S_IFDIR | 0755, dir,
2266 			   &ns->unconfined->label.count,
2267 			   NULL, NULL, &ns_dir_inode_operations);
2268 	if (IS_ERR(dent))
2269 		return PTR_ERR(dent);
2270 	ns_subns_dir(ns) = dent;
2271 
2272 	return 0;
2273 }
2274 
2275 /*
2276  * Requires: @ns->lock held
2277  */
2278 int __aafs_ns_mkdir(struct aa_ns *ns, struct dentry *parent, const char *name,
2279 		    struct dentry *dent)
2280 {
2281 	struct aa_ns *sub;
2282 	struct aa_profile *child;
2283 	struct dentry *dir;
2284 	int error;
2285 
2286 	AA_BUG(!ns);
2287 	AA_BUG(!parent);
2288 	AA_BUG(!mutex_is_locked(&ns->lock));
2289 
2290 	if (!name)
2291 		name = ns->base.name;
2292 
2293 	if (!dent) {
2294 		/* create ns dir if it doesn't already exist */
2295 		dent = aafs_create_dir(name, parent);
2296 		if (IS_ERR(dent))
2297 			goto fail;
2298 	} else
2299 		dget(dent);
2300 	ns_dir(ns) = dir = dent;
2301 	error = __aafs_ns_mkdir_entries(ns, dir);
2302 	if (error)
2303 		goto fail2;
2304 
2305 	/* profiles */
2306 	list_for_each_entry(child, &ns->base.profiles, base.list) {
2307 		error = __aafs_profile_mkdir(child, ns_subprofs_dir(ns));
2308 		if (error)
2309 			goto fail2;
2310 	}
2311 
2312 	/* subnamespaces */
2313 	list_for_each_entry(sub, &ns->sub_ns, base.list) {
2314 		mutex_lock_nested(&sub->lock, sub->level);
2315 		error = __aafs_ns_mkdir(sub, ns_subns_dir(ns), NULL, NULL);
2316 		mutex_unlock(&sub->lock);
2317 		if (error)
2318 			goto fail2;
2319 	}
2320 
2321 	return 0;
2322 
2323 fail:
2324 	error = PTR_ERR(dent);
2325 
2326 fail2:
2327 	__aafs_ns_rmdir(ns);
2328 
2329 	return error;
2330 }
2331 
2332 /**
2333  * __next_ns - find the next namespace to list
2334  * @root: root namespace to stop search at (NOT NULL)
2335  * @ns: current ns position (NOT NULL)
2336  *
2337  * Find the next namespace from @ns under @root and handle all locking needed
2338  * while switching current namespace.
2339  *
2340  * Returns: next namespace or NULL if at last namespace under @root
2341  * Requires: ns->parent->lock to be held
2342  * NOTE: will not unlock root->lock
2343  */
2344 static struct aa_ns *__next_ns(struct aa_ns *root, struct aa_ns *ns)
2345 {
2346 	struct aa_ns *parent, *next;
2347 
2348 	AA_BUG(!root);
2349 	AA_BUG(!ns);
2350 	AA_BUG(ns != root && !mutex_is_locked(&ns->parent->lock));
2351 
2352 	/* is next namespace a child */
2353 	if (!list_empty(&ns->sub_ns)) {
2354 		next = list_first_entry(&ns->sub_ns, typeof(*ns), base.list);
2355 		mutex_lock_nested(&next->lock, next->level);
2356 		return next;
2357 	}
2358 
2359 	/* check if the next ns is a sibling, parent, gp, .. */
2360 	parent = ns->parent;
2361 	while (ns != root) {
2362 		mutex_unlock(&ns->lock);
2363 		next = list_next_entry(ns, base.list);
2364 		if (!list_entry_is_head(next, &parent->sub_ns, base.list)) {
2365 			mutex_lock_nested(&next->lock, next->level);
2366 			return next;
2367 		}
2368 		ns = parent;
2369 		parent = parent->parent;
2370 	}
2371 
2372 	return NULL;
2373 }
2374 
2375 /**
2376  * __first_profile - find the first profile in a namespace
2377  * @root: namespace that is root of profiles being displayed (NOT NULL)
2378  * @ns: namespace to start in   (NOT NULL)
2379  *
2380  * Returns: unrefcounted profile or NULL if no profile
2381  * Requires: profile->ns.lock to be held
2382  */
2383 static struct aa_profile *__first_profile(struct aa_ns *root,
2384 					  struct aa_ns *ns)
2385 {
2386 	AA_BUG(!root);
2387 	AA_BUG(ns && !mutex_is_locked(&ns->lock));
2388 
2389 	for (; ns; ns = __next_ns(root, ns)) {
2390 		if (!list_empty(&ns->base.profiles))
2391 			return list_first_entry(&ns->base.profiles,
2392 						struct aa_profile, base.list);
2393 	}
2394 	return NULL;
2395 }
2396 
2397 /**
2398  * __next_profile - step to the next profile in a profile tree
2399  * @p: current profile in tree (NOT NULL)
2400  *
2401  * Perform a depth first traversal on the profile tree in a namespace
2402  *
2403  * Returns: next profile or NULL if done
2404  * Requires: profile->ns.lock to be held
2405  */
2406 static struct aa_profile *__next_profile(struct aa_profile *p)
2407 {
2408 	struct aa_profile *parent;
2409 	struct aa_ns *ns = p->ns;
2410 
2411 	AA_BUG(!mutex_is_locked(&profiles_ns(p)->lock));
2412 
2413 	/* is next profile a child */
2414 	if (!list_empty(&p->base.profiles))
2415 		return list_first_entry(&p->base.profiles, typeof(*p),
2416 					base.list);
2417 
2418 	/* is next profile a sibling, parent sibling, gp, sibling, .. */
2419 	parent = rcu_dereference_protected(p->parent,
2420 					   mutex_is_locked(&p->ns->lock));
2421 	while (parent) {
2422 		p = list_next_entry(p, base.list);
2423 		if (!list_entry_is_head(p, &parent->base.profiles, base.list))
2424 			return p;
2425 		p = parent;
2426 		parent = rcu_dereference_protected(parent->parent,
2427 					    mutex_is_locked(&parent->ns->lock));
2428 	}
2429 
2430 	/* is next another profile in the namespace */
2431 	p = list_next_entry(p, base.list);
2432 	if (!list_entry_is_head(p, &ns->base.profiles, base.list))
2433 		return p;
2434 
2435 	return NULL;
2436 }
2437 
2438 /**
2439  * next_profile - step to the next profile in where ever it may be
2440  * @root: root namespace  (NOT NULL)
2441  * @profile: current profile  (NOT NULL)
2442  *
2443  * Returns: next profile or NULL if there isn't one
2444  */
2445 static struct aa_profile *next_profile(struct aa_ns *root,
2446 				       struct aa_profile *profile)
2447 {
2448 	struct aa_profile *next = __next_profile(profile);
2449 	if (next)
2450 		return next;
2451 
2452 	/* finished all profiles in namespace move to next namespace */
2453 	return __first_profile(root, __next_ns(root, profile->ns));
2454 }
2455 
2456 /**
2457  * p_start - start a depth first traversal of profile tree
2458  * @f: seq_file to fill
2459  * @pos: current position
2460  *
2461  * Returns: first profile under current namespace or NULL if none found
2462  *
2463  * acquires first ns->lock
2464  */
2465 static void *p_start(struct seq_file *f, loff_t *pos)
2466 {
2467 	struct aa_profile *profile = NULL;
2468 	struct aa_ns *root = aa_get_current_ns();
2469 	loff_t l = *pos;
2470 	f->private = root;
2471 
2472 	/* find the first profile */
2473 	mutex_lock_nested(&root->lock, root->level);
2474 	profile = __first_profile(root, root);
2475 
2476 	/* skip to position */
2477 	for (; profile && l > 0; l--)
2478 		profile = next_profile(root, profile);
2479 
2480 	return profile;
2481 }
2482 
2483 /**
2484  * p_next - read the next profile entry
2485  * @f: seq_file to fill
2486  * @p: profile previously returned
2487  * @pos: current position
2488  *
2489  * Returns: next profile after @p or NULL if none
2490  *
2491  * may acquire/release locks in namespace tree as necessary
2492  */
2493 static void *p_next(struct seq_file *f, void *p, loff_t *pos)
2494 {
2495 	struct aa_profile *profile = p;
2496 	struct aa_ns *ns = f->private;
2497 	(*pos)++;
2498 
2499 	return next_profile(ns, profile);
2500 }
2501 
2502 /**
2503  * p_stop - stop depth first traversal
2504  * @f: seq_file we are filling
2505  * @p: the last profile written
2506  *
2507  * Release all locking done by p_start/p_next on namespace tree
2508  */
2509 static void p_stop(struct seq_file *f, void *p)
2510 {
2511 	struct aa_profile *profile = p;
2512 	struct aa_ns *root = f->private, *ns;
2513 
2514 	if (profile) {
2515 		for (ns = profile->ns; ns && ns != root; ns = ns->parent)
2516 			mutex_unlock(&ns->lock);
2517 	}
2518 	mutex_unlock(&root->lock);
2519 	aa_put_ns(root);
2520 }
2521 
2522 /**
2523  * seq_show_profile - show a profile entry
2524  * @f: seq_file to file
2525  * @p: current position (profile)    (NOT NULL)
2526  *
2527  * Returns: error on failure
2528  */
2529 static int seq_show_profile(struct seq_file *f, void *p)
2530 {
2531 	struct aa_profile *profile = (struct aa_profile *)p;
2532 	struct aa_ns *root = f->private;
2533 
2534 	aa_label_seq_xprint(f, root, &profile->label,
2535 			    FLAG_SHOW_MODE | FLAG_VIEW_SUBNS, GFP_KERNEL);
2536 	seq_putc(f, '\n');
2537 
2538 	return 0;
2539 }
2540 
2541 static const struct seq_operations aa_sfs_profiles_op = {
2542 	.start = p_start,
2543 	.next = p_next,
2544 	.stop = p_stop,
2545 	.show = seq_show_profile,
2546 };
2547 
2548 static int profiles_open(struct inode *inode, struct file *file)
2549 {
2550 	if (!aa_current_policy_view_capable(NULL))
2551 		return -EACCES;
2552 
2553 	return seq_open(file, &aa_sfs_profiles_op);
2554 }
2555 
2556 static int profiles_release(struct inode *inode, struct file *file)
2557 {
2558 	return seq_release(inode, file);
2559 }
2560 
2561 static const struct file_operations aa_sfs_profiles_fops = {
2562 	.open = profiles_open,
2563 	.read = seq_read,
2564 	.llseek = seq_lseek,
2565 	.release = profiles_release,
2566 };
2567 
2568 
2569 /** Base file system setup **/
2570 static struct aa_sfs_entry aa_sfs_entry_file[] = {
2571 	AA_SFS_FILE_STRING("mask",
2572 			   "create read write exec append mmap_exec link lock"),
2573 	{ }
2574 };
2575 
2576 static struct aa_sfs_entry aa_sfs_entry_ptrace[] = {
2577 	AA_SFS_FILE_STRING("mask", "read trace"),
2578 	{ }
2579 };
2580 
2581 static struct aa_sfs_entry aa_sfs_entry_signal[] = {
2582 	AA_SFS_FILE_STRING("mask", AA_SFS_SIG_MASK),
2583 	{ }
2584 };
2585 
2586 static struct aa_sfs_entry aa_sfs_entry_attach[] = {
2587 	AA_SFS_FILE_BOOLEAN("xattr", 1),
2588 	{ }
2589 };
2590 static struct aa_sfs_entry aa_sfs_entry_domain[] = {
2591 	AA_SFS_FILE_BOOLEAN("change_hat",	1),
2592 	AA_SFS_FILE_BOOLEAN("change_hatv",	1),
2593 	AA_SFS_FILE_BOOLEAN("unconfined_allowed_children",	1),
2594 	AA_SFS_FILE_BOOLEAN("change_onexec",	1),
2595 	AA_SFS_FILE_BOOLEAN("change_profile",	1),
2596 	AA_SFS_FILE_BOOLEAN("stack",		1),
2597 	AA_SFS_FILE_BOOLEAN("fix_binfmt_elf_mmap",	1),
2598 	AA_SFS_FILE_BOOLEAN("post_nnp_subset",	1),
2599 	AA_SFS_FILE_BOOLEAN("computed_longest_left",	1),
2600 	AA_SFS_DIR("attach_conditions",		aa_sfs_entry_attach),
2601 	AA_SFS_FILE_BOOLEAN("disconnected.path",            1),
2602 	AA_SFS_FILE_BOOLEAN("kill.signal",		1),
2603 	AA_SFS_FILE_STRING("version", "1.2"),
2604 	{ }
2605 };
2606 
2607 static struct aa_sfs_entry aa_sfs_entry_unconfined[] = {
2608 	AA_SFS_FILE_BOOLEAN("change_profile", 1),
2609 	{ }
2610 };
2611 
2612 static struct aa_sfs_entry aa_sfs_entry_versions[] = {
2613 	AA_SFS_FILE_BOOLEAN("v5",	1),
2614 	AA_SFS_FILE_BOOLEAN("v6",	1),
2615 	AA_SFS_FILE_BOOLEAN("v7",	1),
2616 	AA_SFS_FILE_BOOLEAN("v8",	1),
2617 	AA_SFS_FILE_BOOLEAN("v9",	1),
2618 	{ }
2619 };
2620 
2621 #define PERMS32STR "allow deny subtree cond kill complain prompt audit quiet hide xindex tag label"
2622 static struct aa_sfs_entry aa_sfs_entry_policy[] = {
2623 	AA_SFS_DIR("versions",			aa_sfs_entry_versions),
2624 	AA_SFS_FILE_BOOLEAN("set_load",		1),
2625 	AA_SFS_FILE_BOOLEAN("diff-encode",		1),
2626 	/* number of out of band transitions supported */
2627 	AA_SFS_FILE_U64("outofband",		MAX_OOB_SUPPORTED),
2628 	AA_SFS_FILE_U64("permstable32_version",	3),
2629 	AA_SFS_FILE_STRING("permstable32", PERMS32STR),
2630 	AA_SFS_FILE_U64("state32",	1),
2631 	AA_SFS_DIR("unconfined_restrictions",   aa_sfs_entry_unconfined),
2632 #ifdef CONFIG_SECURITY_APPARMOR_COMPRESSED_POLICY
2633 	AA_SFS_FILE_BOOLEAN("compressed_load",	1),
2634 	AA_SFS_FILE_BOOLEAN("extended_policy_header",	1),
2635 #endif
2636 	{ }
2637 };
2638 
2639 static struct aa_sfs_entry aa_sfs_entry_mount[] = {
2640 	AA_SFS_FILE_STRING("mask", "mount umount pivot_root"),
2641 	AA_SFS_FILE_STRING("move_mount", "detached"),
2642 	{ }
2643 };
2644 
2645 static struct aa_sfs_entry aa_sfs_entry_ns[] = {
2646 	AA_SFS_FILE_BOOLEAN("profile",		1),
2647 	AA_SFS_FILE_BOOLEAN("pivot_root",	0),
2648 	AA_SFS_FILE_STRING("mask", "userns_create"),
2649 	{ }
2650 };
2651 
2652 static struct aa_sfs_entry aa_sfs_entry_dbus[] = {
2653 	AA_SFS_FILE_STRING("mask", "acquire send receive"),
2654 	{ }
2655 };
2656 
2657 static struct aa_sfs_entry aa_sfs_entry_query_label[] = {
2658 	AA_SFS_FILE_STRING("perms", "allow deny audit quiet"),
2659 	AA_SFS_FILE_BOOLEAN("data",		1),
2660 	AA_SFS_FILE_BOOLEAN("multi_transaction",	1),
2661 	{ }
2662 };
2663 
2664 static struct aa_sfs_entry aa_sfs_entry_query[] = {
2665 	AA_SFS_DIR("label",			aa_sfs_entry_query_label),
2666 	{ }
2667 };
2668 
2669 static struct aa_sfs_entry aa_sfs_entry_io_uring[] = {
2670 	AA_SFS_FILE_STRING("mask", "sqpoll override_creds"),
2671 	{ }
2672 };
2673 
2674 static struct aa_sfs_entry aa_sfs_entry_features[] = {
2675 	AA_SFS_DIR("policy",			aa_sfs_entry_policy),
2676 	AA_SFS_DIR("domain",			aa_sfs_entry_domain),
2677 	AA_SFS_DIR("file",			aa_sfs_entry_file),
2678 	AA_SFS_DIR("network_v8",		aa_sfs_entry_network),
2679 	AA_SFS_DIR("network_v9",		aa_sfs_entry_networkv9),
2680 	AA_SFS_DIR("mount",			aa_sfs_entry_mount),
2681 	AA_SFS_DIR("namespaces",		aa_sfs_entry_ns),
2682 	AA_SFS_FILE_U64("capability",		VFS_CAP_FLAGS_MASK),
2683 	AA_SFS_DIR("rlimit",			aa_sfs_entry_rlimit),
2684 	AA_SFS_DIR("caps",			aa_sfs_entry_caps),
2685 	AA_SFS_DIR("ptrace",			aa_sfs_entry_ptrace),
2686 	AA_SFS_DIR("signal",			aa_sfs_entry_signal),
2687 	AA_SFS_DIR("dbus",			aa_sfs_entry_dbus),
2688 	AA_SFS_DIR("query",			aa_sfs_entry_query),
2689 	AA_SFS_DIR("io_uring",			aa_sfs_entry_io_uring),
2690 	{ }
2691 };
2692 
2693 static struct aa_sfs_entry aa_sfs_entry_apparmor[] = {
2694 	AA_SFS_FILE_FOPS(".access", 0666, &aa_sfs_access),
2695 	AA_SFS_FILE_FOPS(".stacked", 0444, &seq_ns_stacked_fops),
2696 	AA_SFS_FILE_FOPS(".ns_stacked", 0444, &seq_ns_nsstacked_fops),
2697 	AA_SFS_FILE_FOPS(".ns_level", 0444, &seq_ns_level_fops),
2698 	AA_SFS_FILE_FOPS(".ns_name", 0444, &seq_ns_name_fops),
2699 	AA_SFS_FILE_FOPS("profiles", 0444, &aa_sfs_profiles_fops),
2700 #ifdef CONFIG_SECURITY_APPARMOR_EXPORT_BINARY
2701 	AA_SFS_FILE_FOPS("raw_data_compression_level_min", 0444, &seq_ns_compress_min_fops),
2702 	AA_SFS_FILE_FOPS("raw_data_compression_level_max", 0444, &seq_ns_compress_max_fops),
2703 #endif
2704 	AA_SFS_DIR("features", aa_sfs_entry_features),
2705 	{ }
2706 };
2707 
2708 static struct aa_sfs_entry aa_sfs_entry =
2709 	AA_SFS_DIR("apparmor", aa_sfs_entry_apparmor);
2710 
2711 /**
2712  * entry_create_file - create a file entry in the apparmor securityfs
2713  * @fs_file: aa_sfs_entry to build an entry for (NOT NULL)
2714  * @parent: the parent dentry in the securityfs
2715  *
2716  * Use entry_remove_file to remove entries created with this fn.
2717  */
2718 static int __init entry_create_file(struct aa_sfs_entry *fs_file,
2719 				    struct dentry *parent)
2720 {
2721 	int error = 0;
2722 
2723 	fs_file->dentry = securityfs_create_file(fs_file->name,
2724 						 S_IFREG | fs_file->mode,
2725 						 parent, fs_file,
2726 						 fs_file->file_ops);
2727 	if (IS_ERR(fs_file->dentry)) {
2728 		error = PTR_ERR(fs_file->dentry);
2729 		fs_file->dentry = NULL;
2730 	}
2731 	return error;
2732 }
2733 
2734 static void __init entry_remove_dir(struct aa_sfs_entry *fs_dir);
2735 /**
2736  * entry_create_dir - recursively create a directory entry in the securityfs
2737  * @fs_dir: aa_sfs_entry (and all child entries) to build (NOT NULL)
2738  * @parent: the parent dentry in the securityfs
2739  *
2740  * Use entry_remove_dir to remove entries created with this fn.
2741  */
2742 static int __init entry_create_dir(struct aa_sfs_entry *fs_dir,
2743 				   struct dentry *parent)
2744 {
2745 	struct aa_sfs_entry *fs_file;
2746 	struct dentry *dir;
2747 	int error;
2748 
2749 	dir = securityfs_create_dir(fs_dir->name, parent);
2750 	if (IS_ERR(dir))
2751 		return PTR_ERR(dir);
2752 	fs_dir->dentry = dir;
2753 
2754 	for (fs_file = fs_dir->v.files; fs_file && fs_file->name; ++fs_file) {
2755 		if (fs_file->v_type == AA_SFS_TYPE_DIR)
2756 			error = entry_create_dir(fs_file, fs_dir->dentry);
2757 		else
2758 			error = entry_create_file(fs_file, fs_dir->dentry);
2759 		if (error)
2760 			goto failed;
2761 	}
2762 
2763 	return 0;
2764 
2765 failed:
2766 	entry_remove_dir(fs_dir);
2767 
2768 	return error;
2769 }
2770 
2771 /**
2772  * entry_remove_file - drop a single file entry in the apparmor securityfs
2773  * @fs_file: aa_sfs_entry to detach from the securityfs (NOT NULL)
2774  */
2775 static void __init entry_remove_file(struct aa_sfs_entry *fs_file)
2776 {
2777 	if (!fs_file->dentry)
2778 		return;
2779 
2780 	securityfs_remove(fs_file->dentry);
2781 	fs_file->dentry = NULL;
2782 }
2783 
2784 /**
2785  * entry_remove_dir - recursively drop a directory entry from the securityfs
2786  * @fs_dir: aa_sfs_entry (and all child entries) to detach (NOT NULL)
2787  */
2788 static void __init entry_remove_dir(struct aa_sfs_entry *fs_dir)
2789 {
2790 	struct aa_sfs_entry *fs_file;
2791 
2792 	for (fs_file = fs_dir->v.files; fs_file && fs_file->name; ++fs_file) {
2793 		if (fs_file->v_type == AA_SFS_TYPE_DIR)
2794 			entry_remove_dir(fs_file);
2795 		else
2796 			entry_remove_file(fs_file);
2797 	}
2798 
2799 	entry_remove_file(fs_dir);
2800 }
2801 
2802 /**
2803  * aa_destroy_aafs - cleanup and free aafs
2804  *
2805  * releases dentries allocated by aa_create_aafs
2806  */
2807 void __init aa_destroy_aafs(void)
2808 {
2809 	entry_remove_dir(&aa_sfs_entry);
2810 }
2811 
2812 
2813 #define NULL_FILE_NAME ".null"
2814 struct path aa_null;
2815 
2816 static int aa_mk_null_file(struct dentry *parent)
2817 {
2818 	struct vfsmount *mount = NULL;
2819 	struct dentry *dentry;
2820 	struct inode *inode;
2821 	int count = 0;
2822 	int error = simple_pin_fs(parent->d_sb->s_type, &mount, &count);
2823 
2824 	if (error)
2825 		return error;
2826 
2827 	dentry = simple_start_creating(parent, NULL_FILE_NAME);
2828 	if (IS_ERR(dentry)) {
2829 		error = PTR_ERR(dentry);
2830 		goto out;
2831 	}
2832 	inode = new_inode(parent->d_inode->i_sb);
2833 	if (!inode) {
2834 		error = -ENOMEM;
2835 		goto out;
2836 	}
2837 
2838 	inode->i_ino = get_next_ino();
2839 	inode->i_mode = S_IFCHR | S_IRUGO | S_IWUGO;
2840 	simple_inode_init_ts(inode);
2841 	init_special_inode(inode, S_IFCHR | S_IRUGO | S_IWUGO,
2842 			   MKDEV(MEM_MAJOR, 3));
2843 	d_instantiate(dentry, inode);
2844 	aa_null.dentry = dget(dentry);
2845 	aa_null.mnt = mntget(mount);
2846 
2847 out:
2848 	simple_done_creating(dentry);
2849 	simple_release_fs(&mount, &count);
2850 	return error;
2851 }
2852 
2853 static const char *policy_get_link(struct dentry *dentry,
2854 				   struct inode *inode,
2855 				   struct delayed_call *done)
2856 {
2857 	struct aa_ns *ns;
2858 	struct path path;
2859 	int error;
2860 
2861 	if (!dentry)
2862 		return ERR_PTR(-ECHILD);
2863 
2864 	ns = aa_get_current_ns();
2865 	path.mnt = mntget(aafs_mnt);
2866 	path.dentry = dget(ns_dir(ns));
2867 	error = nd_jump_link(&path);
2868 	aa_put_ns(ns);
2869 
2870 	return ERR_PTR(error);
2871 }
2872 
2873 static int policy_readlink(struct dentry *dentry, char __user *buffer,
2874 			   int buflen)
2875 {
2876 	char name[32];
2877 	int res;
2878 
2879 	res = snprintf(name, sizeof(name), "%s:[%llu]", AAFS_NAME,
2880 		       d_inode(dentry)->i_ino);
2881 	if (res > 0 && res < sizeof(name))
2882 		res = readlink_copy(buffer, buflen, name, strlen(name));
2883 	else
2884 		res = -ENOENT;
2885 
2886 	return res;
2887 }
2888 
2889 static const struct inode_operations policy_link_iops = {
2890 	.readlink	= policy_readlink,
2891 	.get_link	= policy_get_link,
2892 };
2893 
2894 
2895 /**
2896  * aa_create_aafs - create the apparmor security filesystem
2897  *
2898  * dentries created here are released by aa_destroy_aafs
2899  *
2900  * Returns: error on failure
2901  */
2902 int __init aa_create_aafs(void)
2903 {
2904 	struct dentry *dent;
2905 	int error;
2906 
2907 	if (!apparmor_initialized)
2908 		return 0;
2909 
2910 	if (aa_sfs_entry.dentry) {
2911 		AA_ERROR("%s: AppArmor securityfs already exists\n", __func__);
2912 		return -EEXIST;
2913 	}
2914 
2915 	/* setup apparmorfs used to virtualize policy/ */
2916 	aafs_mnt = kern_mount(&aafs_ops);
2917 	if (IS_ERR(aafs_mnt))
2918 		panic("can't set apparmorfs up\n");
2919 	aafs_mnt->mnt_sb->s_flags &= ~SB_NOUSER;
2920 
2921 	/* Populate fs tree. */
2922 	error = entry_create_dir(&aa_sfs_entry, NULL);
2923 	if (error)
2924 		goto error;
2925 
2926 	dent = securityfs_create_file(".load", 0666, aa_sfs_entry.dentry,
2927 				      NULL, &aa_fs_profile_load);
2928 	if (IS_ERR(dent))
2929 		goto dent_error;
2930 	ns_subload(root_ns) = dent;
2931 
2932 	dent = securityfs_create_file(".replace", 0666, aa_sfs_entry.dentry,
2933 				      NULL, &aa_fs_profile_replace);
2934 	if (IS_ERR(dent))
2935 		goto dent_error;
2936 	ns_subreplace(root_ns) = dent;
2937 
2938 	dent = securityfs_create_file(".remove", 0666, aa_sfs_entry.dentry,
2939 				      NULL, &aa_fs_profile_remove);
2940 	if (IS_ERR(dent))
2941 		goto dent_error;
2942 	ns_subremove(root_ns) = dent;
2943 
2944 	dent = securityfs_create_file("revision", 0444, aa_sfs_entry.dentry,
2945 				      NULL, &aa_fs_ns_revision_fops);
2946 	if (IS_ERR(dent))
2947 		goto dent_error;
2948 	ns_subrevision(root_ns) = dent;
2949 
2950 	/* policy tree referenced by magic policy symlink */
2951 	mutex_lock_nested(&root_ns->lock, root_ns->level);
2952 	error = __aafs_ns_mkdir(root_ns, aafs_mnt->mnt_root, ".policy",
2953 				aafs_mnt->mnt_root);
2954 	mutex_unlock(&root_ns->lock);
2955 	if (error)
2956 		goto error;
2957 
2958 	/* magic symlink similar to nsfs redirects based on task policy */
2959 	dent = securityfs_create_symlink("policy", aa_sfs_entry.dentry,
2960 					 NULL, &policy_link_iops);
2961 	if (IS_ERR(dent))
2962 		goto dent_error;
2963 
2964 	error = aa_mk_null_file(aa_sfs_entry.dentry);
2965 	if (error)
2966 		goto error;
2967 
2968 	/* TODO: add default profile to apparmorfs */
2969 
2970 	/* Report that AppArmor fs is enabled */
2971 	aa_info_message("AppArmor Filesystem Enabled");
2972 	return 0;
2973 
2974 dent_error:
2975 	error = PTR_ERR(dent);
2976 error:
2977 	aa_destroy_aafs();
2978 	AA_ERROR("Error creating AppArmor securityfs\n");
2979 	return error;
2980 }
2981