apparmor/parser/parser_regex.c

1077 lines
30 KiB
C
Raw Normal View History

/*
2007-04-11 08:12:51 +00:00
* Copyright (c) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007
* NOVELL (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 <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <linux/limits.h>
parser: Add make variable to build against local or system libapparmor [v3] By default, statically link against the in-tree libapparmor. If the in-tree libapparmor is not yet built, print a helpful error message. To build against the system libapparmor, the USE_SYSTEM make variable can be set on the command line like so: $ make USE_SYSTEM=1 This patch also fixes issues around the inclusion of the apparmor.h header. Previously, the in-tree apparmor.h was always being included even if the parser was being linked against the system libapparmor. It modifies the apparmor.h include path based on the previous patch separating them out in the libapparmor source. This was needed because header file name collisions were already occurring. For source files needing to include apparmor.h, the make targets were also updated to depend on the local apparmor.h when building against the in-tree libapparmor. When building against the system libapparmor, the variable used in the dependency list is empty. Likewise, a libapparmor.a dependency is added to the apparmor_parser target when building against the in-tree apparmor. Patch history: v1: from Tyler Hicks <tyhicks@canonical.com> - initial version v2: revert to altering the include search path rather than including the apparmor.h header directly via cpp arguments, alter the include statements to <sys/apparmor.h> which will work against either in-tree or (default) system paths. v3: convert controlling variable to USE_SYSTEM from SYSTEM_LIBAPPARMOR to unify between the parser and the regression tests. Signed-off-by: Tyler Hicks <tyhicks@canonical.com> Signed-off-by: Steve Beattie <steve@nxnw.org>
2014-01-06 14:46:10 -08:00
#include <sys/apparmor.h>
#include <iomanip>
#include <string>
#include <sstream>
/* #define DEBUG */
#include "lib.h"
#include "parser.h"
#include "profile.h"
2007-02-27 02:29:16 +00:00
#include "libapparmor_re/apparmor_re.h"
#include "libapparmor_re/aare_rules.h"
Add mount rules Add the ability to control mounting and unmounting The basic form of the rules are. [audit] [deny] mount [conds]* [device] [ -> [conds] path], [audit] [deny] remount [conds]* [path], [audit] [deny] umount [conds]* [path], [audit] [deny] pivotroot [oldroot=<value>] <path> -> <profile> remount is just a short cut for mount options=remount where [conds] can be fstype=<expr> options=<expr> conds follow the extended conditional syntax of allowing either: * a single value after the equals, which has the same character range as regular IDS (ie most anything but it can't be terminated with a , (comma) and if spaces or other characters are needed it can be quoted eg. options=foo options = foo options="foo bar" * a list of values after the equals, the list of values is enclosed within parenthesis () and its has a slightly reduced character set but again elements can be quoted. the separation between elements is whitespace and commas. eg. options=(foo bar) options=(foo, bar) options=(foo , bar) options=(foo,bar) The rules are flexible and follow a similar pattern as network, capability, etc. mount, # allow all mounts, but not umount or pivotroot mount fstype=procfs, # allow mounting procfs anywhere mount options=(bind, ro) /foo -> /bar, # readonly bind mount mount /dev/sda -> /mnt, mount /dev/sd** -> /mnt/**, mount fstype=overlayfs options=(rw,upperdir=/tmp/upper/,lowerdir=/) overlay -> /mnt/ umount, umount /m*, Currently variables and regexs are are supported on the device and mount point. ie. mount <devince> -> <mount point>, Regexes are supported in fstype and options. The options have a further caveat that regexs only work if the option is fs specific option. eg. options=(upperdir=/tmp/*,lowerdir=/) regex's will not currently work against the standard options like ro, rw nosuid Conditionals (fstype) can only be applied to the device (source) at this time and will be disregarded in situations where the mount is manipulating an existing mount (bind, remount). Options can be specified multiple times mount option=rw option=(nosuid,upperdir=/foo), and will be combined together into a single set of values The ordering of the standard mount options (rw,ro, ...) does not matter but the ordering of fs specific options does. Specifying that the value of a particular option does not matter can be acheived by providing both the positive and negative forms of and option option=(rw,ro) options=(suid,nosuid) For the fs specific options specifying that a particular value does not matter is achieve using a regex with alternations. Improvements to the syntax and order restrictions are planned for the future. Signed-off-by: John Johansen <john.johansen@canonical.com>
2012-02-24 04:19:38 -08:00
#include "policydb.h"
#include "rule.h"
enum error_type {
e_no_error,
e_parse_error,
};
/* Filters out multiple slashes (except if the first two are slashes,
* that's a distinct namespace in linux) and trailing slashes.
* NOTE: modifies in place the contents of the path argument */
void filter_slashes(char *path)
{
char *sptr, *dptr;
BOOL seen_slash = 0;
if (!path || (strlen(path) < 2))
return;
sptr = dptr = path;
/* special case for linux // namespace */
if (sptr[0] == '/' && sptr[1] == '/' && sptr[2] != '/') {
sptr += 2;
dptr += 2;
}
while (*sptr) {
if (*sptr == '/') {
if (seen_slash) {
++sptr;
} else {
*dptr++ = *sptr++;
seen_slash = TRUE;
}
} else {
seen_slash = 0;
if (dptr < sptr) {
*dptr++ = *sptr++;
} else {
dptr++;
sptr++;
}
}
}
*dptr = 0;
}
static error_type append_glob(std::string &pcre, int glob,
const char *default_glob, const char *null_glob)
{
switch (glob) {
case glob_default:
pcre.append(default_glob);
break;
case glob_null:
pcre.append(null_glob);
break;
default:
PERROR(_("%s: Invalid glob type %d\n"), progname, glob);
return e_parse_error;
break;
}
return e_no_error;
}
/* converts the apparmor regex in aare and appends pcre regex output
* to pcre string */
pattern_t convert_aaregex_to_pcre(const char *aare, int anchor, int glob,
std::string& pcre, int *first_re_pos)
{
#define update_re_pos(X) if (!(*first_re_pos)) { *first_re_pos = (X); }
#define MAX_ALT_DEPTH 50
*first_re_pos = 0;
int ret = TRUE;
/* flag to indicate input error */
enum error_type error;
const char *sptr;
pattern_t ptype;
BOOL bEscape = 0; /* flag to indicate escape */
int ingrouping = 0; /* flag to indicate {} context */
int incharclass = 0; /* flag to indicate [ ] context */
int grouping_count[MAX_ALT_DEPTH] = {0};
error = e_no_error;
ptype = ePatternBasic; /* assume no regex */
2007-02-27 02:29:16 +00:00
sptr = aare;
This adds a basic debug dump for the conversion of each rule in a profile to its expression tree. It is limited in that it doesn't currently handle the permissions of a rule. conversion output presents an aare -> prce conversion followed by 1 or more expression tree rules, governed by what the rule does. eg. aare: /** -> /[^/\x00][^\x00]* rule: /[^/\x00][^\x00]* -> /[^\0000/]([^\0000])* eg. echo "/foo { /** rwlkmix, } " | ./apparmor_parser -QT -D rule-exprs -D expr-tree aare: /foo -> /foo aare: /** -> /[^/\x00][^\x00]* rule: /[^/\x00][^\x00]* -> /[^\0000/]([^\0000])* rule: /[^/\x00][^\x00]*\x00/[^/].* -> /[^\0000/]([^\0000])*\0000/[^/](.)* DFA: Expression Tree (/[^\0000/]([^\0000])*(((((((((((((<513>|<2>)|<4>)|<8>)|<16>)|<32>)|<64>)|<8404992>)|<32768>)|<65536>)|<131072>)|<262144>)|<524288>)|<1048576>)|/[^\0000/]([^\0000])*\0000/[^/](.)*((<16>|<32>)|<262144>)) This simple example shows many things 1. The profile name under goes pcre conversion. But since no regular expressions where found it doesn't generate any expr rules 2. /** is converted into the pcre expression /[^\0000/]([^\0000])* 3. The pcre expression /[^\0000/]([^\0000])* is converted into two rules that are then converted into expression trees. The reason for this can not be seen by the output as this is actually triggered by permissions separation for the rule. In this case the link permission is separated into what is shown as the second rule: statement. 4. DFA: Expression Tree dump shows how these rules are combined together You will notice that the rule conversion statement is fairly redundant currently as it just show pcre to expression tree pcre. This will change when direct aare parsing occurs, but currently serves to verify the pcre conversion step. It is not the prettiest patch, as its touching some ugly code that is schedule to be cleaned up/replaced. eg. convert_aaregex_to_pcre is going to replaced with native parse conversion from an aare straight to the expression tree, and dfaflag passing will become part of the rule set.
2010-07-23 13:29:35 +02:00
if (dfaflags & DFA_DUMP_RULE_EXPR)
fprintf(stderr, "aare: %s -> ", aare);
2007-02-27 02:29:16 +00:00
if (anchor)
/* anchor beginning of regular expression */
pcre.append("^");
while (error == e_no_error && *sptr) {
switch (*sptr) {
case '\\':
/* concurrent escapes are allowed now and
* output as two consecutive escapes so that
* pcre won't interpret them
* \\\{...\\\} will be emitted as \\\{...\\\}
* for pcre matching. For string matching
* and globbing only one escape is output
* this is done by stripping later
*/
if (bEscape) {
pcre.append("\\\\");
} else {
bEscape = TRUE;
++sptr;
continue; /*skip turning bEscape off */
} /* bEscape */
2007-02-01 20:18:50 +00:00
break;
case '*':
if (bEscape) {
/* '*' is a PCRE special character */
/* We store an escaped *, in case we
* end up using this regex buffer (i.e another
* non-escaped regex follows)
*/
pcre.append("\\*");
} else {
if ((pcre.length() > 0) && pcre[pcre.length() - 1] == '/') {
#if 0
// handle comment containing use
// of C comment characters
// /* /*/ and /** to describe paths
//
// modify what is emitted for * and **
// when used as the only path
// component
// ex.
// /* /*/ /**/ /**
// this prevents these expressions
// from matching directories or
// invalid paths
// in these case * and ** must
// match at least 1 character to
// get a valid path element.
// ex.
// /foo/* -> should not match /foo/
// /foo/*bar -> should match /foo/bar
// /*/foo -> should not match //foo
#endif
const char *s = sptr;
while (*s == '*')
s++;
if (*s == '/' || !*s)
error = append_glob(pcre, glob, "[^/\\x00]", "[^/]");
}
if (*(sptr + 1) == '*') {
/* is this the first regex form we
* have seen and also the end of
* pattern? If so, we can use
* optimised tail globbing rather
* than full regex.
*/
update_re_pos(sptr - aare);
if (*(sptr + 2) == '\0' &&
ptype == ePatternBasic) {
ptype = ePatternTailGlob;
} else {
ptype = ePatternRegex;
}
error = append_glob(pcre, glob, "[^\\x00]*", ".*");
sptr++;
} else {
update_re_pos(sptr - aare);
ptype = ePatternRegex;
error = append_glob(pcre, glob, "[^/\\x00]*", "[^/]*");
} /* *(sptr+1) == '*' */
} /* bEscape */
break;
case '?':
if (bEscape) {
/* ? is not a PCRE regex character
* so no need to escape, just skip
* transform
*/
pcre.append(1, *sptr);
} else {
update_re_pos(sptr - aare);
ptype = ePatternRegex;
pcre.append("[^/\\x00]");
}
break;
case '[':
if (bEscape) {
/* [ is a PCRE special character */
pcre.append("\\[");
} else {
update_re_pos(sptr - aare);
incharclass = 1;
ptype = ePatternRegex;
pcre.append(1, *sptr);
}
break;
case ']':
if (bEscape) {
/* ] is a PCRE special character */
pcre.append("\\]");
} else {
if (incharclass == 0) {
error = e_parse_error;
PERROR(_("%s: Regex grouping error: Invalid close ], no matching open [ detected\n"), progname);
}
incharclass = 0;
pcre.append(1, *sptr);
}
break;
case '{':
if (bEscape) {
/* { is a PCRE special character */
pcre.append("\\{");
} else {
if (incharclass) {
/* don't expand inside [] */
pcre.append("{");
2008-11-07 01:31:19 +00:00
} else {
update_re_pos(sptr - aare);
ingrouping++;
if (ingrouping >= MAX_ALT_DEPTH) {
error = e_parse_error;
PERROR(_("%s: Regex grouping error: Exceeded maximum nesting of {}\n"), progname);
} else {
grouping_count[ingrouping] = 0;
ptype = ePatternRegex;
pcre.append("(");
}
} /* incharclass */
}
break;
case '}':
if (bEscape) {
/* { is a PCRE special character */
pcre.append("\\}");
} else {
if (incharclass) {
/* don't expand inside [] */
pcre.append("}");
} else {
if (grouping_count[ingrouping] == 0) {
error = e_parse_error;
PERROR(_("%s: Regex grouping error: Invalid number of items between {}\n"), progname);
}
ingrouping--;
if (ingrouping < 0) {
error = e_parse_error;
PERROR(_("%s: Regex grouping error: Invalid close }, no matching open { detected\n"), progname);
ingrouping = 0;
}
pcre.append(")");
} /* incharclass */
} /* bEscape */
break;
case ',':
if (bEscape) {
if (incharclass) {
/* escape inside char class is a
* valid matching char for '\'
*/
pcre.append("\\,");
} else {
/* ',' is not a PCRE regex character
* so no need to escape, just skip
* transform
*/
pcre.append(1, *sptr);
}
} else {
if (ingrouping && !incharclass) {
grouping_count[ingrouping]++;
pcre.append("|");
} else {
pcre.append(1, *sptr);
}
}
break;
/* these are special outside of character
* classes but not in them */
case '^':
case '$':
if (incharclass) {
pcre.append(1, *sptr);
} else {
pcre.append("\\");
pcre.append(1, *sptr);
}
break;
/*
* Not a subdomain regex, but needs to be
* escaped as it is a pcre metacharacter which
* we don't want to support. We always escape
* these, so no need to check bEscape
*/
case '.':
case '+':
case '|':
case '(':
case ')':
pcre.append("\\");
// fall through to default
default:
if (bEscape) {
const char *pos = sptr;
int c;
if ((c = str_escseq(&pos, "")) != -1) {
/* valid escape we don't want to
* interpret here */
pcre.append("\\");
pcre.append(sptr, pos - sptr);
sptr += (pos - sptr) - 1;
} else {
/* quoting mark used for something that
* does not need to be quoted; give a
* warning */
pwarn("Character %c was quoted "
"unnecessarily, dropped preceding"
" quote ('\\') character\n",
*sptr);
pcre.append(1, *sptr);
}
} else
pcre.append(1, *sptr);
break;
} /* switch (*sptr) */
bEscape = FALSE;
++sptr;
} /* while error == e_no_error && *sptr) */
if (ingrouping > 0 || incharclass) {
error = e_parse_error;
PERROR(_("%s: Regex grouping error: Unclosed grouping or character class, expecting close }\n"),
progname);
}
if ((error == e_no_error) && bEscape) {
/* trailing backslash quote */
error = e_parse_error;
PERROR(_("%s: Regex error: trailing '\\' escape character\n"),
progname);
}
/* anchor end and terminate pattern string */
2007-02-27 02:29:16 +00:00
if ((error == e_no_error) && anchor) {
pcre.append("$");
}
/* check error again, as above STORE may have set it */
if (error != e_no_error) {
PERROR(_("%s: Unable to parse input line '%s'\n"),
2007-02-27 02:29:16 +00:00
progname, aare);
ret = FALSE;
goto out;
}
2007-02-27 02:29:16 +00:00
out:
if (ret == FALSE)
ptype = ePatternInvalid;
This adds a basic debug dump for the conversion of each rule in a profile to its expression tree. It is limited in that it doesn't currently handle the permissions of a rule. conversion output presents an aare -> prce conversion followed by 1 or more expression tree rules, governed by what the rule does. eg. aare: /** -> /[^/\x00][^\x00]* rule: /[^/\x00][^\x00]* -> /[^\0000/]([^\0000])* eg. echo "/foo { /** rwlkmix, } " | ./apparmor_parser -QT -D rule-exprs -D expr-tree aare: /foo -> /foo aare: /** -> /[^/\x00][^\x00]* rule: /[^/\x00][^\x00]* -> /[^\0000/]([^\0000])* rule: /[^/\x00][^\x00]*\x00/[^/].* -> /[^\0000/]([^\0000])*\0000/[^/](.)* DFA: Expression Tree (/[^\0000/]([^\0000])*(((((((((((((<513>|<2>)|<4>)|<8>)|<16>)|<32>)|<64>)|<8404992>)|<32768>)|<65536>)|<131072>)|<262144>)|<524288>)|<1048576>)|/[^\0000/]([^\0000])*\0000/[^/](.)*((<16>|<32>)|<262144>)) This simple example shows many things 1. The profile name under goes pcre conversion. But since no regular expressions where found it doesn't generate any expr rules 2. /** is converted into the pcre expression /[^\0000/]([^\0000])* 3. The pcre expression /[^\0000/]([^\0000])* is converted into two rules that are then converted into expression trees. The reason for this can not be seen by the output as this is actually triggered by permissions separation for the rule. In this case the link permission is separated into what is shown as the second rule: statement. 4. DFA: Expression Tree dump shows how these rules are combined together You will notice that the rule conversion statement is fairly redundant currently as it just show pcre to expression tree pcre. This will change when direct aare parsing occurs, but currently serves to verify the pcre conversion step. It is not the prettiest patch, as its touching some ugly code that is schedule to be cleaned up/replaced. eg. convert_aaregex_to_pcre is going to replaced with native parse conversion from an aare straight to the expression tree, and dfaflag passing will become part of the rule set.
2010-07-23 13:29:35 +02:00
if (dfaflags & DFA_DUMP_RULE_EXPR)
fprintf(stderr, "%s\n", pcre.c_str());
This adds a basic debug dump for the conversion of each rule in a profile to its expression tree. It is limited in that it doesn't currently handle the permissions of a rule. conversion output presents an aare -> prce conversion followed by 1 or more expression tree rules, governed by what the rule does. eg. aare: /** -> /[^/\x00][^\x00]* rule: /[^/\x00][^\x00]* -> /[^\0000/]([^\0000])* eg. echo "/foo { /** rwlkmix, } " | ./apparmor_parser -QT -D rule-exprs -D expr-tree aare: /foo -> /foo aare: /** -> /[^/\x00][^\x00]* rule: /[^/\x00][^\x00]* -> /[^\0000/]([^\0000])* rule: /[^/\x00][^\x00]*\x00/[^/].* -> /[^\0000/]([^\0000])*\0000/[^/](.)* DFA: Expression Tree (/[^\0000/]([^\0000])*(((((((((((((<513>|<2>)|<4>)|<8>)|<16>)|<32>)|<64>)|<8404992>)|<32768>)|<65536>)|<131072>)|<262144>)|<524288>)|<1048576>)|/[^\0000/]([^\0000])*\0000/[^/](.)*((<16>|<32>)|<262144>)) This simple example shows many things 1. The profile name under goes pcre conversion. But since no regular expressions where found it doesn't generate any expr rules 2. /** is converted into the pcre expression /[^\0000/]([^\0000])* 3. The pcre expression /[^\0000/]([^\0000])* is converted into two rules that are then converted into expression trees. The reason for this can not be seen by the output as this is actually triggered by permissions separation for the rule. In this case the link permission is separated into what is shown as the second rule: statement. 4. DFA: Expression Tree dump shows how these rules are combined together You will notice that the rule conversion statement is fairly redundant currently as it just show pcre to expression tree pcre. This will change when direct aare parsing occurs, but currently serves to verify the pcre conversion step. It is not the prettiest patch, as its touching some ugly code that is schedule to be cleaned up/replaced. eg. convert_aaregex_to_pcre is going to replaced with native parse conversion from an aare straight to the expression tree, and dfaflag passing will become part of the rule set.
2010-07-23 13:29:35 +02:00
2007-02-27 02:29:16 +00:00
return ptype;
}
static const char *local_name(const char *name)
{
const char *t;
for (t = strstr(name, "//") ; t ; t = strstr(name, "//"))
name = t + 2;
return name;
}
static int process_profile_name_xmatch(Profile *prof)
{
std::string tbuf;
pattern_t ptype;
const char *name;
/* don't filter_slashes for profile names */
if (prof->attachment)
name = prof->attachment;
else
name = local_name(prof->name);
ptype = convert_aaregex_to_pcre(name, 0, glob_default, tbuf,
&prof->xmatch_len);
if (ptype == ePatternBasic)
prof->xmatch_len = strlen(name);
if (ptype == ePatternInvalid) {
PERROR(_("%s: Invalid profile name '%s' - bad regular expression\n"), progname, name);
return FALSE;
} else if (ptype == ePatternBasic && !(prof->altnames || prof->attachment)) {
/* no regex so do not set xmatch */
prof->xmatch = NULL;
prof->xmatch_len = 0;
prof->xmatch_size = 0;
} else {
/* build a dfa */
aare_rules *rules = new aare_rules();
if (!rules)
return FALSE;
if (!rules->add_rule(tbuf.c_str(), 0, AA_MAY_EXEC, 0, dfaflags)) {
delete rules;
return FALSE;
}
if (prof->altnames) {
struct alt_name *alt;
list_for_each(prof->altnames, alt) {
int len;
tbuf.clear();
ptype = convert_aaregex_to_pcre(alt->name, 0,
glob_default,
tbuf, &len);
if (ptype == ePatternBasic)
len = strlen(alt->name);
if (len < prof->xmatch_len)
prof->xmatch_len = len;
if (!rules->add_rule(tbuf.c_str(), 0, AA_MAY_EXEC, 0, dfaflags)) {
delete rules;
return FALSE;
}
}
}
prof->xmatch = rules->create_dfa(&prof->xmatch_size, dfaflags);
delete rules;
if (!prof->xmatch)
return FALSE;
}
return TRUE;
}
static int warn_change_profile = 1;
static bool is_change_profile_mode(int mode)
{
/**
* A change_profile entry will have the AA_CHANGE_PROFILE bit set.
* It could also have the (AA_EXEC_BITS | ALL_AA_EXEC_UNSAFE) bits
* set by the frontend parser. That means that it is incorrect to
* identify change_profile modes using a test like this:
*
* (mode & ~AA_CHANGE_PROFILE)
*
* The above test would incorrectly return true on a
* change_profile mode that has the
* (AA_EXEC_BITS | ALL_AA_EXEC_UNSAFE) bits set.
*/
return mode & AA_CHANGE_PROFILE;
}
static int process_dfa_entry(aare_rules *dfarules, struct cod_entry *entry)
2007-02-27 02:29:16 +00:00
{
std::string tbuf;
2007-02-27 02:29:16 +00:00
pattern_t ptype;
int pos;
2007-02-27 02:29:16 +00:00
if (!entry) /* shouldn't happen */
return TRUE;
if (!is_change_profile_mode(entry->mode))
filter_slashes(entry->name);
ptype = convert_aaregex_to_pcre(entry->name, 0, glob_default, tbuf, &pos);
2007-02-27 02:29:16 +00:00
if (ptype == ePatternInvalid)
return FALSE;
entry->pattern_type = ptype;
/* ix implies m but the apparmor module does not add m bit to
* dfa states like it does for pcre
*/
2008-04-16 04:44:21 +00:00
if ((entry->mode >> AA_OTHER_SHIFT) & AA_EXEC_INHERIT)
entry->mode |= AA_OLD_EXEC_MMAP << AA_OTHER_SHIFT;
2008-04-16 04:44:21 +00:00
if ((entry->mode >> AA_USER_SHIFT) & AA_EXEC_INHERIT)
entry->mode |= AA_OLD_EXEC_MMAP << AA_USER_SHIFT;
2007-11-16 09:35:57 +00:00
Add Audit control to AppArmor through, the use of audit and deny key words. Deny is also used to subtract permissions from the profiles permission set. the audit key word can be prepended to any file, network, or capability rule, to force a selective audit when that rule is matched. Audit permissions accumulate just like standard permissions. eg. audit /bin/foo rw, will force an audit message when the file /bin/foo is opened for read or write. audit /etc/shadow w, /etc/shadow r, will force an audit message when /etc/shadow is opened for writing. The audit message is per permission bit so only opening the file for read access will not, force an audit message. audit can also be used in block form instead of prepending audit to every rule. audit { /bin/foo rw, /etc/shadow w, } /etc/shadow r, # don't audit r access to /etc/shadow the deny key word can be prepended to file, network and capability rules, to result in a denial of permissions when matching that rule. The deny rule specifically does 3 things - it gives AppArmor the ability to remember what has been denied so that the tools don't prompt for what has been denied in previous profiling sessions. - it subtracts globally from the allowed permissions. Deny permissions accumulate in the the deny set just as allow permissions accumulate then, the deny set is subtracted from the allow set. - it quiets known rejects. The default audit behavior of deny rules is to quiet known rejects so that audit logs are not flooded with already known rejects. To have known rejects logged prepend the audit keyword to the deny rule. Deny rules do not have a block form. eg. deny /foo/bar rw, audit deny /etc/shadow w, audit { deny owner /blah w, deny other /foo w, deny /etc/shadow w, }
2008-03-13 17:39:03 +00:00
/* the link bit on the first pair entry should not get masked
* out by a deny rule, as both pieces of the link pair must
* match. audit info for the link is carried on the second
* entry of the pair
*
* So if a deny rule only record it if there are permissions other
* than link in the entry.
* TODO: split link and change_profile entries earlier
Add Audit control to AppArmor through, the use of audit and deny key words. Deny is also used to subtract permissions from the profiles permission set. the audit key word can be prepended to any file, network, or capability rule, to force a selective audit when that rule is matched. Audit permissions accumulate just like standard permissions. eg. audit /bin/foo rw, will force an audit message when the file /bin/foo is opened for read or write. audit /etc/shadow w, /etc/shadow r, will force an audit message when /etc/shadow is opened for writing. The audit message is per permission bit so only opening the file for read access will not, force an audit message. audit can also be used in block form instead of prepending audit to every rule. audit { /bin/foo rw, /etc/shadow w, } /etc/shadow r, # don't audit r access to /etc/shadow the deny key word can be prepended to file, network and capability rules, to result in a denial of permissions when matching that rule. The deny rule specifically does 3 things - it gives AppArmor the ability to remember what has been denied so that the tools don't prompt for what has been denied in previous profiling sessions. - it subtracts globally from the allowed permissions. Deny permissions accumulate in the the deny set just as allow permissions accumulate then, the deny set is subtracted from the allow set. - it quiets known rejects. The default audit behavior of deny rules is to quiet known rejects so that audit logs are not flooded with already known rejects. To have known rejects logged prepend the audit keyword to the deny rule. Deny rules do not have a block form. eg. deny /foo/bar rw, audit deny /etc/shadow w, audit { deny owner /blah w, deny other /foo w, deny /etc/shadow w, }
2008-03-13 17:39:03 +00:00
*/
if (entry->deny) {
if ((entry->mode & ~AA_LINK_BITS) &&
!is_change_profile_mode(entry->mode) &&
!dfarules->add_rule(tbuf.c_str(), entry->deny,
entry->mode & ~(AA_LINK_BITS | AA_CHANGE_PROFILE),
entry->audit & ~(AA_LINK_BITS | AA_CHANGE_PROFILE),
dfaflags))
Add Audit control to AppArmor through, the use of audit and deny key words. Deny is also used to subtract permissions from the profiles permission set. the audit key word can be prepended to any file, network, or capability rule, to force a selective audit when that rule is matched. Audit permissions accumulate just like standard permissions. eg. audit /bin/foo rw, will force an audit message when the file /bin/foo is opened for read or write. audit /etc/shadow w, /etc/shadow r, will force an audit message when /etc/shadow is opened for writing. The audit message is per permission bit so only opening the file for read access will not, force an audit message. audit can also be used in block form instead of prepending audit to every rule. audit { /bin/foo rw, /etc/shadow w, } /etc/shadow r, # don't audit r access to /etc/shadow the deny key word can be prepended to file, network and capability rules, to result in a denial of permissions when matching that rule. The deny rule specifically does 3 things - it gives AppArmor the ability to remember what has been denied so that the tools don't prompt for what has been denied in previous profiling sessions. - it subtracts globally from the allowed permissions. Deny permissions accumulate in the the deny set just as allow permissions accumulate then, the deny set is subtracted from the allow set. - it quiets known rejects. The default audit behavior of deny rules is to quiet known rejects so that audit logs are not flooded with already known rejects. To have known rejects logged prepend the audit keyword to the deny rule. Deny rules do not have a block form. eg. deny /foo/bar rw, audit deny /etc/shadow w, audit { deny owner /blah w, deny other /foo w, deny /etc/shadow w, }
2008-03-13 17:39:03 +00:00
return FALSE;
} else if (!is_change_profile_mode(entry->mode)) {
if (!dfarules->add_rule(tbuf.c_str(), entry->deny, entry->mode,
entry->audit, dfaflags))
Add Audit control to AppArmor through, the use of audit and deny key words. Deny is also used to subtract permissions from the profiles permission set. the audit key word can be prepended to any file, network, or capability rule, to force a selective audit when that rule is matched. Audit permissions accumulate just like standard permissions. eg. audit /bin/foo rw, will force an audit message when the file /bin/foo is opened for read or write. audit /etc/shadow w, /etc/shadow r, will force an audit message when /etc/shadow is opened for writing. The audit message is per permission bit so only opening the file for read access will not, force an audit message. audit can also be used in block form instead of prepending audit to every rule. audit { /bin/foo rw, /etc/shadow w, } /etc/shadow r, # don't audit r access to /etc/shadow the deny key word can be prepended to file, network and capability rules, to result in a denial of permissions when matching that rule. The deny rule specifically does 3 things - it gives AppArmor the ability to remember what has been denied so that the tools don't prompt for what has been denied in previous profiling sessions. - it subtracts globally from the allowed permissions. Deny permissions accumulate in the the deny set just as allow permissions accumulate then, the deny set is subtracted from the allow set. - it quiets known rejects. The default audit behavior of deny rules is to quiet known rejects so that audit logs are not flooded with already known rejects. To have known rejects logged prepend the audit keyword to the deny rule. Deny rules do not have a block form. eg. deny /foo/bar rw, audit deny /etc/shadow w, audit { deny owner /blah w, deny other /foo w, deny /etc/shadow w, }
2008-03-13 17:39:03 +00:00
return FALSE;
}
2008-04-09 23:56:31 +00:00
2007-11-16 09:36:42 +00:00
if (entry->mode & (AA_LINK_BITS)) {
/* add the pair rule */
std::string lbuf;
2007-11-16 09:36:42 +00:00
int perms = AA_LINK_BITS & entry->mode;
const char *vec[2];
int pos;
vec[0] = tbuf.c_str();
if (entry->link_name) {
ptype = convert_aaregex_to_pcre(entry->link_name, 0, glob_default, lbuf, &pos);
if (ptype == ePatternInvalid)
return FALSE;
if (entry->subset)
perms |= LINK_TO_LINK_SUBSET(perms);
vec[1] = lbuf.c_str();
} else {
perms |= LINK_TO_LINK_SUBSET(perms);
vec[1] = "/[^/].*";
}
if (!dfarules->add_rule_vec(entry->deny, perms, entry->audit & AA_LINK_BITS, 2, vec, dfaflags))
2007-11-16 09:36:42 +00:00
return FALSE;
}
if (is_change_profile_mode(entry->mode)) {
const char *vec[3];
std::string lbuf, xbuf;
autofree char *ns = NULL;
autofree char *name = NULL;
int index = 1;
uint32_t onexec_perms = AA_ONEXEC;
if ((warnflags & WARN_RULE_DOWNGRADED) && entry->audit && warn_change_profile) {
/* don't have profile name here, so until this code
* gets refactored just throw out a generic warning
*/
fprintf(stderr, "Warning kernel does not support audit modifier for change_profile rule.\n");
warn_change_profile = 0;
}
if (entry->onexec) {
ptype = convert_aaregex_to_pcre(entry->onexec, 0, glob_default, xbuf, &pos);
if (ptype == ePatternInvalid)
return FALSE;
vec[0] = xbuf.c_str();
} else
/* allow change_profile for all execs */
vec[0] = "/[^/\\x00][^\\x00]*";
if (!kernel_supports_stacking) {
bool stack;
if (!parse_label(&stack, &ns, &name,
tbuf.c_str(), false)) {
return FALSE;
}
if (stack) {
fprintf(stderr,
_("The current kernel does not support stacking of named transitions: %s\n"),
tbuf.c_str());
return FALSE;
}
if (ns)
vec[index++] = ns;
vec[index++] = name;
} else {
vec[index++] = tbuf.c_str();
}
/* regular change_profile rule */
if (!dfarules->add_rule_vec(entry->deny,
AA_CHANGE_PROFILE | onexec_perms,
0, index - 1, &vec[1], dfaflags))
return FALSE;
/* onexec rules - both rules are needed for onexec */
if (!dfarules->add_rule_vec(entry->deny, onexec_perms,
0, 1, vec, dfaflags))
return FALSE;
/**
* pick up any exec bits, from the frontend parser, related to
* unsafe exec transitions
*/
onexec_perms |= (entry->mode & (AA_EXEC_BITS | ALL_AA_EXEC_UNSAFE));
if (!dfarules->add_rule_vec(entry->deny, onexec_perms,
0, index, vec, dfaflags))
return FALSE;
}
2007-11-16 09:36:42 +00:00
return TRUE;
2007-02-27 02:29:16 +00:00
}
int post_process_entries(Profile *prof)
{
int ret = TRUE;
struct cod_entry *entry;
list_for_each(prof->entries, entry) {
if (!process_dfa_entry(prof->dfa.rules, entry))
ret = FALSE;
}
return ret;
}
int process_profile_regex(Profile *prof)
{
2007-02-27 02:29:16 +00:00
int error = -1;
2008-11-07 01:31:19 +00:00
if (!process_profile_name_xmatch(prof))
goto out;
prof->dfa.rules = new aare_rules();
if (!prof->dfa.rules)
goto out;
if (!post_process_entries(prof))
2007-02-27 02:29:16 +00:00
goto out;
if (prof->dfa.rules->rule_count > 0) {
prof->dfa.dfa = prof->dfa.rules->create_dfa(&prof->dfa.size,
dfaflags);
delete prof->dfa.rules;
prof->dfa.rules = NULL;
if (!prof->dfa.dfa)
2007-02-27 02:29:16 +00:00
goto out;
/*
if (prof->dfa_size == 0) {
2007-02-27 02:29:16 +00:00
PERROR(_("profile %s: has merged rules (%s) with "
"multiple x modifiers\n"),
prof->name, (char *) prof->dfa);
free(prof->dfa);
prof->dfa = NULL;
2007-02-27 02:29:16 +00:00
goto out;
}
*/
}
2007-02-01 20:18:50 +00:00
2007-02-27 02:29:16 +00:00
error = 0;
out:
return error;
}
int build_list_val_expr(std::string& buffer, struct value_list *list)
Add mount rules Add the ability to control mounting and unmounting The basic form of the rules are. [audit] [deny] mount [conds]* [device] [ -> [conds] path], [audit] [deny] remount [conds]* [path], [audit] [deny] umount [conds]* [path], [audit] [deny] pivotroot [oldroot=<value>] <path> -> <profile> remount is just a short cut for mount options=remount where [conds] can be fstype=<expr> options=<expr> conds follow the extended conditional syntax of allowing either: * a single value after the equals, which has the same character range as regular IDS (ie most anything but it can't be terminated with a , (comma) and if spaces or other characters are needed it can be quoted eg. options=foo options = foo options="foo bar" * a list of values after the equals, the list of values is enclosed within parenthesis () and its has a slightly reduced character set but again elements can be quoted. the separation between elements is whitespace and commas. eg. options=(foo bar) options=(foo, bar) options=(foo , bar) options=(foo,bar) The rules are flexible and follow a similar pattern as network, capability, etc. mount, # allow all mounts, but not umount or pivotroot mount fstype=procfs, # allow mounting procfs anywhere mount options=(bind, ro) /foo -> /bar, # readonly bind mount mount /dev/sda -> /mnt, mount /dev/sd** -> /mnt/**, mount fstype=overlayfs options=(rw,upperdir=/tmp/upper/,lowerdir=/) overlay -> /mnt/ umount, umount /m*, Currently variables and regexs are are supported on the device and mount point. ie. mount <devince> -> <mount point>, Regexes are supported in fstype and options. The options have a further caveat that regexs only work if the option is fs specific option. eg. options=(upperdir=/tmp/*,lowerdir=/) regex's will not currently work against the standard options like ro, rw nosuid Conditionals (fstype) can only be applied to the device (source) at this time and will be disregarded in situations where the mount is manipulating an existing mount (bind, remount). Options can be specified multiple times mount option=rw option=(nosuid,upperdir=/foo), and will be combined together into a single set of values The ordering of the standard mount options (rw,ro, ...) does not matter but the ordering of fs specific options does. Specifying that the value of a particular option does not matter can be acheived by providing both the positive and negative forms of and option option=(rw,ro) options=(suid,nosuid) For the fs specific options specifying that a particular value does not matter is achieve using a regex with alternations. Improvements to the syntax and order restrictions are planned for the future. Signed-off-by: John Johansen <john.johansen@canonical.com>
2012-02-24 04:19:38 -08:00
{
struct value_list *ent;
pattern_t ptype;
int pos;
if (!list) {
buffer.append(default_match_pattern);
Add mount rules Add the ability to control mounting and unmounting The basic form of the rules are. [audit] [deny] mount [conds]* [device] [ -> [conds] path], [audit] [deny] remount [conds]* [path], [audit] [deny] umount [conds]* [path], [audit] [deny] pivotroot [oldroot=<value>] <path> -> <profile> remount is just a short cut for mount options=remount where [conds] can be fstype=<expr> options=<expr> conds follow the extended conditional syntax of allowing either: * a single value after the equals, which has the same character range as regular IDS (ie most anything but it can't be terminated with a , (comma) and if spaces or other characters are needed it can be quoted eg. options=foo options = foo options="foo bar" * a list of values after the equals, the list of values is enclosed within parenthesis () and its has a slightly reduced character set but again elements can be quoted. the separation between elements is whitespace and commas. eg. options=(foo bar) options=(foo, bar) options=(foo , bar) options=(foo,bar) The rules are flexible and follow a similar pattern as network, capability, etc. mount, # allow all mounts, but not umount or pivotroot mount fstype=procfs, # allow mounting procfs anywhere mount options=(bind, ro) /foo -> /bar, # readonly bind mount mount /dev/sda -> /mnt, mount /dev/sd** -> /mnt/**, mount fstype=overlayfs options=(rw,upperdir=/tmp/upper/,lowerdir=/) overlay -> /mnt/ umount, umount /m*, Currently variables and regexs are are supported on the device and mount point. ie. mount <devince> -> <mount point>, Regexes are supported in fstype and options. The options have a further caveat that regexs only work if the option is fs specific option. eg. options=(upperdir=/tmp/*,lowerdir=/) regex's will not currently work against the standard options like ro, rw nosuid Conditionals (fstype) can only be applied to the device (source) at this time and will be disregarded in situations where the mount is manipulating an existing mount (bind, remount). Options can be specified multiple times mount option=rw option=(nosuid,upperdir=/foo), and will be combined together into a single set of values The ordering of the standard mount options (rw,ro, ...) does not matter but the ordering of fs specific options does. Specifying that the value of a particular option does not matter can be acheived by providing both the positive and negative forms of and option option=(rw,ro) options=(suid,nosuid) For the fs specific options specifying that a particular value does not matter is achieve using a regex with alternations. Improvements to the syntax and order restrictions are planned for the future. Signed-off-by: John Johansen <john.johansen@canonical.com>
2012-02-24 04:19:38 -08:00
return TRUE;
}
buffer.append("(");
Add mount rules Add the ability to control mounting and unmounting The basic form of the rules are. [audit] [deny] mount [conds]* [device] [ -> [conds] path], [audit] [deny] remount [conds]* [path], [audit] [deny] umount [conds]* [path], [audit] [deny] pivotroot [oldroot=<value>] <path> -> <profile> remount is just a short cut for mount options=remount where [conds] can be fstype=<expr> options=<expr> conds follow the extended conditional syntax of allowing either: * a single value after the equals, which has the same character range as regular IDS (ie most anything but it can't be terminated with a , (comma) and if spaces or other characters are needed it can be quoted eg. options=foo options = foo options="foo bar" * a list of values after the equals, the list of values is enclosed within parenthesis () and its has a slightly reduced character set but again elements can be quoted. the separation between elements is whitespace and commas. eg. options=(foo bar) options=(foo, bar) options=(foo , bar) options=(foo,bar) The rules are flexible and follow a similar pattern as network, capability, etc. mount, # allow all mounts, but not umount or pivotroot mount fstype=procfs, # allow mounting procfs anywhere mount options=(bind, ro) /foo -> /bar, # readonly bind mount mount /dev/sda -> /mnt, mount /dev/sd** -> /mnt/**, mount fstype=overlayfs options=(rw,upperdir=/tmp/upper/,lowerdir=/) overlay -> /mnt/ umount, umount /m*, Currently variables and regexs are are supported on the device and mount point. ie. mount <devince> -> <mount point>, Regexes are supported in fstype and options. The options have a further caveat that regexs only work if the option is fs specific option. eg. options=(upperdir=/tmp/*,lowerdir=/) regex's will not currently work against the standard options like ro, rw nosuid Conditionals (fstype) can only be applied to the device (source) at this time and will be disregarded in situations where the mount is manipulating an existing mount (bind, remount). Options can be specified multiple times mount option=rw option=(nosuid,upperdir=/foo), and will be combined together into a single set of values The ordering of the standard mount options (rw,ro, ...) does not matter but the ordering of fs specific options does. Specifying that the value of a particular option does not matter can be acheived by providing both the positive and negative forms of and option option=(rw,ro) options=(suid,nosuid) For the fs specific options specifying that a particular value does not matter is achieve using a regex with alternations. Improvements to the syntax and order restrictions are planned for the future. Signed-off-by: John Johansen <john.johansen@canonical.com>
2012-02-24 04:19:38 -08:00
ptype = convert_aaregex_to_pcre(list->value, 0, glob_default, buffer, &pos);
Add mount rules Add the ability to control mounting and unmounting The basic form of the rules are. [audit] [deny] mount [conds]* [device] [ -> [conds] path], [audit] [deny] remount [conds]* [path], [audit] [deny] umount [conds]* [path], [audit] [deny] pivotroot [oldroot=<value>] <path> -> <profile> remount is just a short cut for mount options=remount where [conds] can be fstype=<expr> options=<expr> conds follow the extended conditional syntax of allowing either: * a single value after the equals, which has the same character range as regular IDS (ie most anything but it can't be terminated with a , (comma) and if spaces or other characters are needed it can be quoted eg. options=foo options = foo options="foo bar" * a list of values after the equals, the list of values is enclosed within parenthesis () and its has a slightly reduced character set but again elements can be quoted. the separation between elements is whitespace and commas. eg. options=(foo bar) options=(foo, bar) options=(foo , bar) options=(foo,bar) The rules are flexible and follow a similar pattern as network, capability, etc. mount, # allow all mounts, but not umount or pivotroot mount fstype=procfs, # allow mounting procfs anywhere mount options=(bind, ro) /foo -> /bar, # readonly bind mount mount /dev/sda -> /mnt, mount /dev/sd** -> /mnt/**, mount fstype=overlayfs options=(rw,upperdir=/tmp/upper/,lowerdir=/) overlay -> /mnt/ umount, umount /m*, Currently variables and regexs are are supported on the device and mount point. ie. mount <devince> -> <mount point>, Regexes are supported in fstype and options. The options have a further caveat that regexs only work if the option is fs specific option. eg. options=(upperdir=/tmp/*,lowerdir=/) regex's will not currently work against the standard options like ro, rw nosuid Conditionals (fstype) can only be applied to the device (source) at this time and will be disregarded in situations where the mount is manipulating an existing mount (bind, remount). Options can be specified multiple times mount option=rw option=(nosuid,upperdir=/foo), and will be combined together into a single set of values The ordering of the standard mount options (rw,ro, ...) does not matter but the ordering of fs specific options does. Specifying that the value of a particular option does not matter can be acheived by providing both the positive and negative forms of and option option=(rw,ro) options=(suid,nosuid) For the fs specific options specifying that a particular value does not matter is achieve using a regex with alternations. Improvements to the syntax and order restrictions are planned for the future. Signed-off-by: John Johansen <john.johansen@canonical.com>
2012-02-24 04:19:38 -08:00
if (ptype == ePatternInvalid)
goto fail;
list_for_each(list->next, ent) {
buffer.append("|");
ptype = convert_aaregex_to_pcre(ent->value, 0, glob_default, buffer, &pos);
Add mount rules Add the ability to control mounting and unmounting The basic form of the rules are. [audit] [deny] mount [conds]* [device] [ -> [conds] path], [audit] [deny] remount [conds]* [path], [audit] [deny] umount [conds]* [path], [audit] [deny] pivotroot [oldroot=<value>] <path> -> <profile> remount is just a short cut for mount options=remount where [conds] can be fstype=<expr> options=<expr> conds follow the extended conditional syntax of allowing either: * a single value after the equals, which has the same character range as regular IDS (ie most anything but it can't be terminated with a , (comma) and if spaces or other characters are needed it can be quoted eg. options=foo options = foo options="foo bar" * a list of values after the equals, the list of values is enclosed within parenthesis () and its has a slightly reduced character set but again elements can be quoted. the separation between elements is whitespace and commas. eg. options=(foo bar) options=(foo, bar) options=(foo , bar) options=(foo,bar) The rules are flexible and follow a similar pattern as network, capability, etc. mount, # allow all mounts, but not umount or pivotroot mount fstype=procfs, # allow mounting procfs anywhere mount options=(bind, ro) /foo -> /bar, # readonly bind mount mount /dev/sda -> /mnt, mount /dev/sd** -> /mnt/**, mount fstype=overlayfs options=(rw,upperdir=/tmp/upper/,lowerdir=/) overlay -> /mnt/ umount, umount /m*, Currently variables and regexs are are supported on the device and mount point. ie. mount <devince> -> <mount point>, Regexes are supported in fstype and options. The options have a further caveat that regexs only work if the option is fs specific option. eg. options=(upperdir=/tmp/*,lowerdir=/) regex's will not currently work against the standard options like ro, rw nosuid Conditionals (fstype) can only be applied to the device (source) at this time and will be disregarded in situations where the mount is manipulating an existing mount (bind, remount). Options can be specified multiple times mount option=rw option=(nosuid,upperdir=/foo), and will be combined together into a single set of values The ordering of the standard mount options (rw,ro, ...) does not matter but the ordering of fs specific options does. Specifying that the value of a particular option does not matter can be acheived by providing both the positive and negative forms of and option option=(rw,ro) options=(suid,nosuid) For the fs specific options specifying that a particular value does not matter is achieve using a regex with alternations. Improvements to the syntax and order restrictions are planned for the future. Signed-off-by: John Johansen <john.johansen@canonical.com>
2012-02-24 04:19:38 -08:00
if (ptype == ePatternInvalid)
goto fail;
}
buffer.append(")");
Add mount rules Add the ability to control mounting and unmounting The basic form of the rules are. [audit] [deny] mount [conds]* [device] [ -> [conds] path], [audit] [deny] remount [conds]* [path], [audit] [deny] umount [conds]* [path], [audit] [deny] pivotroot [oldroot=<value>] <path> -> <profile> remount is just a short cut for mount options=remount where [conds] can be fstype=<expr> options=<expr> conds follow the extended conditional syntax of allowing either: * a single value after the equals, which has the same character range as regular IDS (ie most anything but it can't be terminated with a , (comma) and if spaces or other characters are needed it can be quoted eg. options=foo options = foo options="foo bar" * a list of values after the equals, the list of values is enclosed within parenthesis () and its has a slightly reduced character set but again elements can be quoted. the separation between elements is whitespace and commas. eg. options=(foo bar) options=(foo, bar) options=(foo , bar) options=(foo,bar) The rules are flexible and follow a similar pattern as network, capability, etc. mount, # allow all mounts, but not umount or pivotroot mount fstype=procfs, # allow mounting procfs anywhere mount options=(bind, ro) /foo -> /bar, # readonly bind mount mount /dev/sda -> /mnt, mount /dev/sd** -> /mnt/**, mount fstype=overlayfs options=(rw,upperdir=/tmp/upper/,lowerdir=/) overlay -> /mnt/ umount, umount /m*, Currently variables and regexs are are supported on the device and mount point. ie. mount <devince> -> <mount point>, Regexes are supported in fstype and options. The options have a further caveat that regexs only work if the option is fs specific option. eg. options=(upperdir=/tmp/*,lowerdir=/) regex's will not currently work against the standard options like ro, rw nosuid Conditionals (fstype) can only be applied to the device (source) at this time and will be disregarded in situations where the mount is manipulating an existing mount (bind, remount). Options can be specified multiple times mount option=rw option=(nosuid,upperdir=/foo), and will be combined together into a single set of values The ordering of the standard mount options (rw,ro, ...) does not matter but the ordering of fs specific options does. Specifying that the value of a particular option does not matter can be acheived by providing both the positive and negative forms of and option option=(rw,ro) options=(suid,nosuid) For the fs specific options specifying that a particular value does not matter is achieve using a regex with alternations. Improvements to the syntax and order restrictions are planned for the future. Signed-off-by: John Johansen <john.johansen@canonical.com>
2012-02-24 04:19:38 -08:00
return TRUE;
fail:
return FALSE;
}
int convert_entry(std::string& buffer, char *entry)
Add mount rules Add the ability to control mounting and unmounting The basic form of the rules are. [audit] [deny] mount [conds]* [device] [ -> [conds] path], [audit] [deny] remount [conds]* [path], [audit] [deny] umount [conds]* [path], [audit] [deny] pivotroot [oldroot=<value>] <path> -> <profile> remount is just a short cut for mount options=remount where [conds] can be fstype=<expr> options=<expr> conds follow the extended conditional syntax of allowing either: * a single value after the equals, which has the same character range as regular IDS (ie most anything but it can't be terminated with a , (comma) and if spaces or other characters are needed it can be quoted eg. options=foo options = foo options="foo bar" * a list of values after the equals, the list of values is enclosed within parenthesis () and its has a slightly reduced character set but again elements can be quoted. the separation between elements is whitespace and commas. eg. options=(foo bar) options=(foo, bar) options=(foo , bar) options=(foo,bar) The rules are flexible and follow a similar pattern as network, capability, etc. mount, # allow all mounts, but not umount or pivotroot mount fstype=procfs, # allow mounting procfs anywhere mount options=(bind, ro) /foo -> /bar, # readonly bind mount mount /dev/sda -> /mnt, mount /dev/sd** -> /mnt/**, mount fstype=overlayfs options=(rw,upperdir=/tmp/upper/,lowerdir=/) overlay -> /mnt/ umount, umount /m*, Currently variables and regexs are are supported on the device and mount point. ie. mount <devince> -> <mount point>, Regexes are supported in fstype and options. The options have a further caveat that regexs only work if the option is fs specific option. eg. options=(upperdir=/tmp/*,lowerdir=/) regex's will not currently work against the standard options like ro, rw nosuid Conditionals (fstype) can only be applied to the device (source) at this time and will be disregarded in situations where the mount is manipulating an existing mount (bind, remount). Options can be specified multiple times mount option=rw option=(nosuid,upperdir=/foo), and will be combined together into a single set of values The ordering of the standard mount options (rw,ro, ...) does not matter but the ordering of fs specific options does. Specifying that the value of a particular option does not matter can be acheived by providing both the positive and negative forms of and option option=(rw,ro) options=(suid,nosuid) For the fs specific options specifying that a particular value does not matter is achieve using a regex with alternations. Improvements to the syntax and order restrictions are planned for the future. Signed-off-by: John Johansen <john.johansen@canonical.com>
2012-02-24 04:19:38 -08:00
{
pattern_t ptype;
int pos;
if (entry) {
ptype = convert_aaregex_to_pcre(entry, 0, glob_default, buffer, &pos);
Add mount rules Add the ability to control mounting and unmounting The basic form of the rules are. [audit] [deny] mount [conds]* [device] [ -> [conds] path], [audit] [deny] remount [conds]* [path], [audit] [deny] umount [conds]* [path], [audit] [deny] pivotroot [oldroot=<value>] <path> -> <profile> remount is just a short cut for mount options=remount where [conds] can be fstype=<expr> options=<expr> conds follow the extended conditional syntax of allowing either: * a single value after the equals, which has the same character range as regular IDS (ie most anything but it can't be terminated with a , (comma) and if spaces or other characters are needed it can be quoted eg. options=foo options = foo options="foo bar" * a list of values after the equals, the list of values is enclosed within parenthesis () and its has a slightly reduced character set but again elements can be quoted. the separation between elements is whitespace and commas. eg. options=(foo bar) options=(foo, bar) options=(foo , bar) options=(foo,bar) The rules are flexible and follow a similar pattern as network, capability, etc. mount, # allow all mounts, but not umount or pivotroot mount fstype=procfs, # allow mounting procfs anywhere mount options=(bind, ro) /foo -> /bar, # readonly bind mount mount /dev/sda -> /mnt, mount /dev/sd** -> /mnt/**, mount fstype=overlayfs options=(rw,upperdir=/tmp/upper/,lowerdir=/) overlay -> /mnt/ umount, umount /m*, Currently variables and regexs are are supported on the device and mount point. ie. mount <devince> -> <mount point>, Regexes are supported in fstype and options. The options have a further caveat that regexs only work if the option is fs specific option. eg. options=(upperdir=/tmp/*,lowerdir=/) regex's will not currently work against the standard options like ro, rw nosuid Conditionals (fstype) can only be applied to the device (source) at this time and will be disregarded in situations where the mount is manipulating an existing mount (bind, remount). Options can be specified multiple times mount option=rw option=(nosuid,upperdir=/foo), and will be combined together into a single set of values The ordering of the standard mount options (rw,ro, ...) does not matter but the ordering of fs specific options does. Specifying that the value of a particular option does not matter can be acheived by providing both the positive and negative forms of and option option=(rw,ro) options=(suid,nosuid) For the fs specific options specifying that a particular value does not matter is achieve using a regex with alternations. Improvements to the syntax and order restrictions are planned for the future. Signed-off-by: John Johansen <john.johansen@canonical.com>
2012-02-24 04:19:38 -08:00
if (ptype == ePatternInvalid)
return FALSE;
} else {
buffer.append(default_match_pattern);
Add mount rules Add the ability to control mounting and unmounting The basic form of the rules are. [audit] [deny] mount [conds]* [device] [ -> [conds] path], [audit] [deny] remount [conds]* [path], [audit] [deny] umount [conds]* [path], [audit] [deny] pivotroot [oldroot=<value>] <path> -> <profile> remount is just a short cut for mount options=remount where [conds] can be fstype=<expr> options=<expr> conds follow the extended conditional syntax of allowing either: * a single value after the equals, which has the same character range as regular IDS (ie most anything but it can't be terminated with a , (comma) and if spaces or other characters are needed it can be quoted eg. options=foo options = foo options="foo bar" * a list of values after the equals, the list of values is enclosed within parenthesis () and its has a slightly reduced character set but again elements can be quoted. the separation between elements is whitespace and commas. eg. options=(foo bar) options=(foo, bar) options=(foo , bar) options=(foo,bar) The rules are flexible and follow a similar pattern as network, capability, etc. mount, # allow all mounts, but not umount or pivotroot mount fstype=procfs, # allow mounting procfs anywhere mount options=(bind, ro) /foo -> /bar, # readonly bind mount mount /dev/sda -> /mnt, mount /dev/sd** -> /mnt/**, mount fstype=overlayfs options=(rw,upperdir=/tmp/upper/,lowerdir=/) overlay -> /mnt/ umount, umount /m*, Currently variables and regexs are are supported on the device and mount point. ie. mount <devince> -> <mount point>, Regexes are supported in fstype and options. The options have a further caveat that regexs only work if the option is fs specific option. eg. options=(upperdir=/tmp/*,lowerdir=/) regex's will not currently work against the standard options like ro, rw nosuid Conditionals (fstype) can only be applied to the device (source) at this time and will be disregarded in situations where the mount is manipulating an existing mount (bind, remount). Options can be specified multiple times mount option=rw option=(nosuid,upperdir=/foo), and will be combined together into a single set of values The ordering of the standard mount options (rw,ro, ...) does not matter but the ordering of fs specific options does. Specifying that the value of a particular option does not matter can be acheived by providing both the positive and negative forms of and option option=(rw,ro) options=(suid,nosuid) For the fs specific options specifying that a particular value does not matter is achieve using a regex with alternations. Improvements to the syntax and order restrictions are planned for the future. Signed-off-by: John Johansen <john.johansen@canonical.com>
2012-02-24 04:19:38 -08:00
}
Add mount rules Add the ability to control mounting and unmounting The basic form of the rules are. [audit] [deny] mount [conds]* [device] [ -> [conds] path], [audit] [deny] remount [conds]* [path], [audit] [deny] umount [conds]* [path], [audit] [deny] pivotroot [oldroot=<value>] <path> -> <profile> remount is just a short cut for mount options=remount where [conds] can be fstype=<expr> options=<expr> conds follow the extended conditional syntax of allowing either: * a single value after the equals, which has the same character range as regular IDS (ie most anything but it can't be terminated with a , (comma) and if spaces or other characters are needed it can be quoted eg. options=foo options = foo options="foo bar" * a list of values after the equals, the list of values is enclosed within parenthesis () and its has a slightly reduced character set but again elements can be quoted. the separation between elements is whitespace and commas. eg. options=(foo bar) options=(foo, bar) options=(foo , bar) options=(foo,bar) The rules are flexible and follow a similar pattern as network, capability, etc. mount, # allow all mounts, but not umount or pivotroot mount fstype=procfs, # allow mounting procfs anywhere mount options=(bind, ro) /foo -> /bar, # readonly bind mount mount /dev/sda -> /mnt, mount /dev/sd** -> /mnt/**, mount fstype=overlayfs options=(rw,upperdir=/tmp/upper/,lowerdir=/) overlay -> /mnt/ umount, umount /m*, Currently variables and regexs are are supported on the device and mount point. ie. mount <devince> -> <mount point>, Regexes are supported in fstype and options. The options have a further caveat that regexs only work if the option is fs specific option. eg. options=(upperdir=/tmp/*,lowerdir=/) regex's will not currently work against the standard options like ro, rw nosuid Conditionals (fstype) can only be applied to the device (source) at this time and will be disregarded in situations where the mount is manipulating an existing mount (bind, remount). Options can be specified multiple times mount option=rw option=(nosuid,upperdir=/foo), and will be combined together into a single set of values The ordering of the standard mount options (rw,ro, ...) does not matter but the ordering of fs specific options does. Specifying that the value of a particular option does not matter can be acheived by providing both the positive and negative forms of and option option=(rw,ro) options=(suid,nosuid) For the fs specific options specifying that a particular value does not matter is achieve using a regex with alternations. Improvements to the syntax and order restrictions are planned for the future. Signed-off-by: John Johansen <john.johansen@canonical.com>
2012-02-24 04:19:38 -08:00
return TRUE;
}
int clear_and_convert_entry(std::string& buffer, char *entry)
{
buffer.clear();
return convert_entry(buffer, entry);
}
int post_process_policydb_ents(Profile *prof)
Add mount rules Add the ability to control mounting and unmounting The basic form of the rules are. [audit] [deny] mount [conds]* [device] [ -> [conds] path], [audit] [deny] remount [conds]* [path], [audit] [deny] umount [conds]* [path], [audit] [deny] pivotroot [oldroot=<value>] <path> -> <profile> remount is just a short cut for mount options=remount where [conds] can be fstype=<expr> options=<expr> conds follow the extended conditional syntax of allowing either: * a single value after the equals, which has the same character range as regular IDS (ie most anything but it can't be terminated with a , (comma) and if spaces or other characters are needed it can be quoted eg. options=foo options = foo options="foo bar" * a list of values after the equals, the list of values is enclosed within parenthesis () and its has a slightly reduced character set but again elements can be quoted. the separation between elements is whitespace and commas. eg. options=(foo bar) options=(foo, bar) options=(foo , bar) options=(foo,bar) The rules are flexible and follow a similar pattern as network, capability, etc. mount, # allow all mounts, but not umount or pivotroot mount fstype=procfs, # allow mounting procfs anywhere mount options=(bind, ro) /foo -> /bar, # readonly bind mount mount /dev/sda -> /mnt, mount /dev/sd** -> /mnt/**, mount fstype=overlayfs options=(rw,upperdir=/tmp/upper/,lowerdir=/) overlay -> /mnt/ umount, umount /m*, Currently variables and regexs are are supported on the device and mount point. ie. mount <devince> -> <mount point>, Regexes are supported in fstype and options. The options have a further caveat that regexs only work if the option is fs specific option. eg. options=(upperdir=/tmp/*,lowerdir=/) regex's will not currently work against the standard options like ro, rw nosuid Conditionals (fstype) can only be applied to the device (source) at this time and will be disregarded in situations where the mount is manipulating an existing mount (bind, remount). Options can be specified multiple times mount option=rw option=(nosuid,upperdir=/foo), and will be combined together into a single set of values The ordering of the standard mount options (rw,ro, ...) does not matter but the ordering of fs specific options does. Specifying that the value of a particular option does not matter can be acheived by providing both the positive and negative forms of and option option=(rw,ro) options=(suid,nosuid) For the fs specific options specifying that a particular value does not matter is achieve using a regex with alternations. Improvements to the syntax and order restrictions are planned for the future. Signed-off-by: John Johansen <john.johansen@canonical.com>
2012-02-24 04:19:38 -08:00
{
for (RuleList::iterator i = prof->rule_ents.begin(); i != prof->rule_ents.end(); i++) {
if ((*i)->gen_policy_re(*prof) == RULE_ERROR)
Add mount rules Add the ability to control mounting and unmounting The basic form of the rules are. [audit] [deny] mount [conds]* [device] [ -> [conds] path], [audit] [deny] remount [conds]* [path], [audit] [deny] umount [conds]* [path], [audit] [deny] pivotroot [oldroot=<value>] <path> -> <profile> remount is just a short cut for mount options=remount where [conds] can be fstype=<expr> options=<expr> conds follow the extended conditional syntax of allowing either: * a single value after the equals, which has the same character range as regular IDS (ie most anything but it can't be terminated with a , (comma) and if spaces or other characters are needed it can be quoted eg. options=foo options = foo options="foo bar" * a list of values after the equals, the list of values is enclosed within parenthesis () and its has a slightly reduced character set but again elements can be quoted. the separation between elements is whitespace and commas. eg. options=(foo bar) options=(foo, bar) options=(foo , bar) options=(foo,bar) The rules are flexible and follow a similar pattern as network, capability, etc. mount, # allow all mounts, but not umount or pivotroot mount fstype=procfs, # allow mounting procfs anywhere mount options=(bind, ro) /foo -> /bar, # readonly bind mount mount /dev/sda -> /mnt, mount /dev/sd** -> /mnt/**, mount fstype=overlayfs options=(rw,upperdir=/tmp/upper/,lowerdir=/) overlay -> /mnt/ umount, umount /m*, Currently variables and regexs are are supported on the device and mount point. ie. mount <devince> -> <mount point>, Regexes are supported in fstype and options. The options have a further caveat that regexs only work if the option is fs specific option. eg. options=(upperdir=/tmp/*,lowerdir=/) regex's will not currently work against the standard options like ro, rw nosuid Conditionals (fstype) can only be applied to the device (source) at this time and will be disregarded in situations where the mount is manipulating an existing mount (bind, remount). Options can be specified multiple times mount option=rw option=(nosuid,upperdir=/foo), and will be combined together into a single set of values The ordering of the standard mount options (rw,ro, ...) does not matter but the ordering of fs specific options does. Specifying that the value of a particular option does not matter can be acheived by providing both the positive and negative forms of and option option=(rw,ro) options=(suid,nosuid) For the fs specific options specifying that a particular value does not matter is achieve using a regex with alternations. Improvements to the syntax and order restrictions are planned for the future. Signed-off-by: John Johansen <john.johansen@canonical.com>
2012-02-24 04:19:38 -08:00
return FALSE;
}
return TRUE;
}
parser: Fix AF_UNIX stub rule creation The patch titled "parser: Add support for unix domain socket rules." modified the code the creates the stub rules for rule types that the parser supports. It added new stub rules for extended network and AF_UNIX rule types but it also changed the stub rules for all existing rule types. That change causes the kernel to not enforce some rule types. This patch fixes the stub rule creation so that existing rule types continue to be enforced, as well as AF_UNIX rule types when the parser and kernel both support them. Here's the DFA states generated before applying the patch mentioned above: $ echo "/t { /f r, }" | ./apparmor_parser -qQD dfa-states {1} <== (allow/deny/audit/quiet) {3} (0x 10004/0/0/0) {1} -> {2}: 0x2f / {2} -> {3}: 0x66 f {1} <== (allow/deny/audit/quiet) {2} (0x 4/0/0/0) {1} -> {2}: 0x2 {1} -> {2}: 0x7 {1} -> {2}: 0x9 {1} -> {2}: 0xa {1} -> {2}: 0x20 \ Here are the DFA states generated after applying the patch mentioned above: $ echo "/t { /f r, }" | ./apparmor_parser -qQD dfa-states {1} <== (allow/deny/audit/quiet) {3} (0x 10004/0/0/0) {1} -> {2}: 0x2f / {2} -> {3}: 0x66 f {1} <== (allow/deny/audit/quiet) {4} (0x 4/0/0/0) {1} -> {2}: 0x0 {1} -> {3}: 0x34 4 {2} -> {4}: 0x2 {2} -> {4}: 0x4 {2} -> {4}: 0x7 {2} -> {4}: 0x9 {2} -> {4}: 0xa {2} -> {4}: 0x20 \ {3} -> {4}: 0x31 1 Here are DFA states generated after applying this patch: $ echo "/t { /f r, }" | ./apparmor_parser -qQD dfa-states {1} <== (allow/deny/audit/quiet) {3} (0x 10004/0/0/0) {1} -> {2}: 0x2f / {2} -> {3}: 0x66 f {1} <== (allow/deny/audit/quiet) {2} (0x 4/0/0/0) {1} -> {2}: 0x2 {1} -> {2}: 0x4 {1} -> {2}: 0x7 {1} -> {2}: 0x9 {1} -> {2}: 0xa {1} -> {2}: 0x20 \ {1} -> {3}: 0x34 4 {3} -> {4}: 0x0 {4} -> {2}: 0x31 1 Signed-off-by: Tyler Hicks <tyhicks@canonical.com> Acked-by: John Johansen <john.johansen@canonical.com>
2014-09-03 13:45:44 -07:00
#define MAKE_STR(X) #X
#define CLASS_STR(X) "\\d" MAKE_STR(X)
#define MAKE_SUB_STR(X) "\\000" MAKE_STR(X)
#define CLASS_SUB_STR(X, Y) MAKE_STR(X) MAKE_SUB_STR(Y)
static const char *mediates_file = CLASS_STR(AA_CLASS_FILE);
static const char *mediates_mount = CLASS_STR(AA_CLASS_MOUNT);
static const char *mediates_dbus = CLASS_STR(AA_CLASS_DBUS);
static const char *mediates_signal = CLASS_STR(AA_CLASS_SIGNAL);
static const char *mediates_ptrace = CLASS_STR(AA_CLASS_PTRACE);
parser: first step implementing fine grained mediation for unix domain sockets This patch implements parsing of fine grained mediation for unix domain sockets, that have abstract and anonymous paths. Sockets with file system paths are handled by regular file access rules. The unix network rules follow the general fine grained network rule pattern of [<qualifiers>] af_name [<access expr>] [<rule conds>] [<local expr>] [<peer expr>] specifically for af_unix this is [<qualifiers>] 'unix' [<access expr>] [<rule conds>] [<local expr>] [<peer expr>] <qualifiers> = [ 'audit' ] [ 'allow' | 'deny' ] <access expr> = ( <access> | <access list> ) <access> = ( 'server' | 'create' | 'bind' | 'listen' | 'accept' | 'connect' | 'shutdown' | 'getattr' | 'setattr' | 'getopt' | 'setopt' | 'send' | 'receive' | 'r' | 'w' | 'rw' ) (some access modes are incompatible with some rules or require additional parameters) <access list> = '(' <access> ( [','] <WS> <access> )* ')' <WS> = white space <rule conds> = ( <type cond> | <protocol cond> )* each cond can appear at most once <type cond> = 'type' '=' ( <AARE> | '(' ( '"' <AARE> '"' | <AARE> )+ ')' ) <protocol cond> = 'protocol' '=' ( <AARE> | '(' ( '"' <AARE> '"' | <AARE> )+ ')' ) <local expr> = ( <path cond> | <attr cond> | <opt cond> )* each cond can appear at most once <peer expr> = 'peer' '=' ( <path cond> | <label cond> )+ each cond can appear at most once <path cond> = 'path' '=' ( <AARE> | '(' '"' <AARE> '"' | <AARE> ')' ) <label cond> = 'label' '=' ( <AARE> | '(' '"' <AARE> '"' | <AARE> ')') <attr cond> = 'attr' '=' ( <AARE> | '(' '"' <AARE> '"' | <AARE> ')' ) <opt cond> = 'opt' '=' ( <AARE> | '(' '"' <AARE> '"' | <AARE> ')' ) <AARE> = ?*[]{}^ ( see man page ) unix domain socket rules are accumulated so that the granted unix socket permissions are the union of all the listed unix rule permissions. unix domain socket rules are broad and general and become more restrictive as further information is specified. Policy may be specified down to the path and label level. The content of the communication is not examined. Some permissions are not compatible with all unix rules. unix socket rule permissions are implied when a rule does not explicitly state an access list. By default if a rule does not have an access list all permissions that are compatible with the specified set of local and peer conditionals are implied. The 'server', 'r', 'w' and 'rw' permissions are aliases for other permissions. server = (create, bind, listen, accept) r = (receive, getattr, getopt) w = (create, connect, send, setattr, setopt) In addition it supports the v7 kernel abi semantics around generic network rules. The v7 abi removes the masking unix and netlink address families from the generic masking and uses fine grained mediation for an address type if supplied. This means that the rules network unix, network netlink, are now enforced instead of ignored. The parser previously could accept these but the kernel would ignore anything written to them. If a network rule is supplied it takes precedence over the finer grained mediation rule. If permission is not granted via a broad network access rule fine grained mediation is applied. Signed-off-by: John Johansen <john.johansen@canonical.com> Acked-by: Seth Arnold <seth.arnold@canonical.com>
2014-09-03 13:22:26 -07:00
static const char *mediates_extended_net = CLASS_STR(AA_CLASS_NET);
static const char *mediates_net_unix = CLASS_SUB_STR(AA_CLASS_NET, AF_UNIX);
int process_profile_policydb(Profile *prof)
{
int error = -1;
prof->policy.rules = new aare_rules();
if (!prof->policy.rules)
goto out;
Add mount rules Add the ability to control mounting and unmounting The basic form of the rules are. [audit] [deny] mount [conds]* [device] [ -> [conds] path], [audit] [deny] remount [conds]* [path], [audit] [deny] umount [conds]* [path], [audit] [deny] pivotroot [oldroot=<value>] <path> -> <profile> remount is just a short cut for mount options=remount where [conds] can be fstype=<expr> options=<expr> conds follow the extended conditional syntax of allowing either: * a single value after the equals, which has the same character range as regular IDS (ie most anything but it can't be terminated with a , (comma) and if spaces or other characters are needed it can be quoted eg. options=foo options = foo options="foo bar" * a list of values after the equals, the list of values is enclosed within parenthesis () and its has a slightly reduced character set but again elements can be quoted. the separation between elements is whitespace and commas. eg. options=(foo bar) options=(foo, bar) options=(foo , bar) options=(foo,bar) The rules are flexible and follow a similar pattern as network, capability, etc. mount, # allow all mounts, but not umount or pivotroot mount fstype=procfs, # allow mounting procfs anywhere mount options=(bind, ro) /foo -> /bar, # readonly bind mount mount /dev/sda -> /mnt, mount /dev/sd** -> /mnt/**, mount fstype=overlayfs options=(rw,upperdir=/tmp/upper/,lowerdir=/) overlay -> /mnt/ umount, umount /m*, Currently variables and regexs are are supported on the device and mount point. ie. mount <devince> -> <mount point>, Regexes are supported in fstype and options. The options have a further caveat that regexs only work if the option is fs specific option. eg. options=(upperdir=/tmp/*,lowerdir=/) regex's will not currently work against the standard options like ro, rw nosuid Conditionals (fstype) can only be applied to the device (source) at this time and will be disregarded in situations where the mount is manipulating an existing mount (bind, remount). Options can be specified multiple times mount option=rw option=(nosuid,upperdir=/foo), and will be combined together into a single set of values The ordering of the standard mount options (rw,ro, ...) does not matter but the ordering of fs specific options does. Specifying that the value of a particular option does not matter can be acheived by providing both the positive and negative forms of and option option=(rw,ro) options=(suid,nosuid) For the fs specific options specifying that a particular value does not matter is achieve using a regex with alternations. Improvements to the syntax and order restrictions are planned for the future. Signed-off-by: John Johansen <john.johansen@canonical.com>
2012-02-24 04:19:38 -08:00
if (!post_process_policydb_ents(prof))
goto out;
/* insert entries to show indicate what compiler/policy expects
* to be supported
*/
parser: first step implementing fine grained mediation for unix domain sockets This patch implements parsing of fine grained mediation for unix domain sockets, that have abstract and anonymous paths. Sockets with file system paths are handled by regular file access rules. The unix network rules follow the general fine grained network rule pattern of [<qualifiers>] af_name [<access expr>] [<rule conds>] [<local expr>] [<peer expr>] specifically for af_unix this is [<qualifiers>] 'unix' [<access expr>] [<rule conds>] [<local expr>] [<peer expr>] <qualifiers> = [ 'audit' ] [ 'allow' | 'deny' ] <access expr> = ( <access> | <access list> ) <access> = ( 'server' | 'create' | 'bind' | 'listen' | 'accept' | 'connect' | 'shutdown' | 'getattr' | 'setattr' | 'getopt' | 'setopt' | 'send' | 'receive' | 'r' | 'w' | 'rw' ) (some access modes are incompatible with some rules or require additional parameters) <access list> = '(' <access> ( [','] <WS> <access> )* ')' <WS> = white space <rule conds> = ( <type cond> | <protocol cond> )* each cond can appear at most once <type cond> = 'type' '=' ( <AARE> | '(' ( '"' <AARE> '"' | <AARE> )+ ')' ) <protocol cond> = 'protocol' '=' ( <AARE> | '(' ( '"' <AARE> '"' | <AARE> )+ ')' ) <local expr> = ( <path cond> | <attr cond> | <opt cond> )* each cond can appear at most once <peer expr> = 'peer' '=' ( <path cond> | <label cond> )+ each cond can appear at most once <path cond> = 'path' '=' ( <AARE> | '(' '"' <AARE> '"' | <AARE> ')' ) <label cond> = 'label' '=' ( <AARE> | '(' '"' <AARE> '"' | <AARE> ')') <attr cond> = 'attr' '=' ( <AARE> | '(' '"' <AARE> '"' | <AARE> ')' ) <opt cond> = 'opt' '=' ( <AARE> | '(' '"' <AARE> '"' | <AARE> ')' ) <AARE> = ?*[]{}^ ( see man page ) unix domain socket rules are accumulated so that the granted unix socket permissions are the union of all the listed unix rule permissions. unix domain socket rules are broad and general and become more restrictive as further information is specified. Policy may be specified down to the path and label level. The content of the communication is not examined. Some permissions are not compatible with all unix rules. unix socket rule permissions are implied when a rule does not explicitly state an access list. By default if a rule does not have an access list all permissions that are compatible with the specified set of local and peer conditionals are implied. The 'server', 'r', 'w' and 'rw' permissions are aliases for other permissions. server = (create, bind, listen, accept) r = (receive, getattr, getopt) w = (create, connect, send, setattr, setopt) In addition it supports the v7 kernel abi semantics around generic network rules. The v7 abi removes the masking unix and netlink address families from the generic masking and uses fine grained mediation for an address type if supplied. This means that the rules network unix, network netlink, are now enforced instead of ignored. The parser previously could accept these but the kernel would ignore anything written to them. If a network rule is supplied it takes precedence over the finer grained mediation rule. If permission is not granted via a broad network access rule fine grained mediation is applied. Signed-off-by: John Johansen <john.johansen@canonical.com> Acked-by: Seth Arnold <seth.arnold@canonical.com>
2014-09-03 13:22:26 -07:00
/* note: this activates fs based unix domain sockets mediation on connect */
Add the ability to separate policy_version from kernel and parser abi This will allow for the parser to invalidate its caches separate of whether the kernel policy version has changed. This can be desirable if a parser bug is discovered, a new version the parser is shipped and we need to force cache files to be regenerated. Policy current stores a 32 bit version number in the header binary policy. For newer policy (> v5 kernel abi) split this number into 3 separate fields policy_version, parser_abi, kernel_abi. If binary policy with a split version number is loaded to an older kernel it will be correctly rejected as unsupported as those kernels will see it as a none v5 version. For kernels that only support v5 policy on the kernel abi version is written. The rules for policy versioning should be policy_version: Set by text policy language version. Parsers that don't understand a specified version may fail, or drop rules they are unaware of. parser_abi_version: gets bumped when a userspace bug is discovered that requires policy be recompiled. The policy version could be reset for each new kernel version but since the parser needs to support multiple kernel versions tracking this is extra work and should be avoided. kernel_abi_version: gets bumped when semantic changes need to be applied. Eg unix domain sockets being mediated at connect. the kernel abi version does not encapsulate all supported features. As kernels could have different sets of patches supplied. Basic feature support is determined by the policy_mediates() encoding in the policydb. As such comparing cache features to kernel features is still needed to determine if cached policy is best matched to the kernel. Signed-off-by: John Johansen <john.johansen@canonical.com> Acked-by: Seth Arnold <seth.arnold@canonical.com>
2014-04-23 11:00:32 -07:00
if (kernel_abi_version > 5 &&
!prof->policy.rules->add_rule(mediates_file, 0, AA_MAY_READ, 0, dfaflags))
goto out;
if (kernel_supports_mount &&
!prof->policy.rules->add_rule(mediates_mount, 0, AA_MAY_READ, 0, dfaflags))
goto out;
if (kernel_supports_dbus &&
!prof->policy.rules->add_rule(mediates_dbus, 0, AA_MAY_READ, 0, dfaflags))
goto out;
if (kernel_supports_signal &&
!prof->policy.rules->add_rule(mediates_signal, 0, AA_MAY_READ, 0, dfaflags))
goto out;
if (kernel_supports_ptrace &&
!prof->policy.rules->add_rule(mediates_ptrace, 0, AA_MAY_READ, 0, dfaflags))
goto out;
parser: first step implementing fine grained mediation for unix domain sockets This patch implements parsing of fine grained mediation for unix domain sockets, that have abstract and anonymous paths. Sockets with file system paths are handled by regular file access rules. The unix network rules follow the general fine grained network rule pattern of [<qualifiers>] af_name [<access expr>] [<rule conds>] [<local expr>] [<peer expr>] specifically for af_unix this is [<qualifiers>] 'unix' [<access expr>] [<rule conds>] [<local expr>] [<peer expr>] <qualifiers> = [ 'audit' ] [ 'allow' | 'deny' ] <access expr> = ( <access> | <access list> ) <access> = ( 'server' | 'create' | 'bind' | 'listen' | 'accept' | 'connect' | 'shutdown' | 'getattr' | 'setattr' | 'getopt' | 'setopt' | 'send' | 'receive' | 'r' | 'w' | 'rw' ) (some access modes are incompatible with some rules or require additional parameters) <access list> = '(' <access> ( [','] <WS> <access> )* ')' <WS> = white space <rule conds> = ( <type cond> | <protocol cond> )* each cond can appear at most once <type cond> = 'type' '=' ( <AARE> | '(' ( '"' <AARE> '"' | <AARE> )+ ')' ) <protocol cond> = 'protocol' '=' ( <AARE> | '(' ( '"' <AARE> '"' | <AARE> )+ ')' ) <local expr> = ( <path cond> | <attr cond> | <opt cond> )* each cond can appear at most once <peer expr> = 'peer' '=' ( <path cond> | <label cond> )+ each cond can appear at most once <path cond> = 'path' '=' ( <AARE> | '(' '"' <AARE> '"' | <AARE> ')' ) <label cond> = 'label' '=' ( <AARE> | '(' '"' <AARE> '"' | <AARE> ')') <attr cond> = 'attr' '=' ( <AARE> | '(' '"' <AARE> '"' | <AARE> ')' ) <opt cond> = 'opt' '=' ( <AARE> | '(' '"' <AARE> '"' | <AARE> ')' ) <AARE> = ?*[]{}^ ( see man page ) unix domain socket rules are accumulated so that the granted unix socket permissions are the union of all the listed unix rule permissions. unix domain socket rules are broad and general and become more restrictive as further information is specified. Policy may be specified down to the path and label level. The content of the communication is not examined. Some permissions are not compatible with all unix rules. unix socket rule permissions are implied when a rule does not explicitly state an access list. By default if a rule does not have an access list all permissions that are compatible with the specified set of local and peer conditionals are implied. The 'server', 'r', 'w' and 'rw' permissions are aliases for other permissions. server = (create, bind, listen, accept) r = (receive, getattr, getopt) w = (create, connect, send, setattr, setopt) In addition it supports the v7 kernel abi semantics around generic network rules. The v7 abi removes the masking unix and netlink address families from the generic masking and uses fine grained mediation for an address type if supplied. This means that the rules network unix, network netlink, are now enforced instead of ignored. The parser previously could accept these but the kernel would ignore anything written to them. If a network rule is supplied it takes precedence over the finer grained mediation rule. If permission is not granted via a broad network access rule fine grained mediation is applied. Signed-off-by: John Johansen <john.johansen@canonical.com> Acked-by: Seth Arnold <seth.arnold@canonical.com>
2014-09-03 13:22:26 -07:00
if (kernel_supports_unix &&
(!prof->policy.rules->add_rule(mediates_extended_net, 0, AA_MAY_READ, 0, dfaflags) ||
!prof->policy.rules->add_rule(mediates_net_unix, 0, AA_MAY_READ, 0, dfaflags)))
goto out;
if (prof->policy.rules->rule_count > 0) {
prof->policy.dfa = prof->policy.rules->create_dfa(&prof->policy.size, dfaflags);
delete prof->policy.rules;
prof->policy.rules = NULL;
if (!prof->policy.dfa)
goto out;
} else {
delete prof->policy.rules;
prof->policy.rules = NULL;
}
error = 0;
out:
delete prof->policy.rules;
prof->policy.rules = NULL;
return error;
}
#ifdef UNIT_TEST
#include "unit_test.h"
#define MY_FILTER_TEST(input, expected_str) \
do { \
char *test_string = NULL; \
char *output_string = NULL; \
\
test_string = strdup((input)); \
filter_slashes(test_string); \
asprintf(&output_string, "simple filter / conversion for '%s'\texpected = '%s'\tresult = '%s'", \
(input), (expected_str), test_string); \
MY_TEST(strcmp(test_string, (expected_str)) == 0, output_string); \
\
free(test_string); \
free(output_string); \
} \
while (0)
static int test_filter_slashes(void)
{
int rc = 0;
MY_FILTER_TEST("///foo//////f//oo////////////////", "/foo/f/oo/");
MY_FILTER_TEST("/foo/f/oo", "/foo/f/oo");
MY_FILTER_TEST("/", "/");
MY_FILTER_TEST("", "");
/* tests for "//" namespace */
MY_FILTER_TEST("//usr", "//usr");
MY_FILTER_TEST("//", "//");
/* tests for not "//" namespace */
MY_FILTER_TEST("///usr", "/usr");
MY_FILTER_TEST("///", "/");
MY_FILTER_TEST("/a/", "/a/");
return rc;
}
#define MY_REGEX_EXT_TEST(glob, input, expected_str, expected_type) \
do { \
std::string tbuf; \
std::string tbuf2 = "testprefix"; \
char *output_string = NULL; \
std::string expected_str2; \
pattern_t ptype; \
int pos; \
\
ptype = convert_aaregex_to_pcre((input), 0, glob, tbuf, &pos); \
asprintf(&output_string, "simple regex conversion for '%s'\texpected = '%s'\tresult = '%s'", \
(input), (expected_str), tbuf.c_str()); \
MY_TEST(strcmp(tbuf.c_str(), (expected_str)) == 0, output_string); \
MY_TEST(ptype == (expected_type), "simple regex conversion type check for '" input "'"); \
free(output_string); \
/* ensure convert_aaregex_to_pcre appends only to passed ref string */ \
expected_str2 = tbuf2; \
expected_str2.append((expected_str)); \
ptype = convert_aaregex_to_pcre((input), 0, glob, tbuf2, &pos); \
asprintf(&output_string, "simple regex conversion %sfor '%s'\texpected = '%s'\tresult = '%s'", \
glob == glob_null ? "with null allowed in glob " : "",\
(input), expected_str2.c_str(), tbuf2.c_str()); \
MY_TEST((tbuf2 == expected_str2), output_string); \
free(output_string); \
} \
while (0)
#define MY_REGEX_TEST(input, expected_str, expected_type) MY_REGEX_EXT_TEST(glob_default, input, expected_str, expected_type)
#define MY_REGEX_FAIL_TEST(input) \
do { \
std::string tbuf; \
pattern_t ptype; \
int pos; \
\
ptype = convert_aaregex_to_pcre((input), 0, glob_default, tbuf, &pos); \
MY_TEST(ptype == ePatternInvalid, "simple regex conversion invalid type check for '" input "'"); \
} \
while (0)
static int test_aaregex_to_pcre(void)
{
int rc = 0;
MY_REGEX_TEST("/most/basic/test", "/most/basic/test", ePatternBasic);
MY_REGEX_FAIL_TEST("\\");
MY_REGEX_TEST("\\\\", "\\\\", ePatternBasic);
MY_REGEX_TEST("\\blort", "blort", ePatternBasic);
MY_REGEX_TEST("\\\\blort", "\\\\blort", ePatternBasic);
MY_REGEX_FAIL_TEST("blort\\");
MY_REGEX_TEST("blort\\\\", "blort\\\\", ePatternBasic);
MY_REGEX_TEST("*", "[^/\\x00]*", ePatternRegex);
MY_REGEX_TEST("blort*", "blort[^/\\x00]*", ePatternRegex);
MY_REGEX_TEST("*blort", "[^/\\x00]*blort", ePatternRegex);
MY_REGEX_TEST("\\*", "\\*", ePatternBasic);
MY_REGEX_TEST("blort\\*", "blort\\*", ePatternBasic);
MY_REGEX_TEST("\\*blort", "\\*blort", ePatternBasic);
/* simple quoting */
MY_REGEX_TEST("\\[", "\\[", ePatternBasic);
MY_REGEX_TEST("\\]", "\\]", ePatternBasic);
MY_REGEX_TEST("\\?", "?", ePatternBasic);
MY_REGEX_TEST("\\{", "\\{", ePatternBasic);
MY_REGEX_TEST("\\}", "\\}", ePatternBasic);
MY_REGEX_TEST("\\,", ",", ePatternBasic);
MY_REGEX_TEST("^", "\\^", ePatternBasic);
MY_REGEX_TEST("$", "\\$", ePatternBasic);
MY_REGEX_TEST(".", "\\.", ePatternBasic);
MY_REGEX_TEST("+", "\\+", ePatternBasic);
MY_REGEX_TEST("|", "\\|", ePatternBasic);
MY_REGEX_TEST("(", "\\(", ePatternBasic);
MY_REGEX_TEST(")", "\\)", ePatternBasic);
MY_REGEX_TEST("\\^", "\\^", ePatternBasic);
MY_REGEX_TEST("\\$", "\\$", ePatternBasic);
MY_REGEX_TEST("\\.", "\\.", ePatternBasic);
MY_REGEX_TEST("\\+", "\\+", ePatternBasic);
MY_REGEX_TEST("\\|", "\\|", ePatternBasic);
MY_REGEX_TEST("\\(", "\\(", ePatternBasic);
MY_REGEX_TEST("\\)", "\\)", ePatternBasic);
/* simple character class tests */
MY_REGEX_TEST("[blort]", "[blort]", ePatternRegex);
MY_REGEX_FAIL_TEST("[blort");
MY_REGEX_FAIL_TEST("b[lort");
MY_REGEX_FAIL_TEST("blort[");
MY_REGEX_FAIL_TEST("blort]");
MY_REGEX_FAIL_TEST("blo]rt");
MY_REGEX_FAIL_TEST("]blort");
MY_REGEX_TEST("b[lor]t", "b[lor]t", ePatternRegex);
/* simple alternation tests */
MY_REGEX_TEST("{alpha,beta}", "(alpha|beta)", ePatternRegex);
MY_REGEX_TEST("baz{alpha,beta}blort", "baz(alpha|beta)blort", ePatternRegex);
MY_REGEX_FAIL_TEST("{beta}");
MY_REGEX_FAIL_TEST("biz{beta");
MY_REGEX_FAIL_TEST("biz}beta");
MY_REGEX_FAIL_TEST("biz{be,ta");
MY_REGEX_FAIL_TEST("biz,be}ta");
MY_REGEX_FAIL_TEST("biz{}beta");
/* nested alternations */
MY_REGEX_TEST("{{alpha,blort,nested},beta}", "((alpha|blort|nested)|beta)", ePatternRegex);
MY_REGEX_FAIL_TEST("{{alpha,blort,nested}beta}");
MY_REGEX_TEST("{{alpha,{blort,nested}},beta}", "((alpha|(blort|nested))|beta)", ePatternRegex);
MY_REGEX_TEST("{{alpha,alpha{blort,nested}}beta,beta}", "((alpha|alpha(blort|nested))beta|beta)", ePatternRegex);
MY_REGEX_TEST("{{alpha,alpha{blort,nested}}beta,beta}", "((alpha|alpha(blort|nested))beta|beta)", ePatternRegex);
MY_REGEX_TEST("{{a,b{c,d}}e,{f,{g,{h{i,j,k},l}m},n}o}", "((a|b(c|d))e|(f|(g|(h(i|j|k)|l)m)|n)o)", ePatternRegex);
/* max nesting depth = 50 */
MY_REGEX_TEST("{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a,b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b}b,blort}",
"(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)|b)b|blort)", ePatternRegex);
MY_REGEX_FAIL_TEST("{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a{a,b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b},b}b,blort}");
/* simple single char */
MY_REGEX_TEST("blor?t", "blor[^/\\x00]t", ePatternRegex);
/* simple globbing */
MY_REGEX_TEST("/*", "/[^/\\x00][^/\\x00]*", ePatternRegex);
MY_REGEX_TEST("/blort/*", "/blort/[^/\\x00][^/\\x00]*", ePatternRegex);
MY_REGEX_TEST("/*/blort", "/[^/\\x00][^/\\x00]*/blort", ePatternRegex);
MY_REGEX_TEST("/*/", "/[^/\\x00][^/\\x00]*/", ePatternRegex);
MY_REGEX_TEST("/**", "/[^/\\x00][^\\x00]*", ePatternTailGlob);
MY_REGEX_TEST("/blort/**", "/blort/[^/\\x00][^\\x00]*", ePatternTailGlob);
MY_REGEX_TEST("/**/blort", "/[^/\\x00][^\\x00]*/blort", ePatternRegex);
MY_REGEX_TEST("/**/", "/[^/\\x00][^\\x00]*/", ePatternRegex);
/* more complicated quoting */
MY_REGEX_FAIL_TEST("\\\\[");
MY_REGEX_FAIL_TEST("\\\\]");
MY_REGEX_TEST("\\\\?", "\\\\[^/\\x00]", ePatternRegex);
MY_REGEX_FAIL_TEST("\\\\{");
MY_REGEX_FAIL_TEST("\\\\}");
MY_REGEX_TEST("\\\\,", "\\\\,", ePatternBasic);
MY_REGEX_TEST("\\\\^", "\\\\\\^", ePatternBasic);
MY_REGEX_TEST("\\\\$", "\\\\\\$", ePatternBasic);
MY_REGEX_TEST("\\\\.", "\\\\\\.", ePatternBasic);
MY_REGEX_TEST("\\\\+", "\\\\\\+", ePatternBasic);
MY_REGEX_TEST("\\\\|", "\\\\\\|", ePatternBasic);
MY_REGEX_TEST("\\\\(", "\\\\\\(", ePatternBasic);
MY_REGEX_TEST("\\\\)", "\\\\\\)", ePatternBasic);
MY_REGEX_TEST("\\000", "\\000", ePatternBasic);
MY_REGEX_TEST("\\x00", "\\x00", ePatternBasic);
MY_REGEX_TEST("\\d000", "\\d000", ePatternBasic);
/* more complicated character class tests */
/* -- embedded alternations */
MY_REGEX_TEST("b[\\lor]t", "b[lor]t", ePatternRegex);
MY_REGEX_TEST("b[{a,b}]t", "b[{a,b}]t", ePatternRegex);
MY_REGEX_TEST("{alpha,b[{a,b}]t,gamma}", "(alpha|b[{a,b}]t|gamma)", ePatternRegex);
/* pcre will ignore the '\' before '\{', but it should be okay
* for us to pass this on to pcre as '\{' */
MY_REGEX_TEST("b[\\{a,b\\}]t", "b[\\{a,b\\}]t", ePatternRegex);
MY_REGEX_TEST("{alpha,b[\\{a,b\\}]t,gamma}", "(alpha|b[\\{a,b\\}]t|gamma)", ePatternRegex);
MY_REGEX_TEST("{alpha,b[\\{a\\,b\\}]t,gamma}", "(alpha|b[\\{a\\,b\\}]t|gamma)", ePatternRegex);
/* test different globbing behavior conversion */
MY_REGEX_EXT_TEST(glob_default, "/foo/**", "/foo/[^/\\x00][^\\x00]*", ePatternTailGlob);
MY_REGEX_EXT_TEST(glob_null, "/foo/**", "/foo/[^/].*", ePatternTailGlob);
MY_REGEX_EXT_TEST(glob_default, "/foo/f**", "/foo/f[^\\x00]*", ePatternTailGlob);
MY_REGEX_EXT_TEST(glob_null, "/foo/f**", "/foo/f.*", ePatternTailGlob);
MY_REGEX_EXT_TEST(glob_default, "/foo/*", "/foo/[^/\\x00][^/\\x00]*", ePatternRegex);
MY_REGEX_EXT_TEST(glob_null, "/foo/*", "/foo/[^/][^/]*", ePatternRegex);
MY_REGEX_EXT_TEST(glob_default, "/foo/f*", "/foo/f[^/\\x00]*", ePatternRegex);
MY_REGEX_EXT_TEST(glob_null, "/foo/f*", "/foo/f[^/]*", ePatternRegex);
MY_REGEX_EXT_TEST(glob_default, "/foo/**.ext", "/foo/[^\\x00]*\\.ext", ePatternRegex);
MY_REGEX_EXT_TEST(glob_null, "/foo/**.ext", "/foo/.*\\.ext", ePatternRegex);
MY_REGEX_EXT_TEST(glob_default, "/foo/f**.ext", "/foo/f[^\\x00]*\\.ext", ePatternRegex);
MY_REGEX_EXT_TEST(glob_null, "/foo/f**.ext", "/foo/f.*\\.ext", ePatternRegex);
MY_REGEX_EXT_TEST(glob_default, "/foo/*.ext", "/foo/[^/\\x00]*\\.ext", ePatternRegex);
MY_REGEX_EXT_TEST(glob_null, "/foo/*.ext", "/foo/[^/]*\\.ext", ePatternRegex);
MY_REGEX_EXT_TEST(glob_default, "/foo/f*.ext", "/foo/f[^/\\x00]*\\.ext", ePatternRegex);
MY_REGEX_EXT_TEST(glob_null, "/foo/f*.ext", "/foo/f[^/]*\\.ext", ePatternRegex);
return rc;
}
int main(void)
{
int rc = 0;
int retval;
retval = test_filter_slashes();
if (retval != 0)
rc = retval;
retval = test_aaregex_to_pcre();
if (retval != 0)
rc = retval;
return rc;
}
#endif /* UNIT_TEST */