Skip to contentSkip to conversation

AppArmor security module

PATCH In review John Johansen 8 participants 30 messages Jul 29, 2010 – Aug 26, 2010

Subsystems (3)
lore
Share & tools
lore

John Johansen

author maintainer
#0 lore raw

cover AppArmor security module

This is the seveth general posting of the newest version of the AppArmor security module it has been rewritten to use the security_path hooks instead of the previous vfs approach. The current implementation is aimed at being as semantically close to previous versions of AppArmor as possible while using the existing LSM infrastructure.

Development is on going and
improvements to file, capability, network, resource usage and ipc mediation are planned.

With this submission we believe AppArmor is ready for inclusion into the kernel.

_Issues NOT specifically addressed_
* The d_namespace_path function still manually strips the " (deleted)" string that __d_path appends. A fix to __d_path is being pursued independently of the AppArmor submission.

http://lkml.org/lkml/2010/7/6/186

_Issues Addressed Since Last Time AppArmor was Posted_

All changes requested by feed back
* Add comment for embedded \0 in fqnames and their validation
* Add comment for kvmalloc minimum size of work_struct when falling back to vmalloc
* Spell check of comments and general cleanup any need change found during the spell check.
* updated aa_info_message
* removed extraneous if (profile) checks
* removed unused AA_NEW_SID symbol
* added __init and __initdata to fns and variables where appropriate
* removed patch text not related to apparmor that was being added to Documentation/kernel-parameters.txt

Misc fixes and cleanups as result of above changes
* fixed missing include for vmalloc.h in lib.c that would cause build failure on some platforms
* Added simple Documentation/apparmor.txt

A Detailed list of all changes and patches are available from the AppArmor git repository, from commit 5e43ceab0299aa8ee786e17048a31a865de3163f

The AppArmor project has recently transitioned away from Novell forge. Code and Documentation can be found at the following locations
* Mailing List - [email protected]
* Documentation (wip) - http://apparmor.wiki.kernel.org/
* User space tools - https://launchpad.net/apparmor
* Kernel module -
git://git.kernel.org/pub/scm/linux/kernel/git/jj/apparmor-dev.git

author maintainer
#1 lore raw

PATCH 1/13 AppArmor: misc. base functions and defines

Miscellaneous functions and defines needed by AppArmor, including the base path resolution routines.

---
 security/apparmor/include/apparmor.h |   92 +++++++++++++
 security/apparmor/include/path.h     |   31 +++++
 security/apparmor/lib.c              |  133 +++++++++++++++++++
 security/apparmor/path.c             |  235 ++++++++++++++++++++++++++++++++++
 4 files changed, 491 insertions(+), 0 deletions(-)
 create mode 100644 security/apparmor/include/apparmor.h
 create mode 100644 security/apparmor/include/path.h
 create mode 100644 security/apparmor/lib.c
 create mode 100644 security/apparmor/path.c
security/apparmor/include/apparmor.h new file +92 -0
new file mode 100644
index 0000000..38ccaea
@@ -0,0 +1,92 @@
+/*
+ * AppArmor security module
+ *
+ * This file contains AppArmor basic global and lib definitions
+ *
+ * Copyright (C) 1998-2008 Novell/SUSE
+ * Copyright 2009-2010 Canonical Ltd.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, version 2 of the
+ * License.
+ */
+
+#ifndef __APPARMOR_H
+#define __APPARMOR_H
+
+#include <linux/fs.h>
+
+#include "match.h"
+
+/* Control parameters settable through module/boot flags */
+extern enum audit_mode aa_g_audit;
+extern int aa_g_audit_header;
+extern int aa_g_debug;
+extern int aa_g_lock_policy;
+extern int aa_g_logsyscall;
+extern int aa_g_paranoid_load;
+extern unsigned int aa_g_path_max;
+
+/*
+ * DEBUG remains global (no per profile flag) since it is mostly used in sysctl
+ * which is not related to profile accesses.
+ */
+
+#define AA_DEBUG(fmt, args...)						\
+	do {								\
+		if (aa_g_debug && printk_ratelimit())			\
+			printk(KERN_DEBUG "AppArmor: " fmt, ##args);	\
+	} while (0)
+
+#define AA_ERROR(fmt, args...)						\
+	do {								\
+		if (printk_ratelimit())					\
+			printk(KERN_ERR "AppArmor: " fmt, ##args);	\
+	} while (0)
+
+/* Flag indicating whether initialization completed */
+extern int apparmor_initialized __initdata;
+
+/* fn's in lib */
+char *aa_split_fqname(char *args, char **ns_name);
+void aa_info_message(const char *str);
+void *kvmalloc(size_t size);
+void kvfree(void *buffer);
+
+
+/**
+ * aa_strneq - compare null terminated @str to a non null terminated substring
+ * @str: a null terminated string
+ * @sub: a substring, not necessarily null terminated
+ * @len: length of @sub to compare
+ *
+ * The @str string must be full consumed for this to be considered a match
+ */
+static inline bool aa_strneq(const char *str, const char *sub, int len)
+{
+	return !strncmp(str, sub, len) && !str[len];
+}
+
+/**
+ * aa_dfa_null_transition - step to next state after null character
+ * @dfa: the dfa to match against
+ * @start: the state of the dfa to start matching in
+ *
+ * aa_dfa_null_transition transitions to the next state after a null
+ * character which is not used in standard matching and is only
+ * used to separate pairs.
+ */
+static inline unsigned int aa_dfa_null_transition(struct aa_dfa *dfa,
+						  unsigned int start)
+{
+	/* the null transition only needs the string's null terminator byte */
+	return aa_dfa_match_len(dfa, start, "", 1);
+}
+
+static inline bool mediated_filesystem(struct inode *inode)
+{
+	return !(inode->i_sb->s_flags & MS_NOUSER);
+}
+
+#endif /* __APPARMOR_H */
security/apparmor/include/path.h new file +31 -0
new file mode 100644
index 0000000..27b327a
@@ -0,0 +1,31 @@
+/*
+ * AppArmor security module
+ *
+ * This file contains AppArmor basic path manipulation function definitions.
+ *
+ * Copyright (C) 1998-2008 Novell/SUSE
+ * Copyright 2009-2010 Canonical Ltd.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, version 2 of the
+ * License.
+ */
+
+#ifndef __AA_PATH_H
+#define __AA_PATH_H
+
+
+enum path_flags {
+	PATH_IS_DIR = 0x1,		/* path is a directory */
+	PATH_CONNECT_PATH = 0x4,	/* connect disconnected paths to / */
+	PATH_CHROOT_REL = 0x8,		/* do path lookup relative to chroot */
+	PATH_CHROOT_NSCONNECT = 0x10,	/* connect paths that are at ns root */
+
+	PATH_DELEGATE_DELETED = 0x08000, /* delegate deleted files */
+	PATH_MEDIATE_DELETED = 0x10000,	/* mediate deleted paths */
+};
+
+int aa_get_name(struct path *path, int flags, char **buffer, const char **name);
+
+#endif /* __AA_PATH_H */
security/apparmor/lib.c new file +133 -0

133 lines not on this page · raw message

security/apparmor/path.c new file +235 -0

235 lines not on this page · raw message

Signature · 1 line
1.7.1
#2 lore raw

Re: [PATCH 01/13] AppArmor: misc. base functions and defines

Quoted 9 lines · John Johansen
security/apparmor/lib.c new file +9 -0
+/**
+ * kvmalloc - do allocation preferring kmalloc but falling back to vmalloc
+ * @size: size of allocation
+ *
+ * Return: allocated buffer or NULL if failed
+ *
+ * It is possible that policy being loaded from the user is larger than
+ * what can be allocated by kmalloc, in those cases fall back to vmalloc.
+ */

security/apparmor/lib.c line 91

Quoted 10 lines
security/apparmor/lib.c new file +10 -0
+void *kvmalloc(size_t size)
+{
+       void *buffer = NULL;
+
+       if (size == 0)
+               return NULL;
+
+       /* do not attempt kmalloc if we need more than 16 pages at once */
+       if (size <= (16*PAGE_SIZE))
+               buffer = kmalloc(size, GFP_NOIO | __GFP_NOWARN);

16 pages is a lot of memory for 64 K pages. What's the purpose of GFP_NOIO here? vmalloc() will do GFP_KERNEL allocations anyway.

Quoted 10 lines

+       if (!buffer) {
+               /* see kvfree for why size must be at least work_struct size
+                * when allocated via vmalloc
+                */
+               if (size < sizeof(struct work_struct))
+                       size = sizeof(struct work_struct);
+               buffer = vmalloc(size);
+       }
+       return buffer;
+}

Please don't hide this into apparmor internals. People have invented this function in the past so maybe it's time to put it in mm/util.c?

Quoted 19 lines
security/apparmor/lib.c new file +19 -0
+
+/**
+ * do_vfree - workqueue routine for freeing vmalloced memory
+ * @work: data to be freed
+ *
+ * The work_struct is overlaid to the data being freed, as at the point
+ * the work is scheduled the data is no longer valid, be its freeing
+ * needs to be delayed until safe.
+ */
+static void do_vfree(struct work_struct *work)
+{
+       vfree(work);
+}
+
+/**
+ * kvfree - free an allocation do by kvmalloc
+ * @buffer: buffer to free (MAYBE_NULL)
+ *
+ * Free a buffer allocated by kvmalloc

security/apparmor/lib.c line 130

Quoted 10 lines
security/apparmor/lib.c new file +10 -0
+ */
+void kvfree(void *buffer)
+{
+       if (is_vmalloc_addr(buffer)) {
+               /* Data is no longer valid so just use the allocated space
+                * as the work_struct
+                */
+               struct work_struct *work = (struct work_struct *) buffer;
+               INIT_WORK(work, do_vfree);
+               schedule_work(work);

I don't understand this part here. Is it needed for interrupt contexts or does vfree() sleep somewhere? If it's for the former, I think we can just add a comment saying that kvmalloc/kvfree is not safe from interrupt context and remove the schedule_work() parts here.

Quoted 3 lines

+       } else
+               kfree(buffer);
+}

author maintainer
#3 lore raw

Re: [PATCH 01/13] AppArmor: misc. base functions and defines

Quoted 15 lines · Pekka Enberg
Quoted 13 lines · John Johansen
security/apparmor/lib.c new file +13 -0
+/**
+ * kvmalloc - do allocation preferring kmalloc but falling back to vmalloc
+ * @size: size of allocation
+ *
+ * Return: allocated buffer or NULL if failed
+ *
+ * It is possible that policy being loaded from the user is larger than
+ * what can be allocated by kmalloc, in those cases fall back to vmalloc.
+ */
+void *kvmalloc(size_t size)
+{
+       void *buffer = NULL;
+
Quoted 8 lines

security/apparmor/lib.c line 91

Quoted 6 lines
security/apparmor/lib.c new file +6 -0
+       if (size == 0)
+               return NULL;
+
+       /* do not attempt kmalloc if we need more than 16 pages at once */
+       if (size <= (16*PAGE_SIZE))
+               buffer = kmalloc(size, GFP_NOIO | __GFP_NOWARN);

16 pages is a lot of memory for 64 K pages. What's the purpose of

yes it is, and I don't expect it will every allocate that much, though it will occassionally with large policies do allocations larger than 16*4K. The figure here is some what arbitrary, and I would certainly be willing to shrink it. Basically it is there to put a clamp on allocating precious physically contiguous memory.

Quoted 2 lines

GFP_NOIO here? vmalloc() will do GFP_KERNEL allocations anyway.

yep, and it used to be GFP_KERNEL too, looking back GFP_NOIO happend when poking at a bug where apparmor was trigger a IO when it was allocating its memory. Turned out the bug wasn't apparmor related just being triggered while apparmor was loading policy, but the GFP_NOIO flag stuck here. I am more than willing to flip it back.

Quoted 11 lines

security/apparmor/lib.c line 101

Quoted 10 lines
security/apparmor/lib.c new file +10 -0
+       if (!buffer) {
+               /* see kvfree for why size must be at least work_struct size
+                * when allocated via vmalloc
+                */
+               if (size < sizeof(struct work_struct))
+                       size = sizeof(struct work_struct);
+               buffer = vmalloc(size);
+       }
+       return buffer;
+}
Quoted 3 lines

Please don't hide this into apparmor internals. People have invented this function in the past so maybe it's time to put it in mm/util.c?

sure, I would be more than willing to replace this with a generic system fn. The last attempt I saw at adding generic routines of this nature was here
http://www.spinics.net/lists/linux-fsdevel/msg31407.html

Quoted 26 lines
Quoted 26 lines
security/apparmor/lib.c new file +26 -0
+
+/**
+ * do_vfree - workqueue routine for freeing vmalloced memory
+ * @work: data to be freed
+ *
+ * The work_struct is overlaid to the data being freed, as at the point
+ * the work is scheduled the data is no longer valid, be its freeing
+ * needs to be delayed until safe.
+ */
+static void do_vfree(struct work_struct *work)
+{
+       vfree(work);
+}
+
+/**
+ * kvfree - free an allocation do by kvmalloc
+ * @buffer: buffer to free (MAYBE_NULL)
+ *
+ * Free a buffer allocated by kvmalloc
+ */
+void kvfree(void *buffer)
+{
+       if (is_vmalloc_addr(buffer)) {
+               /* Data is no longer valid so just use the allocated space
+                * as the work_struct
+                */
Quoted 9 lines

security/apparmor/lib.c line 130

Quoted 3 lines
security/apparmor/lib.c new file +3 -0
+               struct work_struct *work = (struct work_struct *) buffer;
+               INIT_WORK(work, do_vfree);
+               schedule_work(work);

I don't understand this part here. Is it needed for interrupt contexts or does vfree() sleep somewhere? If it's for the former, I think we can just add a comment saying that kvmalloc/kvfree is not safe from interrupt context and remove the schedule_work() parts here.

vfree can sleep, and skipping the schedule_work parts won't work for apparmor as many of these allocations are being freed via rcu callbacks as most of our object life cycles are dependent on cred refcounting.

#4 lore raw

Re: [PATCH 01/13] AppArmor: misc. base functions and defines

Quoted 21 lines · John Johansen
Quoted 12 lines
Quoted 12 lines
security/apparmor/lib.c new file +12 -0
+/**
+ * kvfree - free an allocation do by kvmalloc
+ * @buffer: buffer to free (MAYBE_NULL)
+ *
+ * Free a buffer allocated by kvmalloc
+ */
+void kvfree(void *buffer)
+{
+       if (is_vmalloc_addr(buffer)) {
+               /* Data is no longer valid so just use the allocated space
+                * as the work_struct
+                */
Quoted 8 lines
Quoted 3 lines

+               struct work_struct *work = (struct work_struct *) buffer;
+               INIT_WORK(work, do_vfree);
+               schedule_work(work);

I don't understand this part here. Is it needed for interrupt contexts or does vfree() sleep somewhere? If it's for the former, I think we can just add a comment saying that kvmalloc/kvfree is not safe from interrupt context and remove the schedule_work() parts here.

Quoted 3 lines

vfree can sleep, and skipping the schedule_work parts won't work for apparmor as many of these allocations are being freed via rcu callbacks as most of our object life cycles are dependent on cred refcounting.

Can someone point me to where vfree() actually sleeps? I'm unable to find the exact spot.

#5 lore raw

Re: [PATCH 01/13] AppArmor: misc. base functions and defines

Quoted 9 lines · Pekka Enberg

On Fri, Jul 30, 2010 at 1:01 PM, John Johansen

Quoted 4 lines

vfree can sleep, and skipping the schedule_work parts won't work for apparmor as many of these allocations are being freed via rcu callbacks as most of our object life cycles are dependent on cred refcounting.

Can someone point me to where vfree() actually sleeps? I'm unable to find the exact spot.

http://lxr.linux.no/linux+v2.6.34.1/mm/vmalloc.c#L1405 . vfree -> __vunmap, vunmap -> __vunmap, and there is a might_sleep() function in vunmap.

BTW: I'll respin the kvmalloc patch later.

Thanks.

Signature · 2 lines
Regards,
Changli Gao([email protected])
#6 lore raw

Re: [PATCH 01/13] AppArmor: misc. base functions and defines

Quoted 7 lines · Changli Gao
Quoted 6 lines · Pekka Enberg

On Fri, Jul 30, 2010 at 1:01 PM, John Johansen

Quoted 4 lines

vfree can sleep, and skipping the schedule_work parts won't work for apparmor as many of these allocations are being freed via rcu callbacks as most of our object life cycles are dependent on cred refcounting.

Quoted 6 lines
Quoted 2 lines

Can someone point me to where vfree() actually sleeps? I'm unable to find the exact spot.

http://lxr.linux.no/linux+v2.6.34.1/mm/vmalloc.c#L1405 . vfree -> __vunmap, vunmap -> __vunmap, and there is a might_sleep() function in vunmap.

Yes, but that doesn't answer my question. Where's the actual call-site that can sleep? I can't find it!

Quoted 1 line

BTW: I'll respin the kvmalloc patch later.

Great!

author maintainer
#7 lore raw

PATCH 2/13 AppArmor: basic auditing infrastructure.

In reply to John Johansen

Update lsm_audit for AppArmor specific data, and add the core routines for AppArmor uses for auditing.

---
 include/linux/lsm_audit.h         |   27 +++++
 security/apparmor/audit.c         |  215 +++++++++++++++++++++++++++++++++++++
 security/apparmor/include/audit.h |  123 +++++++++++++++++++++
 3 files changed, 365 insertions(+), 0 deletions(-)
 create mode 100644 security/apparmor/audit.c
 create mode 100644 security/apparmor/include/audit.h
include/linux/lsm_audit.h +27 -0
index 6907251..13b5c9a 100644
@@ -94,6 +94,33 @@ struct common_audit_data {
 			int result;
 		} selinux_audit_data;
 #endif
+#ifdef CONFIG_SECURITY_APPARMOR
+		struct {
+			int error;
+			int op;
+			int type;
+			void *profile;
+			const char *name;
+			const char *info;
+			union {
+				void *target;
+				struct {
+					long pos;
+					void *target;
+				} iface;
+				struct {
+					int rlim;
+					unsigned long max;
+				} rlim;
+				struct {
+					const char *target;
+					u32 request;
+					u32 denied;
+					uid_t ouid;
+				} fs;
+			};
+		} apparmor_audit_data;
+#endif
 	};
 	/* these callback will be implemented by a specific LSM */
 	void (*lsm_pre_audit)(struct audit_buffer *, void *);
security/apparmor/audit.c new file +215 -0

215 lines not on this page · raw message

security/apparmor/include/audit.h new file +123 -0

123 lines not on this page · raw message

Signature · 1 line
1.7.1
author maintainer
#8 lore raw

PATCH 3/13 AppArmor: contexts used in attaching policy to system objects

In reply to John Johansen

AppArmor contexts attach profiles and state to tasks, files, etc. when a direct profile reference is not sufficient.

---
 security/apparmor/context.c         |  216 +++++++++++++++++++++++++++++++++++
 security/apparmor/include/context.h |  154 +++++++++++++++++++++++++
 2 files changed, 370 insertions(+), 0 deletions(-)
 create mode 100644 security/apparmor/context.c
 create mode 100644 security/apparmor/include/context.h
security/apparmor/context.c new file +216 -0
new file mode 100644
index 0000000..8a9b502
@@ -0,0 +1,216 @@
+/*
+ * AppArmor security module
+ *
+ * This file contains AppArmor functions used to manipulate object security
+ * contexts.
+ *
+ * Copyright (C) 1998-2008 Novell/SUSE
+ * Copyright 2009-2010 Canonical Ltd.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, version 2 of the
+ * License.
+ *
+ *
+ * AppArmor sets confinement on every task, via the the aa_task_cxt and
+ * the aa_task_cxt.profile, both of which are required and are not allowed
+ * to be NULL.  The aa_task_cxt is not reference counted and is unique
+ * to each cred (which is reference count).  The profile pointed to by
+ * the task_cxt is reference counted.
+ *
+ * TODO
+ * If a task uses change_hat it currently does not return to the old
+ * cred or task context but instead creates a new one.  Ideally the task
+ * should return to the previous cred if it has not been modified.
+ *
+ */
+
+#include "include/context.h"
+#include "include/policy.h"
+
+/**
+ * aa_alloc_task_context - allocate a new task_cxt
+ * @flags: gfp flags for allocation
+ *
+ * Returns: allocated buffer or NULL on failure
+ */
+struct aa_task_cxt *aa_alloc_task_context(gfp_t flags)
+{
+	return kzalloc(sizeof(struct aa_task_cxt), flags);
+}
+
+/**
+ * aa_free_task_context - free a task_cxt
+ * @cxt: task_cxt to free (MAYBE NULL)
+ */
+void aa_free_task_context(struct aa_task_cxt *cxt)
+{
+	if (cxt) {
+		aa_put_profile(cxt->profile);
+		aa_put_profile(cxt->previous);
+		aa_put_profile(cxt->onexec);
+
+		kzfree(cxt);
+	}
+}
+
+/**
+ * aa_dup_task_context - duplicate a task context, incrementing reference counts
+ * @new: a blank task context      (NOT NULL)
+ * @old: the task context to copy  (NOT NULL)
+ */
+void aa_dup_task_context(struct aa_task_cxt *new, const struct aa_task_cxt *old)
+{
+	*new = *old;
+	aa_get_profile(new->profile);
+	aa_get_profile(new->previous);
+	aa_get_profile(new->onexec);
+}
+
+/**
+ * aa_replace_current_profile - replace the current tasks profiles
+ * @profile: new profile  (NOT NULL)
+ *
+ * Returns: 0 or error on failure
+ */
+int aa_replace_current_profile(struct aa_profile *profile)
+{
+	struct aa_task_cxt *cxt = current_cred()->security;
+	struct cred *new;
+	BUG_ON(!profile);
+
+	if (cxt->profile == profile)
+		return 0;
+
+	new  = prepare_creds();
+	if (!new)
+		return -ENOMEM;
+
+	cxt = new->security;
+	if (unconfined(profile) || (cxt->profile->ns != profile->ns)) {
+		/* if switching to unconfined or a different profile namespace
+		 * clear out context state
+		 */
+		aa_put_profile(cxt->previous);
+		aa_put_profile(cxt->onexec);
+		cxt->previous = NULL;
+		cxt->onexec = NULL;
+		cxt->token = 0;
+	}
+	/* be careful switching cxt->profile, when racing replacement it
+	 * is possible that cxt->profile->replacedby is the reference keeping
+	 * @profile valid, so make sure to get its reference before dropping
+	 * the reference on cxt->profile */
+	aa_get_profile(profile);
+	aa_put_profile(cxt->profile);
+	cxt->profile = profile;
+
+	commit_creds(new);
+	return 0;
+}
+
+/**
+ * aa_set_current_onexec - set the tasks change_profile to happen onexec
+ * @profile: system profile to set at exec  (MAYBE NULL to clear value)
+ *
+ * Returns: 0 or error on failure
+ */
+int aa_set_current_onexec(struct aa_profile *profile)
+{
+	struct aa_task_cxt *cxt;
+	struct cred *new = prepare_creds();
+	if (!new)
+		return -ENOMEM;
+
+	cxt = new->security;
+	aa_get_profile(profile);
+	aa_put_profile(cxt->onexec);
+	cxt->onexec = profile;
+
+	commit_creds(new);
+	return 0;
+}
+
+/**
+ * aa_set_current_hat - set the current tasks hat
+ * @profile: profile to set as the current hat  (NOT NULL)
+ * @token: token value that must be specified to change from the hat
+ *
+ * Do switch of tasks hat.  If the task is currently in a hat
+ * validate the token to match.
+ *
+ * Returns: 0 or error on failure
+ */
+int aa_set_current_hat(struct aa_profile *profile, u64 token)
+{
+	struct aa_task_cxt *cxt;
+	struct cred *new = prepare_creds();
+	if (!new)
+		return -ENOMEM;
+	BUG_ON(!profile);
+
+	cxt = new->security;
+	if (!cxt->previous) {
+		/* transfer refcount */
+		cxt->previous = cxt->profile;
+		cxt->token = token;
+	} else if (cxt->token == token) {
+		aa_put_profile(cxt->profile);
+	} else {
+		/* previous_profile && cxt->token != token */
+		abort_creds(new);
+		return -EACCES;
+	}
+	cxt->profile = aa_get_profile(aa_newest_version(profile));
+	/* clear exec on switching context */
+	aa_put_profile(cxt->onexec);
+	cxt->onexec = NULL;
+
+	commit_creds(new);
+	return 0;
+}
+
+/**
+ * aa_restore_previous_profile - exit from hat context restoring the profile
+ * @token: the token that must be matched to exit hat context
+ *
+ * Attempt to return out of a hat to the previous profile.  The token
+ * must match the stored token value.
+ *
+ * Returns: 0 or error of failure
+ */
+int aa_restore_previous_profile(u64 token)
+{
+	struct aa_task_cxt *cxt;
+	struct cred *new = prepare_creds();
+	if (!new)
+		return -ENOMEM;
+
+	cxt = new->security;
+	if (cxt->token != token) {
+		abort_creds(new);
+		return -EACCES;
+	}
+	/* ignore restores when there is no saved profile */
+	if (!cxt->previous) {
+		abort_creds(new);
+		return 0;
+	}
+
+	aa_put_profile(cxt->profile);
+	cxt->profile = aa_newest_version(cxt->previous);
+	BUG_ON(!cxt->profile);
+	if (unlikely(cxt->profile != cxt->previous)) {
+		aa_get_profile(cxt->profile);
+		aa_put_profile(cxt->previous);
+	}
+	/* clear exec && prev information when restoring to previous context */
+	cxt->previous = NULL;
+	cxt->token = 0;
+	aa_put_profile(cxt->onexec);
+	cxt->onexec = NULL;
+
+	commit_creds(new);
+	return 0;
+}
security/apparmor/include/context.h new file +154 -0

154 lines not on this page · raw message

Signature · 1 line
1.7.1
author maintainer
#9 lore raw

PATCH 4/13 AppArmor: core policy routines

In reply to John Johansen

The basic routines and defines for AppArmor policy. AppArmor policy is defined by a few basic components.
profiles - the basic unit of confinement contain all the information
to enforce policy on a task

Profiles tend to be named after an executable that they will attach to but this is not required.
namespaces - a container for a set of profiles that will be used
during attachment and transitions between profiles.
sids - which provide a unique id for each profile

---
 security/apparmor/include/policy.h |  305 +++++++++
 security/apparmor/include/sid.h    |   24 +
 security/apparmor/policy.c         | 1184 ++++++++++++++++++++++++++++++++++++
 security/apparmor/sid.c            |   55 ++
 4 files changed, 1568 insertions(+), 0 deletions(-)
 create mode 100644 security/apparmor/include/policy.h
 create mode 100644 security/apparmor/include/sid.h
 create mode 100644 security/apparmor/policy.c
 create mode 100644 security/apparmor/sid.c
security/apparmor/include/policy.h new file +305 -0
new file mode 100644
index 0000000..aeda5cf
@@ -0,0 +1,305 @@
+/*
+ * AppArmor security module
+ *
+ * This file contains AppArmor policy definitions.
+ *
+ * Copyright (C) 1998-2008 Novell/SUSE
+ * Copyright 2009-2010 Canonical Ltd.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, version 2 of the
+ * License.
+ */
+
+#ifndef __AA_POLICY_H
+#define __AA_POLICY_H
+
+#include <linux/capability.h>
+#include <linux/cred.h>
+#include <linux/kref.h>
+#include <linux/sched.h>
+#include <linux/slab.h>
+#include <linux/socket.h>
+
+#include "apparmor.h"
+#include "audit.h"
+#include "capability.h"
+#include "domain.h"
+#include "file.h"
+#include "resource.h"
+
+extern const char *profile_mode_names[];
+#define APPARMOR_NAMES_MAX_INDEX 3
+
+#define COMPLAIN_MODE(_profile)	\
+	((aa_g_profile_mode == APPARMOR_COMPLAIN) || \
+	 ((_profile)->mode == APPARMOR_COMPLAIN))
+
+#define KILL_MODE(_profile) \
+	((aa_g_profile_mode == APPARMOR_KILL) || \
+	 ((_profile)->mode == APPARMOR_KILL))
+
+#define PROFILE_IS_HAT(_profile) ((_profile)->flags & PFLAG_HAT)
+
+/*
+ * FIXME: currently need a clean way to replace and remove profiles as a
+ * set.  It should be done at the namespace level.
+ * Either, with a set of profiles loaded at the namespace level or via
+ * a mark and remove marked interface.
+ */
+enum profile_mode {
+	APPARMOR_ENFORCE,	/* enforce access rules */
+	APPARMOR_COMPLAIN,	/* allow and log access violations */
+	APPARMOR_KILL,		/* kill task on access violation */
+};
+
+enum profile_flags {
+	PFLAG_HAT = 1,			/* profile is a hat */
+	PFLAG_UNCONFINED = 2,		/* profile is an unconfined profile */
+	PFLAG_NULL = 4,			/* profile is null learning profile */
+	PFLAG_IX_ON_NAME_ERROR = 8,	/* fallback to ix on name lookup fail */
+	PFLAG_IMMUTABLE = 0x10,		/* don't allow changes/replacement */
+	PFLAG_USER_DEFINED = 0x20,	/* user based profile - lower privs */
+	PFLAG_NO_LIST_REF = 0x40,	/* list doesn't keep profile ref */
+	PFLAG_OLD_NULL_TRANS = 0x100,	/* use // as the null transition */
+
+	/* These flags must correspond with PATH_flags */
+	PFLAG_MEDIATE_DELETED = 0x10000, /* mediate instead delegate deleted */
+};
+
+struct aa_profile;
+
+/* struct aa_policy - common part of both namespaces and profiles
+ * @name: name of the object
+ * @hname - The hierarchical name
+ * @count: reference count of the obj
+ * @list: list policy object is on
+ * @profiles: head of the profiles list contained in the object
+ */
+struct aa_policy {
+	char *name;
+	char *hname;
+	struct kref count;
+	struct list_head list;
+	struct list_head profiles;
+};
+
+/* struct aa_ns_acct - accounting of profiles in namespace
+ * @max_size: maximum space allowed for all profiles in namespace
+ * @max_count: maximum number of profiles that can be in this namespace
+ * @size: current size of profiles
+ * @count: current count of profiles (includes null profiles)
+ */
+struct aa_ns_acct {
+	int max_size;
+	int max_count;
+	int size;
+	int count;
+};
+
+/* struct aa_namespace - namespace for a set of profiles
+ * @base: common policy
+ * @parent: parent of namespace
+ * @lock: lock for modifying the object
+ * @acct: accounting for the namespace
+ * @unconfined: special unconfined profile for the namespace
+ * @sub_ns: list of namespaces under the current namespace.
+ *
+ * An aa_namespace defines the set profiles that are searched to determine
+ * which profile to attach to a task.  Profiles can not be shared between
+ * aa_namespaces and profile names within a namespace are guaranteed to be
+ * unique.  When profiles in separate namespaces have the same name they
+ * are NOT considered to be equivalent.
+ *
+ * Namespaces are hierarchical and only namespaces and profiles below the
+ * current namespace are visible.
+ *
+ * Namespace names must be unique and can not contain the characters :/\0
+ *
+ * FIXME TODO: add vserver support of namespaces (can it all be done in
+ *             userspace?)
+ */
+struct aa_namespace {
+	struct aa_policy base;
+	struct aa_namespace *parent;
+	rwlock_t lock;
+	struct aa_ns_acct acct;
+	struct aa_profile *unconfined;
+	struct list_head sub_ns;
+};
+
+/* struct aa_profile - basic confinement data
+ * @base - base components of the profile (name, refcount, lists, lock ...)
+ * @parent: parent of profile
+ * @ns: namespace the profile is in
+ * @replacedby: is set to the profile that replaced this profile
+ * @rename: optional profile name that this profile renamed
+ * @xmatch: optional extended matching for unconfined executables names
+ * @xmatch_len: xmatch prefix len, used to determine xmatch priority
+ * @sid: the unique security id number of this profile
+ * @audit: the auditing mode of the profile
+ * @mode: the enforcement mode of the profile
+ * @flags: flags controlling profile behavior
+ * @path_flags: flags controlling path generation behavior
+ * @size: the memory consumed by this profiles rules
+ * @file: The set of rules governing basic file access and domain transitions
+ * @caps: capabilities for the profile
+ * @rlimits: rlimits for the profile
+ *
+ * The AppArmor profile contains the basic confinement data.  Each profile
+ * has a name, and exists in a namespace.  The @name and @exec_match are
+ * used to determine profile attachment against unconfined tasks.  All other
+ * attachments are determined by profile X transition rules.
+ *
+ * The @replacedby field is write protected by the profile lock.  Reads
+ * are assumed to be atomic, and are done without locking.
+ *
+ * Profiles have a hierarchy where hats and children profiles keep
+ * a reference to their parent.
+ *
+ * Profile names can not begin with a : and can not contain the \0
+ * character.  If a profile name begins with / it will be considered when
+ * determining profile attachment on "unconfined" tasks.
+ */
+struct aa_profile {
+	struct aa_policy base;
+	struct aa_profile *parent;
+
+	struct aa_namespace *ns;
+	struct aa_profile *replacedby;
+	const char *rename;
+
+	struct aa_dfa *xmatch;
+	int xmatch_len;
+	u32 sid;
+	enum audit_mode audit;
+	enum profile_mode mode;
+	u32 flags;
+	u32 path_flags;
+	int size;
+
+	struct aa_file_rules file;
+	struct aa_caps caps;
+	struct aa_rlimit rlimits;
+};
+
+extern struct aa_namespace *root_ns;
+extern enum profile_mode aa_g_profile_mode;
+
+void aa_add_profile(struct aa_policy *common, struct aa_profile *profile);
+
+bool aa_ns_visible(struct aa_namespace *curr, struct aa_namespace *view);
+const char *aa_ns_name(struct aa_namespace *parent, struct aa_namespace *child);
+int aa_alloc_root_ns(void);
+void aa_free_root_ns(void);
+void aa_free_namespace_kref(struct kref *kref);
+
+struct aa_namespace *aa_find_namespace(struct aa_namespace *root,
+				       const char *name);
+
+static inline struct aa_policy *aa_get_common(struct aa_policy *c)
+{
+	if (c)
+		kref_get(&c->count);
+
+	return c;
+}
+
+/**
+ * aa_get_namespace - increment references count on @ns
+ * @ns: namespace to increment reference count of (MAYBE NULL)
+ *
+ * Returns: pointer to @ns, if @ns is NULL returns NULL
+ * Requires: @ns must be held with valid refcount when called
+ */
+static inline struct aa_namespace *aa_get_namespace(struct aa_namespace *ns)
+{
+	if (ns)
+		kref_get(&(ns->base.count));
+
+	return ns;
+}
+
+/**
+ * aa_put_namespace - decrement refcount on @ns
+ * @ns: namespace to put reference of
+ *
+ * Decrement reference count of @ns and if no longer in use free it
+ */
+static inline void aa_put_namespace(struct aa_namespace *ns)
+{
+	if (ns)
+		kref_put(&ns->base.count, aa_free_namespace_kref);
+}
+
+struct aa_profile *aa_alloc_profile(const char *name);
+struct aa_profile *aa_new_null_profile(struct aa_profile *parent, int hat);
+void aa_free_profile_kref(struct kref *kref);
+struct aa_profile *aa_find_child(struct aa_profile *parent, const char *name);
+struct aa_profile *aa_lookup_profile(struct aa_namespace *ns, const char *name);
+struct aa_profile *aa_match_profile(struct aa_namespace *ns, const char *name);
+
+ssize_t aa_replace_profiles(void *udata, size_t size, bool noreplace);
+ssize_t aa_remove_profiles(char *name, size_t size);
+
+#define PROF_ADD 1
+#define PROF_REPLACE 0
+
+#define unconfined(X) ((X)->flags & PFLAG_UNCONFINED)
+
+/**
+ * aa_newest_version - find the newest version of @profile
+ * @profile: the profile to check for newer versions of (NOT NULL)
+ *
+ * Returns: newest version of @profile, if @profile is the newest version
+ *          return @profile.
+ *
+ * NOTE: the profile returned is not refcounted, The refcount on @profile
+ * must be held until the caller decides what to do with the returned newest
+ * version.
+ */
+static inline struct aa_profile *aa_newest_version(struct aa_profile *profile)
+{
+	while (profile->replacedby)
+		profile = profile->replacedby;
+
+	return profile;
+}
+
+/**
+ * aa_get_profile - increment refcount on profile @p
+ * @p: profile  (MAYBE NULL)
+ *
+ * Returns: pointer to @p if @p is NULL will return NULL
+ * Requires: @p must be held with valid refcount when called
+ */
+static inline struct aa_profile *aa_get_profile(struct aa_profile *p)
+{
+	if (p)
+		kref_get(&(p->base.count));
+
+	return p;
+}
+
+/**
+ * aa_put_profile - decrement refcount on profile @p
+ * @p: profile  (MAYBE NULL)
+ */
+static inline void aa_put_profile(struct aa_profile *p)
+{
+	if (p)
+		kref_put(&p->base.count, aa_free_profile_kref);
+}
+
+static inline int AUDIT_MODE(struct aa_profile *profile)
+{
+	if (aa_g_audit != AUDIT_NORMAL)
+		return aa_g_audit;
+
+	return profile->audit;
+}
+
+bool aa_may_manage_policy(int op);
+
+#endif /* __AA_POLICY_H */
security/apparmor/include/sid.h new file +24 -0
new file mode 100644
index 0000000..020db35
@@ -0,0 +1,24 @@
+/*
+ * AppArmor security module
+ *
+ * This file contains AppArmor security identifier (sid) definitions
+ *
+ * Copyright 2009-2010 Canonical Ltd.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, version 2 of the
+ * License.
+ */
+
+#ifndef __AA_SID_H
+#define __AA_SID_H
+
+#include <linux/types.h>
+
+struct aa_profile;
+
+u32 aa_alloc_sid(void);
+void aa_free_sid(u32 sid);
+
+#endif /* __AA_SID_H */
security/apparmor/policy.c new file +1184 -0

1,184 lines not on this page · raw message

security/apparmor/sid.c new file +55 -0

55 lines not on this page · raw message

Signature · 1 line
1.7.1
author maintainer
#10 lore raw

PATCH 5/13 AppArmor: dfa match engine

In reply to John Johansen

A basic dfa matching engine based off the dfa engine in the Dragon Book. It uses simple row comb compression with a check field.

This allows AppArmor to do pattern matching in linear time, and also avoids stack issues that an nfa based engine may have. The dfa engine uses a byte based comparison, with all values being valid. Any potential character encoding are handled user side when the dfa tables are created. By convention AppArmor uses \0 to separate two dependent path matches since \0 is not a valid path character (this is done in the link permission check).

The dfa tables are generated in user space and are verified at load time to be internally consistent.

There are several future improvements planned for the dfa engine:
* The dfa engine may be converted to a hybrid nfa-dfa engine, with a fixed size limited stack. This would allow for size time tradeoffs, by inserting limited nfa states to help control state explosion that can occur with dfas.
* The dfa engine may pickup the ability to do limited dynamic variable matching, instead of fixing all variables at policy load time.

---
 security/apparmor/include/match.h |  132 ++++++++++++++
 security/apparmor/match.c         |  353 +++++++++++++++++++++++++++++++++++++
 2 files changed, 485 insertions(+), 0 deletions(-)
 create mode 100644 security/apparmor/include/match.h
 create mode 100644 security/apparmor/match.c
security/apparmor/include/match.h new file +132 -0
new file mode 100644
index 0000000..734a6d3
@@ -0,0 +1,132 @@
+/*
+ * AppArmor security module
+ *
+ * This file contains AppArmor policy dfa matching engine definitions.
+ *
+ * Copyright (C) 1998-2008 Novell/SUSE
+ * Copyright 2009-2010 Canonical Ltd.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, version 2 of the
+ * License.
+ */
+
+#ifndef __AA_MATCH_H
+#define __AA_MATCH_H
+
+#include <linux/workqueue.h>
+
+#define DFA_NOMATCH			0
+#define DFA_START			1
+
+#define DFA_VALID_PERM_MASK		0xffffffff
+#define DFA_VALID_PERM2_MASK		0xffffffff
+
+/**
+ * The format used for transition tables is based on the GNU flex table
+ * file format (--tables-file option; see Table File Format in the flex
+ * info pages and the flex sources for documentation). The magic number
+ * used in the header is 0x1B5E783D insted of 0xF13C57B1 though, because
+ * the YY_ID_CHK (check) and YY_ID_DEF (default) tables are used
+ * slightly differently (see the apparmor-parser package).
+ */
+
+#define YYTH_MAGIC	0x1B5E783D
+#define YYTH_DEF_RECURSE 0x1			/* DEF Table is recursive */
+
+struct table_set_header {
+	u32 th_magic;		/* YYTH_MAGIC */
+	u32 th_hsize;
+	u32 th_ssize;
+	u16 th_flags;
+	char th_version[];
+};
+
+/* The YYTD_ID are one less than flex table mappings.  The flex id
+ * has 1 subtracted at table load time, this allows us to directly use the
+ * ID's as indexes.
+ */
+#define	YYTD_ID_ACCEPT	0
+#define YYTD_ID_BASE	1
+#define YYTD_ID_CHK	2
+#define YYTD_ID_DEF	3
+#define YYTD_ID_EC	4
+#define YYTD_ID_META	5
+#define YYTD_ID_ACCEPT2 6
+#define YYTD_ID_NXT	7
+#define YYTD_ID_TSIZE	8
+
+#define YYTD_DATA8	1
+#define YYTD_DATA16	2
+#define YYTD_DATA32	4
+#define YYTD_DATA64	8
+
+/* Each ACCEPT2 table gets 6 dedicated flags, YYTD_DATAX define the
+ * first flags
+ */
+#define ACCEPT1_FLAGS(X) ((X) & 0x3f)
+#define ACCEPT2_FLAGS(X) ACCEPT1_FLAGS((X) >> YYTD_ID_ACCEPT2)
+#define TO_ACCEPT1_FLAG(X) ACCEPT1_FLAGS(X)
+#define TO_ACCEPT2_FLAG(X) (ACCEPT1_FLAGS(X) << YYTD_ID_ACCEPT2)
+#define DFA_FLAG_VERIFY_STATES 0x1000
+
+struct table_header {
+	u16 td_id;
+	u16 td_flags;
+	u32 td_hilen;
+	u32 td_lolen;
+	char td_data[];
+};
+
+#define DEFAULT_TABLE(DFA) ((u16 *)((DFA)->tables[YYTD_ID_DEF]->td_data))
+#define BASE_TABLE(DFA) ((u32 *)((DFA)->tables[YYTD_ID_BASE]->td_data))
+#define NEXT_TABLE(DFA) ((u16 *)((DFA)->tables[YYTD_ID_NXT]->td_data))
+#define CHECK_TABLE(DFA) ((u16 *)((DFA)->tables[YYTD_ID_CHK]->td_data))
+#define EQUIV_TABLE(DFA) ((u8 *)((DFA)->tables[YYTD_ID_EC]->td_data))
+#define ACCEPT_TABLE(DFA) ((u32 *)((DFA)->tables[YYTD_ID_ACCEPT]->td_data))
+#define ACCEPT_TABLE2(DFA) ((u32 *)((DFA)->tables[YYTD_ID_ACCEPT2]->td_data))
+
+struct aa_dfa {
+	struct kref count;
+	u16 flags;
+	struct table_header *tables[YYTD_ID_TSIZE];
+};
+
+#define byte_to_byte(X) (X)
+
+#define UNPACK_ARRAY(TABLE, BLOB, LEN, TYPE, NTOHX) \
+	do { \
+		typeof(LEN) __i; \
+		TYPE *__t = (TYPE *) TABLE; \
+		TYPE *__b = (TYPE *) BLOB; \
+		for (__i = 0; __i < LEN; __i++) { \
+			__t[__i] = NTOHX(__b[__i]); \
+		} \
+	} while (0)
+
+static inline size_t table_size(size_t len, size_t el_size)
+{
+	return ALIGN(sizeof(struct table_header) + len * el_size, 8);
+}
+
+struct aa_dfa *aa_dfa_unpack(void *blob, size_t size, int flags);
+unsigned int aa_dfa_match_len(struct aa_dfa *dfa, unsigned int start,
+			      const char *str, int len);
+unsigned int aa_dfa_match(struct aa_dfa *dfa, unsigned int start,
+			  const char *str);
+void aa_dfa_free_kref(struct kref *kref);
+
+/**
+ * aa_put_dfa - put a dfa refcount
+ * @dfa: dfa to put refcount   (MAYBE NULL)
+ *
+ * Requires: if @dfa != NULL that a valid refcount be held
+ */
+static inline void aa_put_dfa(struct aa_dfa *dfa)
+{
+	if (dfa)
+		kref_put(&dfa->count, aa_dfa_free_kref);
+}
+
+#endif /* __AA_MATCH_H */
security/apparmor/match.c new file +353 -0

353 lines not on this page · raw message

Signature · 1 line
1.7.1
author maintainer
#11 lore raw

PATCH 6/13 AppArmor: policy routines for loading and unpacking policy

In reply to John Johansen

AppArmor policy is loaded in a platform independent flattened binary stream. Verify and unpack the data converting it to the internal format needed for enforcement.

---
 security/apparmor/include/policy_unpack.h |   20 +
 security/apparmor/policy_unpack.c         |  703 +++++++++++++++++++++++++++++
 2 files changed, 723 insertions(+), 0 deletions(-)
 create mode 100644 security/apparmor/include/policy_unpack.h
 create mode 100644 security/apparmor/policy_unpack.c
security/apparmor/include/policy_unpack.h new file +20 -0
new file mode 100644
index 0000000..a2dccca
@@ -0,0 +1,20 @@
+/*
+ * AppArmor security module
+ *
+ * This file contains AppArmor policy loading interface function definitions.
+ *
+ * Copyright (C) 1998-2008 Novell/SUSE
+ * Copyright 2009-2010 Canonical Ltd.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, version 2 of the
+ * License.
+ */
+
+#ifndef __POLICY_INTERFACE_H
+#define __POLICY_INTERFACE_H
+
+struct aa_profile *aa_unpack(void *udata, size_t size, const char **ns);
+
+#endif /* __POLICY_INTERFACE_H */
security/apparmor/policy_unpack.c new file +703 -0

703 lines not on this page · raw message

Signature · 1 line
1.7.1
author maintainer
#12 lore raw

PATCH 7/13 AppArmor: userspace interfaces

In reply to John Johansen

The /proc/<pid>/attr/* interface is used for process introspection and commands. While the apparmorfs interface is used for global introspection and loading and removing policy.

The interface currently only contains the files necessary for loading policy, and will be extended in the future to include sysfs style single per file introspection inteface.

The old AppArmor 2.4 interface files have been removed into a compatibility patch, that distros can use to maintain backwards compatibility.

---
 security/apparmor/apparmorfs.c         |  239 ++++++++++++++++++++++++++++++++
 security/apparmor/include/apparmorfs.h |   20 +++
 security/apparmor/include/procattr.h   |   26 ++++
 security/apparmor/procattr.c           |  170 +++++++++++++++++++++++
 4 files changed, 455 insertions(+), 0 deletions(-)
 create mode 100644 security/apparmor/apparmorfs.c
 create mode 100644 security/apparmor/include/apparmorfs.h
 create mode 100644 security/apparmor/include/procattr.h
 create mode 100644 security/apparmor/procattr.c
security/apparmor/apparmorfs.c new file +239 -0
new file mode 100644
index 0000000..7320331
@@ -0,0 +1,239 @@
+/*
+ * AppArmor security module
+ *
+ * This file contains AppArmor /sys/kernel/security/apparmor interface functions
+ *
+ * Copyright (C) 1998-2008 Novell/SUSE
+ * Copyright 2009-2010 Canonical Ltd.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, version 2 of the
+ * License.
+ */
+
+#include <linux/security.h>
+#include <linux/vmalloc.h>
+#include <linux/module.h>
+#include <linux/seq_file.h>
+#include <linux/uaccess.h>
+#include <linux/namei.h>
+
+#include "include/apparmor.h"
+#include "include/apparmorfs.h"
+#include "include/audit.h"
+#include "include/context.h"
+#include "include/policy.h"
+
+/**
+ * aa_simple_write_to_buffer - common routine for getting policy from user
+ * @op: operation doing the user buffer copy
+ * @userbuf: user buffer to copy data from  (NOT NULL)
+ * @alloc_size: size of user buffer
+ * @copy_size: size of data to copy from user buffer
+ * @pos: position write is at in the file (NOT NULL)
+ *
+ * Returns: kernel buffer containing copy of user buffer data or an
+ *          ERR_PTR on failure.
+ */
+static char *aa_simple_write_to_buffer(int op, const char __user *userbuf,
+				       size_t alloc_size, size_t copy_size,
+				       loff_t *pos)
+{
+	char *data;
+
+	if (*pos != 0)
+		/* only writes from pos 0, that is complete writes */
+		return ERR_PTR(-ESPIPE);
+
+	/*
+	 * Don't allow profile load/replace/remove from profiles that don't
+	 * have CAP_MAC_ADMIN
+	 */
+	if (!aa_may_manage_policy(op))
+		return ERR_PTR(-EACCES);
+
+	/* freed by caller to simple_write_to_buffer */
+	data = kvmalloc(alloc_size);
+	if (data == NULL)
+		return ERR_PTR(-ENOMEM);
+
+	if (copy_from_user(data, userbuf, copy_size)) {
+		kvfree(data);
+		return ERR_PTR(-EFAULT);
+	}
+
+	return data;
+}
+
+
+/* .load file hook fn to load policy */
+static ssize_t profile_load(struct file *f, const char __user *buf, size_t size,
+			    loff_t *pos)
+{
+	char *data;
+	ssize_t error;
+
+	data = aa_simple_write_to_buffer(OP_PROF_LOAD, buf, size, size, pos);
+
+	error = PTR_ERR(data);
+	if (!IS_ERR(data)) {
+		error = aa_replace_profiles(data, size, PROF_ADD);
+		kvfree(data);
+	}
+
+	return error;
+}
+
+static const struct file_operations aa_fs_profile_load = {
+	.write = profile_load
+};
+
+/* .replace file hook fn to load and/or replace policy */
+static ssize_t profile_replace(struct file *f, const char __user *buf,
+			       size_t size, loff_t *pos)
+{
+	char *data;
+	ssize_t error;
+
+	data = aa_simple_write_to_buffer(OP_PROF_REPL, buf, size, size, pos);
+	error = PTR_ERR(data);
+	if (!IS_ERR(data)) {
+		error = aa_replace_profiles(data, size, PROF_REPLACE);
+		kvfree(data);
+	}
+
+	return error;
+}
+
+static const struct file_operations aa_fs_profile_replace = {
+	.write = profile_replace
+};
+
+/* .remove file hook fn to remove loaded policy */
+static ssize_t profile_remove(struct file *f, const char __user *buf,
+			      size_t size, loff_t *pos)
+{
+	char *data;
+	ssize_t error;
+
+	/*
+	 * aa_remove_profile needs a null terminated string so 1 extra
+	 * byte is allocated and the copied data is null terminated.
+	 */
+	data = aa_simple_write_to_buffer(OP_PROF_RM, buf, size + 1, size, pos);
+
+	error = PTR_ERR(data);
+	if (!IS_ERR(data)) {
+		data[size] = 0;
+		error = aa_remove_profiles(data, size);
+		kvfree(data);
+	}
+
+	return error;
+}
+
+static const struct file_operations aa_fs_profile_remove = {
+	.write = profile_remove
+};
+
+/** Base file system setup **/
+
+static struct dentry *aa_fs_dentry __initdata;
+
+static void __init aafs_remove(const char *name)
+{
+	struct dentry *dentry;
+
+	dentry = lookup_one_len(name, aa_fs_dentry, strlen(name));
+	if (!IS_ERR(dentry)) {
+		securityfs_remove(dentry);
+		dput(dentry);
+	}
+}
+
+/**
+ * aafs_create - create an entry in the apparmor filesystem
+ * @name: name of the entry (NOT NULL)
+ * @mask: file permission mask of the file
+ * @fops: file operations for the file (NOT NULL)
+ *
+ * Used aafs_remove to remove entries created with this fn.
+ */
+static int __init aafs_create(const char *name, int mask,
+			      const struct file_operations *fops)
+{
+	struct dentry *dentry;
+
+	dentry = securityfs_create_file(name, S_IFREG | mask, aa_fs_dentry,
+					NULL, fops);
+
+	return IS_ERR(dentry) ? PTR_ERR(dentry) : 0;
+}
+
+/**
+ * aa_destroy_aafs - cleanup and free aafs
+ *
+ * releases dentries allocated by aa_create_aafs
+ */
+void __init aa_destroy_aafs(void)
+{
+	if (aa_fs_dentry) {
+		aafs_remove(".remove");
+		aafs_remove(".replace");
+		aafs_remove(".load");
+
+		securityfs_remove(aa_fs_dentry);
+		aa_fs_dentry = NULL;
+	}
+}
+
+/**
+ * aa_create_aafs - create the apparmor security filesystem
+ *
+ * dentries created here are released by aa_destroy_aafs
+ *
+ * Returns: error on failure
+ */
+int __init aa_create_aafs(void)
+{
+	int error;
+
+	if (!apparmor_initialized)
+		return 0;
+
+	if (aa_fs_dentry) {
+		AA_ERROR("%s: AppArmor securityfs already exists\n", __func__);
+		return -EEXIST;
+	}
+
+	aa_fs_dentry = securityfs_create_dir("apparmor", NULL);
+	if (IS_ERR(aa_fs_dentry)) {
+		error = PTR_ERR(aa_fs_dentry);
+		aa_fs_dentry = NULL;
+		goto error;
+	}
+
+	error = aafs_create(".load", 0640, &aa_fs_profile_load);
+	if (error)
+		goto error;
+	error = aafs_create(".replace", 0640, &aa_fs_profile_replace);
+	if (error)
+		goto error;
+	error = aafs_create(".remove", 0640, &aa_fs_profile_remove);
+	if (error)
+		goto error;
+
+	/* TODO: add support for apparmorfs_null and apparmorfs_mnt */
+
+	/* Report that AppArmor fs is enabled */
+	aa_info_message("AppArmor Filesystem Enabled");
+	return 0;
+
+error:
+	aa_destroy_aafs();
+	AA_ERROR("Error creating AppArmor securityfs\n");
+	return error;
+}
+
+fs_initcall(aa_create_aafs);
security/apparmor/include/apparmorfs.h new file +20 -0
new file mode 100644
index 0000000..cb1e93a
@@ -0,0 +1,20 @@
+/*
+ * AppArmor security module
+ *
+ * This file contains AppArmor filesystem definitions.
+ *
+ * Copyright (C) 1998-2008 Novell/SUSE
+ * Copyright 2009-2010 Canonical Ltd.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, version 2 of the
+ * License.
+ */
+
+#ifndef __AA_APPARMORFS_H
+#define __AA_APPARMORFS_H
+
+extern void __init aa_destroy_aafs(void);
+
+#endif /* __AA_APPARMORFS_H */
security/apparmor/include/procattr.h new file +26 -0
new file mode 100644
index 0000000..544aa6b
@@ -0,0 +1,26 @@
+/*
+ * AppArmor security module
+ *
+ * This file contains AppArmor /proc/<pid>/attr/ interface function definitions.
+ *
+ * Copyright (C) 1998-2008 Novell/SUSE
+ * Copyright 2009-2010 Canonical Ltd.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, version 2 of the
+ * License.
+ */
+
+#ifndef __AA_PROCATTR_H
+#define __AA_PROCATTR_H
+
+#define AA_DO_TEST 1
+#define AA_ONEXEC  1
+
+int aa_getprocattr(struct aa_profile *profile, char **string);
+int aa_setprocattr_changehat(char *args, size_t size, int test);
+int aa_setprocattr_changeprofile(char *fqname, bool onexec, int test);
+int aa_setprocattr_permipc(char *fqname);
+
+#endif /* __AA_PROCATTR_H */
security/apparmor/procattr.c new file +170 -0

170 lines not on this page · raw message

Signature · 1 line
1.7.1
author maintainer
#13 lore raw

PATCH 8/13 AppArmor: file enforcement routines

In reply to John Johansen

AppArmor does files enforcement via pathname matching. Matching is done at file open using a dfa match engine. Permission is against the final file object not parent directories, ie. the traversal of directories as part of the file match is implicitly allowed. In the case of nonexistant files (creation) permissions are checked against the target file not the directory. eg. In case of creating the file /dir/new, permissions are checked against the match /dir/new not against /dir/.

The permissions for matches are currently stored in the dfa accept table, but this will change to allow for dfa reuse and also to allow for sharing of wider accept states.

---
 security/apparmor/file.c         |  457 ++++++++++++++++++++++++++++++++++++++
 security/apparmor/include/file.h |  217 ++++++++++++++++++
 2 files changed, 674 insertions(+), 0 deletions(-)
 create mode 100644 security/apparmor/file.c
 create mode 100644 security/apparmor/include/file.h
security/apparmor/file.c new file +457 -0
new file mode 100644
index 0000000..7312db7
@@ -0,0 +1,457 @@
+/*
+ * AppArmor security module
+ *
+ * This file contains AppArmor mediation of files
+ *
+ * Copyright (C) 1998-2008 Novell/SUSE
+ * Copyright 2009-2010 Canonical Ltd.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, version 2 of the
+ * License.
+ */
+
+#include "include/apparmor.h"
+#include "include/audit.h"
+#include "include/file.h"
+#include "include/match.h"
+#include "include/path.h"
+#include "include/policy.h"
+
+struct file_perms nullperms;
+
+
+/**
+ * audit_file_mask - convert mask to permission string
+ * @buffer: buffer to write string to (NOT NULL)
+ * @mask: permission mask to convert
+ */
+static void audit_file_mask(struct audit_buffer *ab, u32 mask)
+{
+	char str[10];
+
+	char *m = str;
+
+	if (mask & AA_EXEC_MMAP)
+		*m++ = 'm';
+	if (mask & (MAY_READ | AA_MAY_META_READ))
+		*m++ = 'r';
+	if (mask & (MAY_WRITE | AA_MAY_META_WRITE | AA_MAY_CHMOD |
+		    AA_MAY_CHOWN))
+		*m++ = 'w';
+	else if (mask & MAY_APPEND)
+		*m++ = 'a';
+	if (mask & AA_MAY_CREATE)
+		*m++ = 'c';
+	if (mask & AA_MAY_DELETE)
+		*m++ = 'd';
+	if (mask & AA_MAY_LINK)
+		*m++ = 'l';
+	if (mask & AA_MAY_LOCK)
+		*m++ = 'k';
+	if (mask & MAY_EXEC)
+		*m++ = 'x';
+	*m = '\0';
+
+	audit_log_string(ab, str);
+}
+
+/**
+ * file_audit_cb - call back for file specific audit fields
+ * @ab: audit_buffer  (NOT NULL)
+ * @va: audit struct to audit values of  (NOT NULL)
+ */
+static void file_audit_cb(struct audit_buffer *ab, void *va)
+{
+	struct common_audit_data *sa = va;
+	uid_t fsuid = current_fsuid();
+
+	if (sa->aad.fs.request & AA_AUDIT_FILE_MASK) {
+		audit_log_format(ab, " requested_mask=");
+		audit_file_mask(ab, sa->aad.fs.request);
+	}
+	if (sa->aad.fs.denied & AA_AUDIT_FILE_MASK) {
+		audit_log_format(ab, " denied_mask=");
+		audit_file_mask(ab, sa->aad.fs.denied);
+	}
+	if (sa->aad.fs.request & AA_AUDIT_FILE_MASK) {
+		audit_log_format(ab, " fsuid=%d", fsuid);
+		audit_log_format(ab, " ouid=%d", sa->aad.fs.ouid);
+	}
+
+	if (sa->aad.fs.target) {
+		audit_log_format(ab, " target=");
+		audit_log_untrustedstring(ab, sa->aad.fs.target);
+	}
+}
+
+/**
+ * aa_audit_file - handle the auditing of file operations
+ * @profile: the profile being enforced  (NOT NULL)
+ * @perms: the permissions computed for the request (NOT NULL)
+ * @gfp: allocation flags
+ * @op: operation being mediated
+ * @request: permissions requested
+ * @name: name of object being mediated (MAYBE NULL)
+ * @target: name of target (MAYBE NULL)
+ * @ouid: object uid
+ * @info: extra information message (MAYBE NULL)
+ * @error: 0 if operation allowed else failure error code
+ *
+ * Returns: %0 or error on failure
+ */
+int aa_audit_file(struct aa_profile *profile, struct file_perms *perms,
+		  gfp_t gfp, int op, u32 request, const char *name,
+		  const char *target, uid_t ouid, const char *info, int error)
+{
+	int type = AUDIT_APPARMOR_AUTO;
+	struct common_audit_data sa;
+	COMMON_AUDIT_DATA_INIT(&sa, NONE);
+	sa.aad.op = op,
+	sa.aad.fs.request = request;
+	sa.aad.name = name;
+	sa.aad.fs.target = target;
+	sa.aad.fs.ouid = ouid;
+	sa.aad.info = info;
+	sa.aad.error = error;
+
+	if (likely(!sa.aad.error)) {
+		u32 mask = perms->audit;
+
+		if (unlikely(AUDIT_MODE(profile) == AUDIT_ALL))
+			mask = 0xffff;
+
+		/* mask off perms that are not being force audited */
+		sa.aad.fs.request &= mask;
+
+		if (likely(!sa.aad.fs.request))
+			return 0;
+		type = AUDIT_APPARMOR_AUDIT;
+	} else {
+		/* only report permissions that were denied */
+		sa.aad.fs.request = sa.aad.fs.request & ~perms->allow;
+
+		if (sa.aad.fs.request & perms->kill)
+			type = AUDIT_APPARMOR_KILL;
+
+		/* quiet known rejects, assumes quiet and kill do not overlap */
+		if ((sa.aad.fs.request & perms->quiet) &&
+		    AUDIT_MODE(profile) != AUDIT_NOQUIET &&
+		    AUDIT_MODE(profile) != AUDIT_ALL)
+			sa.aad.fs.request &= ~perms->quiet;
+
+		if (!sa.aad.fs.request)
+			return COMPLAIN_MODE(profile) ? 0 : sa.aad.error;
+	}
+
+	sa.aad.fs.denied = sa.aad.fs.request & ~perms->allow;
+	return aa_audit(type, profile, gfp, &sa, file_audit_cb);
+}
+
+/**
+ * map_old_perms - map old file perms layout to the new layout
+ * @old: permission set in old mapping
+ *
+ * Returns: new permission mapping
+ */
+static u32 map_old_perms(u32 old)
+{
+	u32 new = old & 0xf;
+	if (old & MAY_READ)
+		new |= AA_MAY_META_READ;
+	if (old & MAY_WRITE)
+		new |= AA_MAY_META_WRITE | AA_MAY_CREATE | AA_MAY_DELETE |
+			AA_MAY_CHMOD | AA_MAY_CHOWN;
+	if (old & 0x10)
+		new |= AA_MAY_LINK;
+	/* the old mapping lock and link_subset flags where overlaid
+	 * and use was determined by part of a pair that they were in
+	 */
+	if (old & 0x20)
+		new |= AA_MAY_LOCK | AA_LINK_SUBSET;
+	if (old & 0x40)	/* AA_EXEC_MMAP */
+		new |= AA_EXEC_MMAP;
+
+	new |= AA_MAY_META_READ;
+
+	return new;
+}
+
+/**
+ * compute_perms - convert dfa compressed perms to internal perms
+ * @dfa: dfa to compute perms for   (NOT NULL)
+ * @state: state in dfa
+ * @cond:  conditions to consider  (NOT NULL)
+ *
+ * TODO: convert from dfa + state to permission entry, do computation conversion
+ *       at load time.
+ *
+ * Returns: computed permission set
+ */
+static struct file_perms compute_perms(struct aa_dfa *dfa, unsigned int state,
+				       struct path_cond *cond)
+{
+	struct file_perms perms;
+
+	/* FIXME: change over to new dfa format
+	 * currently file perms are encoded in the dfa, new format
+	 * splits the permissions from the dfa.  This mapping can be
+	 * done at profile load
+	 */
+	perms.kill = 0;
+
+	if (current_fsuid() == cond->uid) {
+		perms.allow = map_old_perms(dfa_user_allow(dfa, state));
+		perms.audit = map_old_perms(dfa_user_audit(dfa, state));
+		perms.quiet = map_old_perms(dfa_user_quiet(dfa, state));
+		perms.xindex = dfa_user_xindex(dfa, state);
+	} else {
+		perms.allow = map_old_perms(dfa_other_allow(dfa, state));
+		perms.audit = map_old_perms(dfa_other_audit(dfa, state));
+		perms.quiet = map_old_perms(dfa_other_quiet(dfa, state));
+		perms.xindex = dfa_other_xindex(dfa, state);
+	}
+
+	/* change_profile wasn't determined by ownership in old mapping */
+	if (ACCEPT_TABLE(dfa)[state] & 0x80000000)
+		perms.allow |= AA_MAY_CHANGE_PROFILE;
+
+	return perms;
+}
+
+/**
+ * aa_str_perms - find permission that match @name
+ * @dfa: to match against  (MAYBE NULL)
+ * @state: state to start matching in
+ * @name: string to match against dfa  (NOT NULL)
+ * @cond: conditions to consider for permission set computation  (NOT NULL)
+ * @perms: Returns - the permissions found when matching @name
+ *
+ * Returns: the final state in @dfa when beginning @start and walking @name
+ */
+unsigned int aa_str_perms(struct aa_dfa *dfa, unsigned int start,
+			  const char *name, struct path_cond *cond,
+			  struct file_perms *perms)
+{
+	unsigned int state;
+	if (!dfa) {
+		*perms = nullperms;
+		return DFA_NOMATCH;
+	}
+
+	state = aa_dfa_match(dfa, start, name);
+	*perms = compute_perms(dfa, state, cond);
+
+	return state;
+}
+
+/**
+ * is_deleted - test if a file has been completely unlinked
+ * @dentry: dentry of file to test for deletion  (NOT NULL)
+ *
+ * Returns: %1 if deleted else %0
+ */
+static inline bool is_deleted(struct dentry *dentry)
+{
+	if (d_unlinked(dentry) && dentry->d_inode->i_nlink == 0)
+		return 1;
+	return 0;
+}
+
+/**
+ * aa_path_perm - do permissions check & audit for @path
+ * @op: operation being checked
+ * @profile: profile being enforced  (NOT NULL)
+ * @path: path to check permissions of  (NOT NULL)
+ * @flags: any additional path flags beyond what the profile specifies
+ * @request: requested permissions
+ * @cond: conditional info for this request  (NOT NULL)
+ *
+ * Returns: %0 else error if access denied or other error
+ */
+int aa_path_perm(int op, struct aa_profile *profile, struct path *path,
+		 int flags, u32 request, struct path_cond *cond)
+{
+	char *buffer = NULL;
+	struct file_perms perms = {};
+	const char *name, *info = NULL;
+	int error;
+
+	flags |= profile->path_flags | (S_ISDIR(cond->mode) ? PATH_IS_DIR : 0);
+	error = aa_get_name(path, flags, &buffer, &name);
+	if (error) {
+		if (error == -ENOENT && is_deleted(path->dentry)) {
+			/* Access to open files that are deleted are
+			 * give a pass (implicit delegation)
+			 */
+			error = 0;
+			perms.allow = request;
+		} else if (error == -ENOENT)
+			info = "Failed name lookup - deleted entry";
+		else if (error == -ESTALE)
+			info = "Failed name lookup - disconnected path";
+		else if (error == -ENAMETOOLONG)
+			info = "Failed name lookup - name too long";
+		else
+			info = "Failed name lookup";
+	} else {
+		aa_str_perms(profile->file.dfa, profile->file.start, name, cond,
+			     &perms);
+		if (request & ~perms.allow)
+			error = -EACCES;
+	}
+	error = aa_audit_file(profile, &perms, GFP_KERNEL, op, request, name,
+			      NULL, cond->uid, info, error);
+	kfree(buffer);
+
+	return error;
+}
+
+/**
+ * xindex_is_subset - helper for aa_path_link
+ * @link: link permission set
+ * @target: target permission set
+ *
+ * test target x permissions are equal OR a subset of link x permissions
+ * this is done as part of the subset test, where a hardlink must have
+ * a subset of permissions that the target has.
+ *
+ * Returns: %1 if subset else %0
+ */
+static inline bool xindex_is_subset(u32 link, u32 target)
+{
+	if (((link & ~AA_X_UNSAFE) != (target & ~AA_X_UNSAFE)) ||
+	    ((link & AA_X_UNSAFE) && !(target & AA_X_UNSAFE)))
+		return 0;
+
+	return 1;
+}
+
+/**
+ * aa_path_link - Handle hard link permission check
+ * @profile: the profile being enforced  (NOT NULL)
+ * @old_dentry: the target dentry  (NOT NULL)
+ * @new_dir: directory the new link will be created in  (NOT NULL)
+ * @new_dentry: the link being created  (NOT NULL)
+ *
+ * Handle the permission test for a link & target pair.  Permission
+ * is encoded as a pair where the link permission is determined
+ * first, and if allowed, the target is tested.  The target test
+ * is done from the point of the link match (not start of DFA)
+ * making the target permission dependent on the link permission match.
+ *
+ * The subset test if required forces that permissions granted
+ * on link are a subset of the permission granted to target.
+ *
+ * Returns: %0 if allowed else error
+ */
+int aa_path_link(struct aa_profile *profile, struct dentry *old_dentry,
+		 struct path *new_dir, struct dentry *new_dentry)
+{
+	struct path link = { new_dir->mnt, new_dentry };
+	struct path target = { new_dir->mnt, old_dentry };
+	struct path_cond cond = {
+		old_dentry->d_inode->i_uid,
+		old_dentry->d_inode->i_mode
+	};
+	char *buffer = NULL, *buffer2 = NULL;
+	const char *lname, *tname = NULL, *info = NULL;
+	struct file_perms lperms, perms;
+	u32 request = AA_MAY_LINK;
+	unsigned int state;
+	int error;
+
+	lperms = nullperms;
+
+	/* buffer freed below, lname is pointer in buffer */
+	error = aa_get_name(&link, profile->path_flags, &buffer, &lname);
+	if (error)
+		goto audit;
+
+	/* buffer2 freed below, tname is pointer in buffer2 */
+	error = aa_get_name(&target, profile->path_flags, &buffer2, &tname);
+	if (error)
+		goto audit;
+
+	error = -EACCES;
+	/* aa_str_perms - handles the case of the dfa being NULL */
+	state = aa_str_perms(profile->file.dfa, profile->file.start, lname,
+			     &cond, &lperms);
+
+	if (!(lperms.allow & AA_MAY_LINK))
+		goto audit;
+
+	/* test to see if target can be paired with link */
+	state = aa_dfa_null_transition(profile->file.dfa, state);
+	aa_str_perms(profile->file.dfa, state, tname, &cond, &perms);
+
+	/* force audit/quiet masks for link are stored in the second entry
+	 * in the link pair.
+	 */
+	lperms.audit = perms.audit;
+	lperms.quiet = perms.quiet;
+	lperms.kill = perms.kill;
+
+	if (!(perms.allow & AA_MAY_LINK)) {
+		info = "target restricted";
+		goto audit;
+	}
+
+	/* done if link subset test is not required */
+	if (!(perms.allow & AA_LINK_SUBSET))
+		goto done_tests;
+
+	/* Do link perm subset test requiring allowed permission on link are a
+	 * subset of the allowed permissions on target.
+	 */
+	aa_str_perms(profile->file.dfa, profile->file.start, tname, &cond,
+		     &perms);
+
+	/* AA_MAY_LINK is not considered in the subset test */
+	request = lperms.allow & ~AA_MAY_LINK;
+	lperms.allow &= perms.allow | AA_MAY_LINK;
+
+	request |= AA_AUDIT_FILE_MASK & (lperms.allow & ~perms.allow);
+	if (request & ~lperms.allow) {
+		goto audit;
+	} else if ((lperms.allow & MAY_EXEC) &&
+		   !xindex_is_subset(lperms.xindex, perms.xindex)) {
+		lperms.allow &= ~MAY_EXEC;
+		request |= MAY_EXEC;
+		info = "link not subset of target";
+		goto audit;
+	}
+
+done_tests:
+	error = 0;
+
+audit:
+	error = aa_audit_file(profile, &lperms, GFP_KERNEL, OP_LINK, request,
+			      lname, tname, cond.uid, info, error);
+	kfree(buffer);
+	kfree(buffer2);
+
+	return error;
+}
+
+/**
+ * aa_file_perm - do permission revalidation check & audit for @file
+ * @op: operation being checked
+ * @profile: profile being enforced   (NOT NULL)
+ * @file: file to revalidate access permissions on  (NOT NULL)
+ * @request: requested permissions
+ *
+ * Returns: %0 if access allowed else error
+ */
+int aa_file_perm(int op, struct aa_profile *profile, struct file *file,
+		 u32 request)
+{
+	struct path_cond cond = {
+		.uid = file->f_path.dentry->d_inode->i_uid,
+		.mode = file->f_path.dentry->d_inode->i_mode
+	};
+
+	return aa_path_perm(op, profile, &file->f_path, PATH_DELEGATE_DELETED,
+			    request, &cond);
+}
security/apparmor/include/file.h new file +217 -0

217 lines not on this page · raw message

Signature · 1 line
1.7.1
author maintainer
#14 lore raw

PATCH 9/13 AppArmor: mediation of non file objects

In reply to John Johansen

ipc:
AppArmor ipc is currently limited to mediation done by file mediation and basic ptrace tests. Improved mediation is a wip.

rlimits:
AppArmor provides basic abilities to set and control rlimits at a per profile level. Only resources specified in a profile are controled or set. AppArmor rules set the hard limit to a value <= to the current hard limit (ie. they can not currently raise hard limits), and if necessary will lower the soft limit to the new hard limit value.

AppArmor does not track resource limits to reset them when a profile is left so that children processes inherit the limits set by the parent even if they are not confined by the same profile.

Capabilities: AppArmor provides a per profile mask of capabilities, that will further restrict.

---
 security/apparmor/capability.c         |  141 ++++++++++++++++++++++++++++++++
 security/apparmor/include/capability.h |   45 ++++++++++
 security/apparmor/include/ipc.h        |   28 ++++++
 security/apparmor/include/resource.h   |   46 ++++++++++
 security/apparmor/ipc.c                |  114 ++++++++++++++++++++++++++
 security/apparmor/resource.c           |  134 ++++++++++++++++++++++++++++++
 6 files changed, 508 insertions(+), 0 deletions(-)
 create mode 100644 security/apparmor/capability.c
 create mode 100644 security/apparmor/include/capability.h
 create mode 100644 security/apparmor/include/ipc.h
 create mode 100644 security/apparmor/include/resource.h
 create mode 100644 security/apparmor/ipc.c
 create mode 100644 security/apparmor/resource.c
security/apparmor/capability.c new file +141 -0
new file mode 100644
index 0000000..9982c48
@@ -0,0 +1,141 @@
+/*
+ * AppArmor security module
+ *
+ * This file contains AppArmor capability mediation functions
+ *
+ * Copyright (C) 1998-2008 Novell/SUSE
+ * Copyright 2009-2010 Canonical Ltd.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, version 2 of the
+ * License.
+ */
+
+#include <linux/capability.h>
+#include <linux/errno.h>
+#include <linux/gfp.h>
+
+#include "include/apparmor.h"
+#include "include/capability.h"
+#include "include/context.h"
+#include "include/policy.h"
+#include "include/audit.h"
+
+/*
+ * Table of capability names: we generate it from capabilities.h.
+ */
+#include "capability_names.h"
+
+struct audit_cache {
+	struct aa_profile *profile;
+	kernel_cap_t caps;
+};
+
+static DEFINE_PER_CPU(struct audit_cache, audit_cache);
+
+/**
+ * audit_cb - call back for capability components of audit struct
+ * @ab - audit buffer   (NOT NULL)
+ * @va - audit struct to audit data from  (NOT NULL)
+ */
+static void audit_cb(struct audit_buffer *ab, void *va)
+{
+	struct common_audit_data *sa = va;
+	audit_log_format(ab, " capname=");
+	audit_log_untrustedstring(ab, capability_names[sa->u.cap]);
+}
+
+/**
+ * audit_caps - audit a capability
+ * @profile: profile confining task (NOT NULL)
+ * @task: task capability test was performed against (NOT NULL)
+ * @cap: capability tested
+ * @error: error code returned by test
+ *
+ * Do auditing of capability and handle, audit/complain/kill modes switching
+ * and duplicate message elimination.
+ *
+ * Returns: 0 or sa->error on success,  error code on failure
+ */
+static int audit_caps(struct aa_profile *profile, struct task_struct *task,
+		      int cap, int error)
+{
+	struct audit_cache *ent;
+	int type = AUDIT_APPARMOR_AUTO;
+	struct common_audit_data sa;
+	COMMON_AUDIT_DATA_INIT(&sa, CAP);
+	sa.tsk = task;
+	sa.u.cap = cap;
+	sa.aad.op = OP_CAPABLE;
+	sa.aad.error = error;
+
+	if (likely(!error)) {
+		/* test if auditing is being forced */
+		if (likely((AUDIT_MODE(profile) != AUDIT_ALL) &&
+			   !cap_raised(profile->caps.audit, cap)))
+			return 0;
+		type = AUDIT_APPARMOR_AUDIT;
+	} else if (KILL_MODE(profile) ||
+		   cap_raised(profile->caps.kill, cap)) {
+		type = AUDIT_APPARMOR_KILL;
+	} else if (cap_raised(profile->caps.quiet, cap) &&
+		   AUDIT_MODE(profile) != AUDIT_NOQUIET &&
+		   AUDIT_MODE(profile) != AUDIT_ALL) {
+		/* quiet auditing */
+		return error;
+	}
+
+	/* Do simple duplicate message elimination */
+	ent = &get_cpu_var(audit_cache);
+	if (profile == ent->profile && cap_raised(ent->caps, cap)) {
+		put_cpu_var(audit_cache);
+		if (COMPLAIN_MODE(profile))
+			return complain_error(error);
+		return error;
+	} else {
+		aa_put_profile(ent->profile);
+		ent->profile = aa_get_profile(profile);
+		cap_raise(ent->caps, cap);
+	}
+	put_cpu_var(audit_cache);
+
+	return aa_audit(type, profile, GFP_ATOMIC, &sa, audit_cb);
+}
+
+/**
+ * profile_capable - test if profile allows use of capability @cap
+ * @profile: profile being enforced    (NOT NULL, NOT unconfined)
+ * @cap: capability to test if allowed
+ *
+ * Returns: 0 if allowed else -EPERM
+ */
+static int profile_capable(struct aa_profile *profile, int cap)
+{
+	return cap_raised(profile->caps.allow, cap) ? 0 : -EPERM;
+}
+
+/**
+ * aa_capable - test permission to use capability
+ * @task: task doing capability test against (NOT NULL)
+ * @profile: profile confining @task (NOT NULL)
+ * @cap: capability to be tested
+ * @audit: whether an audit record should be generated
+ *
+ * Look up capability in profile capability set.
+ *
+ * Returns: 0 on success, or else an error code.
+ */
+int aa_capable(struct task_struct *task, struct aa_profile *profile, int cap,
+	       int audit)
+{
+	int error = profile_capable(profile, cap);
+
+	if (!audit) {
+		if (COMPLAIN_MODE(profile))
+			return complain_error(error);
+		return error;
+	}
+
+	return audit_caps(profile, task, cap, error);
+}
security/apparmor/include/capability.h new file +45 -0

45 lines not on this page · raw message

security/apparmor/include/ipc.h new file +28 -0
new file mode 100644
index 0000000..aeda0fb
@@ -0,0 +1,28 @@
+/*
+ * AppArmor security module
+ *
+ * This file contains AppArmor ipc mediation function definitions.
+ *
+ * Copyright (C) 1998-2008 Novell/SUSE
+ * Copyright 2009-2010 Canonical Ltd.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, version 2 of the
+ * License.
+ */
+
+#ifndef __AA_IPC_H
+#define __AA_IPC_H
+
+#include <linux/sched.h>
+
+struct aa_profile;
+
+int aa_may_ptrace(struct task_struct *tracer_task, struct aa_profile *tracer,
+		  struct aa_profile *tracee, unsigned int mode);
+
+int aa_ptrace(struct task_struct *tracer, struct task_struct *tracee,
+	      unsigned int mode);
+
+#endif /* __AA_IPC_H */
security/apparmor/include/resource.h new file +46 -0

46 lines not on this page · raw message

security/apparmor/ipc.c new file +114 -0

114 lines not on this page · raw message

security/apparmor/resource.c new file +134 -0

134 lines not on this page · raw message

Signature · 1 line
1.7.1
author maintainer
#15 lore raw

PATCH 10/13 AppArmor: functions for domain transitions

In reply to John Johansen

AppArmor routines for controling domain transitions, which can occur at exec or through self directed change_profile/change_hat calls.

Unconfined tasks are checked at exec against the profiles in the confining profile namespace to determine if a profile should be attached to the task.

Confined tasks execs are controlled by the profile which provides rules determining which execs are allowed and if so which profiles should be transitioned to.

Self directed domain transitions allow a task to request transition to a given profile. If the transition is allowed then the profile will be applied, either immeditately or at exec time depending on the request. Immeditate self directed transitions have several security limitations but have uses in setting up stub transition profiles and other limited cases.

---
 security/apparmor/domain.c         |  823 ++++++++++++++++++++++++++++++++++++
 security/apparmor/include/domain.h |   36 ++
 2 files changed, 859 insertions(+), 0 deletions(-)
 create mode 100644 security/apparmor/domain.c
 create mode 100644 security/apparmor/include/domain.h
security/apparmor/domain.c new file +823 -0
new file mode 100644
index 0000000..08bbe63
@@ -0,0 +1,823 @@
+/*
+ * AppArmor security module
+ *
+ * This file contains AppArmor policy attachment and domain transitions
+ *
+ * Copyright (C) 2002-2008 Novell/SUSE
+ * Copyright 2009-2010 Canonical Ltd.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, version 2 of the
+ * License.
+ */
+
+#include <linux/errno.h>
+#include <linux/fdtable.h>
+#include <linux/file.h>
+#include <linux/mount.h>
+#include <linux/syscalls.h>
+#include <linux/tracehook.h>
+#include <linux/personality.h>
+
+#include "include/audit.h"
+#include "include/apparmorfs.h"
+#include "include/context.h"
+#include "include/domain.h"
+#include "include/file.h"
+#include "include/ipc.h"
+#include "include/match.h"
+#include "include/path.h"
+#include "include/policy.h"
+
+/**
+ * aa_free_domain_entries - free entries in a domain table
+ * @domain: the domain table to free  (MAYBE NULL)
+ */
+void aa_free_domain_entries(struct aa_domain *domain)
+{
+	int i;
+	if (domain) {
+		if (!domain->table)
+			return;
+
+		for (i = 0; i < domain->size; i++)
+			kzfree(domain->table[i]);
+		kzfree(domain->table);
+		domain->table = NULL;
+	}
+}
+
+/**
+ * may_change_ptraced_domain - check if can change profile on ptraced task
+ * @task: task we want to change profile of   (NOT NULL)
+ * @to_profile: profile to change to  (NOT NULL)
+ *
+ * Check if the task is ptraced and if so if the tracing task is allowed
+ * to trace the new domain
+ *
+ * Returns: %0 or error if change not allowed
+ */
+static int may_change_ptraced_domain(struct task_struct *task,
+				     struct aa_profile *to_profile)
+{
+	struct task_struct *tracer;
+	struct cred *cred = NULL;
+	struct aa_profile *tracerp = NULL;
+	int error = 0;
+
+	rcu_read_lock();
+	tracer = tracehook_tracer_task(task);
+	if (tracer) {
+		/* released below */
+		cred = get_task_cred(tracer);
+		tracerp = aa_cred_profile(cred);
+	}
+	rcu_read_unlock();
+
+	/* not ptraced */
+	if (!tracer || unconfined(tracerp))
+		goto out;
+
+	error = aa_may_ptrace(tracer, tracerp, to_profile, PTRACE_MODE_ATTACH);
+
+out:
+	if (cred)
+		put_cred(cred);
+
+	return error;
+}
+
+/**
+ * change_profile_perms - find permissions for change_profile
+ * @profile: the current profile  (NOT NULL)
+ * @ns: the namespace being switched to  (NOT NULL)
+ * @name: the name of the profile to change to  (NOT NULL)
+ * @request: requested perms
+ * @start: state to start matching in
+ *
+ * Returns: permission set
+ */
+static struct file_perms change_profile_perms(struct aa_profile *profile,
+					      struct aa_namespace *ns,
+					      const char *name, u32 request,
+					      unsigned int start)
+{
+	struct file_perms perms;
+	struct path_cond cond = { };
+	unsigned int state;
+
+	if (unconfined(profile)) {
+		perms.allow = AA_MAY_CHANGE_PROFILE | AA_MAY_ONEXEC;
+		perms.audit = perms.quiet = perms.kill = 0;
+		return perms;
+	} else if (!profile->file.dfa) {
+		return nullperms;
+	} else if ((ns == profile->ns)) {
+		/* try matching against rules with out namespace prepended */
+		aa_str_perms(profile->file.dfa, start, name, &cond, &perms);
+		if (COMBINED_PERM_MASK(perms) & request)
+			return perms;
+	}
+
+	/* try matching with namespace name and then profile */
+	state = aa_dfa_match(profile->file.dfa, start, ns->base.name);
+	state = aa_dfa_match_len(profile->file.dfa, state, ":", 1);
+	aa_str_perms(profile->file.dfa, state, name, &cond, &perms);
+
+	return perms;
+}
+
+/**
+ * __attach_match_ - find an attachment match
+ * @name - to match against  (NOT NULL)
+ * @head - profile list to walk  (NOT NULL)
+ *
+ * Do a linear search on the profiles in the list.  There is a matching
+ * preference where an exact match is preferred over a name which uses
+ * expressions to match, and matching expressions with the greatest
+ * xmatch_len are preferred.
+ *
+ * Requires: @head not be shared or have appropriate locks held
+ *
+ * Returns: profile or NULL if no match found
+ */
+static struct aa_profile *__attach_match(const char *name,
+					 struct list_head *head)
+{
+	int len = 0;
+	struct aa_profile *profile, *candidate = NULL;
+
+	list_for_each_entry(profile, head, base.list) {
+		if (profile->flags & PFLAG_NULL)
+			continue;
+		if (profile->xmatch && profile->xmatch_len > len) {
+			unsigned int state = aa_dfa_match(profile->xmatch,
+							  DFA_START, name);
+			u32 perm = dfa_user_allow(profile->xmatch, state);
+			/* any accepting state means a valid match. */
+			if (perm & MAY_EXEC) {
+				candidate = profile;
+				len = profile->xmatch_len;
+			}
+		} else if (!strcmp(profile->base.name, name))
+			/* exact non-re match, no more searching required */
+			return profile;
+	}
+
+	return candidate;
+}
+
+/**
+ * find_attach - do attachment search for unconfined processes
+ * @ns: the current namespace  (NOT NULL)
+ * @list: list to search  (NOT NULL)
+ * @name: the executable name to match against  (NOT NULL)
+ *
+ * Returns: profile or NULL if no match found
+ */
+static struct aa_profile *find_attach(struct aa_namespace *ns,
+				      struct list_head *list, const char *name)
+{
+	struct aa_profile *profile;
+
+	read_lock(&ns->lock);
+	profile = aa_get_profile(__attach_match(name, list));
+	read_unlock(&ns->lock);
+
+	return profile;
+}
+
+/**
+ * separate_fqname - separate the namespace and profile names
+ * @fqname: the fqname name to split  (NOT NULL)
+ * @ns_name: the namespace name if it exists  (NOT NULL)
+ *
+ * This is the xtable equivalent routine of aa_split_fqname.  It finds the
+ * split in an xtable fqname which contains an embedded \0 instead of a :
+ * if a namespace is specified.  This is done so the xtable is constant and
+ * isn't re-split on every lookup.
+ *
+ * Either the profile or namespace name may be optional but if the namespace
+ * is specified the profile name termination must be present.  This results
+ * in the following possible encodings:
+ * profile_name\0
+ * :ns_name\0profile_name\0
+ * :ns_name\0\0
+ *
+ * NOTE: the xtable fqname is pre-validated at load time in unpack_trans_table
+ *
+ * Returns: profile name if it is specified else NULL
+ */
+static const char *separate_fqname(const char *fqname, const char **ns_name)
+{
+	const char *name;
+
+	if (fqname[0] == ':') {
+		/* In this case there is guaranteed to be two \0 terminators
+		 * in the string.  They are verified at load time by
+		 * by unpack_trans_table
+		 */
+		*ns_name = fqname + 1;		/* skip : */
+		name = *ns_name + strlen(*ns_name) + 1;
+		if (!*name)
+			name = NULL;
+	} else {
+		*ns_name = NULL;
+		name = fqname;
+	}
+
+	return name;
+}
+
+static const char *next_name(int xtype, const char *name)
+{
+	return NULL;
+}
+
+/**
+ * x_table_lookup - lookup an x transition name via transition table
+ * @profile: current profile (NOT NULL)
+ * @xindex: index into x transition table
+ *
+ * Returns: refcounted profile, or NULL on failure (MAYBE NULL)
+ */
+static struct aa_profile *x_table_lookup(struct aa_profile *profile, u32 xindex)
+{
+	struct aa_profile *new_profile = NULL;
+	struct aa_namespace *ns = profile->ns;
+	u32 xtype = xindex & AA_X_TYPE_MASK;
+	int index = xindex & AA_X_INDEX_MASK;
+	const char *name;
+
+	/* index is guaranteed to be in range, validated at load time */
+	for (name = profile->file.trans.table[index]; !new_profile && name;
+	     name = next_name(xtype, name)) {
+		struct aa_namespace *new_ns;
+		const char *xname = NULL;
+
+		new_ns = NULL;
+		if (xindex & AA_X_CHILD) {
+			/* release by caller */
+			new_profile = aa_find_child(profile, name);
+			continue;
+		} else if (*name == ':') {
+			/* switching namespace */
+			const char *ns_name;
+			xname = name = separate_fqname(name, &ns_name);
+			if (!xname)
+				/* no name so use profile name */
+				xname = profile->base.hname;
+			if (*ns_name == '@') {
+				/* TODO: variable support */
+				;
+			}
+			/* released below */
+			new_ns = aa_find_namespace(ns, ns_name);
+			if (!new_ns)
+				continue;
+		} else if (*name == '@') {
+			/* TODO: variable support */
+			continue;
+		} else {
+			/* basic namespace lookup */
+			xname = name;
+		}
+
+		/* released by caller */
+		new_profile = aa_lookup_profile(new_ns ? new_ns : ns, xname);
+		aa_put_namespace(new_ns);
+	}
+
+	/* released by caller */
+	return new_profile;
+}
+
+/**
+ * x_to_profile - get target profile for a given xindex
+ * @profile: current profile  (NOT NULL)
+ * @name: name to lookup (NOT NULL)
+ * @xindex: index into x transition table
+ *
+ * find profile for a transition index
+ *
+ * Returns: refcounted profile or NULL if not found available
+ */
+static struct aa_profile *x_to_profile(struct aa_profile *profile,
+				       const char *name, u32 xindex)
+{
+	struct aa_profile *new_profile = NULL;
+	struct aa_namespace *ns = profile->ns;
+	u32 xtype = xindex & AA_X_TYPE_MASK;
+
+	switch (xtype) {
+	case AA_X_NONE:
+		/* fail exec unless ix || ux fallback - handled by caller */
+		return NULL;
+	case AA_X_NAME:
+		if (xindex & AA_X_CHILD)
+			/* released by caller */
+			new_profile = find_attach(ns, &profile->base.profiles,
+						  name);
+		else
+			/* released by caller */
+			new_profile = find_attach(ns, &ns->base.profiles,
+						  name);
+		break;
+	case AA_X_TABLE:
+		/* released by caller */
+		new_profile = x_table_lookup(profile, xindex);
+		break;
+	}
+
+	/* released by caller */
+	return new_profile;
+}
+
+/**
+ * apparmor_bprm_set_creds - set the new creds on the bprm struct
+ * @bprm: binprm for the exec  (NOT NULL)
+ *
+ * Returns: %0 or error on failure
+ */
+int apparmor_bprm_set_creds(struct linux_binprm *bprm)
+{
+	struct aa_task_cxt *cxt;
+	struct aa_profile *profile, *new_profile = NULL;
+	struct aa_namespace *ns;
+	char *buffer = NULL;
+	unsigned int state;
+	struct file_perms perms = {};
+	struct path_cond cond = {
+		bprm->file->f_path.dentry->d_inode->i_uid,
+		bprm->file->f_path.dentry->d_inode->i_mode
+	};
+	const char *name = NULL, *target = NULL, *info = NULL;
+	int error = cap_bprm_set_creds(bprm);
+	if (error)
+		return error;
+
+	if (bprm->cred_prepared)
+		return 0;
+
+	cxt = bprm->cred->security;
+	BUG_ON(!cxt);
+
+	profile = aa_get_profile(aa_newest_version(cxt->profile));
+	/*
+	 * get the namespace from the replacement profile as replacement
+	 * can change the namespace
+	 */
+	ns = profile->ns;
+	state = profile->file.start;
+
+	/* buffer freed below, name is pointer into buffer */
+	error = aa_get_name(&bprm->file->f_path, profile->path_flags, &buffer,
+			    &name);
+	if (error) {
+		if (profile->flags &
+		    (PFLAG_IX_ON_NAME_ERROR | PFLAG_UNCONFINED))
+			error = 0;
+		info = "Exec failed name resolution";
+		name = bprm->filename;
+		goto audit;
+	}
+
+	/* Test for onexec first as onexec directives override other
+	 * x transitions.
+	 */
+	if (unconfined(profile)) {
+		/* unconfined task */
+		if (cxt->onexec)
+			/* change_profile on exec already been granted */
+			new_profile = aa_get_profile(cxt->onexec);
+		else
+			new_profile = find_attach(ns, &ns->base.profiles, name);
+		if (!new_profile)
+			goto cleanup;
+		goto apply;
+	}
+
+	/* find exec permissions for name */
+	state = aa_str_perms(profile->file.dfa, state, name, &cond, &perms);
+	if (cxt->onexec) {
+		struct file_perms cp;
+		info = "change_profile onexec";
+		if (!(perms.allow & AA_MAY_ONEXEC))
+			goto audit;
+
+		/* test if this exec can be paired with change_profile onexec.
+		 * onexec permission is linked to exec with a standard pairing
+		 * exec\0change_profile
+		 */
+		state = aa_dfa_null_transition(profile->file.dfa, state);
+		cp = change_profile_perms(profile, cxt->onexec->ns, name,
+					  AA_MAY_ONEXEC, state);
+
+		if (!(cp.allow & AA_MAY_ONEXEC))
+			goto audit;
+		new_profile = aa_get_profile(aa_newest_version(cxt->onexec));
+		goto apply;
+	}
+
+	if (perms.allow & MAY_EXEC) {
+		/* exec permission determine how to transition */
+		new_profile = x_to_profile(profile, name, perms.xindex);
+		if (!new_profile) {
+			if (perms.xindex & AA_X_INHERIT) {
+				/* (p|c|n)ix - don't change profile but do
+				 * use the newest version, which was picked
+				 * up above when getting profile
+				 */
+				info = "ix fallback";
+				new_profile = aa_get_profile(profile);
+				goto x_clear;
+			} else if (perms.xindex & AA_X_UNCONFINED) {
+				new_profile = aa_get_profile(ns->unconfined);
+				info = "ux fallback";
+			} else {
+				error = -ENOENT;
+				info = "profile not found";
+			}
+		}
+	} else if (COMPLAIN_MODE(profile)) {
+		/* no exec permission - are we in learning mode */
+		new_profile = aa_new_null_profile(profile, 0);
+		if (!new_profile) {
+			error = -ENOMEM;
+			info = "could not create null profile";
+		} else {
+			error = -EACCES;
+			target = new_profile->base.hname;
+		}
+		perms.xindex |= AA_X_UNSAFE;
+	} else
+		/* fail exec */
+		error = -EACCES;
+
+	if (!new_profile)
+		goto audit;
+
+	if (bprm->unsafe & LSM_UNSAFE_SHARE) {
+		/* FIXME: currently don't mediate shared state */
+		;
+	}
+
+	if (bprm->unsafe & (LSM_UNSAFE_PTRACE | LSM_UNSAFE_PTRACE_CAP)) {
+		error = may_change_ptraced_domain(current, new_profile);
+		if (error) {
+			aa_put_profile(new_profile);
+			goto audit;
+		}
+	}
+
+	/* Determine if secure exec is needed.
+	 * Can be at this point for the following reasons:
+	 * 1. unconfined switching to confined
+	 * 2. confined switching to different confinement
+	 * 3. confined switching to unconfined
+	 *
+	 * Cases 2 and 3 are marked as requiring secure exec
+	 * (unless policy specified "unsafe exec")
+	 *
+	 * bprm->unsafe is used to cache the AA_X_UNSAFE permission
+	 * to avoid having to recompute in secureexec
+	 */
+	if (!(perms.xindex & AA_X_UNSAFE)) {
+		AA_DEBUG("scrubbing environment variables for %s profile=%s\n",
+			 name, new_profile->base.hname);
+		bprm->unsafe |= AA_SECURE_X_NEEDED;
+	}
+apply:
+	target = new_profile->base.hname;
+	/* when transitioning profiles clear unsafe personality bits */
+	bprm->per_clear |= PER_CLEAR_ON_SETID;
+
+x_clear:
+	aa_put_profile(cxt->profile);
+	/* transfer new profile reference will be released when cxt is freed */
+	cxt->profile = new_profile;
+
+	/* clear out all temporary/transitional state from the context */
+	aa_put_profile(cxt->previous);
+	aa_put_profile(cxt->onexec);
+	cxt->previous = NULL;
+	cxt->onexec = NULL;
+	cxt->token = 0;
+
+audit:
+	error = aa_audit_file(profile, &perms, GFP_KERNEL, OP_EXEC, MAY_EXEC,
+			      name, target, cond.uid, info, error);
+
+cleanup:
+	aa_put_profile(profile);
+	kfree(buffer);
+
+	return error;
+}
+
+/**
+ * apparmor_bprm_secureexec - determine if secureexec is needed
+ * @bprm: binprm for exec  (NOT NULL)
+ *
+ * Returns: %1 if secureexec is needed else %0
+ */
+int apparmor_bprm_secureexec(struct linux_binprm *bprm)
+{
+	int ret = cap_bprm_secureexec(bprm);
+
+	/* the decision to use secure exec is computed in set_creds
+	 * and stored in bprm->unsafe.
+	 */
+	if (!ret && (bprm->unsafe & AA_SECURE_X_NEEDED))
+		ret = 1;
+
+	return ret;
+}
+
+/**
+ * apparmor_bprm_committing_creds - do task cleanup on committing new creds
+ * @bprm: binprm for the exec  (NOT NULL)
+ */
+void apparmor_bprm_committing_creds(struct linux_binprm *bprm)
+{
+	struct aa_profile *profile = __aa_current_profile();
+	struct aa_task_cxt *new_cxt = bprm->cred->security;
+
+	/* bail out if unconfined or not changing profile */
+	if ((new_cxt->profile == profile) ||
+	    (unconfined(new_cxt->profile)))
+		return;
+
+	current->pdeath_signal = 0;
+
+	/* reset soft limits and set hard limits for the new profile */
+	__aa_transition_rlimits(profile, new_cxt->profile);
+}
+
+/**
+ * apparmor_bprm_commited_cred - do cleanup after new creds committed
+ * @bprm: binprm for the exec  (NOT NULL)
+ */
+void apparmor_bprm_committed_creds(struct linux_binprm *bprm)
+{
+	/* TODO: cleanup signals - ipc mediation */
+	return;
+}
+
+/*
+ * Functions for self directed profile change
+ */
+
+/**
+ * new_compound_name - create an hname with @n2 appended to @n1
+ * @n1: base of hname  (NOT NULL)
+ * @n2: name to append (NOT NULL)
+ *
+ * Returns: new name or NULL on error
+ */
+static char *new_compound_name(const char *n1, const char *n2)
+{
+	char *name = kmalloc(strlen(n1) + strlen(n2) + 3, GFP_KERNEL);
+	if (name)
+		sprintf(name, "%s//%s", n1, n2);
+	return name;
+}
+
+/**
+ * aa_change_hat - change hat to/from subprofile
+ * @hats: vector of hat names to try changing into (MAYBE NULL if @count == 0)
+ * @count: number of hat names in @hats
+ * @token: magic value to validate the hat change
+ * @permtest: true if this is just a permission test
+ *
+ * Change to the first profile specified in @hats that exists, and store
+ * the @hat_magic in the current task context.  If the count == 0 and the
+ * @token matches that stored in the current task context, return to the
+ * top level profile.
+ *
+ * Returns %0 on success, error otherwise.
+ */
+int aa_change_hat(const char *hats[], int count, u64 token, bool permtest)
+{
+	const struct cred *cred;
+	struct aa_task_cxt *cxt;
+	struct aa_profile *profile, *previous_profile, *hat = NULL;
+	char *name = NULL;
+	int i;
+	struct file_perms perms = {};
+	const char *target = NULL, *info = NULL;
+	int error = 0;
+
+	/* released below */
+	cred = get_current_cred();
+	cxt = cred->security;
+	profile = aa_cred_profile(cred);
+	previous_profile = cxt->previous;
+
+	if (unconfined(profile)) {
+		info = "unconfined";
+		error = -EPERM;
+		goto audit;
+	}
+
+	if (count) {
+		/* attempting to change into a new hat or switch to a sibling */
+		struct aa_profile *root;
+		root = PROFILE_IS_HAT(profile) ? profile->parent : profile;
+
+		/* find first matching hat */
+		for (i = 0; i < count && !hat; i++)
+			/* released below */
+			hat = aa_find_child(root, hats[i]);
+		if (!hat) {
+			if (!COMPLAIN_MODE(root) || permtest) {
+				if (list_empty(&root->base.profiles))
+					error = -ECHILD;
+				else
+					error = -ENOENT;
+				goto out;
+			}
+
+			/*
+			 * In complain mode and failed to match any hats.
+			 * Audit the failure is based off of the first hat
+			 * supplied.  This is done due how userspace
+			 * interacts with change_hat.
+			 *
+			 * TODO: Add logging of all failed hats
+			 */
+
+			/* freed below */
+			name = new_compound_name(root->base.hname, hats[0]);
+			target = name;
+			/* released below */
+			hat = aa_new_null_profile(profile, 1);
+			if (!hat) {
+				info = "failed null profile create";
+				error = -ENOMEM;
+				goto audit;
+			}
+		} else {
+			target = hat->base.hname;
+			if (!PROFILE_IS_HAT(hat)) {
+				info = "target not hat";
+				error = -EPERM;
+				goto audit;
+			}
+		}
+
+		error = may_change_ptraced_domain(current, hat);
+		if (error) {
+			info = "ptraced";
+			error = -EPERM;
+			goto audit;
+		}
+
+		if (!permtest) {
+			error = aa_set_current_hat(hat, token);
+			if (error == -EACCES)
+				/* kill task in case of brute force attacks */
+				perms.kill = AA_MAY_CHANGEHAT;
+			else if (name && !error)
+				/* reset error for learning of new hats */
+				error = -ENOENT;
+		}
+	} else if (previous_profile) {
+		/* Return to saved profile.  Kill task if restore fails
+		 * to avoid brute force attacks
+		 */
+		target = previous_profile->base.hname;
+		error = aa_restore_previous_profile(token);
+		perms.kill = AA_MAY_CHANGEHAT;
+	} else
+		/* ignore restores when there is no saved profile */
+		goto out;
+
+audit:
+	if (!permtest)
+		error = aa_audit_file(profile, &perms, GFP_KERNEL,
+				      OP_CHANGE_HAT, AA_MAY_CHANGEHAT, NULL,
+				      target, 0, info, error);
+
+out:
+	aa_put_profile(hat);
+	kfree(name);
+	put_cred(cred);
+
+	return error;
+}
+
+/**
+ * aa_change_profile - perform a one-way profile transition
+ * @ns_name: name of the profile namespace to change to (MAYBE NULL)
+ * @hname: name of profile to change to (MAYBE NULL)
+ * @onexec: whether this transition is to take place immediately or at exec
+ * @permtest: true if this is just a permission test
+ *
+ * Change to new profile @name.  Unlike with hats, there is no way
+ * to change back.  If @name isn't specified the current profile name is
+ * used.
+ * If @onexec then the transition is delayed until
+ * the next exec.
+ *
+ * Returns %0 on success, error otherwise.
+ */
+int aa_change_profile(const char *ns_name, const char *hname, bool onexec,
+		      bool permtest)
+{
+	const struct cred *cred;
+	struct aa_task_cxt *cxt;
+	struct aa_profile *profile, *target = NULL;
+	struct aa_namespace *ns = NULL;
+	struct file_perms perms = {};
+	const char *name = NULL, *info = NULL;
+	int op, error = 0;
+	u32 request;
+
+	if (!hname && !ns_name)
+		return -EINVAL;
+
+	if (onexec) {
+		request = AA_MAY_ONEXEC;
+		op = OP_CHANGE_ONEXEC;
+	} else {
+		request = AA_MAY_CHANGE_PROFILE;
+		op = OP_CHANGE_PROFILE;
+	}
+
+	cred = get_current_cred();
+	cxt = cred->security;
+	profile = aa_cred_profile(cred);
+
+	if (ns_name) {
+		/* released below */
+		ns = aa_find_namespace(profile->ns, ns_name);
+		if (!ns) {
+			/* we don't create new namespace in complain mode */
+			name = ns_name;
+			info = "namespace not found";
+			error = -ENOENT;
+			goto audit;
+		}
+	} else
+		/* released below */
+		ns = aa_get_namespace(profile->ns);
+
+	/* if the name was not specified, use the name of the current profile */
+	if (!hname) {
+		if (unconfined(profile))
+			hname = ns->unconfined->base.hname;
+		else
+			hname = profile->base.hname;
+	}
+
+	perms = change_profile_perms(profile, ns, hname, request,
+				     profile->file.start);
+	if (!(perms.allow & request)) {
+		error = -EACCES;
+		goto audit;
+	}
+
+	/* released below */
+	target = aa_lookup_profile(ns, hname);
+	if (!target) {
+		info = "profile not found";
+		error = -ENOENT;
+		if (permtest || !COMPLAIN_MODE(profile))
+			goto audit;
+		/* released below */
+		target = aa_new_null_profile(profile, 0);
+		if (!target) {
+			info = "failed null profile create";
+			error = -ENOMEM;
+			goto audit;
+		}
+	}
+
+	/* check if tracing task is allowed to trace target domain */
+	error = may_change_ptraced_domain(current, target);
+	if (error) {
+		info = "ptrace prevents transition";
+		goto audit;
+	}
+
+	if (permtest)
+		goto audit;
+
+	if (onexec)
+		error = aa_set_current_onexec(target);
+	else
+		error = aa_replace_current_profile(target);
+
+audit:
+	if (!permtest)
+		error = aa_audit_file(profile, &perms, GFP_KERNEL, op, request,
+				      name, hname, 0, info, error);
+
+	aa_put_namespace(ns);
+	aa_put_profile(target);
+	put_cred(cred);
+
+	return error;
+}
security/apparmor/include/domain.h new file +36 -0
new file mode 100644
index 0000000..de04464
@@ -0,0 +1,36 @@
+/*
+ * AppArmor security module
+ *
+ * This file contains AppArmor security domain transition function definitions.
+ *
+ * Copyright (C) 1998-2008 Novell/SUSE
+ * Copyright 2009-2010 Canonical Ltd.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, version 2 of the
+ * License.
+ */
+
+#include <linux/binfmts.h>
+#include <linux/types.h>
+
+#ifndef __AA_DOMAIN_H
+#define __AA_DOMAIN_H
+
+struct aa_domain {
+	int size;
+	char **table;
+};
+
+int apparmor_bprm_set_creds(struct linux_binprm *bprm);
+int apparmor_bprm_secureexec(struct linux_binprm *bprm);
+void apparmor_bprm_committing_creds(struct linux_binprm *bprm);
+void apparmor_bprm_committed_creds(struct linux_binprm *bprm);
+
+void aa_free_domain_entries(struct aa_domain *domain);
+int aa_change_hat(const char *hats[], int count, u64 token, bool permtest);
+int aa_change_profile(const char *ns_name, const char *name, bool onexec,
+		      bool permtest);
+
+#endif /* __AA_DOMAIN_H */
Signature · 1 line
1.7.1
author maintainer
#16 lore raw

PATCH 11/13 AppArmor: LSM interface, and security module initialization

In reply to John Johansen

AppArmor hooks to interface with the LSM, module parameters and module initialization.

---
 security/apparmor/lsm.c |  939 +++++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 939 insertions(+), 0 deletions(-)
 create mode 100644 security/apparmor/lsm.c
security/apparmor/lsm.c new file +939 -0
new file mode 100644
index 0000000..7daf0d5
@@ -0,0 +1,939 @@
+/*
+ * AppArmor security module
+ *
+ * This file contains AppArmor LSM hooks.
+ *
+ * Copyright (C) 1998-2008 Novell/SUSE
+ * Copyright 2009-2010 Canonical Ltd.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, version 2 of the
+ * License.
+ */
+
+#include <linux/security.h>
+#include <linux/moduleparam.h>
+#include <linux/mm.h>
+#include <linux/mman.h>
+#include <linux/mount.h>
+#include <linux/namei.h>
+#include <linux/ptrace.h>
+#include <linux/ctype.h>
+#include <linux/sysctl.h>
+#include <linux/audit.h>
+#include <net/sock.h>
+
+#include "include/apparmor.h"
+#include "include/apparmorfs.h"
+#include "include/audit.h"
+#include "include/capability.h"
+#include "include/context.h"
+#include "include/file.h"
+#include "include/ipc.h"
+#include "include/path.h"
+#include "include/policy.h"
+#include "include/procattr.h"
+
+/* Flag indicating whether initialization completed */
+int apparmor_initialized __initdata;
+
+/*
+ * LSM hook functions
+ */
+
+/*
+ * free the associated aa_task_cxt and put its profiles
+ */
+static void apparmor_cred_free(struct cred *cred)
+{
+	aa_free_task_context(cred->security);
+	cred->security = NULL;
+}
+
+/*
+ * allocate the apparmor part of blank credentials
+ */
+static int apparmor_cred_alloc_blank(struct cred *cred, gfp_t gfp)
+{
+	/* freed by apparmor_cred_free */
+	struct aa_task_cxt *cxt = aa_alloc_task_context(gfp);
+	if (!cxt)
+		return -ENOMEM;
+
+	cred->security = cxt;
+	return 0;
+}
+
+/*
+ * prepare new aa_task_cxt for modification by prepare_cred block
+ */
+static int apparmor_cred_prepare(struct cred *new, const struct cred *old,
+				 gfp_t gfp)
+{
+	/* freed by apparmor_cred_free */
+	struct aa_task_cxt *cxt = aa_alloc_task_context(gfp);
+	if (!cxt)
+		return -ENOMEM;
+
+	aa_dup_task_context(cxt, old->security);
+	new->security = cxt;
+	return 0;
+}
+
+/*
+ * transfer the apparmor data to a blank set of creds
+ */
+static void apparmor_cred_transfer(struct cred *new, const struct cred *old)
+{
+	const struct aa_task_cxt *old_cxt = old->security;
+	struct aa_task_cxt *new_cxt = new->security;
+
+	aa_dup_task_context(new_cxt, old_cxt);
+}
+
+static int apparmor_ptrace_access_check(struct task_struct *child,
+					unsigned int mode)
+{
+	int error = cap_ptrace_access_check(child, mode);
+	if (error)
+		return error;
+
+	return aa_ptrace(current, child, mode);
+}
+
+static int apparmor_ptrace_traceme(struct task_struct *parent)
+{
+	int error = cap_ptrace_traceme(parent);
+	if (error)
+		return error;
+
+	return aa_ptrace(parent, current, PTRACE_MODE_ATTACH);
+}
+
+/* Derived from security/commoncap.c:cap_capget */
+static int apparmor_capget(struct task_struct *target, kernel_cap_t *effective,
+			   kernel_cap_t *inheritable, kernel_cap_t *permitted)
+{
+	struct aa_profile *profile;
+	const struct cred *cred;
+
+	rcu_read_lock();
+	cred = __task_cred(target);
+	profile = aa_cred_profile(cred);
+
+	*effective = cred->cap_effective;
+	*inheritable = cred->cap_inheritable;
+	*permitted = cred->cap_permitted;
+
+	if (!unconfined(profile)) {
+		*effective = cap_intersect(*effective, profile->caps.allow);
+		*permitted = cap_intersect(*permitted, profile->caps.allow);
+	}
+	rcu_read_unlock();
+
+	return 0;
+}
+
+static int apparmor_capable(struct task_struct *task, const struct cred *cred,
+			    int cap, int audit)
+{
+	struct aa_profile *profile;
+	/* cap_capable returns 0 on success, else -EPERM */
+	int error = cap_capable(task, cred, cap, audit);
+	if (!error) {
+		profile = aa_cred_profile(cred);
+		if (!unconfined(profile))
+			error = aa_capable(task, profile, cap, audit);
+	}
+	return error;
+}
+
+/**
+ * common_perm - basic common permission check wrapper fn for paths
+ * @op: operation being checked
+ * @path: path to check permission of  (NOT NULL)
+ * @mask: requested permissions mask
+ * @cond: conditional info for the permission request  (NOT NULL)
+ *
+ * Returns: %0 else error code if error or permission denied
+ */
+static int common_perm(int op, struct path *path, u32 mask,
+		       struct path_cond *cond)
+{
+	struct aa_profile *profile;
+	int error = 0;
+
+	profile = __aa_current_profile();
+	if (!unconfined(profile))
+		error = aa_path_perm(op, profile, path, 0, mask, cond);
+
+	return error;
+}
+
+/**
+ * common_perm_dir_dentry - common permission wrapper when path is dir, dentry
+ * @op: operation being checked
+ * @dir: directory of the dentry  (NOT NULL)
+ * @dentry: dentry to check  (NOT NULL)
+ * @mask: requested permissions mask
+ * @cond: conditional info for the permission request  (NOT NULL)
+ *
+ * Returns: %0 else error code if error or permission denied
+ */
+static int common_perm_dir_dentry(int op, struct path *dir,
+				  struct dentry *dentry, u32 mask,
+				  struct path_cond *cond)
+{
+	struct path path = { dir->mnt, dentry };
+
+	return common_perm(op, &path, mask, cond);
+}
+
+/**
+ * common_perm_mnt_dentry - common permission wrapper when mnt, dentry
+ * @op: operation being checked
+ * @mnt: mount point of dentry (NOT NULL)
+ * @dentry: dentry to check  (NOT NULL)
+ * @mask: requested permissions mask
+ *
+ * Returns: %0 else error code if error or permission denied
+ */
+static int common_perm_mnt_dentry(int op, struct vfsmount *mnt,
+				  struct dentry *dentry, u32 mask)
+{
+	struct path path = { mnt, dentry };
+	struct path_cond cond = { dentry->d_inode->i_uid,
+				  dentry->d_inode->i_mode
+	};
+
+	return common_perm(op, &path, mask, &cond);
+}
+
+/**
+ * common_perm_rm - common permission wrapper for operations doing rm
+ * @op: operation being checked
+ * @dir: directory that the dentry is in  (NOT NULL)
+ * @dentry: dentry being rm'd  (NOT NULL)
+ * @mask: requested permission mask
+ *
+ * Returns: %0 else error code if error or permission denied
+ */
+static int common_perm_rm(int op, struct path *dir,
+			  struct dentry *dentry, u32 mask)
+{
+	struct inode *inode = dentry->d_inode;
+	struct path_cond cond = { };
+
+	if (!inode || !dir->mnt || !mediated_filesystem(inode))
+		return 0;
+
+	cond.uid = inode->i_uid;
+	cond.mode = inode->i_mode;
+
+	return common_perm_dir_dentry(op, dir, dentry, mask, &cond);
+}
+
+/**
+ * common_perm_create - common permission wrapper for operations doing create
+ * @op: operation being checked
+ * @dir: directory that dentry will be created in  (NOT NULL)
+ * @dentry: dentry to create   (NOT NULL)
+ * @mask: request permission mask
+ * @mode: created file mode
+ *
+ * Returns: %0 else error code if error or permission denied
+ */
+static int common_perm_create(int op, struct path *dir, struct dentry *dentry,
+			      u32 mask, umode_t mode)
+{
+	struct path_cond cond = { current_fsuid(), mode };
+
+	if (!dir->mnt || !mediated_filesystem(dir->dentry->d_inode))
+		return 0;
+
+	return common_perm_dir_dentry(op, dir, dentry, mask, &cond);
+}
+
+static int apparmor_path_unlink(struct path *dir, struct dentry *dentry)
+{
+	return common_perm_rm(OP_UNLINK, dir, dentry, AA_MAY_DELETE);
+}
+
+static int apparmor_path_mkdir(struct path *dir, struct dentry *dentry,
+			       int mode)
+{
+	return common_perm_create(OP_MKDIR, dir, dentry, AA_MAY_CREATE,
+				  S_IFDIR);
+}
+
+static int apparmor_path_rmdir(struct path *dir, struct dentry *dentry)
+{
+	return common_perm_rm(OP_RMDIR, dir, dentry, AA_MAY_DELETE);
+}
+
+static int apparmor_path_mknod(struct path *dir, struct dentry *dentry,
+			       int mode, unsigned int dev)
+{
+	return common_perm_create(OP_MKNOD, dir, dentry, AA_MAY_CREATE, mode);
+}
+
+static int apparmor_path_truncate(struct path *path, loff_t length,
+				  unsigned int time_attrs)
+{
+	struct path_cond cond = { path->dentry->d_inode->i_uid,
+				  path->dentry->d_inode->i_mode
+	};
+
+	if (!path->mnt || !mediated_filesystem(path->dentry->d_inode))
+		return 0;
+
+	return common_perm(OP_TRUNC, path, MAY_WRITE | AA_MAY_META_WRITE,
+			   &cond);
+}
+
+static int apparmor_path_symlink(struct path *dir, struct dentry *dentry,
+				 const char *old_name)
+{
+	return common_perm_create(OP_SYMLINK, dir, dentry, AA_MAY_CREATE,
+				  S_IFLNK);
+}
+
+static int apparmor_path_link(struct dentry *old_dentry, struct path *new_dir,
+			      struct dentry *new_dentry)
+{
+	struct aa_profile *profile;
+	int error = 0;
+
+	if (!mediated_filesystem(old_dentry->d_inode))
+		return 0;
+
+	profile = aa_current_profile();
+	if (!unconfined(profile))
+		error = aa_path_link(profile, old_dentry, new_dir, new_dentry);
+	return error;
+}
+
+static int apparmor_path_rename(struct path *old_dir, struct dentry *old_dentry,
+				struct path *new_dir, struct dentry *new_dentry)
+{
+	struct aa_profile *profile;
+	int error = 0;
+
+	if (!mediated_filesystem(old_dentry->d_inode))
+		return 0;
+
+	profile = aa_current_profile();
+	if (!unconfined(profile)) {
+		struct path old_path = { old_dir->mnt, old_dentry };
+		struct path new_path = { new_dir->mnt, new_dentry };
+		struct path_cond cond = { old_dentry->d_inode->i_uid,
+					  old_dentry->d_inode->i_mode
+		};
+
+		error = aa_path_perm(OP_RENAME_SRC, profile, &old_path, 0,
+				     MAY_READ | AA_MAY_META_READ | MAY_WRITE |
+				     AA_MAY_META_WRITE | AA_MAY_DELETE,
+				     &cond);
+		if (!error)
+			error = aa_path_perm(OP_RENAME_DEST, profile, &new_path,
+					     0, MAY_WRITE | AA_MAY_META_WRITE |
+					     AA_MAY_CREATE, &cond);
+
+	}
+	return error;
+}
+
+static int apparmor_path_chmod(struct dentry *dentry, struct vfsmount *mnt,
+			       mode_t mode)
+{
+	if (!mediated_filesystem(dentry->d_inode))
+		return 0;
+
+	return common_perm_mnt_dentry(OP_CHMOD, mnt, dentry, AA_MAY_CHMOD);
+}
+
+static int apparmor_path_chown(struct path *path, uid_t uid, gid_t gid)
+{
+	struct path_cond cond =  { path->dentry->d_inode->i_uid,
+				   path->dentry->d_inode->i_mode
+	};
+
+	if (!mediated_filesystem(path->dentry->d_inode))
+		return 0;
+
+	return common_perm(OP_CHOWN, path, AA_MAY_CHOWN, &cond);
+}
+
+static int apparmor_inode_getattr(struct vfsmount *mnt, struct dentry *dentry)
+{
+	if (!mediated_filesystem(dentry->d_inode))
+		return 0;
+
+	return common_perm_mnt_dentry(OP_GETATTR, mnt, dentry,
+				      AA_MAY_META_READ);
+}
+
+static int apparmor_dentry_open(struct file *file, const struct cred *cred)
+{
+	struct aa_file_cxt *fcxt = file->f_security;
+	struct aa_profile *profile;
+	int error = 0;
+
+	if (!mediated_filesystem(file->f_path.dentry->d_inode))
+		return 0;
+
+	/* If in exec, permission is handled by bprm hooks.
+	 * Cache permissions granted by the previous exec check, with
+	 * implicit read and executable mmap which are required to
+	 * actually execute the image.
+	 */
+	if (current->in_execve) {
+		fcxt->allow = MAY_EXEC | MAY_READ | AA_EXEC_MMAP;
+		return 0;
+	}
+
+	profile = aa_cred_profile(cred);
+	if (!unconfined(profile)) {
+		struct inode *inode = file->f_path.dentry->d_inode;
+		struct path_cond cond = { inode->i_uid, inode->i_mode };
+
+		error = aa_path_perm(OP_OPEN, profile, &file->f_path, 0,
+				     aa_map_file_to_perms(file), &cond);
+		/* todo cache full allowed permissions set and state */
+		fcxt->allow = aa_map_file_to_perms(file);
+	}
+
+	return error;
+}
+
+static int apparmor_file_alloc_security(struct file *file)
+{
+	/* freed by apparmor_file_free_security */
+	file->f_security = aa_alloc_file_context(GFP_KERNEL);
+	if (!file->f_security)
+		return -ENOMEM;
+	return 0;
+
+}
+
+static void apparmor_file_free_security(struct file *file)
+{
+	struct aa_file_cxt *cxt = file->f_security;
+
+	aa_free_file_context(cxt);
+}
+
+static int common_file_perm(int op, struct file *file, u32 mask)
+{
+	struct aa_file_cxt *fcxt = file->f_security;
+	struct aa_profile *profile, *fprofile = aa_cred_profile(file->f_cred);
+	int error = 0;
+
+	BUG_ON(!fprofile);
+
+	if (!file->f_path.mnt ||
+	    !mediated_filesystem(file->f_path.dentry->d_inode))
+		return 0;
+
+	profile = __aa_current_profile();
+
+	/* revalidate access, if task is unconfined, or the cached cred
+	 * doesn't match or if the request is for more permissions than
+	 * was granted.
+	 *
+	 * Note: the test for !unconfined(fprofile) is to handle file
+	 *       delegation from unconfined tasks
+	 */
+	if (!unconfined(profile) && !unconfined(fprofile) &&
+	    ((fprofile != profile) || (mask & ~fcxt->allow)))
+		error = aa_file_perm(op, profile, file, mask);
+
+	return error;
+}
+
+static int apparmor_file_permission(struct file *file, int mask)
+{
+	return common_file_perm(OP_FPERM, file, mask);
+}
+
+static int apparmor_file_lock(struct file *file, unsigned int cmd)
+{
+	u32 mask = AA_MAY_LOCK;
+
+	if (cmd == F_WRLCK)
+		mask |= MAY_WRITE;
+
+	return common_file_perm(OP_FLOCK, file, mask);
+}
+
+static int common_mmap(int op, struct file *file, unsigned long prot,
+		       unsigned long flags)
+{
+	struct dentry *dentry;
+	int mask = 0;
+
+	if (!file || !file->f_security)
+		return 0;
+
+	if (prot & PROT_READ)
+		mask |= MAY_READ;
+	/*
+	 * Private mappings don't require write perms since they don't
+	 * write back to the files
+	 */
+	if ((prot & PROT_WRITE) && !(flags & MAP_PRIVATE))
+		mask |= MAY_WRITE;
+	if (prot & PROT_EXEC)
+		mask |= AA_EXEC_MMAP;
+
+	dentry = file->f_path.dentry;
+	return common_file_perm(op, file, mask);
+}
+
+static int apparmor_file_mmap(struct file *file, unsigned long reqprot,
+			      unsigned long prot, unsigned long flags,
+			      unsigned long addr, unsigned long addr_only)
+{
+	int rc = 0;
+
+	/* do DAC check */
+	rc = cap_file_mmap(file, reqprot, prot, flags, addr, addr_only);
+	if (rc || addr_only)
+		return rc;
+
+	return common_mmap(OP_FMMAP, file, prot, flags);
+}
+
+static int apparmor_file_mprotect(struct vm_area_struct *vma,
+				  unsigned long reqprot, unsigned long prot)
+{
+	return common_mmap(OP_FMPROT, vma->vm_file, prot,
+			   !(vma->vm_flags & VM_SHARED) ? MAP_PRIVATE : 0);
+}
+
+static int apparmor_getprocattr(struct task_struct *task, char *name,
+				char **value)
+{
+	int error = -ENOENT;
+	struct aa_profile *profile;
+	/* released below */
+	const struct cred *cred = get_task_cred(task);
+	struct aa_task_cxt *cxt = cred->security;
+	profile = aa_cred_profile(cred);
+
+	if (strcmp(name, "current") == 0)
+		error = aa_getprocattr(aa_newest_version(cxt->profile),
+				       value);
+	else if (strcmp(name, "prev") == 0  && cxt->previous)
+		error = aa_getprocattr(aa_newest_version(cxt->previous),
+				       value);
+	else if (strcmp(name, "exec") == 0 && cxt->onexec)
+		error = aa_getprocattr(aa_newest_version(cxt->onexec),
+				       value);
+	else
+		error = -EINVAL;
+
+	put_cred(cred);
+
+	return error;
+}
+
+static int apparmor_setprocattr(struct task_struct *task, char *name,
+				void *value, size_t size)
+{
+	char *command, *args = value;
+	size_t arg_size;
+	int error;
+
+	if (size == 0)
+		return -EINVAL;
+	/* args points to a PAGE_SIZE buffer, AppArmor requires that
+	 * the buffer must be null terminated or have size <= PAGE_SIZE -1
+	 * so that AppArmor can null terminate them
+	 */
+	if (args[size - 1] != '\0') {
+		if (size == PAGE_SIZE)
+			return -EINVAL;
+		args[size] = '\0';
+	}
+
+	/* task can only write its own attributes */
+	if (current != task)
+		return -EACCES;
+
+	args = value;
+	args = strim(args);
+	command = strsep(&args, " ");
+	if (!args)
+		return -EINVAL;
+	args = skip_spaces(args);
+	if (!*args)
+		return -EINVAL;
+
+	arg_size = size - (args - (char *) value);
+	if (strcmp(name, "current") == 0) {
+		if (strcmp(command, "changehat") == 0) {
+			error = aa_setprocattr_changehat(args, arg_size,
+							 !AA_DO_TEST);
+		} else if (strcmp(command, "permhat") == 0) {
+			error = aa_setprocattr_changehat(args, arg_size,
+							 AA_DO_TEST);
+		} else if (strcmp(command, "changeprofile") == 0) {
+			error = aa_setprocattr_changeprofile(args, !AA_ONEXEC,
+							     !AA_DO_TEST);
+		} else if (strcmp(command, "permprofile") == 0) {
+			error = aa_setprocattr_changeprofile(args, !AA_ONEXEC,
+							     AA_DO_TEST);
+		} else if (strcmp(command, "permipc") == 0) {
+			error = aa_setprocattr_permipc(args);
+		} else {
+			struct common_audit_data sa;
+			COMMON_AUDIT_DATA_INIT(&sa, NONE);
+			sa.aad.op = OP_SETPROCATTR;
+			sa.aad.info = name;
+			sa.aad.error = -EINVAL;
+			return aa_audit(AUDIT_APPARMOR_DENIED, NULL, GFP_KERNEL,
+					&sa, NULL);
+		}
+	} else if (strcmp(name, "exec") == 0) {
+		error = aa_setprocattr_changeprofile(args, AA_ONEXEC,
+						     !AA_DO_TEST);
+	} else {
+		/* only support the "current" and "exec" process attributes */
+		return -EINVAL;
+	}
+	if (!error)
+		error = size;
+	return error;
+}
+
+static int apparmor_task_setrlimit(unsigned int resource,
+				   struct rlimit *new_rlim)
+{
+	struct aa_profile *profile = aa_current_profile();
+	int error = 0;
+
+	if (!unconfined(profile))
+		error = aa_task_setrlimit(profile, resource, new_rlim);
+
+	return error;
+}
+
+static struct security_operations apparmor_ops = {
+	.name =				"apparmor",
+
+	.ptrace_access_check =		apparmor_ptrace_access_check,
+	.ptrace_traceme =		apparmor_ptrace_traceme,
+	.capget =			apparmor_capget,
+	.capable =			apparmor_capable,
+
+	.path_link =			apparmor_path_link,
+	.path_unlink =			apparmor_path_unlink,
+	.path_symlink =			apparmor_path_symlink,
+	.path_mkdir =			apparmor_path_mkdir,
+	.path_rmdir =			apparmor_path_rmdir,
+	.path_mknod =			apparmor_path_mknod,
+	.path_rename =			apparmor_path_rename,
+	.path_chmod =			apparmor_path_chmod,
+	.path_chown =			apparmor_path_chown,
+	.path_truncate =		apparmor_path_truncate,
+	.dentry_open =			apparmor_dentry_open,
+	.inode_getattr =                apparmor_inode_getattr,
+
+	.file_permission =		apparmor_file_permission,
+	.file_alloc_security =		apparmor_file_alloc_security,
+	.file_free_security =		apparmor_file_free_security,
+	.file_mmap =			apparmor_file_mmap,
+	.file_mprotect =		apparmor_file_mprotect,
+	.file_lock =			apparmor_file_lock,
+
+	.getprocattr =			apparmor_getprocattr,
+	.setprocattr =			apparmor_setprocattr,
+
+	.cred_alloc_blank =		apparmor_cred_alloc_blank,
+	.cred_free =			apparmor_cred_free,
+	.cred_prepare =			apparmor_cred_prepare,
+	.cred_transfer =		apparmor_cred_transfer,
+
+	.bprm_set_creds =		apparmor_bprm_set_creds,
+	.bprm_committing_creds =	apparmor_bprm_committing_creds,
+	.bprm_committed_creds =		apparmor_bprm_committed_creds,
+	.bprm_secureexec =		apparmor_bprm_secureexec,
+
+	.task_setrlimit =		apparmor_task_setrlimit,
+};
+
+/*
+ * AppArmor sysfs module parameters
+ */
+
+static int param_set_aabool(const char *val, struct kernel_param *kp);
+static int param_get_aabool(char *buffer, struct kernel_param *kp);
+#define param_check_aabool(name, p) __param_check(name, p, int)
+
+static int param_set_aauint(const char *val, struct kernel_param *kp);
+static int param_get_aauint(char *buffer, struct kernel_param *kp);
+#define param_check_aauint(name, p) __param_check(name, p, int)
+
+static int param_set_aalockpolicy(const char *val, struct kernel_param *kp);
+static int param_get_aalockpolicy(char *buffer, struct kernel_param *kp);
+#define param_check_aalockpolicy(name, p) __param_check(name, p, int)
+
+static int param_set_audit(const char *val, struct kernel_param *kp);
+static int param_get_audit(char *buffer, struct kernel_param *kp);
+#define param_check_audit(name, p) __param_check(name, p, int)
+
+static int param_set_mode(const char *val, struct kernel_param *kp);
+static int param_get_mode(char *buffer, struct kernel_param *kp);
+#define param_check_mode(name, p) __param_check(name, p, int)
+
+/* Flag values, also controllable via /sys/module/apparmor/parameters
+ * We define special types as we want to do additional mediation.
+ */
+
+/* AppArmor global enforcement switch - complain, enforce, kill */
+enum profile_mode aa_g_profile_mode = APPARMOR_ENFORCE;
+module_param_call(mode, param_set_mode, param_get_mode,
+		  &aa_g_profile_mode, S_IRUSR | S_IWUSR);
+
+/* Debug mode */
+int aa_g_debug;
+module_param_named(debug, aa_g_debug, aabool, S_IRUSR | S_IWUSR);
+
+/* Audit mode */
+enum audit_mode aa_g_audit;
+module_param_call(audit, param_set_audit, param_get_audit,
+		  &aa_g_audit, S_IRUSR | S_IWUSR);
+
+/* Determines if audit header is included in audited messages.  This
+ * provides more context if the audit daemon is not running
+ */
+int aa_g_audit_header = 1;
+module_param_named(audit_header, aa_g_audit_header, aabool,
+		   S_IRUSR | S_IWUSR);
+
+/* lock out loading/removal of policy
+ * TODO: add in at boot loading of policy, which is the only way to
+ *       load policy, if lock_policy is set
+ */
+int aa_g_lock_policy;
+module_param_named(lock_policy, aa_g_lock_policy, aalockpolicy,
+		   S_IRUSR | S_IWUSR);
+
+/* Syscall logging mode */
+int aa_g_logsyscall;
+module_param_named(logsyscall, aa_g_logsyscall, aabool, S_IRUSR | S_IWUSR);
+
+/* Maximum pathname length before accesses will start getting rejected */
+unsigned int aa_g_path_max = 2 * PATH_MAX;
+module_param_named(path_max, aa_g_path_max, aauint, S_IRUSR | S_IWUSR);
+
+/* Determines how paranoid loading of policy is and how much verification
+ * on the loaded policy is done.
+ */
+int aa_g_paranoid_load = 1;
+module_param_named(paranoid_load, aa_g_paranoid_load, aabool,
+		   S_IRUSR | S_IWUSR);
+
+/* Boot time disable flag */
+static unsigned int apparmor_enabled = CONFIG_SECURITY_APPARMOR_BOOTPARAM_VALUE;
+module_param_named(enabled, apparmor_enabled, aabool, S_IRUSR);
+
+static int __init apparmor_enabled_setup(char *str)
+{
+	unsigned long enabled;
+	int error = strict_strtoul(str, 0, &enabled);
+	if (!error)
+		apparmor_enabled = enabled ? 1 : 0;
+	return 1;
+}
+
+__setup("apparmor=", apparmor_enabled_setup);
+
+/* set global flag turning off the ability to load policy */
+static int param_set_aalockpolicy(const char *val, struct kernel_param *kp)
+{
+	if (!capable(CAP_MAC_ADMIN))
+		return -EPERM;
+	if (aa_g_lock_policy)
+		return -EACCES;
+	return param_set_bool(val, kp);
+}
+
+static int param_get_aalockpolicy(char *buffer, struct kernel_param *kp)
+{
+	if (!capable(CAP_MAC_ADMIN))
+		return -EPERM;
+	return param_get_bool(buffer, kp);
+}
+
+static int param_set_aabool(const char *val, struct kernel_param *kp)
+{
+	if (!capable(CAP_MAC_ADMIN))
+		return -EPERM;
+	return param_set_bool(val, kp);
+}
+
+static int param_get_aabool(char *buffer, struct kernel_param *kp)
+{
+	if (!capable(CAP_MAC_ADMIN))
+		return -EPERM;
+	return param_get_bool(buffer, kp);
+}
+
+static int param_set_aauint(const char *val, struct kernel_param *kp)
+{
+	if (!capable(CAP_MAC_ADMIN))
+		return -EPERM;
+	return param_set_uint(val, kp);
+}
+
+static int param_get_aauint(char *buffer, struct kernel_param *kp)
+{
+	if (!capable(CAP_MAC_ADMIN))
+		return -EPERM;
+	return param_get_uint(buffer, kp);
+}
+
+static int param_get_audit(char *buffer, struct kernel_param *kp)
+{
+	if (!capable(CAP_MAC_ADMIN))
+		return -EPERM;
+
+	if (!apparmor_enabled)
+		return -EINVAL;
+
+	return sprintf(buffer, "%s", audit_mode_names[aa_g_audit]);
+}
+
+static int param_set_audit(const char *val, struct kernel_param *kp)
+{
+	int i;
+	if (!capable(CAP_MAC_ADMIN))
+		return -EPERM;
+
+	if (!apparmor_enabled)
+		return -EINVAL;
+
+	if (!val)
+		return -EINVAL;
+
+	for (i = 0; i < AUDIT_MAX_INDEX; i++) {
+		if (strcmp(val, audit_mode_names[i]) == 0) {
+			aa_g_audit = i;
+			return 0;
+		}
+	}
+
+	return -EINVAL;
+}
+
+static int param_get_mode(char *buffer, struct kernel_param *kp)
+{
+	if (!capable(CAP_MAC_ADMIN))
+		return -EPERM;
+
+	if (!apparmor_enabled)
+		return -EINVAL;
+
+	return sprintf(buffer, "%s", profile_mode_names[aa_g_profile_mode]);
+}
+
+static int param_set_mode(const char *val, struct kernel_param *kp)
+{
+	int i;
+	if (!capable(CAP_MAC_ADMIN))
+		return -EPERM;
+
+	if (!apparmor_enabled)
+		return -EINVAL;
+
+	if (!val)
+		return -EINVAL;
+
+	for (i = 0; i < APPARMOR_NAMES_MAX_INDEX; i++) {
+		if (strcmp(val, profile_mode_names[i]) == 0) {
+			aa_g_profile_mode = i;
+			return 0;
+		}
+	}
+
+	return -EINVAL;
+}
+
+/*
+ * AppArmor init functions
+ */
+
+/**
+ * set_init_cxt - set a task context and profile on the first task.
+ *
+ * TODO: allow setting an alternate profile than unconfined
+ */
+static int __init set_init_cxt(void)
+{
+	struct cred *cred = (struct cred *)current->real_cred;
+	struct aa_task_cxt *cxt;
+
+	cxt = aa_alloc_task_context(GFP_KERNEL);
+	if (!cxt)
+		return -ENOMEM;
+
+	cxt->profile = aa_get_profile(root_ns->unconfined);
+	cred->security = cxt;
+
+	return 0;
+}
+
+static int __init apparmor_init(void)
+{
+	int error;
+
+	if (!apparmor_enabled || !security_module_enable(&apparmor_ops)) {
+		aa_info_message("AppArmor disabled by boot time parameter");
+		apparmor_enabled = 0;
+		return 0;
+	}
+
+	error = aa_alloc_root_ns();
+	if (error) {
+		AA_ERROR("Unable to allocate default profile namespace\n");
+		goto alloc_out;
+	}
+
+	error = set_init_cxt();
+	if (error) {
+		AA_ERROR("Failed to set context on init task\n");
+		goto register_security_out;
+	}
+
+	error = register_security(&apparmor_ops);
+	if (error) {
+		AA_ERROR("Unable to register AppArmor\n");
+		goto register_security_out;
+	}
+
+	/* Report that AppArmor successfully initialized */
+	apparmor_initialized = 1;
+	if (aa_g_profile_mode == APPARMOR_COMPLAIN)
+		aa_info_message("AppArmor initialized: complain mode enabled");
+	else if (aa_g_profile_mode == APPARMOR_KILL)
+		aa_info_message("AppArmor initialized: kill mode enabled");
+	else
+		aa_info_message("AppArmor initialized");
+
+	return error;
+
+register_security_out:
+	aa_free_root_ns();
+
+alloc_out:
+	aa_destroy_aafs();
+
+	apparmor_enabled = 0;
+	return error;
+
+}
+
+security_initcall(apparmor_init);
Signature · 1 line
1.7.1
author maintainer
#17 lore raw

PATCH 12/13 AppArmor: Enable configuring and building of the AppArmor security module

In reply to John Johansen

Kconfig and Makefiles to enable configuration and building of AppArmor.

---
 security/Kconfig             |    6 ++++++
 security/Makefile            |    2 ++
 security/apparmor/.gitignore |    5 +++++
 security/apparmor/Kconfig    |   31 +++++++++++++++++++++++++++++++
 security/apparmor/Makefile   |   24 ++++++++++++++++++++++++
 5 files changed, 68 insertions(+), 0 deletions(-)
 create mode 100644 security/apparmor/.gitignore
 create mode 100644 security/apparmor/Kconfig
 create mode 100644 security/apparmor/Makefile
security/Kconfig +6 -0
index 226b955..bd72ae6 100644
@@ -140,6 +140,7 @@ config LSM_MMAP_MIN_ADDR
 source security/selinux/Kconfig
 source security/smack/Kconfig
 source security/tomoyo/Kconfig
+source security/apparmor/Kconfig
 
 source security/integrity/ima/Kconfig
 
@@ -148,6 +149,7 @@ choice
 	default DEFAULT_SECURITY_SELINUX if SECURITY_SELINUX
 	default DEFAULT_SECURITY_SMACK if SECURITY_SMACK
 	default DEFAULT_SECURITY_TOMOYO if SECURITY_TOMOYO
+	default DEFAULT_SECURITY_APPARMOR if SECURITY_APPARMOR
 	default DEFAULT_SECURITY_DAC
 
 	help
@@ -163,6 +165,9 @@ choice
 	config DEFAULT_SECURITY_TOMOYO
 		bool "TOMOYO" if SECURITY_TOMOYO=y
 
+	config DEFAULT_SECURITY_APPARMOR
+		bool "AppArmor" if SECURITY_APPARMOR=y
+
 	config DEFAULT_SECURITY_DAC
 		bool "Unix Discretionary Access Controls"
 
@@ -173,6 +178,7 @@ config DEFAULT_SECURITY
 	default "selinux" if DEFAULT_SECURITY_SELINUX
 	default "smack" if DEFAULT_SECURITY_SMACK
 	default "tomoyo" if DEFAULT_SECURITY_TOMOYO
+	default "apparmor" if DEFAULT_SECURITY_APPARMOR
 	default "" if DEFAULT_SECURITY_DAC
 
 endmenu
security/Makefile +2 -0
index da20a19..8bb0fe9 100644
@@ -6,6 +6,7 @@ obj-$(CONFIG_KEYS)			+= keys/
 subdir-$(CONFIG_SECURITY_SELINUX)	+= selinux
 subdir-$(CONFIG_SECURITY_SMACK)		+= smack
 subdir-$(CONFIG_SECURITY_TOMOYO)        += tomoyo
+subdir-$(CONFIG_SECURITY_APPARMOR)	+= apparmor
 
 # always enable default capabilities
 obj-y					+= commoncap.o
@@ -19,6 +20,7 @@ obj-$(CONFIG_SECURITY_SELINUX)		+= selinux/built-in.o
 obj-$(CONFIG_SECURITY_SMACK)		+= smack/built-in.o
 obj-$(CONFIG_AUDIT)			+= lsm_audit.o
 obj-$(CONFIG_SECURITY_TOMOYO)		+= tomoyo/built-in.o
+obj-$(CONFIG_SECURITY_APPARMOR)		+= apparmor/built-in.o
 obj-$(CONFIG_CGROUP_DEVICE)		+= device_cgroup.o
 
 # Object integrity file lists
security/apparmor/.gitignore new file +5 -0
new file mode 100644
index 0000000..0a0a99f
@@ -0,0 +1,5 @@
+#
+# Generated include files
+#
+af_names.h
+capability_names.h
security/apparmor/Kconfig new file +31 -0
new file mode 100644
index 0000000..72555b9
@@ -0,0 +1,31 @@
+config SECURITY_APPARMOR
+	bool "AppArmor support"
+	depends on SECURITY
+	select AUDIT
+	select SECURITY_PATH
+	select SECURITYFS
+	select SECURITY_NETWORK
+	default n
+	help
+	  This enables the AppArmor security module.
+	  Required userspace tools (if they are not included in your
+	  distribution) and further information may be found at
+	  http://apparmor.wiki.kernel.org
+
+	  If you are unsure how to answer this question, answer N.
+
+config SECURITY_APPARMOR_BOOTPARAM_VALUE
+	int "AppArmor boot parameter default value"
+	depends on SECURITY_APPARMOR
+	range 0 1
+	default 1
+	help
+	  This option sets the default value for the kernel parameter
+	  'apparmor', which allows AppArmor to be enabled or disabled
+          at boot.  If this option is set to 0 (zero), the AppArmor
+	  kernel parameter will default to 0, disabling AppArmor at
+	  boot.  If this option is set to 1 (one), the AppArmor
+	  kernel parameter will default to 1, enabling AppArmor at
+	  boot.
+
+	  If you are unsure how to answer this question, answer 1.
security/apparmor/Makefile new file +24 -0
new file mode 100644
index 0000000..f204869
@@ -0,0 +1,24 @@
+# Makefile for AppArmor Linux Security Module
+#
+obj-$(CONFIG_SECURITY_APPARMOR) += apparmor.o
+
+apparmor-y := apparmorfs.o audit.o capability.o context.o ipc.o lib.o match.o \
+              path.o domain.o policy.o policy_unpack.o procattr.o lsm.o \
+              resource.o sid.o file.o
+
+clean-files: capability_names.h af_names.h
+
+quiet_cmd_make-caps = GEN     $@
+cmd_make-caps = echo "static const char *capability_names[] = {" > $@ ; sed -n -e "/CAP_FS_MASK/d" -e "s/^\#define[ \\t]\\+CAP_\\([A-Z0-9_]\\+\\)[ \\t]\\+\\([0-9]\\+\\)\$$/[\\2]  = \"\\1\",/p" $< | tr A-Z a-z >> $@ ; echo "};" >> $@
+
+quiet_cmd_make-rlim = GEN     $@
+cmd_make-rlim = echo "static const char *rlim_names[] = {" > $@ ; sed -n --e "/AF_MAX/d" -e "s/^\# \\?define[ \\t]\\+RLIMIT_\\([A-Z0-9_]\\+\\)[ \\t]\\+\\([0-9]\\+\\)\\(.*\\)\$$/[\\2]  = \"\\1\",/p" $< | tr A-Z a-z >> $@ ; echo "};" >> $@ ; echo "static const int rlim_map[] = {" >> $@ ; sed -n -e "/AF_MAX/d" -e "s/^\# \\?define[ \\t]\\+\\(RLIMIT_[A-Z0-9_]\\+\\)[ \\t]\\+\\([0-9]\\+\\)\\(.*\\)\$$/\\1,/p" $< >> $@ ; echo "};" >> $@
+
+$(obj)/capability.o : $(obj)/capability_names.h
+$(obj)/resource.o : $(obj)/rlim_names.h
+$(obj)/capability_names.h : $(srctree)/include/linux/capability.h
+	$(call cmd,make-caps)
+$(obj)/af_names.h : $(srctree)/include/linux/socket.h
+	$(call cmd,make-af)
+$(obj)/rlim_names.h : $(srctree)/include/asm-generic/resource.h
+	$(call cmd,make-rlim)
Signature · 1 line
1.7.1
author maintainer
#18 lore raw

PATCH 13/13 AppArmor: update Maintainer and Documentation

In reply to John Johansen
---
 Documentation/apparmor.txt          |   40 +++++++++++++++++++++++++++++++++++
 Documentation/kernel-parameters.txt |    8 +++++++
 MAINTAINERS                         |    8 +++++++
 3 files changed, 56 insertions(+), 0 deletions(-)
 create mode 100644 Documentation/apparmor.txt
Documentation/apparmor.txt new file +40 -0
new file mode 100644
index 0000000..6240438
@@ -0,0 +1,40 @@
+--- What is AppArmor? ---
+
+AppArmor is MAC style security extension for the Linux kernel.  It implements
+a task centered policy, with task "profiles" being created and loaded
+from user space.  Tasks on the system that do not have a profile defined for
+them run in an unconfined state which is equivalent to standard Linux DAC
+permissions.
+
+--- How to enable/disable ---
+
+set CONFIG_SECURITY_APPARMOR=y
+
+If AppArmor should be selected as the default security module then
+   set CONFIG_DEFAULT_SECURITY="apparmor"
+   and CONFIG_SECURITY_APPARMOR_BOOTPARAM_VALUE=1
+
+Build the kernel
+
+If AppArmor is not the default security module it can be enabled by passing
+security=apparmor on the kernel's command line.
+
+If AppArmor is the default security module it can be disabled by passing
+apparmor=0, security=XXXX (where XXX is valid security module), on the
+kernel's command line
+
+For AppArmor to enforce any restrictions beyond standard Linux DAC permissions
+policy must be loaded into the kernel from user space (see the Documentation
+and tools links).
+
+--- Documentation ---
+
+Documentation can be found on the wiki.
+
+--- Links ---
+
+Mailing List - [email protected]
+Wiki - http://apparmor.wiki.kernel.org/
+User space tools - https://launchpad.net/apparmor
+Kernel module - git://git.kernel.org/pub/scm/linux/kernel/git/jj/apparmor-dev.git
+
Documentation/kernel-parameters.txt +8 -0
index 4ddb58d..a5c74ca 100644
@@ -93,6 +93,7 @@ parameter is applicable:
 			Documentation/scsi/.
 	SECURITY Different security models are enabled.
 	SELINUX SELinux support is enabled.
+	APPARMOR AppArmor support is enabled.
 	SERIAL	Serial support is enabled.
 	SH	SuperH architecture is enabled.
 	SMP	The kernel is an SMP kernel.
@@ -2312,6 +2313,13 @@ and is between 256 and 4096 characters. It is defined in the file
 			If enabled at boot time, /selinux/disable can be used
 			later to disable prior to initial policy load.
 
+	apparmor=	[APPARMOR] Disable or enable AppArmor at boot time
+			Format: { "0" | "1" }
+			See security/apparmor/Kconfig help text
+			0 -- disable.
+			1 -- enable.
+			Default value is set via kernel config option.
+
 	serialnumber	[BUGS=X86-32]
 
 	shapers=	[NET]
MAINTAINERS +8 -0
index db3d0f5..b4e8b7d 100644
@@ -5061,6 +5061,14 @@ S:	Supported
 F:	include/linux/selinux*
 F:	security/selinux/
 
+APPARMOR SECURITY MODULE
+M:	John Johansen <[email protected]>
+L:	[email protected] (subscribers-only, general discussion)
+W:	apparmor.wiki.kernel.org
+T:	git git://git.kernel.org/pub/scm/linux/kernel/git/jj/apparmor-dev.git
+S:	Supported
+F:	security/apparmor/
+
 SENSABLE PHANTOM
 M:	Jiri Slaby <[email protected]>
 S:	Maintained
Signature · 1 line
1.7.1
maintainer
#19 lore raw
In reply to John Johansen
Quoted 5 lines · John Johansen

This is the seveth general posting of the newest version of the AppArmor security module it has been rewritten to use the security_path hooks instead of the previous vfs approach. The current implementation is aimed at being as semantically close to previous versions of AppArmor as possible while using the existing LSM infrastructure.

Applied to
git://git.kernel.org/pub/scm/linux/kernel/git/jmorris/security-testing-2.6#next

Please carry out any further development against the above tree.

Note that I added the patch below to update AA against the latest version of path_truncate:

commit 08c702abe63c2da88f811d5c9f98eb01eb8edc77

Author: James Morris <[email protected]>
Date:   Fri Jul 30 09:02:04 2010 +1000

AppArmor: update path_truncate method to latest version

Remove extraneous path_truncate arguments from the AppArmor hook, as they've been removed from the LSM API.

security/apparmor/lsm.c +1 -2
index 7daf0d5..8db33a8 100644
@@ -278,8 +278,7 @@ static int apparmor_path_mknod(struct path *dir, struct dentry *dentry,
 	return common_perm_create(OP_MKNOD, dir, dentry, AA_MAY_CREATE, mode);
 }
 
-static int apparmor_path_truncate(struct path *path, loff_t length,
-				  unsigned int time_attrs)
+static int apparmor_path_truncate(struct path *path)
 {
 	struct path_cond cond = { path->dentry->d_inode->i_uid,
 				  path->dentry->d_inode->i_mode
Signature · 2 lines
James Morris
<[email protected]>
#20 lore raw
Quoted 2 lines · James Morris

Applied to
git://git.kernel.org/pub/scm/linux/kernel/git/jmorris/security-testing-2.6#next

Congratulations!

By the way, security/apparmor/Kconfig and security/apparmor/Makefile seems to be missing...

author maintainer
#21 lore raw
Quoted 6 lines · Tetsuo Handa
Quoted 2 lines · James Morris

Applied to
git://git.kernel.org/pub/scm/linux/kernel/git/jmorris/security-testing-2.6#next

Congratulations!

thanks, and thankyou for all the reviewing you did

Quoted 1 line

By the way, security/apparmor/Kconfig and security/apparmor/Makefile seems to be missing...

hrmm,

[PATCH 12/13] AppArmor: Enable configuring and building of the AppArmor security module

Kconfig and Makefiles to enable configuration and building of AppArmor.

---
 security/Kconfig             |    6 ++++++
 security/Makefile            |    2 ++
 security/apparmor/.gitignore |    5 +++++
 security/apparmor/Kconfig    |   31 +++++++++++++++++++++++++++++++
 security/apparmor/Makefile   |   24 ++++++++++++++++++++++++
 5 files changed, 68 insertions(+), 0 deletions(-)

...

#22 lore raw
Quoted 8 lines · John Johansen
Quoted 1 line

By the way, security/apparmor/Kconfig and security/apparmor/Makefile seems to be missing...

hrmm,

[PATCH 12/13] AppArmor: Enable configuring and building of the AppArmor security module

Kconfig and Makefiles to enable configuration and building of AppArmor.

Quoted 8 lines
---
 security/Kconfig             |    6 ++++++
 security/Makefile            |    2 ++
 security/apparmor/.gitignore |    5 +++++
 security/apparmor/Kconfig    |   31 +++++++++++++++++++++++++++++++
 security/apparmor/Makefile   |   24 ++++++++++++++++++++++++
 5 files changed, 68 insertions(+), 0 deletions(-)

Indeed. security/apparmor/.gitignore and security/apparmor/Kconfig and security/apparmor/Makefile are by error dropped when commiting.
http://git.kernel.org/?p=linux/kernel/git/jmorris/security-testing-2.6.git;a=commit;h=32bd8e5273c0be4189274ab55c4d16862f0dd87d
James, please correct.

maintainer
#23 lore raw
Quoted 4 lines · Tetsuo Handa

Indeed. security/apparmor/.gitignore and security/apparmor/Kconfig and security/apparmor/Makefile are by error dropped when commiting.
http://git.kernel.org/?p=linux/kernel/git/jmorris/security-testing-2.6.git;a=commit;h=32bd8e5273c0be4189274ab55c4d16862f0dd87d
James, please correct.

Yep, I had to edit a couple of those files and they did not get added properly (I'm sure I typed git-add...).

Should be fixed now, please test.

Signature · 2 lines
James Morris
<[email protected]>
#24 lore raw
Quoted 1 line · James Morris

Should be fixed now, please test.

Now config and build works. Thanks.

#25 lore raw
In reply to James Morris
Quoted 10 lines · James Morris
Quoted 6 lines · John Johansen

This is the seveth general posting of the newest version of the AppArmor security module it has been rewritten to use the security_path hooks instead of the previous vfs approach. The current implementation is aimed at being as semantically close to previous versions of AppArmor as possible while using the existing LSM infrastructure.

Quoted 5 lines

Applied to
git://git.kernel.org/pub/scm/linux/kernel/git/jmorris/security-testing-2.6#next

Please carry out any further development against the above tree.

Now wasn't that an adventure?

#26 lore raw
In reply to James Morris
Quoted 8 lines · James Morris
Quoted 5 lines · John Johansen

This is the seveth general posting of the newest version of the AppArmor security module it has been rewritten to use the security_path hooks instead of the previous vfs approach. The current implementation is aimed at being as semantically close to previous versions of AppArmor as possible while using the existing LSM infrastructure.

Quoted 7 lines

Applied to
git://git.kernel.org/pub/scm/linux/kernel/git/jmorris/security-testing-2.6#next

Please carry out any further development against the above tree.

Note that I added the patch below to update AA against the latest version of path_truncate:

Ok, so now we have two name-based "security" modules. Can we at least drop TOMOYO? That seems to have all apparmor disadvantages plus some more...

Signature · 2 lines
(english) http://www.livejournal.com/~pavelmachek
(cesky, pictures) http://atrey.karlin.mff.cuni.cz/~pavel/picture/horses/blog.html
#27 lore raw

Hi,

2010/8/5 Pavel Machek <[email protected]>:

Quoted 12 lines · James Morris
Quoted 11 lines · John Johansen
Quoted 6 lines

This is the seveth general posting of the newest version of the AppArmor security module it has been rewritten to use the security_path hooks instead of the previous vfs approach.  The current implementation is aimed at being as semantically close to previous versions of AppArmor as possible while using the existing LSM infrastructure.

Applied to
git://git.kernel.org/pub/scm/linux/kernel/git/jmorris/security-testing-2.6#next

Quoted 8 lines
Quoted 4 lines

Please carry out any further development against the above tree.

Note that I added the patch below to update AA against the latest version of path_truncate:

Ok, so now we have two name-based "security" modules. Can we at least drop TOMOYO? That seems to have all apparmor disadvantages plus some more...

Great idea! I suggest also to throw away the unnecessary filesystems. Ext3 is great - who needs Ext4 or XFS?

Signature · 1 line
Jan III Sobieski
maintainer
#28 lore raw
In reply to Pavel Machek
Quoted 6 lines · Pavel Machek
Quoted 2 lines

Note that I added the patch below to update AA against the latest version of path_truncate:

Ok, so now we have two name-based "security" modules. Can we at least drop TOMOYO? That seems to have all apparmor disadvantages plus some more...

No. The policy is that any security module which implements an access control scheme and meets a well-defined security goal, and passes technical review, may be merged.

aka, The Arjan Protocol:

http://kerneltrap.org/Linux/Documenting_Security_Module_Intent

Signature · 2 lines
James Morris
<[email protected]>
#29 lore raw
Quoted 9 lines · James Morris
Quoted 6 lines · Pavel Machek
Quoted 2 lines

Note that I added the patch below to update AA against the latest version of path_truncate:

Ok, so now we have two name-based "security" modules. Can we at least drop TOMOYO? That seems to have all apparmor disadvantages plus some more...

Quoted 7 lines

No. The policy is that any security module which implements an access control scheme and meets a well-defined security goal, and passes technical review, may be merged.

aka, The Arjan Protocol:

http://kerneltrap.org/Linux/Documenting_Security_Module_Intent

It seems that security subsystem has lower standards than rest of the kernel. Sad.
Pavel

Signature · 2 lines
(english) http://www.livejournal.com/~pavelmachek
(cesky, pictures) http://atrey.karlin.mff.cuni.cz/~pavel/picture/horses/blog.html