xref: /linux/security/apparmor/apparmorfs.c (revision c97204baf840bf850e14ef4f5f43251239ca43b6)
1 /*
2  * AppArmor security module
3  *
4  * This file contains AppArmor /sys/kernel/security/apparmor interface functions
5  *
6  * Copyright (C) 1998-2008 Novell/SUSE
7  * Copyright 2009-2010 Canonical Ltd.
8  *
9  * This program is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU General Public License as
11  * published by the Free Software Foundation, version 2 of the
12  * License.
13  */
14 
15 #include <linux/ctype.h>
16 #include <linux/security.h>
17 #include <linux/vmalloc.h>
18 #include <linux/module.h>
19 #include <linux/seq_file.h>
20 #include <linux/uaccess.h>
21 #include <linux/mount.h>
22 #include <linux/namei.h>
23 #include <linux/capability.h>
24 #include <linux/rcupdate.h>
25 #include <linux/fs.h>
26 #include <uapi/linux/major.h>
27 #include <uapi/linux/magic.h>
28 
29 #include "include/apparmor.h"
30 #include "include/apparmorfs.h"
31 #include "include/audit.h"
32 #include "include/context.h"
33 #include "include/crypto.h"
34 #include "include/policy.h"
35 #include "include/policy_ns.h"
36 #include "include/resource.h"
37 #include "include/policy_unpack.h"
38 
39 /*
40  * The apparmor filesystem interface used for policy load and introspection
41  * The interface is split into two main components based on their function
42  * a securityfs component:
43  *   used for static files that are always available, and which allows
44  *   userspace to specificy the location of the security filesystem.
45  *
46  *   fns and data are prefixed with
47  *      aa_sfs_
48  *
49  * an apparmorfs component:
50  *   used loaded policy content and introspection. It is not part of  a
51  *   regular mounted filesystem and is available only through the magic
52  *   policy symlink in the root of the securityfs apparmor/ directory.
53  *   Tasks queries will be magically redirected to the correct portion
54  *   of the policy tree based on their confinement.
55  *
56  *   fns and data are prefixed with
57  *      aafs_
58  *
59  * The aa_fs_ prefix is used to indicate the fn is used by both the
60  * securityfs and apparmorfs filesystems.
61  */
62 
63 
64 /*
65  * support fns
66  */
67 
68 /**
69  * aa_mangle_name - mangle a profile name to std profile layout form
70  * @name: profile name to mangle  (NOT NULL)
71  * @target: buffer to store mangled name, same length as @name (MAYBE NULL)
72  *
73  * Returns: length of mangled name
74  */
75 static int mangle_name(const char *name, char *target)
76 {
77 	char *t = target;
78 
79 	while (*name == '/' || *name == '.')
80 		name++;
81 
82 	if (target) {
83 		for (; *name; name++) {
84 			if (*name == '/')
85 				*(t)++ = '.';
86 			else if (isspace(*name))
87 				*(t)++ = '_';
88 			else if (isalnum(*name) || strchr("._-", *name))
89 				*(t)++ = *name;
90 		}
91 
92 		*t = 0;
93 	} else {
94 		int len = 0;
95 		for (; *name; name++) {
96 			if (isalnum(*name) || isspace(*name) ||
97 			    strchr("/._-", *name))
98 				len++;
99 		}
100 
101 		return len;
102 	}
103 
104 	return t - target;
105 }
106 
107 
108 /*
109  * aafs - core fns and data for the policy tree
110  */
111 
112 #define AAFS_NAME		"apparmorfs"
113 static struct vfsmount *aafs_mnt;
114 static int aafs_count;
115 
116 
117 static int aafs_show_path(struct seq_file *seq, struct dentry *dentry)
118 {
119 	struct inode *inode = d_inode(dentry);
120 
121 	seq_printf(seq, "%s:[%lu]", AAFS_NAME, inode->i_ino);
122 	return 0;
123 }
124 
125 static void aafs_evict_inode(struct inode *inode)
126 {
127 	truncate_inode_pages_final(&inode->i_data);
128 	clear_inode(inode);
129 	if (S_ISLNK(inode->i_mode))
130 		kfree(inode->i_link);
131 }
132 
133 static const struct super_operations aafs_super_ops = {
134 	.statfs = simple_statfs,
135 	.evict_inode = aafs_evict_inode,
136 	.show_path = aafs_show_path,
137 };
138 
139 static int fill_super(struct super_block *sb, void *data, int silent)
140 {
141 	static struct tree_descr files[] = { {""} };
142 	int error;
143 
144 	error = simple_fill_super(sb, AAFS_MAGIC, files);
145 	if (error)
146 		return error;
147 	sb->s_op = &aafs_super_ops;
148 
149 	return 0;
150 }
151 
152 static struct dentry *aafs_mount(struct file_system_type *fs_type,
153 				 int flags, const char *dev_name, void *data)
154 {
155 	return mount_single(fs_type, flags, data, fill_super);
156 }
157 
158 static struct file_system_type aafs_ops = {
159 	.owner = THIS_MODULE,
160 	.name = AAFS_NAME,
161 	.mount = aafs_mount,
162 	.kill_sb = kill_anon_super,
163 };
164 
165 /**
166  * __aafs_setup_d_inode - basic inode setup for apparmorfs
167  * @dir: parent directory for the dentry
168  * @dentry: dentry we are seting the inode up for
169  * @mode: permissions the file should have
170  * @data: data to store on inode.i_private, available in open()
171  * @link: if symlink, symlink target string
172  * @fops: struct file_operations that should be used
173  * @iops: struct of inode_operations that should be used
174  */
175 static int __aafs_setup_d_inode(struct inode *dir, struct dentry *dentry,
176 			       umode_t mode, void *data, char *link,
177 			       const struct file_operations *fops,
178 			       const struct inode_operations *iops)
179 {
180 	struct inode *inode = new_inode(dir->i_sb);
181 
182 	AA_BUG(!dir);
183 	AA_BUG(!dentry);
184 
185 	if (!inode)
186 		return -ENOMEM;
187 
188 	inode->i_ino = get_next_ino();
189 	inode->i_mode = mode;
190 	inode->i_atime = inode->i_mtime = inode->i_ctime = current_time(inode);
191 	inode->i_private = data;
192 	if (S_ISDIR(mode)) {
193 		inode->i_op = iops ? iops : &simple_dir_inode_operations;
194 		inode->i_fop = &simple_dir_operations;
195 		inc_nlink(inode);
196 		inc_nlink(dir);
197 	} else if (S_ISLNK(mode)) {
198 		inode->i_op = iops ? iops : &simple_symlink_inode_operations;
199 		inode->i_link = link;
200 	} else {
201 		inode->i_fop = fops;
202 	}
203 	d_instantiate(dentry, inode);
204 	dget(dentry);
205 
206 	return 0;
207 }
208 
209 /**
210  * aafs_create - create a dentry in the apparmorfs filesystem
211  *
212  * @name: name of dentry to create
213  * @mode: permissions the file should have
214  * @parent: parent directory for this dentry
215  * @data: data to store on inode.i_private, available in open()
216  * @link: if symlink, symlink target string
217  * @fops: struct file_operations that should be used for
218  * @iops: struct of inode_operations that should be used
219  *
220  * This is the basic "create a xxx" function for apparmorfs.
221  *
222  * Returns a pointer to a dentry if it succeeds, that must be free with
223  * aafs_remove(). Will return ERR_PTR on failure.
224  */
225 static struct dentry *aafs_create(const char *name, umode_t mode,
226 				  struct dentry *parent, void *data, void *link,
227 				  const struct file_operations *fops,
228 				  const struct inode_operations *iops)
229 {
230 	struct dentry *dentry;
231 	struct inode *dir;
232 	int error;
233 
234 	AA_BUG(!name);
235 	AA_BUG(!parent);
236 
237 	if (!(mode & S_IFMT))
238 		mode = (mode & S_IALLUGO) | S_IFREG;
239 
240 	error = simple_pin_fs(&aafs_ops, &aafs_mnt, &aafs_count);
241 	if (error)
242 		return ERR_PTR(error);
243 
244 	dir = d_inode(parent);
245 
246 	inode_lock(dir);
247 	dentry = lookup_one_len(name, parent, strlen(name));
248 	if (IS_ERR(dentry))
249 		goto fail_lock;
250 
251 	if (d_really_is_positive(dentry)) {
252 		error = -EEXIST;
253 		goto fail_dentry;
254 	}
255 
256 	error = __aafs_setup_d_inode(dir, dentry, mode, data, link, fops, iops);
257 	if (error)
258 		goto fail_dentry;
259 	inode_unlock(dir);
260 
261 	return dentry;
262 
263 fail_dentry:
264 	dput(dentry);
265 
266 fail_lock:
267 	inode_unlock(dir);
268 	simple_release_fs(&aafs_mnt, &aafs_count);
269 
270 	return ERR_PTR(error);
271 }
272 
273 /**
274  * aafs_create_file - create a file in the apparmorfs filesystem
275  *
276  * @name: name of dentry to create
277  * @mode: permissions the file should have
278  * @parent: parent directory for this dentry
279  * @data: data to store on inode.i_private, available in open()
280  * @fops: struct file_operations that should be used for
281  *
282  * see aafs_create
283  */
284 static struct dentry *aafs_create_file(const char *name, umode_t mode,
285 				       struct dentry *parent, void *data,
286 				       const struct file_operations *fops)
287 {
288 	return aafs_create(name, mode, parent, data, NULL, fops, NULL);
289 }
290 
291 /**
292  * aafs_create_dir - create a directory in the apparmorfs filesystem
293  *
294  * @name: name of dentry to create
295  * @parent: parent directory for this dentry
296  *
297  * see aafs_create
298  */
299 static struct dentry *aafs_create_dir(const char *name, struct dentry *parent)
300 {
301 	return aafs_create(name, S_IFDIR | 0755, parent, NULL, NULL, NULL,
302 			   NULL);
303 }
304 
305 /**
306  * aafs_create_symlink - create a symlink in the apparmorfs filesystem
307  * @name: name of dentry to create
308  * @parent: parent directory for this dentry
309  * @target: if symlink, symlink target string
310  * @iops: struct of inode_operations that should be used
311  *
312  * If @target parameter is %NULL, then the @iops parameter needs to be
313  * setup to handle .readlink and .get_link inode_operations.
314  */
315 static struct dentry *aafs_create_symlink(const char *name,
316 					  struct dentry *parent,
317 					  const char *target,
318 					  const struct inode_operations *iops)
319 {
320 	struct dentry *dent;
321 	char *link = NULL;
322 
323 	if (target) {
324 		link = kstrdup(target, GFP_KERNEL);
325 		if (!link)
326 			return ERR_PTR(-ENOMEM);
327 	}
328 	dent = aafs_create(name, S_IFLNK | 0444, parent, NULL, link, NULL,
329 			   iops);
330 	if (IS_ERR(dent))
331 		kfree(link);
332 
333 	return dent;
334 }
335 
336 /**
337  * aafs_remove - removes a file or directory from the apparmorfs filesystem
338  *
339  * @dentry: dentry of the file/directory/symlink to removed.
340  */
341 static void aafs_remove(struct dentry *dentry)
342 {
343 	struct inode *dir;
344 
345 	if (!dentry || IS_ERR(dentry))
346 		return;
347 
348 	dir = d_inode(dentry->d_parent);
349 	inode_lock(dir);
350 	if (simple_positive(dentry)) {
351 		if (d_is_dir(dentry))
352 			simple_rmdir(dir, dentry);
353 		else
354 			simple_unlink(dir, dentry);
355 		dput(dentry);
356 	}
357 	inode_unlock(dir);
358 	simple_release_fs(&aafs_mnt, &aafs_count);
359 }
360 
361 
362 /*
363  * aa_fs - policy load/replace/remove
364  */
365 
366 /**
367  * aa_simple_write_to_buffer - common routine for getting policy from user
368  * @userbuf: user buffer to copy data from  (NOT NULL)
369  * @alloc_size: size of user buffer (REQUIRES: @alloc_size >= @copy_size)
370  * @copy_size: size of data to copy from user buffer
371  * @pos: position write is at in the file (NOT NULL)
372  *
373  * Returns: kernel buffer containing copy of user buffer data or an
374  *          ERR_PTR on failure.
375  */
376 static struct aa_loaddata *aa_simple_write_to_buffer(const char __user *userbuf,
377 						     size_t alloc_size,
378 						     size_t copy_size,
379 						     loff_t *pos)
380 {
381 	struct aa_loaddata *data;
382 
383 	AA_BUG(copy_size > alloc_size);
384 
385 	if (*pos != 0)
386 		/* only writes from pos 0, that is complete writes */
387 		return ERR_PTR(-ESPIPE);
388 
389 	/* freed by caller to simple_write_to_buffer */
390 	data = aa_loaddata_alloc(alloc_size);
391 	if (IS_ERR(data))
392 		return data;
393 
394 	data->size = copy_size;
395 	if (copy_from_user(data->data, userbuf, copy_size)) {
396 		kvfree(data);
397 		return ERR_PTR(-EFAULT);
398 	}
399 
400 	return data;
401 }
402 
403 static ssize_t policy_update(int binop, const char __user *buf, size_t size,
404 			     loff_t *pos, struct aa_ns *ns)
405 {
406 	ssize_t error;
407 	struct aa_loaddata *data;
408 	struct aa_profile *profile = aa_current_profile();
409 	const char *op = binop == PROF_ADD ? OP_PROF_LOAD : OP_PROF_REPL;
410 	/* high level check about policy management - fine grained in
411 	 * below after unpack
412 	 */
413 	error = aa_may_manage_policy(profile, ns, op);
414 	if (error)
415 		return error;
416 
417 	data = aa_simple_write_to_buffer(buf, size, size, pos);
418 	error = PTR_ERR(data);
419 	if (!IS_ERR(data)) {
420 		error = aa_replace_profiles(ns ? ns : profile->ns, profile,
421 					    binop, data);
422 		aa_put_loaddata(data);
423 	}
424 
425 	return error;
426 }
427 
428 /* .load file hook fn to load policy */
429 static ssize_t profile_load(struct file *f, const char __user *buf, size_t size,
430 			    loff_t *pos)
431 {
432 	struct aa_ns *ns = aa_get_ns(f->f_inode->i_private);
433 	int error = policy_update(PROF_ADD, buf, size, pos, ns);
434 
435 	aa_put_ns(ns);
436 
437 	return error;
438 }
439 
440 static const struct file_operations aa_fs_profile_load = {
441 	.write = profile_load,
442 	.llseek = default_llseek,
443 };
444 
445 /* .replace file hook fn to load and/or replace policy */
446 static ssize_t profile_replace(struct file *f, const char __user *buf,
447 			       size_t size, loff_t *pos)
448 {
449 	struct aa_ns *ns = aa_get_ns(f->f_inode->i_private);
450 	int error = policy_update(PROF_REPLACE, buf, size, pos, ns);
451 
452 	aa_put_ns(ns);
453 
454 	return error;
455 }
456 
457 static const struct file_operations aa_fs_profile_replace = {
458 	.write = profile_replace,
459 	.llseek = default_llseek,
460 };
461 
462 /* .remove file hook fn to remove loaded policy */
463 static ssize_t profile_remove(struct file *f, const char __user *buf,
464 			      size_t size, loff_t *pos)
465 {
466 	struct aa_loaddata *data;
467 	struct aa_profile *profile;
468 	ssize_t error;
469 	struct aa_ns *ns = aa_get_ns(f->f_inode->i_private);
470 
471 	profile = aa_current_profile();
472 	/* high level check about policy management - fine grained in
473 	 * below after unpack
474 	 */
475 	error = aa_may_manage_policy(profile, ns, OP_PROF_RM);
476 	if (error)
477 		goto out;
478 
479 	/*
480 	 * aa_remove_profile needs a null terminated string so 1 extra
481 	 * byte is allocated and the copied data is null terminated.
482 	 */
483 	data = aa_simple_write_to_buffer(buf, size + 1, size, pos);
484 
485 	error = PTR_ERR(data);
486 	if (!IS_ERR(data)) {
487 		data->data[size] = 0;
488 		error = aa_remove_profiles(ns ? ns : profile->ns, profile,
489 					   data->data, size);
490 		aa_put_loaddata(data);
491 	}
492  out:
493 	aa_put_ns(ns);
494 	return error;
495 }
496 
497 static const struct file_operations aa_fs_profile_remove = {
498 	.write = profile_remove,
499 	.llseek = default_llseek,
500 };
501 
502 void __aa_bump_ns_revision(struct aa_ns *ns)
503 {
504 	ns->revision++;
505 }
506 
507 /**
508  * query_data - queries a policy and writes its data to buf
509  * @buf: the resulting data is stored here (NOT NULL)
510  * @buf_len: size of buf
511  * @query: query string used to retrieve data
512  * @query_len: size of query including second NUL byte
513  *
514  * The buffers pointed to by buf and query may overlap. The query buffer is
515  * parsed before buf is written to.
516  *
517  * The query should look like "<LABEL>\0<KEY>\0", where <LABEL> is the name of
518  * the security confinement context and <KEY> is the name of the data to
519  * retrieve. <LABEL> and <KEY> must not be NUL-terminated.
520  *
521  * Don't expect the contents of buf to be preserved on failure.
522  *
523  * Returns: number of characters written to buf or -errno on failure
524  */
525 static ssize_t query_data(char *buf, size_t buf_len,
526 			  char *query, size_t query_len)
527 {
528 	char *out;
529 	const char *key;
530 	struct aa_profile *profile;
531 	struct aa_data *data;
532 	u32 bytes, blocks;
533 	__le32 outle32;
534 
535 	if (!query_len)
536 		return -EINVAL; /* need a query */
537 
538 	key = query + strnlen(query, query_len) + 1;
539 	if (key + 1 >= query + query_len)
540 		return -EINVAL; /* not enough space for a non-empty key */
541 	if (key + strnlen(key, query + query_len - key) >= query + query_len)
542 		return -EINVAL; /* must end with NUL */
543 
544 	if (buf_len < sizeof(bytes) + sizeof(blocks))
545 		return -EINVAL; /* not enough space */
546 
547 	profile = aa_current_profile();
548 
549 	/* We are going to leave space for two numbers. The first is the total
550 	 * number of bytes we are writing after the first number. This is so
551 	 * users can read the full output without reallocation.
552 	 *
553 	 * The second number is the number of data blocks we're writing. An
554 	 * application might be confined by multiple policies having data in
555 	 * the same key.
556 	 */
557 	memset(buf, 0, sizeof(bytes) + sizeof(blocks));
558 	out = buf + sizeof(bytes) + sizeof(blocks);
559 
560 	blocks = 0;
561 	if (profile->data) {
562 		data = rhashtable_lookup_fast(profile->data, &key,
563 					      profile->data->p);
564 
565 		if (data) {
566 			if (out + sizeof(outle32) + data->size > buf + buf_len)
567 				return -EINVAL; /* not enough space */
568 			outle32 = __cpu_to_le32(data->size);
569 			memcpy(out, &outle32, sizeof(outle32));
570 			out += sizeof(outle32);
571 			memcpy(out, data->data, data->size);
572 			out += data->size;
573 			blocks++;
574 		}
575 	}
576 
577 	outle32 = __cpu_to_le32(out - buf - sizeof(bytes));
578 	memcpy(buf, &outle32, sizeof(outle32));
579 	outle32 = __cpu_to_le32(blocks);
580 	memcpy(buf + sizeof(bytes), &outle32, sizeof(outle32));
581 
582 	return out - buf;
583 }
584 
585 #define QUERY_CMD_DATA		"data\0"
586 #define QUERY_CMD_DATA_LEN	5
587 
588 /**
589  * aa_write_access - generic permissions and data query
590  * @file: pointer to open apparmorfs/access file
591  * @ubuf: user buffer containing the complete query string (NOT NULL)
592  * @count: size of ubuf
593  * @ppos: position in the file (MUST BE ZERO)
594  *
595  * Allows for one permissions or data query per open(), write(), and read()
596  * sequence. The only queries currently supported are label-based queries for
597  * permissions or data.
598  *
599  * For permissions queries, ubuf must begin with "label\0", followed by the
600  * profile query specific format described in the query_label() function
601  * documentation.
602  *
603  * For data queries, ubuf must have the form "data\0<LABEL>\0<KEY>\0", where
604  * <LABEL> is the name of the security confinement context and <KEY> is the
605  * name of the data to retrieve.
606  *
607  * Returns: number of bytes written or -errno on failure
608  */
609 static ssize_t aa_write_access(struct file *file, const char __user *ubuf,
610 			       size_t count, loff_t *ppos)
611 {
612 	char *buf;
613 	ssize_t len;
614 
615 	if (*ppos)
616 		return -ESPIPE;
617 
618 	buf = simple_transaction_get(file, ubuf, count);
619 	if (IS_ERR(buf))
620 		return PTR_ERR(buf);
621 
622 	if (count > QUERY_CMD_DATA_LEN &&
623 		   !memcmp(buf, QUERY_CMD_DATA, QUERY_CMD_DATA_LEN)) {
624 		len = query_data(buf, SIMPLE_TRANSACTION_LIMIT,
625 				 buf + QUERY_CMD_DATA_LEN,
626 				 count - QUERY_CMD_DATA_LEN);
627 	} else
628 		len = -EINVAL;
629 
630 	if (len < 0)
631 		return len;
632 
633 	simple_transaction_set(file, len);
634 
635 	return count;
636 }
637 
638 static const struct file_operations aa_sfs_access = {
639 	.write		= aa_write_access,
640 	.read		= simple_transaction_read,
641 	.release	= simple_transaction_release,
642 	.llseek		= generic_file_llseek,
643 };
644 
645 static int aa_sfs_seq_show(struct seq_file *seq, void *v)
646 {
647 	struct aa_sfs_entry *fs_file = seq->private;
648 
649 	if (!fs_file)
650 		return 0;
651 
652 	switch (fs_file->v_type) {
653 	case AA_SFS_TYPE_BOOLEAN:
654 		seq_printf(seq, "%s\n", fs_file->v.boolean ? "yes" : "no");
655 		break;
656 	case AA_SFS_TYPE_STRING:
657 		seq_printf(seq, "%s\n", fs_file->v.string);
658 		break;
659 	case AA_SFS_TYPE_U64:
660 		seq_printf(seq, "%#08lx\n", fs_file->v.u64);
661 		break;
662 	default:
663 		/* Ignore unpritable entry types. */
664 		break;
665 	}
666 
667 	return 0;
668 }
669 
670 static int aa_sfs_seq_open(struct inode *inode, struct file *file)
671 {
672 	return single_open(file, aa_sfs_seq_show, inode->i_private);
673 }
674 
675 const struct file_operations aa_sfs_seq_file_ops = {
676 	.owner		= THIS_MODULE,
677 	.open		= aa_sfs_seq_open,
678 	.read		= seq_read,
679 	.llseek		= seq_lseek,
680 	.release	= single_release,
681 };
682 
683 /*
684  * profile based file operations
685  *     policy/profiles/XXXX/profiles/ *
686  */
687 
688 #define SEQ_PROFILE_FOPS(NAME)						      \
689 static int seq_profile_ ##NAME ##_open(struct inode *inode, struct file *file)\
690 {									      \
691 	return seq_profile_open(inode, file, seq_profile_ ##NAME ##_show);    \
692 }									      \
693 									      \
694 static const struct file_operations seq_profile_ ##NAME ##_fops = {	      \
695 	.owner		= THIS_MODULE,					      \
696 	.open		= seq_profile_ ##NAME ##_open,			      \
697 	.read		= seq_read,					      \
698 	.llseek		= seq_lseek,					      \
699 	.release	= seq_profile_release,				      \
700 }									      \
701 
702 static int seq_profile_open(struct inode *inode, struct file *file,
703 			    int (*show)(struct seq_file *, void *))
704 {
705 	struct aa_proxy *proxy = aa_get_proxy(inode->i_private);
706 	int error = single_open(file, show, proxy);
707 
708 	if (error) {
709 		file->private_data = NULL;
710 		aa_put_proxy(proxy);
711 	}
712 
713 	return error;
714 }
715 
716 static int seq_profile_release(struct inode *inode, struct file *file)
717 {
718 	struct seq_file *seq = (struct seq_file *) file->private_data;
719 	if (seq)
720 		aa_put_proxy(seq->private);
721 	return single_release(inode, file);
722 }
723 
724 static int seq_profile_name_show(struct seq_file *seq, void *v)
725 {
726 	struct aa_proxy *proxy = seq->private;
727 	struct aa_profile *profile = aa_get_profile_rcu(&proxy->profile);
728 	seq_printf(seq, "%s\n", profile->base.name);
729 	aa_put_profile(profile);
730 
731 	return 0;
732 }
733 
734 static int seq_profile_mode_show(struct seq_file *seq, void *v)
735 {
736 	struct aa_proxy *proxy = seq->private;
737 	struct aa_profile *profile = aa_get_profile_rcu(&proxy->profile);
738 	seq_printf(seq, "%s\n", aa_profile_mode_names[profile->mode]);
739 	aa_put_profile(profile);
740 
741 	return 0;
742 }
743 
744 static int seq_profile_attach_show(struct seq_file *seq, void *v)
745 {
746 	struct aa_proxy *proxy = seq->private;
747 	struct aa_profile *profile = aa_get_profile_rcu(&proxy->profile);
748 	if (profile->attach)
749 		seq_printf(seq, "%s\n", profile->attach);
750 	else if (profile->xmatch)
751 		seq_puts(seq, "<unknown>\n");
752 	else
753 		seq_printf(seq, "%s\n", profile->base.name);
754 	aa_put_profile(profile);
755 
756 	return 0;
757 }
758 
759 static int seq_profile_hash_show(struct seq_file *seq, void *v)
760 {
761 	struct aa_proxy *proxy = seq->private;
762 	struct aa_profile *profile = aa_get_profile_rcu(&proxy->profile);
763 	unsigned int i, size = aa_hash_size();
764 
765 	if (profile->hash) {
766 		for (i = 0; i < size; i++)
767 			seq_printf(seq, "%.2x", profile->hash[i]);
768 		seq_putc(seq, '\n');
769 	}
770 	aa_put_profile(profile);
771 
772 	return 0;
773 }
774 
775 SEQ_PROFILE_FOPS(name);
776 SEQ_PROFILE_FOPS(mode);
777 SEQ_PROFILE_FOPS(attach);
778 SEQ_PROFILE_FOPS(hash);
779 
780 /*
781  * namespace based files
782  *     several root files and
783  *     policy/ *
784  */
785 
786 #define SEQ_NS_FOPS(NAME)						      \
787 static int seq_ns_ ##NAME ##_open(struct inode *inode, struct file *file)     \
788 {									      \
789 	return single_open(file, seq_ns_ ##NAME ##_show, inode->i_private);   \
790 }									      \
791 									      \
792 static const struct file_operations seq_ns_ ##NAME ##_fops = {	      \
793 	.owner		= THIS_MODULE,					      \
794 	.open		= seq_ns_ ##NAME ##_open,			      \
795 	.read		= seq_read,					      \
796 	.llseek		= seq_lseek,					      \
797 	.release	= single_release,				      \
798 }									      \
799 
800 static int seq_ns_level_show(struct seq_file *seq, void *v)
801 {
802 	struct aa_ns *ns = aa_current_profile()->ns;
803 
804 	seq_printf(seq, "%d\n", ns->level);
805 
806 	return 0;
807 }
808 
809 static int seq_ns_name_show(struct seq_file *seq, void *v)
810 {
811 	struct aa_ns *ns = aa_current_profile()->ns;
812 
813 	seq_printf(seq, "%s\n", ns->base.name);
814 
815 	return 0;
816 }
817 
818 SEQ_NS_FOPS(level);
819 SEQ_NS_FOPS(name);
820 
821 
822 /* policy/raw_data/ * file ops */
823 
824 #define SEQ_RAWDATA_FOPS(NAME)						      \
825 static int seq_rawdata_ ##NAME ##_open(struct inode *inode, struct file *file)\
826 {									      \
827 	return seq_rawdata_open(inode, file, seq_rawdata_ ##NAME ##_show);    \
828 }									      \
829 									      \
830 static const struct file_operations seq_rawdata_ ##NAME ##_fops = {	      \
831 	.owner		= THIS_MODULE,					      \
832 	.open		= seq_rawdata_ ##NAME ##_open,			      \
833 	.read		= seq_read,					      \
834 	.llseek		= seq_lseek,					      \
835 	.release	= seq_rawdata_release,				      \
836 }									      \
837 
838 static int seq_rawdata_open(struct inode *inode, struct file *file,
839 			    int (*show)(struct seq_file *, void *))
840 {
841 	struct aa_loaddata *data = __aa_get_loaddata(inode->i_private);
842 	int error;
843 
844 	if (!data)
845 		/* lost race this ent is being reaped */
846 		return -ENOENT;
847 
848 	error = single_open(file, show, data);
849 	if (error) {
850 		AA_BUG(file->private_data &&
851 		       ((struct seq_file *)file->private_data)->private);
852 		aa_put_loaddata(data);
853 	}
854 
855 	return error;
856 }
857 
858 static int seq_rawdata_release(struct inode *inode, struct file *file)
859 {
860 	struct seq_file *seq = (struct seq_file *) file->private_data;
861 
862 	if (seq)
863 		aa_put_loaddata(seq->private);
864 
865 	return single_release(inode, file);
866 }
867 
868 static int seq_rawdata_abi_show(struct seq_file *seq, void *v)
869 {
870 	struct aa_loaddata *data = seq->private;
871 
872 	seq_printf(seq, "v%d\n", data->abi);
873 
874 	return 0;
875 }
876 
877 static int seq_rawdata_revision_show(struct seq_file *seq, void *v)
878 {
879 	struct aa_loaddata *data = seq->private;
880 
881 	seq_printf(seq, "%ld\n", data->revision);
882 
883 	return 0;
884 }
885 
886 static int seq_rawdata_hash_show(struct seq_file *seq, void *v)
887 {
888 	struct aa_loaddata *data = seq->private;
889 	unsigned int i, size = aa_hash_size();
890 
891 	if (data->hash) {
892 		for (i = 0; i < size; i++)
893 			seq_printf(seq, "%.2x", data->hash[i]);
894 		seq_putc(seq, '\n');
895 	}
896 
897 	return 0;
898 }
899 
900 SEQ_RAWDATA_FOPS(abi);
901 SEQ_RAWDATA_FOPS(revision);
902 SEQ_RAWDATA_FOPS(hash);
903 
904 static ssize_t rawdata_read(struct file *file, char __user *buf, size_t size,
905 			    loff_t *ppos)
906 {
907 	struct aa_loaddata *rawdata = file->private_data;
908 
909 	return simple_read_from_buffer(buf, size, ppos, rawdata->data,
910 				       rawdata->size);
911 }
912 
913 static int rawdata_release(struct inode *inode, struct file *file)
914 {
915 	aa_put_loaddata(file->private_data);
916 
917 	return 0;
918 }
919 
920 static int rawdata_open(struct inode *inode, struct file *file)
921 {
922 	if (!policy_view_capable(NULL))
923 		return -EACCES;
924 	file->private_data = __aa_get_loaddata(inode->i_private);
925 	if (!file->private_data)
926 		/* lost race: this entry is being reaped */
927 		return -ENOENT;
928 
929 	return 0;
930 }
931 
932 static const struct file_operations rawdata_fops = {
933 	.open = rawdata_open,
934 	.read = rawdata_read,
935 	.llseek = generic_file_llseek,
936 	.release = rawdata_release,
937 };
938 
939 static void remove_rawdata_dents(struct aa_loaddata *rawdata)
940 {
941 	int i;
942 
943 	for (i = 0; i < AAFS_LOADDATA_NDENTS; i++) {
944 		if (!IS_ERR_OR_NULL(rawdata->dents[i])) {
945 			/* no refcounts on i_private */
946 			securityfs_remove(rawdata->dents[i]);
947 			rawdata->dents[i] = NULL;
948 		}
949 	}
950 }
951 
952 void __aa_fs_remove_rawdata(struct aa_loaddata *rawdata)
953 {
954 	AA_BUG(rawdata->ns && !mutex_is_locked(&rawdata->ns->lock));
955 
956 	if (rawdata->ns) {
957 		remove_rawdata_dents(rawdata);
958 		list_del_init(&rawdata->list);
959 		aa_put_ns(rawdata->ns);
960 		rawdata->ns = NULL;
961 	}
962 }
963 
964 int __aa_fs_create_rawdata(struct aa_ns *ns, struct aa_loaddata *rawdata)
965 {
966 	struct dentry *dent, *dir;
967 
968 	AA_BUG(!ns);
969 	AA_BUG(!rawdata);
970 	AA_BUG(!mutex_is_locked(&ns->lock));
971 	AA_BUG(!ns_subdata_dir(ns));
972 
973 	/*
974 	 * just use ns revision dir was originally created at. This is
975 	 * under ns->lock and if load is successful revision will be
976 	 * bumped and is guaranteed to be unique
977 	 */
978 	rawdata->name = kasprintf(GFP_KERNEL, "%ld", ns->revision);
979 	if (!rawdata->name)
980 		return -ENOMEM;
981 
982 	dir = securityfs_create_dir(rawdata->name, ns_subdata_dir(ns));
983 	if (IS_ERR(dir))
984 		/* ->name freed when rawdata freed */
985 		return PTR_ERR(dir);
986 	rawdata->dents[AAFS_LOADDATA_DIR] = dir;
987 
988 	dent = securityfs_create_file("abi", S_IFREG | 0444, dir, rawdata,
989 				      &seq_rawdata_abi_fops);
990 	if (IS_ERR(dent))
991 		goto fail;
992 	rawdata->dents[AAFS_LOADDATA_ABI] = dent;
993 
994 	dent = securityfs_create_file("revision", S_IFREG | 0444, dir, rawdata,
995 				      &seq_rawdata_revision_fops);
996 	if (IS_ERR(dent))
997 		goto fail;
998 	rawdata->dents[AAFS_LOADDATA_REVISION] = dent;
999 
1000 	if (aa_g_hash_policy) {
1001 		dent = securityfs_create_file("sha1", S_IFREG | 0444, dir,
1002 					      rawdata, &seq_rawdata_hash_fops);
1003 		if (IS_ERR(dent))
1004 			goto fail;
1005 		rawdata->dents[AAFS_LOADDATA_HASH] = dent;
1006 	}
1007 
1008 	dent = securityfs_create_file("raw_data", S_IFREG | 0444,
1009 				      dir, rawdata, &rawdata_fops);
1010 	if (IS_ERR(dent))
1011 		goto fail;
1012 	rawdata->dents[AAFS_LOADDATA_DATA] = dent;
1013 	d_inode(dent)->i_size = rawdata->size;
1014 
1015 	rawdata->ns = aa_get_ns(ns);
1016 	list_add(&rawdata->list, &ns->rawdata_list);
1017 	/* no refcount on inode rawdata */
1018 
1019 	return 0;
1020 
1021 fail:
1022 	remove_rawdata_dents(rawdata);
1023 
1024 	return PTR_ERR(dent);
1025 }
1026 
1027 /** fns to setup dynamic per profile/namespace files **/
1028 
1029 /**
1030  *
1031  * Requires: @profile->ns->lock held
1032  */
1033 void __aafs_profile_rmdir(struct aa_profile *profile)
1034 {
1035 	struct aa_profile *child;
1036 	int i;
1037 
1038 	if (!profile)
1039 		return;
1040 
1041 	list_for_each_entry(child, &profile->base.profiles, base.list)
1042 		__aafs_profile_rmdir(child);
1043 
1044 	for (i = AAFS_PROF_SIZEOF - 1; i >= 0; --i) {
1045 		struct aa_proxy *proxy;
1046 		if (!profile->dents[i])
1047 			continue;
1048 
1049 		proxy = d_inode(profile->dents[i])->i_private;
1050 		securityfs_remove(profile->dents[i]);
1051 		aa_put_proxy(proxy);
1052 		profile->dents[i] = NULL;
1053 	}
1054 }
1055 
1056 /**
1057  *
1058  * Requires: @old->ns->lock held
1059  */
1060 void __aafs_profile_migrate_dents(struct aa_profile *old,
1061 				  struct aa_profile *new)
1062 {
1063 	int i;
1064 
1065 	for (i = 0; i < AAFS_PROF_SIZEOF; i++) {
1066 		new->dents[i] = old->dents[i];
1067 		if (new->dents[i])
1068 			new->dents[i]->d_inode->i_mtime = current_time(new->dents[i]->d_inode);
1069 		old->dents[i] = NULL;
1070 	}
1071 }
1072 
1073 static struct dentry *create_profile_file(struct dentry *dir, const char *name,
1074 					  struct aa_profile *profile,
1075 					  const struct file_operations *fops)
1076 {
1077 	struct aa_proxy *proxy = aa_get_proxy(profile->proxy);
1078 	struct dentry *dent;
1079 
1080 	dent = securityfs_create_file(name, S_IFREG | 0444, dir, proxy, fops);
1081 	if (IS_ERR(dent))
1082 		aa_put_proxy(proxy);
1083 
1084 	return dent;
1085 }
1086 
1087 static int profile_depth(struct aa_profile *profile)
1088 {
1089 	int depth = 0;
1090 
1091 	rcu_read_lock();
1092 	for (depth = 0; profile; profile = rcu_access_pointer(profile->parent))
1093 		depth++;
1094 	rcu_read_unlock();
1095 
1096 	return depth;
1097 }
1098 
1099 static int gen_symlink_name(char *buffer, size_t bsize, int depth,
1100 			    const char *dirname, const char *fname)
1101 {
1102 	int error;
1103 
1104 	for (; depth > 0; depth--) {
1105 		if (bsize < 7)
1106 			return -ENAMETOOLONG;
1107 		strcpy(buffer, "../../");
1108 		buffer += 6;
1109 		bsize -= 6;
1110 	}
1111 
1112 	error = snprintf(buffer, bsize, "raw_data/%s/%s", dirname, fname);
1113 	if (error >= bsize || error < 0)
1114 		return -ENAMETOOLONG;
1115 
1116 	return 0;
1117 }
1118 
1119 /*
1120  * Requires: @profile->ns->lock held
1121  */
1122 int __aafs_profile_mkdir(struct aa_profile *profile, struct dentry *parent)
1123 {
1124 	struct aa_profile *child;
1125 	struct dentry *dent = NULL, *dir;
1126 	int error;
1127 
1128 	if (!parent) {
1129 		struct aa_profile *p;
1130 		p = aa_deref_parent(profile);
1131 		dent = prof_dir(p);
1132 		/* adding to parent that previously didn't have children */
1133 		dent = securityfs_create_dir("profiles", dent);
1134 		if (IS_ERR(dent))
1135 			goto fail;
1136 		prof_child_dir(p) = parent = dent;
1137 	}
1138 
1139 	if (!profile->dirname) {
1140 		int len, id_len;
1141 		len = mangle_name(profile->base.name, NULL);
1142 		id_len = snprintf(NULL, 0, ".%ld", profile->ns->uniq_id);
1143 
1144 		profile->dirname = kmalloc(len + id_len + 1, GFP_KERNEL);
1145 		if (!profile->dirname) {
1146 			error = -ENOMEM;
1147 			goto fail2;
1148 		}
1149 
1150 		mangle_name(profile->base.name, profile->dirname);
1151 		sprintf(profile->dirname + len, ".%ld", profile->ns->uniq_id++);
1152 	}
1153 
1154 	dent = securityfs_create_dir(profile->dirname, parent);
1155 	if (IS_ERR(dent))
1156 		goto fail;
1157 	prof_dir(profile) = dir = dent;
1158 
1159 	dent = create_profile_file(dir, "name", profile,
1160 				   &seq_profile_name_fops);
1161 	if (IS_ERR(dent))
1162 		goto fail;
1163 	profile->dents[AAFS_PROF_NAME] = dent;
1164 
1165 	dent = create_profile_file(dir, "mode", profile,
1166 				   &seq_profile_mode_fops);
1167 	if (IS_ERR(dent))
1168 		goto fail;
1169 	profile->dents[AAFS_PROF_MODE] = dent;
1170 
1171 	dent = create_profile_file(dir, "attach", profile,
1172 				   &seq_profile_attach_fops);
1173 	if (IS_ERR(dent))
1174 		goto fail;
1175 	profile->dents[AAFS_PROF_ATTACH] = dent;
1176 
1177 	if (profile->hash) {
1178 		dent = create_profile_file(dir, "sha1", profile,
1179 					   &seq_profile_hash_fops);
1180 		if (IS_ERR(dent))
1181 			goto fail;
1182 		profile->dents[AAFS_PROF_HASH] = dent;
1183 	}
1184 
1185 	if (profile->rawdata) {
1186 		char target[64];
1187 		int depth = profile_depth(profile);
1188 
1189 		error = gen_symlink_name(target, sizeof(target), depth,
1190 					 profile->rawdata->name, "sha1");
1191 		if (error < 0)
1192 			goto fail2;
1193 		dent = securityfs_create_symlink("raw_sha1", dir, target, NULL);
1194 		if (IS_ERR(dent))
1195 			goto fail;
1196 		profile->dents[AAFS_PROF_RAW_HASH] = dent;
1197 
1198 		error = gen_symlink_name(target, sizeof(target), depth,
1199 					 profile->rawdata->name, "abi");
1200 		if (error < 0)
1201 			goto fail2;
1202 		dent = securityfs_create_symlink("raw_abi", dir, target, NULL);
1203 		if (IS_ERR(dent))
1204 			goto fail;
1205 		profile->dents[AAFS_PROF_RAW_ABI] = dent;
1206 
1207 		error = gen_symlink_name(target, sizeof(target), depth,
1208 					 profile->rawdata->name, "raw_data");
1209 		if (error < 0)
1210 			goto fail2;
1211 		dent = securityfs_create_symlink("raw_data", dir, target, NULL);
1212 		if (IS_ERR(dent))
1213 			goto fail;
1214 		profile->dents[AAFS_PROF_RAW_DATA] = dent;
1215 	}
1216 
1217 	list_for_each_entry(child, &profile->base.profiles, base.list) {
1218 		error = __aafs_profile_mkdir(child, prof_child_dir(profile));
1219 		if (error)
1220 			goto fail2;
1221 	}
1222 
1223 	return 0;
1224 
1225 fail:
1226 	error = PTR_ERR(dent);
1227 
1228 fail2:
1229 	__aafs_profile_rmdir(profile);
1230 
1231 	return error;
1232 }
1233 
1234 static void __aa_fs_list_remove_rawdata(struct aa_ns *ns)
1235 {
1236 	struct aa_loaddata *ent, *tmp;
1237 
1238 	AA_BUG(!mutex_is_locked(&ns->lock));
1239 
1240 	list_for_each_entry_safe(ent, tmp, &ns->rawdata_list, list)
1241 		__aa_fs_remove_rawdata(ent);
1242 }
1243 
1244 /**
1245  *
1246  * Requires: @ns->lock held
1247  */
1248 void __aafs_ns_rmdir(struct aa_ns *ns)
1249 {
1250 	struct aa_ns *sub;
1251 	struct aa_profile *child;
1252 	int i;
1253 
1254 	if (!ns)
1255 		return;
1256 
1257 	list_for_each_entry(child, &ns->base.profiles, base.list)
1258 		__aafs_profile_rmdir(child);
1259 
1260 	list_for_each_entry(sub, &ns->sub_ns, base.list) {
1261 		mutex_lock(&sub->lock);
1262 		__aafs_ns_rmdir(sub);
1263 		mutex_unlock(&sub->lock);
1264 	}
1265 
1266 	__aa_fs_list_remove_rawdata(ns);
1267 
1268 	if (ns_subns_dir(ns)) {
1269 		sub = d_inode(ns_subns_dir(ns))->i_private;
1270 		aa_put_ns(sub);
1271 	}
1272 	if (ns_subload(ns)) {
1273 		sub = d_inode(ns_subload(ns))->i_private;
1274 		aa_put_ns(sub);
1275 	}
1276 	if (ns_subreplace(ns)) {
1277 		sub = d_inode(ns_subreplace(ns))->i_private;
1278 		aa_put_ns(sub);
1279 	}
1280 	if (ns_subremove(ns)) {
1281 		sub = d_inode(ns_subremove(ns))->i_private;
1282 		aa_put_ns(sub);
1283 	}
1284 
1285 	for (i = AAFS_NS_SIZEOF - 1; i >= 0; --i) {
1286 		securityfs_remove(ns->dents[i]);
1287 		ns->dents[i] = NULL;
1288 	}
1289 }
1290 
1291 /* assumes cleanup in caller */
1292 static int __aafs_ns_mkdir_entries(struct aa_ns *ns, struct dentry *dir)
1293 {
1294 	struct dentry *dent;
1295 
1296 	AA_BUG(!ns);
1297 	AA_BUG(!dir);
1298 
1299 	dent = securityfs_create_dir("profiles", dir);
1300 	if (IS_ERR(dent))
1301 		return PTR_ERR(dent);
1302 	ns_subprofs_dir(ns) = dent;
1303 
1304 	dent = securityfs_create_dir("raw_data", dir);
1305 	if (IS_ERR(dent))
1306 		return PTR_ERR(dent);
1307 	ns_subdata_dir(ns) = dent;
1308 
1309 	dent = securityfs_create_file(".load", 0640, dir, ns,
1310 				      &aa_fs_profile_load);
1311 	if (IS_ERR(dent))
1312 		return PTR_ERR(dent);
1313 	aa_get_ns(ns);
1314 	ns_subload(ns) = dent;
1315 
1316 	dent = securityfs_create_file(".replace", 0640, dir, ns,
1317 				      &aa_fs_profile_replace);
1318 	if (IS_ERR(dent))
1319 		return PTR_ERR(dent);
1320 	aa_get_ns(ns);
1321 	ns_subreplace(ns) = dent;
1322 
1323 	dent = securityfs_create_file(".remove", 0640, dir, ns,
1324 				      &aa_fs_profile_remove);
1325 	if (IS_ERR(dent))
1326 		return PTR_ERR(dent);
1327 	aa_get_ns(ns);
1328 	ns_subremove(ns) = dent;
1329 
1330 	dent = securityfs_create_dir("namespaces", dir);
1331 	if (IS_ERR(dent))
1332 		return PTR_ERR(dent);
1333 	aa_get_ns(ns);
1334 	ns_subns_dir(ns) = dent;
1335 
1336 	return 0;
1337 }
1338 
1339 /*
1340  * Requires: @ns->lock held
1341  */
1342 int __aafs_ns_mkdir(struct aa_ns *ns, struct dentry *parent, const char *name)
1343 {
1344 	struct aa_ns *sub;
1345 	struct aa_profile *child;
1346 	struct dentry *dent, *dir;
1347 	int error;
1348 
1349 	AA_BUG(!ns);
1350 	AA_BUG(!parent);
1351 	AA_BUG(!mutex_is_locked(&ns->lock));
1352 
1353 	if (!name)
1354 		name = ns->base.name;
1355 
1356 	/* create ns dir if it doesn't already exist */
1357 	dent = securityfs_create_dir(name, parent);
1358 	if (IS_ERR(dent))
1359 		goto fail;
1360 
1361 	ns_dir(ns) = dir = dent;
1362 	error = __aafs_ns_mkdir_entries(ns, dir);
1363 	if (error)
1364 		goto fail2;
1365 
1366 	/* profiles */
1367 	list_for_each_entry(child, &ns->base.profiles, base.list) {
1368 		error = __aafs_profile_mkdir(child, ns_subprofs_dir(ns));
1369 		if (error)
1370 			goto fail2;
1371 	}
1372 
1373 	/* subnamespaces */
1374 	list_for_each_entry(sub, &ns->sub_ns, base.list) {
1375 		mutex_lock(&sub->lock);
1376 		error = __aafs_ns_mkdir(sub, ns_subns_dir(ns), NULL);
1377 		mutex_unlock(&sub->lock);
1378 		if (error)
1379 			goto fail2;
1380 	}
1381 
1382 	return 0;
1383 
1384 fail:
1385 	error = PTR_ERR(dent);
1386 
1387 fail2:
1388 	__aafs_ns_rmdir(ns);
1389 
1390 	return error;
1391 }
1392 
1393 
1394 #define list_entry_is_head(pos, head, member) (&pos->member == (head))
1395 
1396 /**
1397  * __next_ns - find the next namespace to list
1398  * @root: root namespace to stop search at (NOT NULL)
1399  * @ns: current ns position (NOT NULL)
1400  *
1401  * Find the next namespace from @ns under @root and handle all locking needed
1402  * while switching current namespace.
1403  *
1404  * Returns: next namespace or NULL if at last namespace under @root
1405  * Requires: ns->parent->lock to be held
1406  * NOTE: will not unlock root->lock
1407  */
1408 static struct aa_ns *__next_ns(struct aa_ns *root, struct aa_ns *ns)
1409 {
1410 	struct aa_ns *parent, *next;
1411 
1412 	/* is next namespace a child */
1413 	if (!list_empty(&ns->sub_ns)) {
1414 		next = list_first_entry(&ns->sub_ns, typeof(*ns), base.list);
1415 		mutex_lock(&next->lock);
1416 		return next;
1417 	}
1418 
1419 	/* check if the next ns is a sibling, parent, gp, .. */
1420 	parent = ns->parent;
1421 	while (ns != root) {
1422 		mutex_unlock(&ns->lock);
1423 		next = list_next_entry(ns, base.list);
1424 		if (!list_entry_is_head(next, &parent->sub_ns, base.list)) {
1425 			mutex_lock(&next->lock);
1426 			return next;
1427 		}
1428 		ns = parent;
1429 		parent = parent->parent;
1430 	}
1431 
1432 	return NULL;
1433 }
1434 
1435 /**
1436  * __first_profile - find the first profile in a namespace
1437  * @root: namespace that is root of profiles being displayed (NOT NULL)
1438  * @ns: namespace to start in   (NOT NULL)
1439  *
1440  * Returns: unrefcounted profile or NULL if no profile
1441  * Requires: profile->ns.lock to be held
1442  */
1443 static struct aa_profile *__first_profile(struct aa_ns *root,
1444 					  struct aa_ns *ns)
1445 {
1446 	for (; ns; ns = __next_ns(root, ns)) {
1447 		if (!list_empty(&ns->base.profiles))
1448 			return list_first_entry(&ns->base.profiles,
1449 						struct aa_profile, base.list);
1450 	}
1451 	return NULL;
1452 }
1453 
1454 /**
1455  * __next_profile - step to the next profile in a profile tree
1456  * @profile: current profile in tree (NOT NULL)
1457  *
1458  * Perform a depth first traversal on the profile tree in a namespace
1459  *
1460  * Returns: next profile or NULL if done
1461  * Requires: profile->ns.lock to be held
1462  */
1463 static struct aa_profile *__next_profile(struct aa_profile *p)
1464 {
1465 	struct aa_profile *parent;
1466 	struct aa_ns *ns = p->ns;
1467 
1468 	/* is next profile a child */
1469 	if (!list_empty(&p->base.profiles))
1470 		return list_first_entry(&p->base.profiles, typeof(*p),
1471 					base.list);
1472 
1473 	/* is next profile a sibling, parent sibling, gp, sibling, .. */
1474 	parent = rcu_dereference_protected(p->parent,
1475 					   mutex_is_locked(&p->ns->lock));
1476 	while (parent) {
1477 		p = list_next_entry(p, base.list);
1478 		if (!list_entry_is_head(p, &parent->base.profiles, base.list))
1479 			return p;
1480 		p = parent;
1481 		parent = rcu_dereference_protected(parent->parent,
1482 					    mutex_is_locked(&parent->ns->lock));
1483 	}
1484 
1485 	/* is next another profile in the namespace */
1486 	p = list_next_entry(p, base.list);
1487 	if (!list_entry_is_head(p, &ns->base.profiles, base.list))
1488 		return p;
1489 
1490 	return NULL;
1491 }
1492 
1493 /**
1494  * next_profile - step to the next profile in where ever it may be
1495  * @root: root namespace  (NOT NULL)
1496  * @profile: current profile  (NOT NULL)
1497  *
1498  * Returns: next profile or NULL if there isn't one
1499  */
1500 static struct aa_profile *next_profile(struct aa_ns *root,
1501 				       struct aa_profile *profile)
1502 {
1503 	struct aa_profile *next = __next_profile(profile);
1504 	if (next)
1505 		return next;
1506 
1507 	/* finished all profiles in namespace move to next namespace */
1508 	return __first_profile(root, __next_ns(root, profile->ns));
1509 }
1510 
1511 /**
1512  * p_start - start a depth first traversal of profile tree
1513  * @f: seq_file to fill
1514  * @pos: current position
1515  *
1516  * Returns: first profile under current namespace or NULL if none found
1517  *
1518  * acquires first ns->lock
1519  */
1520 static void *p_start(struct seq_file *f, loff_t *pos)
1521 {
1522 	struct aa_profile *profile = NULL;
1523 	struct aa_ns *root = aa_current_profile()->ns;
1524 	loff_t l = *pos;
1525 	f->private = aa_get_ns(root);
1526 
1527 
1528 	/* find the first profile */
1529 	mutex_lock(&root->lock);
1530 	profile = __first_profile(root, root);
1531 
1532 	/* skip to position */
1533 	for (; profile && l > 0; l--)
1534 		profile = next_profile(root, profile);
1535 
1536 	return profile;
1537 }
1538 
1539 /**
1540  * p_next - read the next profile entry
1541  * @f: seq_file to fill
1542  * @p: profile previously returned
1543  * @pos: current position
1544  *
1545  * Returns: next profile after @p or NULL if none
1546  *
1547  * may acquire/release locks in namespace tree as necessary
1548  */
1549 static void *p_next(struct seq_file *f, void *p, loff_t *pos)
1550 {
1551 	struct aa_profile *profile = p;
1552 	struct aa_ns *ns = f->private;
1553 	(*pos)++;
1554 
1555 	return next_profile(ns, profile);
1556 }
1557 
1558 /**
1559  * p_stop - stop depth first traversal
1560  * @f: seq_file we are filling
1561  * @p: the last profile writen
1562  *
1563  * Release all locking done by p_start/p_next on namespace tree
1564  */
1565 static void p_stop(struct seq_file *f, void *p)
1566 {
1567 	struct aa_profile *profile = p;
1568 	struct aa_ns *root = f->private, *ns;
1569 
1570 	if (profile) {
1571 		for (ns = profile->ns; ns && ns != root; ns = ns->parent)
1572 			mutex_unlock(&ns->lock);
1573 	}
1574 	mutex_unlock(&root->lock);
1575 	aa_put_ns(root);
1576 }
1577 
1578 /**
1579  * seq_show_profile - show a profile entry
1580  * @f: seq_file to file
1581  * @p: current position (profile)    (NOT NULL)
1582  *
1583  * Returns: error on failure
1584  */
1585 static int seq_show_profile(struct seq_file *f, void *p)
1586 {
1587 	struct aa_profile *profile = (struct aa_profile *)p;
1588 	struct aa_ns *root = f->private;
1589 
1590 	if (profile->ns != root)
1591 		seq_printf(f, ":%s://", aa_ns_name(root, profile->ns, true));
1592 	seq_printf(f, "%s (%s)\n", profile->base.hname,
1593 		   aa_profile_mode_names[profile->mode]);
1594 
1595 	return 0;
1596 }
1597 
1598 static const struct seq_operations aa_sfs_profiles_op = {
1599 	.start = p_start,
1600 	.next = p_next,
1601 	.stop = p_stop,
1602 	.show = seq_show_profile,
1603 };
1604 
1605 static int profiles_open(struct inode *inode, struct file *file)
1606 {
1607 	if (!policy_view_capable(NULL))
1608 		return -EACCES;
1609 
1610 	return seq_open(file, &aa_sfs_profiles_op);
1611 }
1612 
1613 static int profiles_release(struct inode *inode, struct file *file)
1614 {
1615 	return seq_release(inode, file);
1616 }
1617 
1618 static const struct file_operations aa_sfs_profiles_fops = {
1619 	.open = profiles_open,
1620 	.read = seq_read,
1621 	.llseek = seq_lseek,
1622 	.release = profiles_release,
1623 };
1624 
1625 
1626 /** Base file system setup **/
1627 static struct aa_sfs_entry aa_sfs_entry_file[] = {
1628 	AA_SFS_FILE_STRING("mask",
1629 			   "create read write exec append mmap_exec link lock"),
1630 	{ }
1631 };
1632 
1633 static struct aa_sfs_entry aa_sfs_entry_domain[] = {
1634 	AA_SFS_FILE_BOOLEAN("change_hat",	1),
1635 	AA_SFS_FILE_BOOLEAN("change_hatv",	1),
1636 	AA_SFS_FILE_BOOLEAN("change_onexec",	1),
1637 	AA_SFS_FILE_BOOLEAN("change_profile",	1),
1638 	AA_SFS_FILE_BOOLEAN("fix_binfmt_elf_mmap",	1),
1639 	AA_SFS_FILE_STRING("version", "1.2"),
1640 	{ }
1641 };
1642 
1643 static struct aa_sfs_entry aa_sfs_entry_versions[] = {
1644 	AA_SFS_FILE_BOOLEAN("v5",	1),
1645 	{ }
1646 };
1647 
1648 static struct aa_sfs_entry aa_sfs_entry_policy[] = {
1649 	AA_SFS_DIR("versions",			aa_sfs_entry_versions),
1650 	AA_SFS_FILE_BOOLEAN("set_load",		1),
1651 	{ }
1652 };
1653 
1654 static struct aa_sfs_entry aa_sfs_entry_features[] = {
1655 	AA_SFS_DIR("policy",			aa_sfs_entry_policy),
1656 	AA_SFS_DIR("domain",			aa_sfs_entry_domain),
1657 	AA_SFS_DIR("file",			aa_sfs_entry_file),
1658 	AA_SFS_FILE_U64("capability",		VFS_CAP_FLAGS_MASK),
1659 	AA_SFS_DIR("rlimit",			aa_sfs_entry_rlimit),
1660 	AA_SFS_DIR("caps",			aa_sfs_entry_caps),
1661 	{ }
1662 };
1663 
1664 static struct aa_sfs_entry aa_sfs_entry_apparmor[] = {
1665 	AA_SFS_FILE_FOPS(".access", 0640, &aa_sfs_access),
1666 	AA_SFS_FILE_FOPS(".ns_level", 0666, &seq_ns_level_fops),
1667 	AA_SFS_FILE_FOPS(".ns_name", 0640, &seq_ns_name_fops),
1668 	AA_SFS_FILE_FOPS("profiles", 0440, &aa_sfs_profiles_fops),
1669 	AA_SFS_DIR("features", aa_sfs_entry_features),
1670 	{ }
1671 };
1672 
1673 static struct aa_sfs_entry aa_sfs_entry =
1674 	AA_SFS_DIR("apparmor", aa_sfs_entry_apparmor);
1675 
1676 /**
1677  * entry_create_file - create a file entry in the apparmor securityfs
1678  * @fs_file: aa_sfs_entry to build an entry for (NOT NULL)
1679  * @parent: the parent dentry in the securityfs
1680  *
1681  * Use entry_remove_file to remove entries created with this fn.
1682  */
1683 static int __init entry_create_file(struct aa_sfs_entry *fs_file,
1684 				    struct dentry *parent)
1685 {
1686 	int error = 0;
1687 
1688 	fs_file->dentry = securityfs_create_file(fs_file->name,
1689 						 S_IFREG | fs_file->mode,
1690 						 parent, fs_file,
1691 						 fs_file->file_ops);
1692 	if (IS_ERR(fs_file->dentry)) {
1693 		error = PTR_ERR(fs_file->dentry);
1694 		fs_file->dentry = NULL;
1695 	}
1696 	return error;
1697 }
1698 
1699 static void __init entry_remove_dir(struct aa_sfs_entry *fs_dir);
1700 /**
1701  * entry_create_dir - recursively create a directory entry in the securityfs
1702  * @fs_dir: aa_sfs_entry (and all child entries) to build (NOT NULL)
1703  * @parent: the parent dentry in the securityfs
1704  *
1705  * Use entry_remove_dir to remove entries created with this fn.
1706  */
1707 static int __init entry_create_dir(struct aa_sfs_entry *fs_dir,
1708 				   struct dentry *parent)
1709 {
1710 	struct aa_sfs_entry *fs_file;
1711 	struct dentry *dir;
1712 	int error;
1713 
1714 	dir = securityfs_create_dir(fs_dir->name, parent);
1715 	if (IS_ERR(dir))
1716 		return PTR_ERR(dir);
1717 	fs_dir->dentry = dir;
1718 
1719 	for (fs_file = fs_dir->v.files; fs_file && fs_file->name; ++fs_file) {
1720 		if (fs_file->v_type == AA_SFS_TYPE_DIR)
1721 			error = entry_create_dir(fs_file, fs_dir->dentry);
1722 		else
1723 			error = entry_create_file(fs_file, fs_dir->dentry);
1724 		if (error)
1725 			goto failed;
1726 	}
1727 
1728 	return 0;
1729 
1730 failed:
1731 	entry_remove_dir(fs_dir);
1732 
1733 	return error;
1734 }
1735 
1736 /**
1737  * entry_remove_file - drop a single file entry in the apparmor securityfs
1738  * @fs_file: aa_sfs_entry to detach from the securityfs (NOT NULL)
1739  */
1740 static void __init entry_remove_file(struct aa_sfs_entry *fs_file)
1741 {
1742 	if (!fs_file->dentry)
1743 		return;
1744 
1745 	securityfs_remove(fs_file->dentry);
1746 	fs_file->dentry = NULL;
1747 }
1748 
1749 /**
1750  * entry_remove_dir - recursively drop a directory entry from the securityfs
1751  * @fs_dir: aa_sfs_entry (and all child entries) to detach (NOT NULL)
1752  */
1753 static void __init entry_remove_dir(struct aa_sfs_entry *fs_dir)
1754 {
1755 	struct aa_sfs_entry *fs_file;
1756 
1757 	for (fs_file = fs_dir->v.files; fs_file && fs_file->name; ++fs_file) {
1758 		if (fs_file->v_type == AA_SFS_TYPE_DIR)
1759 			entry_remove_dir(fs_file);
1760 		else
1761 			entry_remove_file(fs_file);
1762 	}
1763 
1764 	entry_remove_file(fs_dir);
1765 }
1766 
1767 /**
1768  * aa_destroy_aafs - cleanup and free aafs
1769  *
1770  * releases dentries allocated by aa_create_aafs
1771  */
1772 void __init aa_destroy_aafs(void)
1773 {
1774 	entry_remove_dir(&aa_sfs_entry);
1775 }
1776 
1777 
1778 #define NULL_FILE_NAME ".null"
1779 struct path aa_null;
1780 
1781 static int aa_mk_null_file(struct dentry *parent)
1782 {
1783 	struct vfsmount *mount = NULL;
1784 	struct dentry *dentry;
1785 	struct inode *inode;
1786 	int count = 0;
1787 	int error = simple_pin_fs(parent->d_sb->s_type, &mount, &count);
1788 
1789 	if (error)
1790 		return error;
1791 
1792 	inode_lock(d_inode(parent));
1793 	dentry = lookup_one_len(NULL_FILE_NAME, parent, strlen(NULL_FILE_NAME));
1794 	if (IS_ERR(dentry)) {
1795 		error = PTR_ERR(dentry);
1796 		goto out;
1797 	}
1798 	inode = new_inode(parent->d_inode->i_sb);
1799 	if (!inode) {
1800 		error = -ENOMEM;
1801 		goto out1;
1802 	}
1803 
1804 	inode->i_ino = get_next_ino();
1805 	inode->i_mode = S_IFCHR | S_IRUGO | S_IWUGO;
1806 	inode->i_atime = inode->i_mtime = inode->i_ctime = current_time(inode);
1807 	init_special_inode(inode, S_IFCHR | S_IRUGO | S_IWUGO,
1808 			   MKDEV(MEM_MAJOR, 3));
1809 	d_instantiate(dentry, inode);
1810 	aa_null.dentry = dget(dentry);
1811 	aa_null.mnt = mntget(mount);
1812 
1813 	error = 0;
1814 
1815 out1:
1816 	dput(dentry);
1817 out:
1818 	inode_unlock(d_inode(parent));
1819 	simple_release_fs(&mount, &count);
1820 	return error;
1821 }
1822 
1823 
1824 
1825 static const char *policy_get_link(struct dentry *dentry,
1826 				   struct inode *inode,
1827 				   struct delayed_call *done)
1828 {
1829 	struct aa_ns *ns;
1830 	struct path path;
1831 
1832 	if (!dentry)
1833 		return ERR_PTR(-ECHILD);
1834 	ns = aa_get_current_ns();
1835 	path.mnt = mntget(aafs_mnt);
1836 	path.dentry = dget(ns_dir(ns));
1837 	nd_jump_link(&path);
1838 	aa_put_ns(ns);
1839 
1840 	return NULL;
1841 }
1842 
1843 static int ns_get_name(char *buf, size_t size, struct aa_ns *ns,
1844 		       struct inode *inode)
1845 {
1846 	int res = snprintf(buf, size, "%s:[%lu]", AAFS_NAME, inode->i_ino);
1847 
1848 	if (res < 0 || res >= size)
1849 		res = -ENOENT;
1850 
1851 	return res;
1852 }
1853 
1854 static int policy_readlink(struct dentry *dentry, char __user *buffer,
1855 			   int buflen)
1856 {
1857 	struct aa_ns *ns;
1858 	char name[32];
1859 	int res;
1860 
1861 	ns = aa_get_current_ns();
1862 	res = ns_get_name(name, sizeof(name), ns, d_inode(dentry));
1863 	if (res >= 0)
1864 		res = readlink_copy(buffer, buflen, name);
1865 	aa_put_ns(ns);
1866 
1867 	return res;
1868 }
1869 
1870 static const struct inode_operations policy_link_iops = {
1871 	.readlink	= policy_readlink,
1872 	.get_link	= policy_get_link,
1873 };
1874 
1875 
1876 /**
1877  * aa_create_aafs - create the apparmor security filesystem
1878  *
1879  * dentries created here are released by aa_destroy_aafs
1880  *
1881  * Returns: error on failure
1882  */
1883 static int __init aa_create_aafs(void)
1884 {
1885 	struct dentry *dent;
1886 	int error;
1887 
1888 	if (!apparmor_initialized)
1889 		return 0;
1890 
1891 	if (aa_sfs_entry.dentry) {
1892 		AA_ERROR("%s: AppArmor securityfs already exists\n", __func__);
1893 		return -EEXIST;
1894 	}
1895 
1896 	/* setup apparmorfs used to virtualize policy/ */
1897 	aafs_mnt = kern_mount(&aafs_ops);
1898 	if (IS_ERR(aafs_mnt))
1899 		panic("can't set apparmorfs up\n");
1900 	aafs_mnt->mnt_sb->s_flags &= ~MS_NOUSER;
1901 
1902 	/* Populate fs tree. */
1903 	error = entry_create_dir(&aa_sfs_entry, NULL);
1904 	if (error)
1905 		goto error;
1906 
1907 	dent = securityfs_create_file(".load", 0666, aa_sfs_entry.dentry,
1908 				      NULL, &aa_fs_profile_load);
1909 	if (IS_ERR(dent)) {
1910 		error = PTR_ERR(dent);
1911 		goto error;
1912 	}
1913 	ns_subload(root_ns) = dent;
1914 
1915 	dent = securityfs_create_file(".replace", 0666, aa_sfs_entry.dentry,
1916 				      NULL, &aa_fs_profile_replace);
1917 	if (IS_ERR(dent)) {
1918 		error = PTR_ERR(dent);
1919 		goto error;
1920 	}
1921 	ns_subreplace(root_ns) = dent;
1922 
1923 	dent = securityfs_create_file(".remove", 0666, aa_sfs_entry.dentry,
1924 				      NULL, &aa_fs_profile_remove);
1925 	if (IS_ERR(dent)) {
1926 		error = PTR_ERR(dent);
1927 		goto error;
1928 	}
1929 	ns_subremove(root_ns) = dent;
1930 
1931 	mutex_lock(&root_ns->lock);
1932 	error = __aafs_ns_mkdir(root_ns, aa_sfs_entry.dentry, "policy");
1933 	mutex_unlock(&root_ns->lock);
1934 
1935 	if (error)
1936 		goto error;
1937 
1938 	error = aa_mk_null_file(aa_sfs_entry.dentry);
1939 	if (error)
1940 		goto error;
1941 
1942 	/* TODO: add default profile to apparmorfs */
1943 
1944 	/* Report that AppArmor fs is enabled */
1945 	aa_info_message("AppArmor Filesystem Enabled");
1946 	return 0;
1947 
1948 error:
1949 	aa_destroy_aafs();
1950 	AA_ERROR("Error creating AppArmor securityfs\n");
1951 	return error;
1952 }
1953 
1954 fs_initcall(aa_create_aafs);
1955