Thank you for the explanation John.
I have attached the files we have modified. Every piece of code that we
inserted is enclosed
within comment lines 'Custom code begin' and 'Custom code end' so that it's
easy for you to find. Here
is a brief description of the changes made:
AppArmor Parser (user-space) - We modified the grammar of AppArmor's parser to
include additional
grammar rules. These rules store data in class Profile
a) profile.h - 2 new structure definitions to store our custom data
- class Profile now contains a member 'clabel'
b) parser_interface.c - Added code to sd_serialize_profile( ) that serializes
the additional custom
data we added to class Profile during the parsing phase
AppArmor LSM (kernel) :
a) include/policy.h - 2 new structure definitions
- struct aa_profile now contains a member 'clabel'
b) policy_unpack.c - Added code to unpack_profile( ) that unpacks the
serialized object sent from
user-space, and allocates kernel memory for the security structures added to
aa_profile - namely, a label string and a linked list containing allow
permissions
c) policy.c - Added code to function aa_free_profile( ) that frees the
allocated memory
________________________________
From: John Johansen <[email protected]>
Sent: 27 July 2019 00:10:14
To: Abhishek Vijeev <[email protected]>; [email protected]
<[email protected]>
Cc: Rakesh Rajan Beck <[email protected]>
Subject: Re: [apparmor] Questions about AppArmor's Kernel Code
On 7/26/19 5:56 AM, Abhishek Vijeev wrote:
> Hi,
>
>
> I have a few questions about AppArmor's kernel code and would be grateful if
> you could kindly answer them.
>
>
> 1) Why does AppArmor maintain two separate security blobs in cred->security
> as well as task-security for processes? For a simple project that requires
> associating a security context with every task, would it suffice to use just
> one of these?
>
the task->security field is used to store task specific information, that is
not used for general mediation. Currently the information stored their is for
the change_hat and change_onexec apis and some info to track what the
confinement was when no-newprivs was applied to the task.
cred->security is used to store the subjects label (type) for mediation.
Before the task->security field was reintroduce all the information was stored
off the cred in a intermediate structure. Doing so would cause use of the
change_hat and change_onexec api to change the cred of the task even when the
confinement had not changed. The switch to using the task->security field was
pre 4.18
>
> 2) There has been a change in the way security blobs are accessed from kernel
> version 4.18 to 5.2. I see that in v5.2, the security blob's address is
> obtained by adding the size of the blob to the start address. Why has this
> change been made? (For reference:
> https://github.com/torvalds/linux/blob/master/security/apparmor/include/cred.h#L24)
>
see Casey's answer
>
> 3) I tried adding a custom field (pointer to a custom structure) to struct
> aa_profile, at exactly this point -
> https://github.com/torvalds/linux/blob/master/security/apparmor/include/policy.h#L144.
> I have taken care to allocate and free memory for the pointer at the
> appropriate places (allocation is performed here -
> https://github.com/torvalds/linux/blob/master/security/apparmor/policy_unpack.c#L671
> and freeing is performed here -
> https://github.com/torvalds/linux/blob/master/security/apparmor/policy.c#L205).
> However, while booting the kernel, it crashes at the function
> 'security_prepare_creds( )', which I presume invokes 'apparmor_cred_prepare(
> )'. If I was, to assume for a moment that there are no bugs with my memory
> allocation code, is there any other reason why such a crash might have
> occurred? I have attached the kernel crash log file with this email for your
> kind reference.
>
I know the code points but to be able to comment beyond vague guesses I need to
see your changes. I can give you the warning to not add your field after the
current last field,
struct aa_label label;
as it has a variable length field. While that is always 2 entries when its
embedded in the profile the compiler will end up treating it as zero length
over lapping your new field with the start of the variable length array.
I do have a patch to address this using a union but I haven't landed it yet.
/* SPDX-License-Identifier: GPL-2.0-only */
/*
* AppArmor security module
*
* This file contains AppArmor policy definitions.
*
* Copyright (C) 1998-2008 Novell/SUSE
* Copyright 2009-2010 Canonical Ltd.
*/
#ifndef __AA_POLICY_H
#define __AA_POLICY_H
#include <linux/capability.h>
#include <linux/cred.h>
#include <linux/kref.h>
#include <linux/rhashtable.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 "lib.h"
#include "label.h"
#include "net.h"
#include "perms.h"
#include "resource.h"
struct aa_ns;
extern int unprivileged_userns_apparmor_policy;
extern const char *const aa_profile_mode_names[];
#define APPARMOR_MODE_NAMES_MAX_INDEX 4
#define PROFILE_MODE(_profile, _mode) \
((aa_g_profile_mode == (_mode)) || \
((_profile)->mode == (_mode)))
#define COMPLAIN_MODE(_profile) PROFILE_MODE((_profile), APPARMOR_COMPLAIN)
#define KILL_MODE(_profile) PROFILE_MODE((_profile), APPARMOR_KILL)
#define PROFILE_IS_HAT(_profile) ((_profile)->label.flags & FLAG_HAT)
#define profile_is_stale(_profile) (label_is_stale(&(_profile)->label))
#define on_list_rcu(X) (!list_empty(X) && (X)->prev != LIST_POISON2)
/*
* 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 */
APPARMOR_UNCONFINED, /* profile set to unconfined */
};
/* struct aa_policydb - match engine for a policy
* dfa: dfa pattern match
* start: set of start states for the different classes of data
*/
struct aa_policydb {
/* Generic policy DFA specific rule types will be subsections of it */
struct aa_dfa *dfa;
unsigned int start[AA_CLASS_LAST + 1];
};
/* struct aa_data - generic data structure
* key: name for retrieving this data
* size: size of data in bytes
* data: binary data
* head: reserved for rhashtable
*/
struct aa_data {
char *key;
u32 size;
char *data;
struct rhash_head head;
};
// Custom code begin
struct data_list
{
char *data;
struct list_head lh;
};
struct custom_label
{
char *label_name;
int allow_cnt;
struct data_list *allow_list;
};
// Custom code end
/* struct aa_profile - basic confinement data
* @base - base components of the profile (name, refcount, lists, lock ...)
* @label - label this profile is an extension of
* @parent: parent of profile
* @ns: namespace the profile is in
* @rename: optional profile name that this profile renamed
* @attach: human readable attachment string
* @xmatch: optional extended matching for unconfined executables names
* @xmatch_len: xmatch prefix len, used to determine xmatch priority
* @audit: the auditing mode of the profile
* @mode: the enforcement mode of the profile
* @path_flags: flags controlling path generation behavior
* @disconnected: what to prepend if attach_disconnected is specified
* @size: the memory consumed by this profiles rules
* @policy: general match rules governing policy
* @file: The set of rules governing basic file access and domain transitions
* @caps: capabilities for the profile
* @rlimits: rlimits for the profile
*
* @dents: dentries for the profiles file entries in apparmorfs
* @dirname: name of the profile dir in apparmorfs
* @data: hashtable for free-form policy aa_data
*
* 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.
*
* 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 __rcu *parent;
struct aa_ns *ns;
const char *rename;
const char *attach;
struct aa_dfa *xmatch;
int xmatch_len;
enum audit_mode audit;
long mode;
u32 path_flags;
const char *disconnected;
int size;
// Custom code begin
struct custom_label *clabel;
// Custom code end
struct aa_policydb policy;
struct aa_file_rules file;
struct aa_caps caps;
int xattr_count;
char **xattrs;
struct aa_rlimit rlimits;
int secmark_count;
struct aa_secmark *secmark;
struct aa_loaddata *rawdata;
unsigned char *hash;
char *dirname;
struct dentry *dents[AAFS_PROF_SIZEOF];
struct rhashtable *data;
struct aa_label label;
};
extern enum profile_mode aa_g_profile_mode;
#define AA_MAY_LOAD_POLICY AA_MAY_APPEND
#define AA_MAY_REPLACE_POLICY AA_MAY_WRITE
#define AA_MAY_REMOVE_POLICY AA_MAY_DELETE
#define profiles_ns(P) ((P)->ns)
#define name_is_shared(A, B) ((A)->hname && (A)->hname == (B)->hname)
void aa_add_profile(struct aa_policy *common, struct aa_profile *profile);
void aa_free_proxy_kref(struct kref *kref);
struct aa_profile *aa_alloc_profile(const char *name, struct aa_proxy *proxy,
gfp_t gfp);
struct aa_profile *aa_new_null_profile(struct aa_profile *parent, bool hat,
const char *base, gfp_t gfp);
void aa_free_profile(struct aa_profile *profile);
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_lookupn_profile(struct aa_ns *ns, const char *hname,
size_t n);
struct aa_profile *aa_lookup_profile(struct aa_ns *ns, const char *name);
struct aa_profile *aa_fqlookupn_profile(struct aa_label *base,
const char *fqname, size_t n);
struct aa_profile *aa_match_profile(struct aa_ns *ns, const char *name);
ssize_t aa_replace_profiles(struct aa_ns *view, struct aa_label *label,
u32 mask, struct aa_loaddata *udata);
ssize_t aa_remove_profiles(struct aa_ns *view, struct aa_label *label,
char *name, size_t size);
void __aa_profile_list_release(struct list_head *head);
#define PROF_ADD 1
#define PROF_REPLACE 0
#define profile_unconfined(X) ((X)->mode == APPARMOR_UNCONFINED)
/**
* aa_get_newest_profile - simple wrapper fn to wrap the label version
* @p: profile (NOT NULL)
*
* Returns refcount to newest version of the profile (maybe @p)
*
* Requires: @p must be held with a valid refcount
*/
static inline struct aa_profile *aa_get_newest_profile(struct aa_profile *p)
{
return labels_profile(aa_get_newest_label(&p->label));
}
static inline unsigned int PROFILE_MEDIATES(struct aa_profile *profile,
unsigned char class)
{
if (class <= AA_CLASS_LAST)
return profile->policy.start[class];
else
return aa_dfa_match_len(profile->policy.dfa,
profile->policy.start[0], &class, 1);
}
static inline unsigned int PROFILE_MEDIATES_AF(struct aa_profile *profile,
u16 AF) {
unsigned int state = PROFILE_MEDIATES(profile, AA_CLASS_NET);
__be16 be_af = cpu_to_be16(AF);
if (!state)
return 0;
return aa_dfa_match_len(profile->policy.dfa, state, (char *) &be_af, 2);
}
/**
* 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->label.count));
return p;
}
/**
* aa_get_profile_not0 - increment refcount on profile @p found via lookup
* @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_not0(struct aa_profile *p)
{
if (p && kref_get_unless_zero(&p->label.count))
return p;
return NULL;
}
/**
* aa_get_profile_rcu - increment a refcount profile that can be replaced
* @p: pointer to profile that can be replaced (NOT NULL)
*
* Returns: pointer to a refcounted profile.
* else NULL if no profile
*/
static inline struct aa_profile *aa_get_profile_rcu(struct aa_profile __rcu **p)
{
struct aa_profile *c;
rcu_read_lock();
do {
c = rcu_dereference(*p);
} while (c && !kref_get_unless_zero(&c->label.count));
rcu_read_unlock();
return c;
}
/**
* 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->label.count, aa_label_kref);
}
static inline int AUDIT_MODE(struct aa_profile *profile)
{
if (aa_g_audit != AUDIT_NORMAL)
return aa_g_audit;
return profile->audit;
}
bool policy_view_capable(struct aa_ns *ns);
bool policy_admin_capable(struct aa_ns *ns);
int aa_may_manage_policy(struct aa_label *label, struct aa_ns *ns,
u32 mask);
#endif /* __AA_POLICY_H */
// SPDX-License-Identifier: GPL-2.0-only
/*
* AppArmor security module
*
* This file contains AppArmor functions for unpacking policy loaded from
* userspace.
*
* Copyright (C) 1998-2008 Novell/SUSE
* Copyright 2009-2010 Canonical Ltd.
*
* AppArmor uses a serialized binary format for loading policy. To find
* policy format documentation see Documentation/admin-guide/LSM/apparmor.rst
* All policy is validated before it is used.
*/
#include <asm/unaligned.h>
#include <linux/ctype.h>
#include <linux/errno.h>
#include "include/apparmor.h"
#include "include/audit.h"
#include "include/cred.h"
#include "include/crypto.h"
#include "include/match.h"
#include "include/path.h"
#include "include/policy.h"
#include "include/policy_unpack.h"
#define K_ABI_MASK 0x3ff
#define FORCE_COMPLAIN_FLAG 0x800
#define VERSION_LT(X, Y) (((X) & K_ABI_MASK) < ((Y) & K_ABI_MASK))
#define VERSION_GT(X, Y) (((X) & K_ABI_MASK) > ((Y) & K_ABI_MASK))
#define v5 5 /* base version */
#define v6 6 /* per entry policydb mediation check */
#define v7 7
#define v8 8 /* full network masking */
/*
* The AppArmor interface treats data as a type byte followed by the
* actual data. The interface has the notion of a a named entry
* which has a name (AA_NAME typecode followed by name string) followed by
* the entries typecode and data. Named types allow for optional
* elements and extensions to be added and tested for without breaking
* backwards compatibility.
*/
enum aa_code {
AA_U8,
AA_U16,
AA_U32,
AA_U64,
AA_NAME, /* same as string except it is items name */
AA_STRING,
AA_BLOB,
AA_STRUCT,
AA_STRUCTEND,
AA_LIST,
AA_LISTEND,
AA_ARRAY,
AA_ARRAYEND,
};
/*
* aa_ext is the read of the buffer containing the serialized profile. The
* data is copied into a kernel buffer in apparmorfs and then handed off to
* the unpack routines.
*/
struct aa_ext {
void *start;
void *end;
void *pos; /* pointer to current position in the buffer */
u32 version;
};
/* audit callback for unpack fields */
static void audit_cb(struct audit_buffer *ab, void *va)
{
struct common_audit_data *sa = va;
if (aad(sa)->iface.ns) {
audit_log_format(ab, " ns=");
audit_log_untrustedstring(ab, aad(sa)->iface.ns);
}
if (aad(sa)->name) {
audit_log_format(ab, " name=");
audit_log_untrustedstring(ab, aad(sa)->name);
}
if (aad(sa)->iface.pos)
audit_log_format(ab, " offset=%ld", aad(sa)->iface.pos);
}
/**
* audit_iface - do audit message for policy unpacking/load/replace/remove
* @new: profile if it has been allocated (MAYBE NULL)
* @ns_name: name of the ns the profile is to be loaded to (MAY BE NULL)
* @name: name of the profile being manipulated (MAYBE NULL)
* @info: any extra info about the failure (MAYBE NULL)
* @e: buffer position info
* @error: error code
*
* Returns: %0 or error
*/
static int audit_iface(struct aa_profile *new, const char *ns_name,
const char *name, const char *info, struct aa_ext *e,
int error)
{
struct aa_profile *profile = labels_profile(aa_current_raw_label());
DEFINE_AUDIT_DATA(sa, LSM_AUDIT_DATA_NONE, NULL);
if (e)
aad(&sa)->iface.pos = e->pos - e->start;
aad(&sa)->iface.ns = ns_name;
if (new)
aad(&sa)->name = new->base.hname;
else
aad(&sa)->name = name;
aad(&sa)->info = info;
aad(&sa)->error = error;
return aa_audit(AUDIT_APPARMOR_STATUS, profile, &sa, audit_cb);
}
void __aa_loaddata_update(struct aa_loaddata *data, long revision)
{
AA_BUG(!data);
AA_BUG(!data->ns);
AA_BUG(!data->dents[AAFS_LOADDATA_REVISION]);
AA_BUG(!mutex_is_locked(&data->ns->lock));
AA_BUG(data->revision > revision);
data->revision = revision;
d_inode(data->dents[AAFS_LOADDATA_DIR])->i_mtime =
current_time(d_inode(data->dents[AAFS_LOADDATA_DIR]));
d_inode(data->dents[AAFS_LOADDATA_REVISION])->i_mtime =
current_time(d_inode(data->dents[AAFS_LOADDATA_REVISION]));
}
bool aa_rawdata_eq(struct aa_loaddata *l, struct aa_loaddata *r)
{
if (l->size != r->size)
return false;
if (aa_g_hash_policy && memcmp(l->hash, r->hash, aa_hash_size()) != 0)
return false;
return memcmp(l->data, r->data, r->size) == 0;
}
/*
* need to take the ns mutex lock which is NOT safe most places that
* put_loaddata is called, so we have to delay freeing it
*/
static void do_loaddata_free(struct work_struct *work)
{
struct aa_loaddata *d = container_of(work, struct aa_loaddata, work);
struct aa_ns *ns = aa_get_ns(d->ns);
if (ns) {
mutex_lock_nested(&ns->lock, ns->level);
__aa_fs_remove_rawdata(d);
mutex_unlock(&ns->lock);
aa_put_ns(ns);
}
kzfree(d->hash);
kzfree(d->name);
kvfree(d->data);
kzfree(d);
}
void aa_loaddata_kref(struct kref *kref)
{
struct aa_loaddata *d = container_of(kref, struct aa_loaddata, count);
if (d) {
INIT_WORK(&d->work, do_loaddata_free);
schedule_work(&d->work);
}
}
struct aa_loaddata *aa_loaddata_alloc(size_t size)
{
struct aa_loaddata *d;
d = kzalloc(sizeof(*d), GFP_KERNEL);
if (d == NULL)
return ERR_PTR(-ENOMEM);
d->data = kvzalloc(size, GFP_KERNEL);
if (!d->data) {
kfree(d);
return ERR_PTR(-ENOMEM);
}
kref_init(&d->count);
INIT_LIST_HEAD(&d->list);
return d;
}
/* test if read will be in packed data bounds */
static bool inbounds(struct aa_ext *e, size_t size)
{
return (size <= e->end - e->pos);
}
static void *kvmemdup(const void *src, size_t len)
{
void *p = kvmalloc(len, GFP_KERNEL);
if (p)
memcpy(p, src, len);
return p;
}
/**
* aa_u16_chunck - test and do bounds checking for a u16 size based chunk
* @e: serialized data read head (NOT NULL)
* @chunk: start address for chunk of data (NOT NULL)
*
* Returns: the size of chunk found with the read head at the end of the chunk.
*/
static size_t unpack_u16_chunk(struct aa_ext *e, char **chunk)
{
size_t size = 0;
void *pos = e->pos;
if (!inbounds(e, sizeof(u16)))
goto fail;
size = le16_to_cpu(get_unaligned((__le16 *) e->pos));
e->pos += sizeof(__le16);
if (!inbounds(e, size))
goto fail;
*chunk = e->pos;
e->pos += size;
return size;
fail:
e->pos = pos;
return 0;
}
/* unpack control byte */
static bool unpack_X(struct aa_ext *e, enum aa_code code)
{
if (!inbounds(e, 1))
return 0;
if (*(u8 *) e->pos != code)
return 0;
e->pos++;
return 1;
}
/**
* unpack_nameX - check is the next element is of type X with a name of @name
* @e: serialized data extent information (NOT NULL)
* @code: type code
* @name: name to match to the serialized element. (MAYBE NULL)
*
* check that the next serialized data element is of type X and has a tag
* name @name. If @name is specified then there must be a matching
* name element in the stream. If @name is NULL any name element will be
* skipped and only the typecode will be tested.
*
* Returns 1 on success (both type code and name tests match) and the read
* head is advanced past the headers
*
* Returns: 0 if either match fails, the read head does not move
*/
static bool unpack_nameX(struct aa_ext *e, enum aa_code code, const char *name)
{
/*
* May need to reset pos if name or type doesn't match
*/
void *pos = e->pos;
/*
* Check for presence of a tagname, and if present name size
* AA_NAME tag value is a u16.
*/
if (unpack_X(e, AA_NAME)) {
char *tag = NULL;
size_t size = unpack_u16_chunk(e, &tag);
/* if a name is specified it must match. otherwise skip tag */
if (name && (!size || tag[size-1] != '\0' || strcmp(name, tag)))
goto fail;
} else if (name) {
/* if a name is specified and there is no name tag fail */
goto fail;
}
/* now check if type code matches */
if (unpack_X(e, code))
return 1;
fail:
e->pos = pos;
return 0;
}
static bool unpack_u8(struct aa_ext *e, u8 *data, const char *name)
{
void *pos = e->pos;
if (unpack_nameX(e, AA_U8, name)) {
if (!inbounds(e, sizeof(u8)))
goto fail;
if (data)
*data = get_unaligned((u8 *)e->pos);
e->pos += sizeof(u8);
return 1;
}
fail:
e->pos = pos;
return 0;
}
static bool unpack_u32(struct aa_ext *e, u32 *data, const char *name)
{
void *pos = e->pos;
if (unpack_nameX(e, AA_U32, name)) {
if (!inbounds(e, sizeof(u32)))
goto fail;
if (data)
*data = le32_to_cpu(get_unaligned((__le32 *) e->pos));
e->pos += sizeof(u32);
return 1;
}
fail:
e->pos = pos;
return 0;
}
static bool unpack_u64(struct aa_ext *e, u64 *data, const char *name)
{
void *pos = e->pos;
if (unpack_nameX(e, AA_U64, name)) {
if (!inbounds(e, sizeof(u64)))
goto fail;
if (data)
*data = le64_to_cpu(get_unaligned((__le64 *) e->pos));
e->pos += sizeof(u64);
return 1;
}
fail:
e->pos = pos;
return 0;
}
static size_t unpack_array(struct aa_ext *e, const char *name)
{
void *pos = e->pos;
if (unpack_nameX(e, AA_ARRAY, name)) {
int size;
if (!inbounds(e, sizeof(u16)))
goto fail;
size = (int)le16_to_cpu(get_unaligned((__le16 *) e->pos));
e->pos += sizeof(u16);
return size;
}
fail:
e->pos = pos;
return 0;
}
static size_t unpack_blob(struct aa_ext *e, char **blob, const char *name)
{
void *pos = e->pos;
if (unpack_nameX(e, AA_BLOB, name)) {
u32 size;
if (!inbounds(e, sizeof(u32)))
goto fail;
size = le32_to_cpu(get_unaligned((__le32 *) e->pos));
e->pos += sizeof(u32);
if (inbounds(e, (size_t) size)) {
*blob = e->pos;
e->pos += size;
return size;
}
}
fail:
e->pos = pos;
return 0;
}
static int unpack_str(struct aa_ext *e, const char **string, const char *name)
{
char *src_str;
size_t size = 0;
void *pos = e->pos;
*string = NULL;
if (unpack_nameX(e, AA_STRING, name)) {
size = unpack_u16_chunk(e, &src_str);
if (size) {
/* strings are null terminated, length is size - 1 */
if (src_str[size - 1] != 0)
goto fail;
*string = src_str;
return size;
}
}
fail:
e->pos = pos;
return 0;
}
static int unpack_strdup(struct aa_ext *e, char **string, const char *name)
{
const char *tmp;
void *pos = e->pos;
int res = unpack_str(e, &tmp, name);
*string = NULL;
if (!res)
return 0;
*string = kmemdup(tmp, res, GFP_KERNEL);
if (!*string) {
e->pos = pos;
return 0;
}
return res;
}
/**
* unpack_dfa - unpack a file rule dfa
* @e: serialized data extent information (NOT NULL)
*
* returns dfa or ERR_PTR or NULL if no dfa
*/
static struct aa_dfa *unpack_dfa(struct aa_ext *e)
{
char *blob = NULL;
size_t size;
struct aa_dfa *dfa = NULL;
size = unpack_blob(e, &blob, "aadfa");
if (size) {
/*
* The dfa is aligned with in the blob to 8 bytes
* from the beginning of the stream.
* alignment adjust needed by dfa unpack
*/
size_t sz = blob - (char *) e->start -
((e->pos - e->start) & 7);
size_t pad = ALIGN(sz, 8) - sz;
int flags = TO_ACCEPT1_FLAG(YYTD_DATA32) |
TO_ACCEPT2_FLAG(YYTD_DATA32) | DFA_FLAG_VERIFY_STATES;
dfa = aa_dfa_unpack(blob + pad, size - pad, flags);
if (IS_ERR(dfa))
return dfa;
}
return dfa;
}
/**
* unpack_trans_table - unpack a profile transition table
* @e: serialized data extent information (NOT NULL)
* @profile: profile to add the accept table to (NOT NULL)
*
* Returns: 1 if table successfully unpacked
*/
static bool unpack_trans_table(struct aa_ext *e, struct aa_profile *profile)
{
void *saved_pos = e->pos;
/* exec table is optional */
if (unpack_nameX(e, AA_STRUCT, "xtable")) {
int i, size;
size = unpack_array(e, NULL);
/* currently 4 exec bits and entries 0-3 are reserved iupcx */
if (size > 16 - 4)
goto fail;
profile->file.trans.table = kcalloc(size, sizeof(char *),
GFP_KERNEL);
if (!profile->file.trans.table)
goto fail;
profile->file.trans.size = size;
for (i = 0; i < size; i++) {
char *str;
int c, j, pos, size2 = unpack_strdup(e, &str, NULL);
/* unpack_strdup verifies that the last character is
* null termination byte.
*/
if (!size2)
goto fail;
profile->file.trans.table[i] = str;
/* verify that name doesn't start with space */
if (isspace(*str))
goto fail;
/* count internal # of internal \0 */
for (c = j = 0; j < size2 - 1; j++) {
if (!str[j]) {
pos = j;
c++;
}
}
if (*str == ':') {
/* first character after : must be valid */
if (!str[1])
goto fail;
/* beginning with : requires an embedded \0,
* verify that exactly 1 internal \0 exists
* trailing \0 already verified by unpack_strdup
*
* convert \0 back to : for label_parse
*/
if (c == 1)
str[pos] = ':';
else if (c > 1)
goto fail;
} else if (c)
/* fail - all other cases with embedded \0 */
goto fail;
}
if (!unpack_nameX(e, AA_ARRAYEND, NULL))
goto fail;
if (!unpack_nameX(e, AA_STRUCTEND, NULL))
goto fail;
}
return 1;
fail:
aa_free_domain_entries(&profile->file.trans);
e->pos = saved_pos;
return 0;
}
static bool unpack_xattrs(struct aa_ext *e, struct aa_profile *profile)
{
void *pos = e->pos;
if (unpack_nameX(e, AA_STRUCT, "xattrs")) {
int i, size;
size = unpack_array(e, NULL);
profile->xattr_count = size;
profile->xattrs = kcalloc(size, sizeof(char *), GFP_KERNEL);
if (!profile->xattrs)
goto fail;
for (i = 0; i < size; i++) {
if (!unpack_strdup(e, &profile->xattrs[i], NULL))
goto fail;
}
if (!unpack_nameX(e, AA_ARRAYEND, NULL))
goto fail;
if (!unpack_nameX(e, AA_STRUCTEND, NULL))
goto fail;
}
return 1;
fail:
e->pos = pos;
return 0;
}
static bool unpack_secmark(struct aa_ext *e, struct aa_profile *profile)
{
void *pos = e->pos;
int i, size;
if (unpack_nameX(e, AA_STRUCT, "secmark")) {
size = unpack_array(e, NULL);
profile->secmark = kcalloc(size, sizeof(struct aa_secmark),
GFP_KERNEL);
if (!profile->secmark)
goto fail;
profile->secmark_count = size;
for (i = 0; i < size; i++) {
if (!unpack_u8(e, &profile->secmark[i].audit, NULL))
goto fail;
if (!unpack_u8(e, &profile->secmark[i].deny, NULL))
goto fail;
if (!unpack_strdup(e, &profile->secmark[i].label, NULL))
goto fail;
}
if (!unpack_nameX(e, AA_ARRAYEND, NULL))
goto fail;
if (!unpack_nameX(e, AA_STRUCTEND, NULL))
goto fail;
}
return 1;
fail:
if (profile->secmark) {
for (i = 0; i < size; i++)
kfree(profile->secmark[i].label);
kfree(profile->secmark);
profile->secmark_count = 0;
profile->secmark = NULL;
}
e->pos = pos;
return 0;
}
static bool unpack_rlimits(struct aa_ext *e, struct aa_profile *profile)
{
void *pos = e->pos;
/* rlimits are optional */
if (unpack_nameX(e, AA_STRUCT, "rlimits")) {
int i, size;
u32 tmp = 0;
if (!unpack_u32(e, &tmp, NULL))
goto fail;
profile->rlimits.mask = tmp;
size = unpack_array(e, NULL);
if (size > RLIM_NLIMITS)
goto fail;
for (i = 0; i < size; i++) {
u64 tmp2 = 0;
int a = aa_map_resource(i);
if (!unpack_u64(e, &tmp2, NULL))
goto fail;
profile->rlimits.limits[a].rlim_max = tmp2;
}
if (!unpack_nameX(e, AA_ARRAYEND, NULL))
goto fail;
if (!unpack_nameX(e, AA_STRUCTEND, NULL))
goto fail;
}
return 1;
fail:
e->pos = pos;
return 0;
}
static u32 strhash(const void *data, u32 len, u32 seed)
{
const char * const *key = data;
return jhash(*key, strlen(*key), seed);
}
static int datacmp(struct rhashtable_compare_arg *arg, const void *obj)
{
const struct aa_data *data = obj;
const char * const *key = arg->key;
return strcmp(data->key, *key);
}
/**
* unpack_profile - unpack a serialized profile
* @e: serialized data extent information (NOT NULL)
*
* NOTE: unpack profile sets audit struct if there is a failure
*/
static struct aa_profile *unpack_profile(struct aa_ext *e, char **ns_name)
{
struct aa_profile *profile = NULL;
const char *tmpname, *tmpns = NULL, *name = NULL;
const char *info = "failed to unpack profile";
size_t ns_len;
struct rhashtable_params params = { 0 };
char *key = NULL;
struct aa_data *data;
int i, error = -EPROTO;
kernel_cap_t tmpcap;
u32 tmp;
*ns_name = NULL;
/* check that we have the right struct being passed */
if (!unpack_nameX(e, AA_STRUCT, "profile"))
goto fail;
if (!unpack_str(e, &name, NULL))
goto fail;
if (*name == '\0')
goto fail;
tmpname = aa_splitn_fqname(name, strlen(name), &tmpns, &ns_len);
if (tmpns) {
*ns_name = kstrndup(tmpns, ns_len, GFP_KERNEL);
if (!*ns_name) {
info = "out of memory";
goto fail;
}
name = tmpname;
}
profile = aa_alloc_profile(name, NULL, GFP_KERNEL);
if (!profile)
return ERR_PTR(-ENOMEM);
/* profile renaming is optional */
(void) unpack_str(e, &profile->rename, "rename");
/* attachment string is optional */
(void) unpack_str(e, &profile->attach, "attach");
/* xmatch is optional and may be NULL */
profile->xmatch = unpack_dfa(e);
if (IS_ERR(profile->xmatch)) {
error = PTR_ERR(profile->xmatch);
profile->xmatch = NULL;
info = "bad xmatch";
goto fail;
}
/* xmatch_len is not optional if xmatch is set */
if (profile->xmatch) {
if (!unpack_u32(e, &tmp, NULL)) {
info = "missing xmatch len";
goto fail;
}
profile->xmatch_len = tmp;
}
/* disconnected attachment string is optional */
(void) unpack_str(e, &profile->disconnected, "disconnected");
// Custom code begin
if (unpack_nameX(e, AA_STRUCT, "custom_label"))
{
profile->clabel = kzalloc (sizeof(struct custom_label), GFP_KERNEL);
if (!profile->clabel)
goto fail;
if (!unpack_str(e, &name, NULL))
goto fail;
profile->clabel->label_name = kzalloc (strlen(name), GFP_KERNEL);
if (!profile->clabel->label_name)
goto fail;
strcpy (profile->clabel->label_name, name);
if (!unpack_u32(e, &(profile->clabel->allow_cnt), NULL))
goto fail;
if (unpack_nameX(e, AA_STRUCT, "data_list"))
{
profile->clabel->allow_list = kzalloc(sizeof(struct data_list), GFP_KERNEL);
if (!profile->clabel->allow_list)
goto fail;
INIT_LIST_HEAD(&(profile->clabel->allow_list->lh));
for (i = 0; i < profile->clabel->allow_cnt; i++)
{
if (!unpack_str(e, &name, NULL))
goto fail;
struct data_list *new_node = kzalloc(sizeof(struct data_list), GFP_KERNEL);
if (!new_node)
goto fail;
new_node->data = kzalloc(strlen(name), GFP_KERNEL);
if (!new_node->data)
goto fail;
strcpy(new_node->data, name);
INIT_LIST_HEAD(&(new_node->lh));
list_add(&(new_node->lh), &(profile->clabel->allow_list->lh));
}
if (!unpack_nameX(e, AA_STRUCTEND, NULL))
goto fail;
}
if (!unpack_nameX(e, AA_STRUCTEND, NULL))
goto fail;
}
// Custom code end
/* per profile debug flags (complain, audit) */
if (!unpack_nameX(e, AA_STRUCT, "flags")) {
info = "profile missing flags";
goto fail;
}
info = "failed to unpack profile flags";
if (!unpack_u32(e, &tmp, NULL))
goto fail;
if (tmp & PACKED_FLAG_HAT)
profile->label.flags |= FLAG_HAT;
if (!unpack_u32(e, &tmp, NULL))
goto fail;
if (tmp == PACKED_MODE_COMPLAIN || (e->version & FORCE_COMPLAIN_FLAG))
profile->mode = APPARMOR_COMPLAIN;
else if (tmp == PACKED_MODE_KILL)
profile->mode = APPARMOR_KILL;
else if (tmp == PACKED_MODE_UNCONFINED)
profile->mode = APPARMOR_UNCONFINED;
if (!unpack_u32(e, &tmp, NULL))
goto fail;
if (tmp)
profile->audit = AUDIT_ALL;
if (!unpack_nameX(e, AA_STRUCTEND, NULL))
goto fail;
/* path_flags is optional */
if (unpack_u32(e, &profile->path_flags, "path_flags"))
profile->path_flags |= profile->label.flags &
PATH_MEDIATE_DELETED;
else
/* set a default value if path_flags field is not present */
profile->path_flags = PATH_MEDIATE_DELETED;
info = "failed to unpack profile capabilities";
if (!unpack_u32(e, &(profile->caps.allow.cap[0]), NULL))
goto fail;
if (!unpack_u32(e, &(profile->caps.audit.cap[0]), NULL))
goto fail;
if (!unpack_u32(e, &(profile->caps.quiet.cap[0]), NULL))
goto fail;
if (!unpack_u32(e, &tmpcap.cap[0], NULL))
goto fail;
info = "failed to unpack upper profile capabilities";
if (unpack_nameX(e, AA_STRUCT, "caps64")) {
/* optional upper half of 64 bit caps */
if (!unpack_u32(e, &(profile->caps.allow.cap[1]), NULL))
goto fail;
if (!unpack_u32(e, &(profile->caps.audit.cap[1]), NULL))
goto fail;
if (!unpack_u32(e, &(profile->caps.quiet.cap[1]), NULL))
goto fail;
if (!unpack_u32(e, &(tmpcap.cap[1]), NULL))
goto fail;
if (!unpack_nameX(e, AA_STRUCTEND, NULL))
goto fail;
}
info = "failed to unpack extended profile capabilities";
if (unpack_nameX(e, AA_STRUCT, "capsx")) {
/* optional extended caps mediation mask */
if (!unpack_u32(e, &(profile->caps.extended.cap[0]), NULL))
goto fail;
if (!unpack_u32(e, &(profile->caps.extended.cap[1]), NULL))
goto fail;
if (!unpack_nameX(e, AA_STRUCTEND, NULL))
goto fail;
}
if (!unpack_xattrs(e, profile)) {
info = "failed to unpack profile xattrs";
goto fail;
}
if (!unpack_rlimits(e, profile)) {
info = "failed to unpack profile rlimits";
goto fail;
}
if (!unpack_secmark(e, profile)) {
info = "failed to unpack profile secmark rules";
goto fail;
}
if (unpack_nameX(e, AA_STRUCT, "policydb")) {
/* generic policy dfa - optional and may be NULL */
info = "failed to unpack policydb";
profile->policy.dfa = unpack_dfa(e);
if (IS_ERR(profile->policy.dfa)) {
error = PTR_ERR(profile->policy.dfa);
profile->policy.dfa = NULL;
goto fail;
} else if (!profile->policy.dfa) {
error = -EPROTO;
goto fail;
}
if (!unpack_u32(e, &profile->policy.start[0], "start"))
/* default start state */
profile->policy.start[0] = DFA_START;
/* setup class index */
for (i = AA_CLASS_FILE; i <= AA_CLASS_LAST; i++) {
profile->policy.start[i] =
aa_dfa_next(profile->policy.dfa,
profile->policy.start[0],
i);
}
if (!unpack_nameX(e, AA_STRUCTEND, NULL))
goto fail;
} else
profile->policy.dfa = aa_get_dfa(nulldfa);
/* get file rules */
profile->file.dfa = unpack_dfa(e);
if (IS_ERR(profile->file.dfa)) {
error = PTR_ERR(profile->file.dfa);
profile->file.dfa = NULL;
info = "failed to unpack profile file rules";
goto fail;
} else if (profile->file.dfa) {
if (!unpack_u32(e, &profile->file.start, "dfa_start"))
/* default start state */
profile->file.start = DFA_START;
} else if (profile->policy.dfa &&
profile->policy.start[AA_CLASS_FILE]) {
profile->file.dfa = aa_get_dfa(profile->policy.dfa);
profile->file.start = profile->policy.start[AA_CLASS_FILE];
} else
profile->file.dfa = aa_get_dfa(nulldfa);
if (!unpack_trans_table(e, profile)) {
info = "failed to unpack profile transition table";
goto fail;
}
if (unpack_nameX(e, AA_STRUCT, "data")) {
info = "out of memory";
profile->data = kzalloc(sizeof(*profile->data), GFP_KERNEL);
if (!profile->data)
goto fail;
params.nelem_hint = 3;
params.key_len = sizeof(void *);
params.key_offset = offsetof(struct aa_data, key);
params.head_offset = offsetof(struct aa_data, head);
params.hashfn = strhash;
params.obj_cmpfn = datacmp;
if (rhashtable_init(profile->data, ¶ms)) {
info = "failed to init key, value hash table";
goto fail;
}
while (unpack_strdup(e, &key, NULL)) {
data = kzalloc(sizeof(*data), GFP_KERNEL);
if (!data) {
kzfree(key);
goto fail;
}
data->key = key;
data->size = unpack_blob(e, &data->data, NULL);
data->data = kvmemdup(data->data, data->size);
if (data->size && !data->data) {
kzfree(data->key);
kzfree(data);
goto fail;
}
rhashtable_insert_fast(profile->data, &data->head,
profile->data->p);
}
if (!unpack_nameX(e, AA_STRUCTEND, NULL)) {
info = "failed to unpack end of key, value data table";
goto fail;
}
}
if (!unpack_nameX(e, AA_STRUCTEND, NULL)) {
info = "failed to unpack end of profile";
goto fail;
}
return profile;
fail:
if (profile)
name = NULL;
else if (!name)
name = "unknown";
audit_iface(profile, NULL, name, info, e, error);
aa_free_profile(profile);
return ERR_PTR(error);
}
/**
* verify_head - unpack serialized stream header
* @e: serialized data read head (NOT NULL)
* @required: whether the header is required or optional
* @ns: Returns - namespace if one is specified else NULL (NOT NULL)
*
* Returns: error or 0 if header is good
*/
static int verify_header(struct aa_ext *e, int required, const char **ns)
{
int error = -EPROTONOSUPPORT;
const char *name = NULL;
*ns = NULL;
/* get the interface version */
if (!unpack_u32(e, &e->version, "version")) {
if (required) {
audit_iface(NULL, NULL, NULL, "invalid profile format",
e, error);
return error;
}
}
/* Check that the interface version is currently supported.
* if not specified use previous version
* Mask off everything that is not kernel abi version
*/
if (VERSION_LT(e->version, v5) || VERSION_GT(e->version, v7)) {
audit_iface(NULL, NULL, NULL, "unsupported interface version",
e, error);
return error;
}
/* read the namespace if present */
if (unpack_str(e, &name, "namespace")) {
if (*name == '\0') {
audit_iface(NULL, NULL, NULL, "invalid namespace name",
e, error);
return error;
}
if (*ns && strcmp(*ns, name))
audit_iface(NULL, NULL, NULL, "invalid ns change", e,
error);
else if (!*ns)
*ns = name;
}
return 0;
}
static bool verify_xindex(int xindex, int table_size)
{
int index, xtype;
xtype = xindex & AA_X_TYPE_MASK;
index = xindex & AA_X_INDEX_MASK;
if (xtype == AA_X_TABLE && index >= table_size)
return 0;
return 1;
}
/* verify dfa xindexes are in range of transition tables */
static bool verify_dfa_xindex(struct aa_dfa *dfa, int table_size)
{
int i;
for (i = 0; i < dfa->tables[YYTD_ID_ACCEPT]->td_lolen; i++) {
if (!verify_xindex(dfa_user_xindex(dfa, i), table_size))
return 0;
if (!verify_xindex(dfa_other_xindex(dfa, i), table_size))
return 0;
}
return 1;
}
/**
* verify_profile - Do post unpack analysis to verify profile consistency
* @profile: profile to verify (NOT NULL)
*
* Returns: 0 if passes verification else error
*/
static int verify_profile(struct aa_profile *profile)
{
if (profile->file.dfa &&
!verify_dfa_xindex(profile->file.dfa,
profile->file.trans.size)) {
audit_iface(profile, NULL, NULL, "Invalid named transition",
NULL, -EPROTO);
return -EPROTO;
}
return 0;
}
void aa_load_ent_free(struct aa_load_ent *ent)
{
if (ent) {
aa_put_profile(ent->rename);
aa_put_profile(ent->old);
aa_put_profile(ent->new);
kfree(ent->ns_name);
kzfree(ent);
}
}
struct aa_load_ent *aa_load_ent_alloc(void)
{
struct aa_load_ent *ent = kzalloc(sizeof(*ent), GFP_KERNEL);
if (ent)
INIT_LIST_HEAD(&ent->list);
return ent;
}
/**
* aa_unpack - unpack packed binary profile(s) data loaded from user space
* @udata: user data copied to kmem (NOT NULL)
* @lh: list to place unpacked profiles in a aa_repl_ws
* @ns: Returns namespace profile is in if specified else NULL (NOT NULL)
*
* Unpack user data and return refcounted allocated profile(s) stored in
* @lh in order of discovery, with the list chain stored in base.list
* or error
*
* Returns: profile(s) on @lh else error pointer if fails to unpack
*/
int aa_unpack(struct aa_loaddata *udata, struct list_head *lh,
const char **ns)
{
struct aa_load_ent *tmp, *ent;
struct aa_profile *profile = NULL;
int error;
struct aa_ext e = {
.start = udata->data,
.end = udata->data + udata->size,
.pos = udata->data,
};
*ns = NULL;
while (e.pos < e.end) {
char *ns_name = NULL;
void *start;
error = verify_header(&e, e.pos == e.start, ns);
if (error)
goto fail;
start = e.pos;
profile = unpack_profile(&e, &ns_name);
if (IS_ERR(profile)) {
error = PTR_ERR(profile);
goto fail;
}
error = verify_profile(profile);
if (error)
goto fail_profile;
if (aa_g_hash_policy)
error = aa_calc_profile_hash(profile, e.version, start,
e.pos - start);
if (error)
goto fail_profile;
ent = aa_load_ent_alloc();
if (!ent) {
error = -ENOMEM;
goto fail_profile;
}
ent->new = profile;
ent->ns_name = ns_name;
list_add_tail(&ent->list, lh);
}
udata->abi = e.version & K_ABI_MASK;
if (aa_g_hash_policy) {
udata->hash = aa_calc_hash(udata->data, udata->size);
if (IS_ERR(udata->hash)) {
error = PTR_ERR(udata->hash);
udata->hash = NULL;
goto fail;
}
}
return 0;
fail_profile:
aa_put_profile(profile);
fail:
list_for_each_entry_safe(ent, tmp, lh, list) {
list_del_init(&ent->list);
aa_load_ent_free(ent);
}
return error;
}
/*
* Copyright (c) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007
* NOVELL (All rights reserved)
*
* Copyright (c) 2013
* Canonical Ltd. (All rights reserved)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of version 2 of the GNU General Public
* License published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, contact Novell, Inc.
*/
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <string>
#include <sstream>
#include <sys/apparmor.h>
#include "lib.h"
#include "parser.h"
#include "profile.h"
#include "libapparmor_re/apparmor_re.h"
#include <unistd.h>
#include <linux/unistd.h>
#define SD_CODE_SIZE (sizeof(u8))
#define SD_STR_LEN (sizeof(u16))
int __sd_serialize_profile(int option, aa_kernel_interface *kernel_interface,
Profile *prof, int cache_fd);
static void print_error(int error)
{
switch (error) {
case -ESPIPE:
PERROR(_("Bad write position\n"));
break;
case -EPERM:
PERROR(_("Permission denied\n"));
break;
case -ENOMEM:
PERROR(_("Out of memory\n"));
break;
case -EFAULT:
PERROR(_("Couldn't copy profile: Bad memory address\n"));
break;
case -EPROTO:
PERROR(_("Profile doesn't conform to protocol\n"));
break;
case -EBADMSG:
PERROR(_("Profile does not match signature\n"));
break;
case -EPROTONOSUPPORT:
PERROR(_("Profile version not supported by Apparmor module\n"));
break;
case -EEXIST:
PERROR(_("Profile already exists\n"));
break;
case -ENOENT:
PERROR(_("Profile doesn't exist\n"));
break;
case -EACCES:
PERROR(_("Permission denied; attempted to load a profile while confined?\n"));
break;
default:
PERROR(_("Unknown error (%d): %s\n"), -error, strerror(-error));
break;
}
}
int load_profile(int option, aa_kernel_interface *kernel_interface,
Profile *prof, int cache_fd)
{
int retval = 0;
int error = 0;
PDEBUG("Serializing policy for %s.\n", prof->name);
retval = __sd_serialize_profile(option, kernel_interface, prof, cache_fd);
if (retval < 0) {
error = retval; /* yeah, we'll just report the last error */
switch (option) {
case OPTION_ADD:
PERROR(_("%s: Unable to add \"%s\". "),
progname, prof->name);
print_error(error);
break;
case OPTION_REPLACE:
PERROR(_("%s: Unable to replace \"%s\". "),
progname, prof->name);
print_error(error);
break;
case OPTION_REMOVE:
PERROR(_("%s: Unable to remove \"%s\". "),
progname, prof->name);
print_error(error);
break;
case OPTION_STDOUT:
PERROR(_("%s: Unable to write to stdout\n"),
progname);
break;
case OPTION_OFILE:
PERROR(_("%s: Unable to write to output file\n"),
progname);
default:
PERROR(_("%s: ASSERT: Invalid option: %d\n"),
progname, option);
exit(1);
break;
}
} else if (conf_verbose) {
switch (option) {
case OPTION_ADD:
printf(_("Addition succeeded for \"%s\".\n"),
prof->name);
break;
case OPTION_REPLACE:
printf(_("Replacement succeeded for \"%s\".\n"),
prof->name);
break;
case OPTION_REMOVE:
printf(_("Removal succeeded for \"%s\".\n"),
prof->name);
break;
case OPTION_STDOUT:
case OPTION_OFILE:
break;
default:
PERROR(_("%s: ASSERT: Invalid option: %d\n"),
progname, option);
exit(1);
break;
}
}
return error;
}
enum sd_code {
SD_U8,
SD_U16,
SD_U32,
SD_U64,
SD_NAME, /* same as string except it is items name */
SD_STRING,
SD_BLOB,
SD_STRUCT,
SD_STRUCTEND,
SD_LIST,
SD_LISTEND,
SD_ARRAY,
SD_ARRAYEND,
SD_OFFSET
};
const char *sd_code_names[] = {
"SD_U8",
"SD_U16",
"SD_U32",
"SD_U64",
"SD_NAME",
"SD_STRING",
"SD_BLOB",
"SD_STRUCT",
"SD_STRUCTEND",
"SD_LIST",
"SD_LISTEND",
"SD_ARRAY",
"SD_ARRAYEND",
"SD_OFFSET"
};
static inline void sd_write8(std::ostringstream &buf, u8 b)
{
buf.write((const char *) &b, 1);
}
static inline void sd_write16(std::ostringstream &buf, u16 b)
{
u16 tmp;
tmp = cpu_to_le16(b);
buf.write((const char *) &tmp, 2);
}
static inline void sd_write32(std::ostringstream &buf, u32 b)
{
u32 tmp;
tmp = cpu_to_le32(b);
buf.write((const char *) &tmp, 4);
}
static inline void sd_write64(std::ostringstream &buf, u64 b)
{
u64 tmp;
printf ("sd_write64: b=%d\n", b);
printf ("sd_write64: b=%x\n", b);
tmp = cpu_to_le64(b);
buf.write((const char *) &tmp, 8);
}
static inline void sd_write_uint8(std::ostringstream &buf, u8 b)
{
sd_write8(buf, SD_U8);
sd_write8(buf, b);
}
static inline void sd_write_uint16(std::ostringstream &buf, u16 b)
{
sd_write8(buf, SD_U16);
sd_write16(buf, b);
}
static inline void sd_write_uint32(std::ostringstream &buf, u32 b)
{
sd_write8(buf, SD_U32);
sd_write32(buf, b);
}
static inline void sd_write_uint64(std::ostringstream &buf, u64 b)
{
sd_write8(buf, SD_U64);
sd_write64(buf, b);
}
static inline void sd_write_name(std::ostringstream &buf, const char *name)
{
PDEBUG("Writing name '%s'\n", name);
if (name) {
sd_write8(buf, SD_NAME);
sd_write16(buf, strlen(name) + 1);
buf.write(name, strlen(name) + 1);
}
}
static inline void sd_write_blob(std::ostringstream &buf, void *b, int buf_size, char *name)
{
sd_write_name(buf, name);
sd_write8(buf, SD_BLOB);
sd_write32(buf, buf_size);
buf.write((const char *) b, buf_size);
}
static char zeros[64];
#define align64(X) (((X) + (typeof(X)) 7) & ~((typeof(X)) 7))
static inline void sd_write_aligned_blob(std::ostringstream &buf, void *b, int b_size,
const char *name)
{
sd_write_name(buf, name);
/* pad calculation MUST come after name is written */
size_t pad = align64(buf.tellp() + ((std::streamoff) 5l)) - (buf.tellp() + ((std::streamoff) 5l));
sd_write8(buf, SD_BLOB);
sd_write32(buf, b_size + pad);
buf.write(zeros, pad);
buf.write((const char *) b, b_size);
}
static void sd_write_strn(std::ostringstream &buf, char *b, int size, const char *name)
{
sd_write_name(buf, name);
sd_write8(buf, SD_STRING);
sd_write16(buf, size);
buf.write(b, size);
}
static inline void sd_write_string(std::ostringstream &buf, char *b, const char *name)
{
sd_write_strn(buf, b, strlen(b) + 1, name);
}
static inline void sd_write_struct(std::ostringstream &buf, const char *name)
{
sd_write_name(buf, name);
sd_write8(buf, SD_STRUCT);
}
static inline void sd_write_structend(std::ostringstream &buf)
{
sd_write8(buf, SD_STRUCTEND);
}
static inline void sd_write_array(std::ostringstream &buf, const char *name, int size)
{
sd_write_name(buf, name);
sd_write8(buf, SD_ARRAY);
sd_write16(buf, size);
}
static inline void sd_write_arrayend(std::ostringstream &buf)
{
sd_write8(buf, SD_ARRAYEND);
}
static inline void sd_write_list(std::ostringstream &buf, const char *name)
{
sd_write_name(buf, name);
sd_write8(buf, SD_LIST);
}
static inline void sd_write_listend(std::ostringstream &buf)
{
sd_write8(buf, SD_LISTEND);
}
void sd_serialize_dfa(std::ostringstream &buf, void *dfa, size_t size)
{
if (dfa)
sd_write_aligned_blob(buf, dfa, size, "aadfa");
}
void sd_serialize_rlimits(std::ostringstream &buf, struct aa_rlimits *limits)
{
if (!limits->specified)
return;
sd_write_struct(buf, "rlimits");
sd_write_uint32(buf, limits->specified);
sd_write_array(buf, NULL, RLIM_NLIMITS);
for (int i = 0; i < RLIM_NLIMITS; i++) {
sd_write_uint64(buf, limits->limits[i]);
}
sd_write_arrayend(buf);
sd_write_structend(buf);
}
void sd_serialize_xtable(std::ostringstream &buf, char **table)
{
int count;
if (!table[4])
return;
sd_write_struct(buf, "xtable");
count = 0;
for (int i = 4; i < AA_EXEC_COUNT; i++) {
if (table[i])
count++;
}
sd_write_array(buf, NULL, count);
for (int i = 4; i < count + 4; i++) {
int len = strlen(table[i]) + 1;
/* if its a namespace make sure the second : is overwritten
* with 0, so that the namespace and name are \0 seperated
*/
if (*table[i] == ':') {
char *tmp = table[i] + 1;
strsep(&tmp, ":");
}
sd_write_strn(buf, table[i], len, NULL);
}
sd_write_arrayend(buf);
sd_write_structend(buf);
}
void sd_serialize_profile(std::ostringstream &buf, Profile *profile,
int flattened)
{
uint64_t allowed_caps;
sd_write_struct(buf, "profile");
if (flattened) {
assert(profile->parent);
autofree char *name = (char *) malloc(3 + strlen(profile->name) + strlen(profile->parent->name));
if (!name)
return;
sprintf(name, "%s//%s", profile->parent->name, profile->name);
sd_write_string(buf, name, NULL);
} else {
sd_write_string(buf, profile->name, NULL);
}
/* only emit this if current kernel at least supports "create" */
if (perms_create) {
if (profile->xmatch) {
sd_serialize_dfa(buf, profile->xmatch, profile->xmatch_size);
sd_write_uint32(buf, profile->xmatch_len);
}
}
// Custom code begin
if (profile->clabel != NULL)
{
sd_write_struct(buf, "custom_label");
sd_write_string(buf, profile->clabel->label_name, NULL);
sd_write_uint32(buf, profile->clabel->allow_cnt);
if (profile->clabel->allow_cnt > 0)
{
sd_write_struct(buf, "data_list");
struct data_list *tmp = profile->clabel->allow_list;
while (tmp != NULL)
{
sd_write_string(buf, tmp->data, NULL);
tmp = tmp->next;
}
sd_write_structend(buf);
}
sd_write_structend(buf);
}
// Custom code end
sd_write_struct(buf, "flags");
/* used to be flags.debug, but that's no longer supported */
sd_write_uint32(buf, profile->flags.hat);
sd_write_uint32(buf, profile->flags.complain);
sd_write_uint32(buf, profile->flags.audit);
sd_write_structend(buf);
if (profile->flags.path) {
int flags = 0;
if (profile->flags.path & PATH_CHROOT_REL)
flags |= 0x8;
if (profile->flags.path & PATH_MEDIATE_DELETED)
flags |= 0x10000;
if (profile->flags.path & PATH_ATTACH)
flags |= 0x4;
if (profile->flags.path & PATH_CHROOT_NSATTACH)
flags |= 0x10;
sd_write_name(buf, "path_flags");
sd_write_uint32(buf, flags);
}
#define low_caps(X) ((u32) ((X) & 0xffffffff))
#define high_caps(X) ((u32) (((X) >> 32) & 0xffffffff))
allowed_caps = (profile->caps.allow) & ~profile->caps.deny;
sd_write_uint32(buf, low_caps(allowed_caps));
sd_write_uint32(buf, low_caps(allowed_caps & profile->caps.audit));
sd_write_uint32(buf, low_caps(profile->caps.deny & profile->caps.quiet));
sd_write_uint32(buf, 0);
sd_write_struct(buf, "caps64");
sd_write_uint32(buf, high_caps(allowed_caps));
sd_write_uint32(buf, high_caps(allowed_caps & profile->caps.audit));
sd_write_uint32(buf, high_caps(profile->caps.deny & profile->caps.quiet));
sd_write_uint32(buf, 0);
sd_write_structend(buf);
sd_serialize_rlimits(buf, &profile->rlimits);
if (profile->net.allow && kernel_supports_network) {
size_t i;
sd_write_array(buf, "net_allowed_af", get_af_max());
for (i = 0; i < get_af_max(); i++) {
u16 allowed = profile->net.allow[i] &
~profile->net.deny[i];
sd_write_uint16(buf, allowed);
sd_write_uint16(buf, allowed & profile->net.audit[i]);
sd_write_uint16(buf, profile->net.deny[i] & profile->net.quiet[i]);
}
sd_write_arrayend(buf);
} else if (profile->net.allow && (warnflags & WARN_RULE_NOT_ENFORCED))
pwarn(_("profile %s network rules not enforced\n"), profile->name);
if (profile->policy.dfa) {
sd_write_struct(buf, "policydb");
sd_serialize_dfa(buf, profile->policy.dfa, profile->policy.size);
sd_write_structend(buf);
}
/* either have a single dfa or lists of different entry types */
sd_serialize_dfa(buf, profile->dfa.dfa, profile->dfa.size);
sd_serialize_xtable(buf, profile->exec_table);
sd_write_structend(buf);
}
void sd_serialize_top_profile(std::ostringstream &buf, Profile *profile)
{
uint32_t version;
version = ENCODE_VERSION(force_complain, policy_version,
parser_abi_version, kernel_abi_version);
sd_write_name(buf, "version");
sd_write_uint32(buf, version);
if (profile->ns) {
sd_write_string(buf, profile->ns, "namespace");
}
sd_serialize_profile(buf, profile, profile->parent ? 1 : 0);
}
int __sd_serialize_profile(int option, aa_kernel_interface *kernel_interface,
Profile *prof, int cache_fd)
{
autoclose int fd = -1;
int error, size, wsize;
std::ostringstream work_area;
switch (option) {
case OPTION_ADD:
case OPTION_REPLACE:
case OPTION_REMOVE:
break;
case OPTION_STDOUT:
fd = dup(1);
if (fd < 0) {
error = -errno;
PERROR(_("Unable to open stdout - %s\n"),
strerror(errno));
goto exit;
}
break;
case OPTION_OFILE:
fd = dup(fileno(ofile));
if (fd < 0) {
error = -errno;
PERROR(_("Unable to open output file - %s\n"),
strerror(errno));
goto exit;
}
break;
default:
error = -EINVAL;
goto exit;
break;
}
error = 0;
if (option == OPTION_REMOVE) {
if (kernel_load) {
if (aa_kernel_interface_remove_policy(kernel_interface,
prof->fqname().c_str()) == -1)
error = -errno;
}
} else {
std::string tmp;
sd_serialize_top_profile(work_area, prof);
tmp = work_area.str();
// printf ("__sd_serialize_profile: kernel_load=%d, buffer_len=%d\n", kernel_load, tmp.length());
//size_t size_2 = sizeof(tmp.c_str()); /* or however much you're planning to write */
// fwrite(tmp.c_str(), 1, tmp.length(), stdout);
// printf("\n");
size = (long) work_area.tellp();
printf ("size of serialized data=%d\n", size);
if (kernel_load) {
// printf ("__sd_serialize_profile: inside kernel_load, option value=%d\n", option);
if (option == OPTION_ADD )
{
// printf ("__sd_serialize_profile: inside option_add\n");
if (aa_kernel_interface_load_policy(kernel_interface,
tmp.c_str(), size) == -1)
error = -errno;
// else
// printf ("__sd_serialize_profile: inside option_add, else part\n");
} else if (option == OPTION_REPLACE &&
aa_kernel_interface_replace_policy(kernel_interface,
tmp.c_str(), size) == -1) {
error = -errno;
}
// else
// printf ("__sd_serialize_profile: none of the above were executed\n");
} else if ((option == OPTION_STDOUT || option == OPTION_OFILE) &&
aa_kernel_interface_write_policy(fd, tmp.c_str(), size) == -1) {
error = -errno;
}
// printf ("__sd_serialize_profile: after kernel_load\n");
if (cache_fd != -1) {
wsize = write(cache_fd, tmp.c_str(), size);
if (wsize < 0) {
error = -errno;
} else if (wsize < size) {
PERROR(_("%s: Unable to write entire profile entry to cache\n"),
progname);
error = -EIO;
}
}
}
if (!prof->hat_table.empty() && option != OPTION_REMOVE) {
if (load_flattened_hats(prof, option, kernel_interface, cache_fd) == 0)
return 0;
}
exit:
return error;
}
/*
* Copyright (c) 2012
* Canonical, Ltd. (All rights reserved)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of version 2 of the GNU General Public
* License published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#ifndef __AA_PROFILE_H
#define __AA_PROFILE_H
#include <set>
#include <string>
#include <iostream>
#include "parser.h"
#include "rule.h"
#include "libapparmor_re/aare_rules.h"
#include "network.h"
class Profile;
class block {
public:
};
struct deref_profileptr_lt {
bool operator()(Profile * const &lhs, Profile * const &rhs) const;
};
class ProfileList {
public:
set<Profile *, deref_profileptr_lt> list;
typedef set<Profile *, deref_profileptr_lt>::iterator iterator;
iterator begin() { return list.begin(); }
iterator end() { return list.end(); }
ProfileList() { };
virtual ~ProfileList() { clear(); }
virtual bool empty(void) { return list.empty(); }
virtual pair<ProfileList::iterator,bool> insert(Profile *);
virtual void erase(ProfileList::iterator pos);
void clear(void);
void dump(void);
void dump_profile_names(bool children);
};
class flagvals {
public:
int hat;
int complain;
int audit;
int path;
void dump(void)
{
printf("Profile Mode:\t");
if (complain)
printf("Complain");
else
printf("Enforce");
if (audit)
printf(", Audit");
if (hat)
printf(", Hat");
printf("\n");
}
};
struct capabilities {
uint64_t allow;
uint64_t audit;
uint64_t deny;
uint64_t quiet;
capabilities(void) { allow = audit = deny = quiet = 0; }
void dump()
{
if (allow != 0ull)
__debug_capabilities(allow, "Capabilities");
if (audit != 0ull)
__debug_capabilities(audit, "Audit Caps");
if (deny != 0ull)
__debug_capabilities(deny, "Deny Caps");
if (quiet != 0ull)
__debug_capabilities(quiet, "Quiet Caps");
};
};
struct dfa_stuff {
aare_rules *rules;
void *dfa;
size_t size;
dfa_stuff(void): rules(NULL), dfa(NULL), size(0) { }
};
// Custom code begin
struct data_list
{
char *data;
struct data_list *next;
}
struct custom_label
{
char *label_name;
int allow_cnt;
struct data_list *allow_list;
}
// Custom code end
class Profile {
public:
//profile_base
char *ns;
//profile_base
char *name;
//sets inside profile_base:
char *attachment;
struct alt_name *altnames;
//inside parser_regex->process_profile_name_xmatch
void *xmatch;
size_t xmatch_size;
int xmatch_len;
/* char *sub_name; */ /* subdomain name or NULL */
/* int default_deny; */ /* TRUE or FALSE */
//sets inside local_profile:
int local;
int local_mode; /* true if local, not hat */
int local_audit;
//sets inside hats: | local_profile:
Profile *parent;
//profile_base, profile, hat
flagvals flags;
//capability
struct capabilities caps;
//network_rule
struct network net;
//sets inside last rules:
struct aa_rlimits rlimits;
char *exec_table[AA_EXEC_COUNT];
//rule, change_profile
struct cod_entry *entries;
//network_rule, mnt_rule, dbus_rule, signal_rule, ptrace_rule, unix_rule
RuleList rule_ents;
ProfileList hat_table;
//inside parser_regex -> process_profile_regex
//is filled inside process_profile_regex
struct dfa_stuff dfa;
//inside parser_regex -> process_profile_policydb
struct dfa_stuff policy;
// Custom code begin
struct custom_label *clabel;
// Custom code end
Profile(void)
{
ns = name = attachment = NULL;
altnames = NULL;
xmatch = NULL;
xmatch_size = 0;
xmatch_len = 0;
local = local_mode = local_audit = 0;
parent = NULL;
flags = { 0, 0, 0, 0};
rlimits = {0, {}};
std::fill(exec_table, exec_table + AA_EXEC_COUNT, (char *)NULL);
entries = NULL;
current_domain = NULL;
allow_net_domains = NULL;
deny_net_domains = NULL;
};
virtual ~Profile();
bool operator<(Profile const &rhs)const
{
if (ns) {
if (rhs.ns) {
int res = strcmp(ns, rhs.ns);
if (res != 0)
return res < 0;
} else
return false;
} else if (rhs.ns)
return true;
return strcmp(name, rhs.name) < 0;
}
void dump(void)
{
if (ns)
printf("Ns:\t\t%s\n", ns);
if (name)
printf("Name:\t\t%s\n", name);
else
printf("Name:\t\t<NULL>\n");
if (local) {
if (parent)
printf("Local To:\t%s\n", parent->name);
else
printf("Local To:\t<NULL>\n");
}
printf ("flags------------------------------\n");
flags.dump();
printf ("caps------------------------------\n");
caps.dump();
printf ("net------------------------------\n");
net.dump();
printf ("cod_entries------------------------------\n");
if (entries)
debug_cod_entries(entries);
printf ("rulelist------------------------------\n");
for (RuleList::iterator i = rule_ents.begin(); i != rule_ents.end(); i++) {
(*i)->dump(cout);
}
printf("\n");
printf ("hat_table------------------------------\n");
hat_table.dump();
printf ("exec_table------------------------------\n");
for(int i = 0; i < AA_EXEC_COUNT; i++)
{
printf ("%s\n", exec_table[i]);
}
}
bool alloc_net_table();
std::string hname(void)
{
if (!parent)
return name;
return parent->hname() + "//" + name;
}
/* assumes ns is set as part of profile creation */
std::string fqname(void)
{
if (parent)
return parent->fqname() + "//" + name;
else if (!ns)
return hname();
return ":" + std::string(ns) + "://" + hname();
}
std::string get_name(bool fqp)
{
if (fqp)
return fqname();
return hname();
}
void dump_name(bool fqp)
{
cout << get_name(fqp);;
}
};
#endif /* __AA_PROFILE_H */
// SPDX-License-Identifier: GPL-2.0-only
/*
* AppArmor security module
*
* This file contains AppArmor policy manipulation functions
*
* Copyright (C) 1998-2008 Novell/SUSE
* Copyright 2009-2010 Canonical Ltd.
*
* AppArmor policy is based around profiles, which contain the rules a
* task is confined by. Every task in the system has a profile attached
* to it determined either by matching "unconfined" tasks against the
* visible set of profiles or by following a profiles attachment rules.
*
* Each profile exists in a profile namespace which is a container of
* visible profiles. Each namespace contains a special "unconfined" profile,
* which doesn't enforce any confinement on a task beyond DAC.
*
* Namespace and profile names can be written together in either
* of two syntaxes.
* :namespace:profile - used by kernel interfaces for easy detection
* namespace://profile - used by policy
*
* Profile names can not start with : or @ or ^ and may not contain \0
*
* Reserved profile names
* unconfined - special automatically generated unconfined profile
* inherit - special name to indicate profile inheritance
* null-XXXX-YYYY - special automatically generated learning profiles
*
* Namespace names may not start with / or @ and may not contain \0 or :
* Reserved namespace names
* user-XXXX - user defined profiles
*
* a // in a profile or namespace name indicates a hierarchical name with the
* name before the // being the parent and the name after the child.
*
* Profile and namespace hierarchies serve two different but similar purposes.
* The namespace contains the set of visible profiles that are considered
* for attachment. The hierarchy of namespaces allows for virtualizing
* the namespace so that for example a chroot can have its own set of profiles
* which may define some local user namespaces.
* The profile hierarchy severs two distinct purposes,
* - it allows for sub profiles or hats, which allows an application to run
* subprograms under its own profile with different restriction than it
* self, and not have it use the system profile.
* eg. if a mail program starts an editor, the policy might make the
* restrictions tighter on the editor tighter than the mail program,
* and definitely different than general editor restrictions
* - it allows for binary hierarchy of profiles, so that execution history
* is preserved. This feature isn't exploited by AppArmor reference policy
* but is allowed. NOTE: this is currently suboptimal because profile
* aliasing is not currently implemented so that a profile for each
* level must be defined.
* eg. /bin/bash///bin/ls as a name would indicate /bin/ls was started
* from /bin/bash
*
* A profile or namespace name that can contain one or more // separators
* is referred to as an hname (hierarchical).
* eg. /bin/bash//bin/ls
*
* An fqname is a name that may contain both namespace and profile hnames.
* eg. :ns:/bin/bash//bin/ls
*
* NOTES:
* - locking of profile lists is currently fairly coarse. All profile
* lists within a namespace use the namespace lock.
* FIXME: move profile lists to using rcu_lists
*/
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/string.h>
#include <linux/cred.h>
#include <linux/rculist.h>
#include <linux/user_namespace.h>
#include "include/apparmor.h"
#include "include/capability.h"
#include "include/cred.h"
#include "include/file.h"
#include "include/ipc.h"
#include "include/match.h"
#include "include/path.h"
#include "include/policy.h"
#include "include/policy_ns.h"
#include "include/policy_unpack.h"
#include "include/resource.h"
int unprivileged_userns_apparmor_policy = 1;
const char *const aa_profile_mode_names[] = {
"enforce",
"complain",
"kill",
"unconfined",
};
/**
* __add_profile - add a profiles to list and label tree
* @list: list to add it to (NOT NULL)
* @profile: the profile to add (NOT NULL)
*
* refcount @profile, should be put by __list_remove_profile
*
* Requires: namespace lock be held, or list not be shared
*/
static void __add_profile(struct list_head *list, struct aa_profile *profile)
{
struct aa_label *l;
AA_BUG(!list);
AA_BUG(!profile);
AA_BUG(!profile->ns);
AA_BUG(!mutex_is_locked(&profile->ns->lock));
list_add_rcu(&profile->base.list, list);
/* get list reference */
aa_get_profile(profile);
l = aa_label_insert(&profile->ns->labels, &profile->label);
AA_BUG(l != &profile->label);
aa_put_label(l);
}
/**
* __list_remove_profile - remove a profile from the list it is on
* @profile: the profile to remove (NOT NULL)
*
* remove a profile from the list, warning generally removal should
* be done with __replace_profile as most profile removals are
* replacements to the unconfined profile.
*
* put @profile list refcount
*
* Requires: namespace lock be held, or list not have been live
*/
static void __list_remove_profile(struct aa_profile *profile)
{
AA_BUG(!profile);
AA_BUG(!profile->ns);
AA_BUG(!mutex_is_locked(&profile->ns->lock));
list_del_rcu(&profile->base.list);
aa_put_profile(profile);
}
/**
* __remove_profile - remove old profile, and children
* @profile: profile to be replaced (NOT NULL)
*
* Requires: namespace list lock be held, or list not be shared
*/
static void __remove_profile(struct aa_profile *profile)
{
AA_BUG(!profile);
AA_BUG(!profile->ns);
AA_BUG(!mutex_is_locked(&profile->ns->lock));
/* release any children lists first */
__aa_profile_list_release(&profile->base.profiles);
/* released by free_profile */
aa_label_remove(&profile->label);
__aafs_profile_rmdir(profile);
__list_remove_profile(profile);
}
/**
* __aa_profile_list_release - remove all profiles on the list and put refs
* @head: list of profiles (NOT NULL)
*
* Requires: namespace lock be held
*/
void __aa_profile_list_release(struct list_head *head)
{
struct aa_profile *profile, *tmp;
list_for_each_entry_safe(profile, tmp, head, base.list)
__remove_profile(profile);
}
/**
* aa_free_data - free a data blob
* @ptr: data to free
* @arg: unused
*/
static void aa_free_data(void *ptr, void *arg)
{
struct aa_data *data = ptr;
kzfree(data->data);
kzfree(data->key);
kzfree(data);
}
/**
* aa_free_profile - free a profile
* @profile: the profile to free (MAYBE NULL)
*
* Free a profile, its hats and null_profile. All references to the profile,
* its hats and null_profile must have been put.
*
* If the profile was referenced from a task context, free_profile() will
* be called from an rcu callback routine, so we must not sleep here.
*/
void aa_free_profile(struct aa_profile *profile)
{
struct rhashtable *rht;
int i;
AA_DEBUG("%s(%p)\n", __func__, profile);
if (!profile)
return;
/* free children profiles */
aa_policy_destroy(&profile->base);
aa_put_profile(rcu_access_pointer(profile->parent));
aa_put_ns(profile->ns);
kzfree(profile->rename);
// Custom code begin
if(profile->clabel)
{
kzfree(profile->clabel->label_name);
if(profile->clabel->allow_list)
{
struct data_list *iterator, *tmp;
iterator = list_first_entry(&(profile->clabel->allow_list->lh), typeof(*iterator), lh);
while( (&iterator->lh) != &(profile->clabel->allow_list->lh))
{
tmp = iterator;
iterator = list_next_entry (iterator, lh);
kzfree (tmp->data);
kzfree (tmp);
}
kzfree(profile->clabel->allow_list);
}
kzfree(profile->clabel);
}
// Custom code end
aa_free_file_rules(&profile->file);
aa_free_cap_rules(&profile->caps);
aa_free_rlimit_rules(&profile->rlimits);
for (i = 0; i < profile->xattr_count; i++)
kzfree(profile->xattrs[i]);
kzfree(profile->xattrs);
for (i = 0; i < profile->secmark_count; i++)
kzfree(profile->secmark[i].label);
kzfree(profile->secmark);
kzfree(profile->dirname);
aa_put_dfa(profile->xmatch);
aa_put_dfa(profile->policy.dfa);
if (profile->data) {
rht = profile->data;
profile->data = NULL;
rhashtable_free_and_destroy(rht, aa_free_data, NULL);
kzfree(rht);
}
kzfree(profile->hash);
aa_put_loaddata(profile->rawdata);
kzfree(profile);
}
/**
* aa_alloc_profile - allocate, initialize and return a new profile
* @hname: name of the profile (NOT NULL)
* @gfp: allocation type
*
* Returns: refcount profile or NULL on failure
*/
struct aa_profile *aa_alloc_profile(const char *hname, struct aa_proxy *proxy,
gfp_t gfp)
{
struct aa_profile *profile;
/* freed by free_profile - usually through aa_put_profile */
profile = kzalloc(sizeof(*profile) + sizeof(struct aa_profile *) * 2,
gfp);
if (!profile)
return NULL;
if (!aa_policy_init(&profile->base, NULL, hname, gfp))
goto fail;
if (!aa_label_init(&profile->label, 1, gfp))
goto fail;
/* update being set needed by fs interface */
if (!proxy) {
proxy = aa_alloc_proxy(&profile->label, gfp);
if (!proxy)
goto fail;
} else
aa_get_proxy(proxy);
profile->label.proxy = proxy;
profile->label.hname = profile->base.hname;
profile->label.flags |= FLAG_PROFILE;
profile->label.vec[0] = profile;
/* refcount released by caller */
return profile;
fail:
aa_free_profile(profile);
return NULL;
}
/* TODO: profile accounting - setup in remove */
/**
* __strn_find_child - find a profile on @head list using substring of @name
* @head: list to search (NOT NULL)
* @name: name of profile (NOT NULL)
* @len: length of @name substring to match
*
* Requires: rcu_read_lock be held
*
* Returns: unrefcounted profile ptr, or NULL if not found
*/
static struct aa_profile *__strn_find_child(struct list_head *head,
const char *name, int len)
{
return (struct aa_profile *)__policy_strn_find(head, name, len);
}
/**
* __find_child - find a profile on @head list with a name matching @name
* @head: list to search (NOT NULL)
* @name: name of profile (NOT NULL)
*
* Requires: rcu_read_lock be held
*
* Returns: unrefcounted profile ptr, or NULL if not found
*/
static struct aa_profile *__find_child(struct list_head *head, const char *name)
{
return __strn_find_child(head, name, strlen(name));
}
/**
* aa_find_child - find a profile by @name in @parent
* @parent: profile to search (NOT NULL)
* @name: profile name to search for (NOT NULL)
*
* Returns: a refcounted profile or NULL if not found
*/
struct aa_profile *aa_find_child(struct aa_profile *parent, const char *name)
{
struct aa_profile *profile;
rcu_read_lock();
do {
profile = __find_child(&parent->base.profiles, name);
} while (profile && !aa_get_profile_not0(profile));
rcu_read_unlock();
/* refcount released by caller */
return profile;
}
/**
* __lookup_parent - lookup the parent of a profile of name @hname
* @ns: namespace to lookup profile in (NOT NULL)
* @hname: hierarchical profile name to find parent of (NOT NULL)
*
* Lookups up the parent of a fully qualified profile name, the profile
* that matches hname does not need to exist, in general this
* is used to load a new profile.
*
* Requires: rcu_read_lock be held
*
* Returns: unrefcounted policy or NULL if not found
*/
static struct aa_policy *__lookup_parent(struct aa_ns *ns,
const char *hname)
{
struct aa_policy *policy;
struct aa_profile *profile = NULL;
char *split;
policy = &ns->base;
for (split = strstr(hname, "//"); split;) {
profile = __strn_find_child(&policy->profiles, hname,
split - hname);
if (!profile)
return NULL;
policy = &profile->base;
hname = split + 2;
split = strstr(hname, "//");
}
if (!profile)
return &ns->base;
return &profile->base;
}
/**
* __lookupn_profile - lookup the profile matching @hname
* @base: base list to start looking up profile name from (NOT NULL)
* @hname: hierarchical profile name (NOT NULL)
* @n: length of @hname
*
* Requires: rcu_read_lock be held
*
* Returns: unrefcounted profile pointer or NULL if not found
*
* Do a relative name lookup, recursing through profile tree.
*/
static struct aa_profile *__lookupn_profile(struct aa_policy *base,
const char *hname, size_t n)
{
struct aa_profile *profile = NULL;
const char *split;
for (split = strnstr(hname, "//", n); split;
split = strnstr(hname, "//", n)) {
profile = __strn_find_child(&base->profiles, hname,
split - hname);
if (!profile)
return NULL;
base = &profile->base;
n -= split + 2 - hname;
hname = split + 2;
}
if (n)
return __strn_find_child(&base->profiles, hname, n);
return NULL;
}
static struct aa_profile *__lookup_profile(struct aa_policy *base,
const char *hname)
{
return __lookupn_profile(base, hname, strlen(hname));
}
/**
* aa_lookup_profile - find a profile by its full or partial name
* @ns: the namespace to start from (NOT NULL)
* @hname: name to do lookup on. Does not contain namespace prefix (NOT NULL)
* @n: size of @hname
*
* Returns: refcounted profile or NULL if not found
*/
struct aa_profile *aa_lookupn_profile(struct aa_ns *ns, const char *hname,
size_t n)
{
struct aa_profile *profile;
rcu_read_lock();
do {
profile = __lookupn_profile(&ns->base, hname, n);
} while (profile && !aa_get_profile_not0(profile));
rcu_read_unlock();
/* the unconfined profile is not in the regular profile list */
if (!profile && strncmp(hname, "unconfined", n) == 0)
profile = aa_get_newest_profile(ns->unconfined);
/* refcount released by caller */
return profile;
}
struct aa_profile *aa_lookup_profile(struct aa_ns *ns, const char *hname)
{
return aa_lookupn_profile(ns, hname, strlen(hname));
}
struct aa_profile *aa_fqlookupn_profile(struct aa_label *base,
const char *fqname, size_t n)
{
struct aa_profile *profile;
struct aa_ns *ns;
const char *name, *ns_name;
size_t ns_len;
name = aa_splitn_fqname(fqname, n, &ns_name, &ns_len);
if (ns_name) {
ns = aa_lookupn_ns(labels_ns(base), ns_name, ns_len);
if (!ns)
return NULL;
} else
ns = aa_get_ns(labels_ns(base));
if (name)
profile = aa_lookupn_profile(ns, name, n - (name - fqname));
else if (ns)
/* default profile for ns, currently unconfined */
profile = aa_get_newest_profile(ns->unconfined);
else
profile = NULL;
aa_put_ns(ns);
return profile;
}
/**
* aa_new_null_profile - create or find a null-X learning profile
* @parent: profile that caused this profile to be created (NOT NULL)
* @hat: true if the null- learning profile is a hat
* @base: name to base the null profile off of
* @gfp: type of allocation
*
* Find/Create a null- complain mode profile used in learning mode. The
* name of the profile is unique and follows the format of parent//null-XXX.
* where XXX is based on the @name or if that fails or is not supplied
* a unique number
*
* null profiles are added to the profile list but the list does not
* hold a count on them so that they are automatically released when
* not in use.
*
* Returns: new refcounted profile else NULL on failure
*/
struct aa_profile *aa_new_null_profile(struct aa_profile *parent, bool hat,
const char *base, gfp_t gfp)
{
struct aa_profile *p, *profile;
const char *bname;
char *name = NULL;
AA_BUG(!parent);
if (base) {
name = kmalloc(strlen(parent->base.hname) + 8 + strlen(base),
gfp);
if (name) {
sprintf(name, "%s//null-%s", parent->base.hname, base);
goto name;
}
/* fall through to try shorter uniq */
}
name = kmalloc(strlen(parent->base.hname) + 2 + 7 + 8, gfp);
if (!name)
return NULL;
sprintf(name, "%s//null-%x", parent->base.hname,
atomic_inc_return(&parent->ns->uniq_null));
name:
/* lookup to see if this is a dup creation */
bname = basename(name);
profile = aa_find_child(parent, bname);
if (profile)
goto out;
profile = aa_alloc_profile(name, NULL, gfp);
if (!profile)
goto fail;
profile->mode = APPARMOR_COMPLAIN;
profile->label.flags |= FLAG_NULL;
if (hat)
profile->label.flags |= FLAG_HAT;
profile->path_flags = parent->path_flags;
/* released on free_profile */
rcu_assign_pointer(profile->parent, aa_get_profile(parent));
profile->ns = aa_get_ns(parent->ns);
profile->file.dfa = aa_get_dfa(nulldfa);
profile->policy.dfa = aa_get_dfa(nulldfa);
mutex_lock_nested(&profile->ns->lock, profile->ns->level);
p = __find_child(&parent->base.profiles, bname);
if (p) {
aa_free_profile(profile);
profile = aa_get_profile(p);
} else {
__add_profile(&parent->base.profiles, profile);
}
mutex_unlock(&profile->ns->lock);
/* refcount released by caller */
out:
kfree(name);
return profile;
fail:
kfree(name);
aa_free_profile(profile);
return NULL;
}
/**
* replacement_allowed - test to see if replacement is allowed
* @profile: profile to test if it can be replaced (MAYBE NULL)
* @noreplace: true if replacement shouldn't be allowed but addition is okay
* @info: Returns - info about why replacement failed (NOT NULL)
*
* Returns: %0 if replacement allowed else error code
*/
static int replacement_allowed(struct aa_profile *profile, int noreplace,
const char **info)
{
if (profile) {
if (profile->label.flags & FLAG_IMMUTIBLE) {
*info = "cannot replace immutible profile";
return -EPERM;
} else if (noreplace) {
*info = "profile already exists";
return -EEXIST;
}
}
return 0;
}
/* audit callback for net specific fields */
static void audit_cb(struct audit_buffer *ab, void *va)
{
struct common_audit_data *sa = va;
if (aad(sa)->iface.ns) {
audit_log_format(ab, " ns=");
audit_log_untrustedstring(ab, aad(sa)->iface.ns);
}
}
/**
* audit_policy - Do auditing of policy changes
* @label: label to check if it can manage policy
* @op: policy operation being performed
* @ns_name: name of namespace being manipulated
* @name: name of profile being manipulated (NOT NULL)
* @info: any extra information to be audited (MAYBE NULL)
* @error: error code
*
* Returns: the error to be returned after audit is done
*/
static int audit_policy(struct aa_label *label, const char *op,
const char *ns_name, const char *name,
const char *info, int error)
{
DEFINE_AUDIT_DATA(sa, LSM_AUDIT_DATA_NONE, op);
aad(&sa)->iface.ns = ns_name;
aad(&sa)->name = name;
aad(&sa)->info = info;
aad(&sa)->error = error;
aad(&sa)->label = label;
aa_audit_msg(AUDIT_APPARMOR_STATUS, &sa, audit_cb);
return error;
}
/**
* policy_view_capable - check if viewing policy in at @ns is allowed
* ns: namespace being viewed by current task (may be NULL)
* Returns: true if viewing policy is allowed
*
* If @ns is NULL then the namespace being viewed is assumed to be the
* tasks current namespace.
*/
bool policy_view_capable(struct aa_ns *ns)
{
struct user_namespace *user_ns = current_user_ns();
struct aa_ns *view_ns = aa_get_current_ns();
bool root_in_user_ns = uid_eq(current_euid(), make_kuid(user_ns, 0)) ||
in_egroup_p(make_kgid(user_ns, 0));
bool response = false;
if (!ns)
ns = view_ns;
if (root_in_user_ns && aa_ns_visible(view_ns, ns, true) &&
(user_ns == &init_user_ns ||
(unprivileged_userns_apparmor_policy != 0 &&
user_ns->level == view_ns->level)))
response = true;
aa_put_ns(view_ns);
return response;
}
bool policy_admin_capable(struct aa_ns *ns)
{
struct user_namespace *user_ns = current_user_ns();
bool capable = ns_capable(user_ns, CAP_MAC_ADMIN);
AA_DEBUG("cap_mac_admin? %d\n", capable);
AA_DEBUG("policy locked? %d\n", aa_g_lock_policy);
return policy_view_capable(ns) && capable && !aa_g_lock_policy;
}
/**
* aa_may_manage_policy - can the current task manage policy
* @label: label to check if it can manage policy
* @op: the policy manipulation operation being done
*
* Returns: 0 if the task is allowed to manipulate policy else error
*/
int aa_may_manage_policy(struct aa_label *label, struct aa_ns *ns, u32 mask)
{
const char *op;
if (mask & AA_MAY_REMOVE_POLICY)
op = OP_PROF_RM;
else if (mask & AA_MAY_REPLACE_POLICY)
op = OP_PROF_REPL;
else
op = OP_PROF_LOAD;
/* check if loading policy is locked out */
if (aa_g_lock_policy)
return audit_policy(label, op, NULL, NULL, "policy_locked",
-EACCES);
if (!policy_admin_capable(ns))
return audit_policy(label, op, NULL, NULL, "not policy admin",
-EACCES);
/* TODO: add fine grained mediation of policy loads */
return 0;
}
static struct aa_profile *__list_lookup_parent(struct list_head *lh,
struct aa_profile *profile)
{
const char *base = basename(profile->base.hname);
long len = base - profile->base.hname;
struct aa_load_ent *ent;
/* parent won't have trailing // so remove from len */
if (len <= 2)
return NULL;
len -= 2;
list_for_each_entry(ent, lh, list) {
if (ent->new == profile)
continue;
if (strncmp(ent->new->base.hname, profile->base.hname, len) ==
0 && ent->new->base.hname[len] == 0)
return ent->new;
}
return NULL;
}
/**
* __replace_profile - replace @old with @new on a list
* @old: profile to be replaced (NOT NULL)
* @new: profile to replace @old with (NOT NULL)
* @share_proxy: transfer @old->proxy to @new
*
* Will duplicate and refcount elements that @new inherits from @old
* and will inherit @old children.
*
* refcount @new for list, put @old list refcount
*
* Requires: namespace list lock be held, or list not be shared
*/
static void __replace_profile(struct aa_profile *old, struct aa_profile *new)
{
struct aa_profile *child, *tmp;
if (!list_empty(&old->base.profiles)) {
LIST_HEAD(lh);
list_splice_init_rcu(&old->base.profiles, &lh, synchronize_rcu);
list_for_each_entry_safe(child, tmp, &lh, base.list) {
struct aa_profile *p;
list_del_init(&child->base.list);
p = __find_child(&new->base.profiles, child->base.name);
if (p) {
/* @p replaces @child */
__replace_profile(child, p);
continue;
}
/* inherit @child and its children */
/* TODO: update hname of inherited children */
/* list refcount transferred to @new */
p = aa_deref_parent(child);
rcu_assign_pointer(child->parent, aa_get_profile(new));
list_add_rcu(&child->base.list, &new->base.profiles);
aa_put_profile(p);
}
}
if (!rcu_access_pointer(new->parent)) {
struct aa_profile *parent = aa_deref_parent(old);
rcu_assign_pointer(new->parent, aa_get_profile(parent));
}
aa_label_replace(&old->label, &new->label);
/* migrate dents must come after label replacement b/c update */
__aafs_profile_migrate_dents(old, new);
if (list_empty(&new->base.list)) {
/* new is not on a list already */
list_replace_rcu(&old->base.list, &new->base.list);
aa_get_profile(new);
aa_put_profile(old);
} else
__list_remove_profile(old);
}
/**
* __lookup_replace - lookup replacement information for a profile
* @ns - namespace the lookup occurs in
* @hname - name of profile to lookup
* @noreplace - true if not replacing an existing profile
* @p - Returns: profile to be replaced
* @info - Returns: info string on why lookup failed
*
* Returns: profile to replace (no ref) on success else ptr error
*/
static int __lookup_replace(struct aa_ns *ns, const char *hname,
bool noreplace, struct aa_profile **p,
const char **info)
{
*p = aa_get_profile(__lookup_profile(&ns->base, hname));
if (*p) {
int error = replacement_allowed(*p, noreplace, info);
if (error) {
*info = "profile can not be replaced";
return error;
}
}
return 0;
}
static void share_name(struct aa_profile *old, struct aa_profile *new)
{
aa_put_str(new->base.hname);
aa_get_str(old->base.hname);
new->base.hname = old->base.hname;
new->base.name = old->base.name;
new->label.hname = old->label.hname;
}
/* Update to newest version of parent after previous replacements
* Returns: unrefcount newest version of parent
*/
static struct aa_profile *update_to_newest_parent(struct aa_profile *new)
{
struct aa_profile *parent, *newest;
parent = rcu_dereference_protected(new->parent,
mutex_is_locked(&new->ns->lock));
newest = aa_get_newest_profile(parent);
/* parent replaced in this atomic set? */
if (newest != parent) {
aa_put_profile(parent);
rcu_assign_pointer(new->parent, newest);
} else
aa_put_profile(newest);
return newest;
}
/**
* aa_replace_profiles - replace profile(s) on the profile list
* @policy_ns: namespace load is occurring on
* @label: label that is attempting to load/replace policy
* @mask: permission mask
* @udata: serialized data stream (NOT NULL)
*
* unpack and replace a profile on the profile list and uses of that profile
* by any task creds via invalidating the old version of the profile, which
* tasks will notice to update their own cred. If the profile does not exist
* on the profile list it is added.
*
* Returns: size of data consumed else error code on failure.
*/
ssize_t aa_replace_profiles(struct aa_ns *policy_ns, struct aa_label *label,
u32 mask, struct aa_loaddata *udata)
{
const char *ns_name, *info = NULL;
struct aa_ns *ns = NULL;
struct aa_load_ent *ent, *tmp;
struct aa_loaddata *rawdata_ent;
const char *op;
ssize_t count, error;
LIST_HEAD(lh);
op = mask & AA_MAY_REPLACE_POLICY ? OP_PROF_REPL : OP_PROF_LOAD;
aa_get_loaddata(udata);
/* released below */
error = aa_unpack(udata, &lh, &ns_name);
if (error)
goto out;
/* ensure that profiles are all for the same ns
* TODO: update locking to remove this constaint. All profiles in
* the load set must succeed as a set or the load will
* fail. Sort ent list and take ns locks in hierarchy order
*/
count = 0;
list_for_each_entry(ent, &lh, list) {
if (ns_name) {
if (ent->ns_name &&
strcmp(ent->ns_name, ns_name) != 0) {
info = "policy load has mixed namespaces";
error = -EACCES;
goto fail;
}
} else if (ent->ns_name) {
if (count) {
info = "policy load has mixed namespaces";
error = -EACCES;
goto fail;
}
ns_name = ent->ns_name;
} else
count++;
}
if (ns_name) {
ns = aa_prepare_ns(policy_ns ? policy_ns : labels_ns(label),
ns_name);
if (IS_ERR(ns)) {
op = OP_PROF_LOAD;
info = "failed to prepare namespace";
error = PTR_ERR(ns);
ns = NULL;
ent = NULL;
goto fail;
}
} else
ns = aa_get_ns(policy_ns ? policy_ns : labels_ns(label));
mutex_lock_nested(&ns->lock, ns->level);
/* check for duplicate rawdata blobs: space and file dedup */
list_for_each_entry(rawdata_ent, &ns->rawdata_list, list) {
if (aa_rawdata_eq(rawdata_ent, udata)) {
struct aa_loaddata *tmp;
tmp = __aa_get_loaddata(rawdata_ent);
/* check we didn't fail the race */
if (tmp) {
aa_put_loaddata(udata);
udata = tmp;
break;
}
}
}
/* setup parent and ns info */
list_for_each_entry(ent, &lh, list) {
struct aa_policy *policy;
ent->new->rawdata = aa_get_loaddata(udata);
error = __lookup_replace(ns, ent->new->base.hname,
!(mask & AA_MAY_REPLACE_POLICY),
&ent->old, &info);
if (error)
goto fail_lock;
if (ent->new->rename) {
error = __lookup_replace(ns, ent->new->rename,
!(mask & AA_MAY_REPLACE_POLICY),
&ent->rename, &info);
if (error)
goto fail_lock;
}
/* released when @new is freed */
ent->new->ns = aa_get_ns(ns);
if (ent->old || ent->rename)
continue;
/* no ref on policy only use inside lock */
policy = __lookup_parent(ns, ent->new->base.hname);
if (!policy) {
struct aa_profile *p;
p = __list_lookup_parent(&lh, ent->new);
if (!p) {
error = -ENOENT;
info = "parent does not exist";
goto fail_lock;
}
rcu_assign_pointer(ent->new->parent, aa_get_profile(p));
} else if (policy != &ns->base) {
/* released on profile replacement or free_profile */
struct aa_profile *p = (struct aa_profile *) policy;
rcu_assign_pointer(ent->new->parent, aa_get_profile(p));
}
}
/* create new fs entries for introspection if needed */
if (!udata->dents[AAFS_LOADDATA_DIR]) {
error = __aa_fs_create_rawdata(ns, udata);
if (error) {
info = "failed to create raw_data dir and files";
ent = NULL;
goto fail_lock;
}
}
list_for_each_entry(ent, &lh, list) {
if (!ent->old) {
struct dentry *parent;
if (rcu_access_pointer(ent->new->parent)) {
struct aa_profile *p;
p = aa_deref_parent(ent->new);
parent = prof_child_dir(p);
} else
parent = ns_subprofs_dir(ent->new->ns);
error = __aafs_profile_mkdir(ent->new, parent);
}
if (error) {
info = "failed to create";
goto fail_lock;
}
}
/* Done with checks that may fail - do actual replacement */
__aa_bump_ns_revision(ns);
__aa_loaddata_update(udata, ns->revision);
list_for_each_entry_safe(ent, tmp, &lh, list) {
list_del_init(&ent->list);
op = (!ent->old && !ent->rename) ? OP_PROF_LOAD : OP_PROF_REPL;
if (ent->old && ent->old->rawdata == ent->new->rawdata) {
/* dedup actual profile replacement */
audit_policy(label, op, ns_name, ent->new->base.hname,
"same as current profile, skipping",
error);
/* break refcount cycle with proxy. */
aa_put_proxy(ent->new->label.proxy);
ent->new->label.proxy = NULL;
goto skip;
}
/*
* TODO: finer dedup based on profile range in data. Load set
* can differ but profile may remain unchanged
*/
audit_policy(label, op, ns_name, ent->new->base.hname, NULL,
error);
if (ent->old) {
share_name(ent->old, ent->new);
__replace_profile(ent->old, ent->new);
} else {
struct list_head *lh;
if (rcu_access_pointer(ent->new->parent)) {
struct aa_profile *parent;
parent = update_to_newest_parent(ent->new);
lh = &parent->base.profiles;
} else
lh = &ns->base.profiles;
__add_profile(lh, ent->new);
}
skip:
aa_load_ent_free(ent);
}
__aa_labelset_update_subtree(ns);
mutex_unlock(&ns->lock);
out:
aa_put_ns(ns);
aa_put_loaddata(udata);
if (error)
return error;
return udata->size;
fail_lock:
mutex_unlock(&ns->lock);
/* audit cause of failure */
op = (ent && !ent->old) ? OP_PROF_LOAD : OP_PROF_REPL;
fail:
audit_policy(label, op, ns_name, ent ? ent->new->base.hname : NULL,
info, error);
/* audit status that rest of profiles in the atomic set failed too */
info = "valid profile in failed atomic policy load";
list_for_each_entry(tmp, &lh, list) {
if (tmp == ent) {
info = "unchecked profile in failed atomic policy load";
/* skip entry that caused failure */
continue;
}
op = (!tmp->old) ? OP_PROF_LOAD : OP_PROF_REPL;
audit_policy(label, op, ns_name, tmp->new->base.hname, info,
error);
}
list_for_each_entry_safe(ent, tmp, &lh, list) {
list_del_init(&ent->list);
aa_load_ent_free(ent);
}
goto out;
}
/**
* aa_remove_profiles - remove profile(s) from the system
* @policy_ns: namespace the remove is being done from
* @subj: label attempting to remove policy
* @fqname: name of the profile or namespace to remove (NOT NULL)
* @size: size of the name
*
* Remove a profile or sub namespace from the current namespace, so that
* they can not be found anymore and mark them as replaced by unconfined
*
* NOTE: removing confinement does not restore rlimits to preconfinement values
*
* Returns: size of data consume else error code if fails
*/
ssize_t aa_remove_profiles(struct aa_ns *policy_ns, struct aa_label *subj,
char *fqname, size_t size)
{
struct aa_ns *ns = NULL;
struct aa_profile *profile = NULL;
const char *name = fqname, *info = NULL;
const char *ns_name = NULL;
ssize_t error = 0;
if (*fqname == 0) {
info = "no profile specified";
error = -ENOENT;
goto fail;
}
if (fqname[0] == ':') {
size_t ns_len;
name = aa_splitn_fqname(fqname, size, &ns_name, &ns_len);
/* released below */
ns = aa_lookupn_ns(policy_ns ? policy_ns : labels_ns(subj),
ns_name, ns_len);
if (!ns) {
info = "namespace does not exist";
error = -ENOENT;
goto fail;
}
} else
/* released below */
ns = aa_get_ns(policy_ns ? policy_ns : labels_ns(subj));
if (!name) {
/* remove namespace - can only happen if fqname[0] == ':' */
mutex_lock_nested(&ns->parent->lock, ns->level);
__aa_remove_ns(ns);
__aa_bump_ns_revision(ns);
mutex_unlock(&ns->parent->lock);
} else {
/* remove profile */
mutex_lock_nested(&ns->lock, ns->level);
profile = aa_get_profile(__lookup_profile(&ns->base, name));
if (!profile) {
error = -ENOENT;
info = "profile does not exist";
goto fail_ns_lock;
}
name = profile->base.hname;
__remove_profile(profile);
__aa_labelset_update_subtree(ns);
__aa_bump_ns_revision(ns);
mutex_unlock(&ns->lock);
}
/* don't fail removal if audit fails */
(void) audit_policy(subj, OP_PROF_RM, ns_name, name, info,
error);
aa_put_ns(ns);
aa_put_profile(profile);
return size;
fail_ns_lock:
mutex_unlock(&ns->lock);
aa_put_ns(ns);
fail:
(void) audit_policy(subj, OP_PROF_RM, ns_name, name, info,
error);
return error;
}
--
AppArmor mailing list
[email protected]
Modify settings or unsubscribe at:
https://lists.ubuntu.com/mailman/listinfo/apparmor