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