Commit graph

181 commits

Author SHA1 Message Date
Ondrej Mosnacek
3d32fc24d6 libsepol: remove leftovers of cil_mem_error_handler
Commit 4459d635b8 ("libsepol: Remove cil_mem_error_handler() function
pointer") replaced cil_mem_error_handler usage with inline contents of
the default handler. However, it left over the header declaration and
two callers. Convert these as well and remove the header declaration.

This also fixes a build failure with -fno-common.

Fixes: 4459d635b8 ("libsepol: Remove cil_mem_error_handler() function pointer")
Signed-off-by: Ondrej Mosnacek <omosnace@redhat.com>
2020-01-27 10:51:18 -05:00
Ondrej Mosnacek
a96e8c59ec libsepol: fix CIL_KEY_* build errors with -fno-common
GCC 10 comes with -fno-common enabled by default - fix the CIL_KEY_*
global variables to be defined only once in cil.c and declared in the
header file correctly with the 'extern' keyword, so that other units
including the file don't generate duplicate definitions.

Signed-off-by: Ondrej Mosnacek <omosnace@redhat.com>
2020-01-27 10:51:14 -05:00
James Carter
11264556d8 libsepol/cil: Fix bug in cil_copy_avrule() in extended permission handling
When copying an avrule with extended permissions (permx) in
cil_copy_avrule(), the check for a named permx checks the new permx
instead of the old one, so the check will always fail. This leads to a
segfault when trying to copy a named permx because there will be an
attempt to copy the nonexistent permx struct instead of the name of
the named permx.

Check whether the original is a named permx instead of the new one.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2020-01-27 09:15:01 +01:00
James Carter
c7527bdb60 libsepol/cil: Report disabling an optional block only at high verbose levels
Since failing to resolve a statement in an optional block is normal,
only display messages about the statement failing to resolve and the
optional block being disabled at the highest verbosity level.

These messages are now only at log level CIL_INFO instead of CIL_WARN.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2019-11-06 12:32:06 -05:00
Nicolas Iooss
b550c0e202
Fix many misspellings
Use codespell (https://github.com/codespell-project/codespell) in order
to find many common misspellings that are present in English texts.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2019-09-18 22:47:35 +02:00
Nicolas Iooss
dddd28e90b libsepol/cil: do not dereference perm_value_to_cil when it has not been allocated
When one of the first allocations of cil_binary_create_allocated_pdb()
fails, the exit label dereferences the items of array perm_value_to_cil
even though it could be still NULL.

This issue has been found using clang's static analyzer:
https://327-118970575-gh.circle-artifacts.com/0/output-scan-build/2019-08-05-203459-6149-1/report-febf85.html#EndPath

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2019-09-17 10:38:45 -04:00
James Carter
4459d635b8 libsepol: Remove cil_mem_error_handler() function pointer
As reported by Nicolas Iooss (nicolas.iooss@m4x.org), static analyzers
have problems understanding that the default memory error handler does
not return since it is called through the cil_mem_error_handler()
function pointer. This results in a number of false positive warnings
about null pointer dereferencing.

Since the ability to set the cil_mem_error_handler() is only through
the function cil_set_mem_error_handler() which is never used and whose
definition is not in any header file, remove that function, remove the
use of cil_mem_error_handler() and directly in-line the contents of
the default handler, cil_default_mem_error_handler().

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2019-09-17 10:38:20 -04:00
James Carter
dc4e54126b libsepol: Make an unknown permission an error in CIL
This patch is loosely based on a patch by Yuli Khodorkovskiy
<yuli@crunchydata.com> from June 13th, 2019.

Since any permission used in the policy should be defined, CIL
should return an error if it cannot resolve a permission used
in a policy. This was the original behavior of CIL.

The behavior was changed over three commits from July to November
2016 (See commits 46e157b47, da51020d6, and 2eefb20d8). The change
was motivated by Fedora trying to remove permissions from its
policy that were never upstreamed (ex/ process ptrace_child and
capability2 compromise_kernel). Local or third party modules
compiled with those permissions would break policy updates.

After three years it seems unlikely that we need to worry about
those local and third party modules and it is time for CIL to
give an error like it should.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2019-09-17 10:38:09 -04:00
Joshua Brindle
9ba35fe8c2 Add default_range glblub support
Policy developers can set a default_range default to glblub and
computed contexts will be the intersection of the ranges of the
source and target contexts. This can be used by MLS userspace
object managers to find the range of clearances that two contexts
have in common. An example usage is computing a transition between
the network context and the context of a user logging into an MLS
application.

For example, one can add a default with
this cil:

(defaultrange db_table glblub)

or in te (base module only):

default_range db_table glblub;

and then test using the compute_create utility:

$ ./compute_create system_u:system_r:kernel_t:s0:c1,c2,c5-s0:c1.c20 system_u:system_r:kernel_t:s0:c0.c20-s0:c0.c36 db_table
system_u:object_r:kernel_t:s0:c1,c2,c5-s0:c1.c20

Some example range transitions are:

User Permitted Range | Network Device Label | Computed Label
---------------------|----------------------|----------------
s0-s1:c0.c12         | s0                   | s0
s0-s1:c0.c12         | s0-s1:c0.c1023       | s0-s1:c0.c12
s0-s4:c0.c512        | s1-s1:c0.c1023       | s1-s1:c0.c512
s0-s15:c0,c2         | s4-s6:c0.c128        | s4-s6:c0,c2
s0-s4                | s2-s6                | s2-s4
s0-s4                | s5-s8                | INVALID
s5-s8                | s0-s4                | INVALID

Signed-off-by: Joshua Brindle <joshua.brindle@crunchydata.com>
2019-09-10 12:30:29 -04:00
Mike Palmiotto
544cc7957b libsepol/cil: fix mlsconstrain segfault
Installing a cil module with invalid mlsconstrain syntax currently
results in a segfault. In the following module, the right-hand side of
the second operand of the OR is a list (mlstrustedobject):

$ cat test.cil
(class test (foo) )
(classorder (unordered test))

(mlsconstrain (test (foo))
	(or
		(dom h1 h2)
		(eq t2 (mlstrustedobject))
	)
)

$ sudo semodule -i test.cil
zsh: segmentation fault  sudo semodule -i test.cil

This syntax is invalid and should error accordingly, rather than
segfaulting. This patch provides this syntax error for the same module:

$ sudo semodule -i test.cil
t1, t2, r1, r2, u1, u2 cannot be used on the left side with a list on the right side
Bad expression tree for constraint
Bad constrain declaration at /var/lib/selinux/mls/tmp/modules/400/test/cil:4
semodule:  Failed!

Signed-off-by: Mike Palmiotto <mike.palmiotto@crunchydata.com>
2019-06-19 09:01:23 -07:00
Richard Haines
159d5063d3 libsepol/cil: Allow validatetrans rules to be resolved
When validatetrans rule is in CIL policy it errors with:
u3, r3, and t3 can only be used with mlsvalidatetrans rules

Will now resolve these examples:
(validatetrans binder (and (and (eq t1 t1_t) (eq t2 t2_t)) (eq t3 t3_t)))
(mlsvalidatetrans file (and (and (eq t1 t1_t) (eq t2 t2_t))
    (and (eq t3 t3_t) (domby h1 h2))))

Signed-off-by: Richard Haines <richard_c_haines@btinternet.com>
2019-05-21 13:49:38 -04:00
Ondrej Mosnacek
3e506bda3b libsepol: add ebitmap_for_each_set_bit macro
Most of the users of ebitmap_for_each_bit() macro only care for the set
bits, so introduce a new ebitmap_for_each_positive_bit() macro that
skips the unset bits. Replace uses of ebitmap_for_each_bit() with the
new macro where appropriate.

Signed-off-by: Ondrej Mosnacek <omosnace@redhat.com>
2019-05-20 14:00:32 -04:00
Nicolas Iooss
913613da66
libsepol/cil: silence static analyser's use-after-free warning
clang's static analyze reports a use-after-free in
__cil_expr_to_string(), when __cil_expr_to_string_helper() does not
modify its third parameter (variable s1 here) in this loop:

    for (curr = curr->next; curr; curr = curr->next) {
        __cil_expr_to_string_helper(curr, flavor, &s1);
        cil_asprintf(&c2, "%s %s", c1, s1);
        free(c1);
        free(s1);
        c1 = c2;
    }

Silence this warning by making sure s1 is always NULL at the beginning
of every iteration of the loop.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2019-02-10 19:32:15 +01:00
James Carter
4ba87e3d2c libsepol: Fix RESOURCE_LEAK defects reported by coverity scan
These were reported by Petr Lautrbach (plautrba@redhat.com) and this
patch was based on his patch with only a few changes.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2019-02-05 09:56:34 +01:00
Nicolas Iooss
45f0525b8e libsepol/cil: use a colon instead of a semicolon to report rc
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2018-06-15 09:03:04 -04:00
Nicolas Iooss
57e1ab328c
libsepol: cil: silence clang analyzer false positive
In cil_tree_print_expr(), "rc < 0" is equivalent to "rc != 0" but
clang's static analyzer does not know about this. Help it.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2018-05-30 21:59:52 +02:00
Stephen Smalley
3ca8762efd libsepol: cil: prevent stack buffer overflow in cil_expr_to_string
Fix the test to prevent overflowing the stack buffer for
boolean expressions.

Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
2018-05-09 11:22:46 -04:00
James Carter
4ba19b541d libsepol/cil: Improve processing of context rules
Improve the processing of netifcon, genfscon, ibpkeycon, ibendportcon,
portcon, nodecon, fsuse, filecon, iomemcon, ioportcon, pcidevicecon,
and devicetreecon rules.

If the multiple-decls option is not used then report errors if duplicate
context rules are found. If it is used then remove duplicate context rules
and report errors when two rules are identical except for the context.

This also changes the ordering of portcon and filecon rules. The protocol
of portcon rules will be compared if the port numbers are the same and the
path strings of filecon rules will be compared if the number of meta
characters, the stem length, string length and file types are the same.

Based on an initial patch by Pierre-Hugues Husson (phh@phh.me)

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2018-03-29 15:53:18 -04:00
Tri Vo
ea8d689b53 Resolve conflicts in expandattribute.
This commit resolves conflicts in values of expandattribute statements
in policy language and expandtypeattribute in CIL.

For example, these statements resolve to false in policy language:
 expandattribute hal_audio true;
 expandattribute hal_audio false;

Similarly, in CIL these also resolve to false.
 (expandtypeattribute (hal_audio) true)
 (expandtypeattribute (hal_audio) false)

A warning will be issued on this conflict.

Motivation
When Android combines multiple .cil files from system.img and vendor.img
it's possible to have conflicting expandattribute statements.

This change deals with this scenario by resolving the value of the
corresponding expandtypeattribute to false. The rationale behind this
override is that true is used for reduce run-time lookups, while
false is used for tests which must pass.

Signed-off-by: Tri Vo <trong@android.com>
Acked-by: Jeff Vander Stoep <jeffv@google.com>
Acked-by: William Roberts <william.c.roberts@intel.com>
Acked-by: James Carter <jwcart2@tycho.nsa.gov>
2018-03-26 12:29:37 -07:00
Richard Haines via Selinux
cf0ab12414 selinux: Add support for the SCTP portcon keyword
Update libsepol, checkpolicy and the CIL compiler to support the SCTP
portcon keyword.

Signed-off-by: Richard Haines <richard_c_haines@btinternet.com>
2018-03-19 12:34:29 -04:00
Nicolas Iooss
2bd82070ef libsepol: cil: show an error when cil_expr_to_string() fails
cil_tree_print_expr() calls cil_expr_to_string() in order to compute a
string expression into expr_str. If this function fails, expr_str is
left unitialized but its value is dereferenced with:

    cil_log(CIL_INFO, "%s)", expr_str);

Prevent such an issue by checking cil_expr_to_string()'s return value
before using expr_str.

This issue has been found with clang's static analyzer.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2018-03-08 14:36:32 -05:00
James Carter
2d49a4b41c libsepol/cil: Create new keep field for type attribute sets
Daniel Cashman <dcashman@android.com> discovered the following:
When using cil_db multiple_decls, the different cil_attribute nodes
all point to the same underlying cil_attribute struct.  This leads
to problems, though, when modifying the used value in the struct.
__cil_post_db_attr() changes the value of the field to based on
the output of cil_typeattribute_used(), for use later in
cil_typeattribute_to_policydb and cil_typeattribute_to_bitmap, but
due to the multiple declarations, cil_typeattribute_used() could be
called again by a second node.  In this second call, the value used
is the modifed value of CIL_TRUE or CIL_FALSE, not the flags actually
needed. This could result in the field being reset again, to an
incorrect CIL_FALSE value.

Add the field "keep" to struct cil_typeattributeset, set its value
using cil_typeattribute_used(), and use it when determining whether
the attribute is to be kept or if it should be expanded.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2017-11-22 11:49:19 -05:00
Nicolas Iooss
13e5fa3b6b libsepol/cil: drop wrong unused attribute
cil_gen_node() has been using its argument "db" since commit
fafe4c212b ("libsepol: cil: Add ability to redeclare
types[attributes]"). Drop attribute "unused" on this argument.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2017-09-05 12:37:23 -04:00
Nicolas Iooss
12f3ef8280 libsepol/cil: fix -Wwrite-strings warning
cil_defaults_to_policy() defines its third argument as non-const "char
*kind" even though it is called with literal strings. This makes gcc
report the following warning when compiling with -Wwrite-strings:

    ../cil/src/cil_policy.c: In function ‘cil_gen_policy’:
    ../cil/src/cil_policy.c:1931:60: error: passing argument 3 of
    ‘cil_defaults_to_policy’ discards ‘const’ qualifier from pointer
    target type [-Werror=discarded-qualifiers]

      cil_defaults_to_policy(out, lists[CIL_LIST_DEFAULT_USER],
                             "default_user");
                             ^~~~~~~~~~~~~~

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2017-09-05 12:37:20 -04:00
Nicolas Iooss
3ab3a218f2 libsepol/cil: __cil_post_db_neverallow_attr_helper() does not use extra_args
Since commit 67b410e80f ("libsepol/cil: Keep attributes used by
generated attributes in neverallow rules") gcc reports the following
warning when building libsepol:

    ../cil/src/cil_post.c: In function
    ‘__cil_post_db_neverallow_attr_helper’:
    ../cil/src/cil_post.c:1322:17: error: unused variable ‘db’
    [-Werror=unused-variable]
      struct cil_db *db = extra_args;
                     ^~

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2017-09-05 12:37:16 -04:00
James Carter
67b410e80f libsepol/cil: Keep attributes used by generated attributes in neverallow rules
In order to reduce policy size, CIL removes attributes that are not used
by a policy rule in the generated binary policy. However, CIL keeps
attributes used by neverallow rules (which are checked at compile time
and not in the binary policy) even if the attribute is not used anywhere
else in the policy. This behavior is useful to Google who pulls neverallow
rules out of the original policy.conf for compatibility testing, but
converts the policy.conf to CIL and uses the CIL compiler to generate
policy. Without this behavior, the generated binary policy might not have
an attribute referred to by one of the neverallow rules used for testing.

The one exception to this behavior is for attributes generated in
module_to_cil (these have an "_typeattr_" in the middle of their name).
Since these attributes are only created because CIL does not allow a
type expression in an AV rule, they are removed if they only appear in
a neverallow rule (which is the case for most of them) or if the
option to expand generated attributes (-G or --expand-generated) is
specified for secilc when compiling the policy.

Removing generated attributes causes a problem, however, if the type
expression that the generated attribute is replacing uses an attribute
that is removed. In this case, the original neverallow rule will refer
to an attribute that does not exist in the generated binary policy.

Now any non-generated attribute used in a typeattributeset rule for a
generated attribute which is used in a neverallow rule will be treated
like it was used in a neverallow rule.

This does not change the behavior of an expandtypeattribute rule for
the attribute. That rule, if it exists, will take precedence.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2017-08-31 14:44:59 -04:00
Dan Cashman
fafe4c212b libsepol: cil: Add ability to redeclare types[attributes]
Modify cil_gen_node() to check to see if the cil_db supports multiple
declarations, and if so, to check whether or not the
repeated symbol is eligible to share the existing, already-stored datum. The
only types considered so far are CIL_TYPE and CIL_TYPEATTRIBUTE, both of
which intall empty datums during AST building, so they automatically return
true.

Test: Build policy with multilpe type and attribute declarations, and
without. Policies are binary-identical.

Signed-off-by: Dan Cashman <dcashman@android.com>
Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2017-08-31 14:42:25 -04:00
Jan Zarsky
1346746d82 libsepol: reset pointer after free
In cil_strpool_destroy(), cil_strpool_tab is freed but it is not reset to NULL.
When cil_strpool_init() is called again it assumes that cil_strpool_tab was
already initialized. Other functions then work with invalid data.

Signed-off-by: Jan Zarsky <jzarsky@redhat.com>
2017-08-28 15:50:13 -04:00
Dan Cashman
7803c8ca99 libsepol: cil: enable cpp compilation of cil.h.
Signed-off-by: Daniel Cashman <dcashman@google.com>
2017-07-26 13:24:22 -04:00
James Carter
5a553e8287 libsepol/cil: Fix bugs when writing policy.conf rules
The typebounds rules should end with a ";".

The netifcon and nodecon rules should not end with a ";".

The default rules are missing a "_". They should be "default_user",
"default_role" and "default_type".

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2017-06-15 13:21:53 -04:00
Richard Haines
c8e135ba22 libsepol/cil: ibendportcon fails to resolve in CIL policy
Fix named ibendportcon context not resolving correctly.

Signed-off-by: Richard Haines <richard_c_haines@btinternet.com>
2017-06-12 11:13:25 -04:00
James Carter
738db6077b libsepol/cil: Fix bug in cil_reset_ibpkeycon()
Nicolas Iooss <nicolas.iooss@m4x.org> discovered with clang's static
analyzer that cil_reset_ibpkeycon() was checking that ibpkeycon->context
was NULL and then passing the NULL value to cil_reset_context() which
expected a non-NULL argument.

Instead, cil_reset_ibpkeycon() should check if ibpkeycon->context_str
is NULL. If it is non-NULL then the context field points to a named
context that was created elsewhere and it will be reset there, but if
the context_str field is NULL, then the context is not named and needs
to be reset.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2017-06-05 11:30:14 -04:00
Steve Lawrence
0be11881d1 libsepol/cil: fix error check in new cil_resolve_name
This prevented cil_resolve_name() from returning an actual thing when a
name resolved to an alias. This appears to have only affected resolution
dealing with sensitivity and category aliases. Type aliases were not
affected since places that dealt with types handled type aliases
specifically and did not rely on this behavior from cil_resolve_name().

Signed-off-by: Steve Lawrence <slawrence@tresys.com>
2017-06-02 12:18:16 -04:00
Stephen Smalley
e41ae676c2 libsepol,libsemanage,libselinux: Fix fallthrough warnings from gcc 7
https://developers.redhat.com/blog/2017/03/10/wimplicit-fallthrough-in-gcc-7/

Fixes the following warnings by annotating with a /* FALLTHRU */ comment.
Unfortunately, the __attribute__ ((fallthrough)); approach does not appear
to work with older compilers.

../cil/src/cil_parser.c: In function ‘cil_parser’:
../cil/src/cil_parser.c:253:14: warning: this statement may fall through [-Wimplicit-fallthrough=]
    tok.value = tok.value+1;
    ~~~~~~~~~~^~~~~~~~~~~~~
../cil/src/cil_parser.c:254:3: note: here
   case SYMBOL:
   ^~~~
../cil/src/cil_parser.c:275:7: warning: this statement may fall through [-Wimplicit-fallthrough=]
    if (tok.type != END_OF_FILE) {
       ^
../cil/src/cil_parser.c:279:3: note: here
   case END_OF_FILE:
   ^~~~

../cil/src/cil_post.c: In function ‘cil_post_fc_fill_data’:
../cil/src/cil_post.c:104:5: warning: this statement may fall through [-Wimplicit-fallthrough=]
    c++;
    ~^~
../cil/src/cil_post.c:105:3: note: here
   default:
   ^~~~~~~

regex.c: In function ‘regex_format_error’:
regex.c:541:10: warning: this statement may fall through [-Wimplicit-fallthrough=]
   *ptr++ = '.';
   ~~~~~~~^~~~~
regex.c:542:2: note: here
  case 3:
  ^~~~
regex.c:543:10: warning: this statement may fall through [-Wimplicit-fallthrough=]
   *ptr++ = '.';
   ~~~~~~~^~~~~
regex.c:544:2: note: here
  case 2:
  ^~~~
regex.c:545:10: warning: this statement may fall through [-Wimplicit-fallthrough=]
   *ptr++ = '.';
   ~~~~~~~^~~~~
regex.c:546:2: note: here
  case 1:
  ^~~~
regex.c: In function ‘regex_format_error’:
regex.c:541:10: warning: this statement may fall through [-Wimplicit-fallthrough=]
   *ptr++ = '.';
   ~~~~~~~^~~~~
regex.c:542:2: note: here
  case 3:
  ^~~~
regex.c:543:10: warning: this statement may fall through [-Wimplicit-fallthrough=]
   *ptr++ = '.';
   ~~~~~~~^~~~~
regex.c:544:2: note: here
  case 2:
  ^~~~
regex.c:545:10: warning: this statement may fall through [-Wimplicit-fallthrough=]
   *ptr++ = '.';
   ~~~~~~~^~~~~
regex.c:546:2: note: here
  case 1:
  ^~~~

modules.c: In function ‘semanage_module_get_path’:
modules.c:602:7: warning: this statement may fall through [-Wimplicit-fallthrough=]
    if (file == NULL) file = "hll";
       ^
modules.c:603:3: note: here
   case SEMANAGE_MODULE_PATH_CIL:
   ^~~~
modules.c:604:7: warning: this statement may fall through [-Wimplicit-fallthrough=]
    if (file == NULL) file = "cil";
       ^
modules.c:605:3: note: here
   case SEMANAGE_MODULE_PATH_LANG_EXT:
   ^~~~

Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
2017-06-01 13:35:45 -04:00
James Carter
800f6b2a89 libsepol/cil: Remove uneeded null checks of unused parameters
Issue reported by Nicola Iooss <nicolas.iooss@m4x.org>

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2017-06-01 12:43:31 -04:00
Steve Lawrence
e501d3b6e8 libsepol/cil: better error message with duplicate aliases + support aliases to aliases
- If two typealiasactual statements exist for the same typealias, we get
  a confusing error message mentioning that the actual arguement is not
  an alias, which is clearly allowed. This poor error occurs because the
  first typealiasactual statement resolves correctly, but when we
  resolve the alias in the second typealiasactual statement,
  cil_resolve_name tries to return what the alias points to, which is a
  type and not the required typealias. This patch creates a new function
  that does not perform the alias to actual conversion, used when we
  want an alias and not what the alias points to. This allows the
  cil_resolve_aliasactual to continue and reach the check for duplicate
  typealiasactual statements, resulting in a more meaningful error
  message.

- Add back support for aliases to aliases (broken in 5c9fcb02e),
  while still ensuring that aliases point to either the correct actual
  flavor or alias flavor, and not something else like a typeattribute.

Signed-off-by: Steve Lawrence <slawrence@tresys.com>
2017-06-01 12:17:29 -04:00
Steve Lawrence
5c9fcb02ec libsepol/cil: fix aliasactual resolution errors
- Set rc to SEPOL_ERR if the alias part of an aliasactual statement
  does not resolve to the correct alias flavor (e.g. typealias, senalias, catalias)
- Add an error check if the actual part of an aliasactual statement
  does not resolve to the correct actual flavor (type, sens, cat)

Signed-off-by: Steve Lawrence <slawrence@tresys.com>
2017-05-31 12:34:23 -04:00
Daniel Jurgens
28663ff135 libsepol: Add IB end port handling to CIL
Add IB end port parsing, symbol table management, and policy generation
to CIL.

Signed-off-by: Daniel Jurgens <danielj@mellanox.com>
2017-05-23 16:20:55 -04:00
Daniel Jurgens
e564f7b5bd libsepol: Add Infiniband Pkey handling to CIL
Add Infiniband pkey parsing, symbol table management, and policy
generation to CIL.

Signed-off-by: Daniel Jurgens <danielj@mellanox.com>
2017-05-23 16:20:54 -04:00
Nicolas Iooss
4a0fab43cb libsepol/cil: do not use an uninitialized value in __cil_fqn_qualify_blocks
In __cil_fqn_qualify_blocks(), when newlen >= CIL_MAX_NAME_LENGTH,
cil_tree_log() is called with child_args.node as argument but this value
has not been initialized yet. Use local variable node instead, which is
initialized early enough in the function.

This issue has been found using clang's static analyzer.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2017-05-15 16:36:49 -04:00
Jeff Vander Stoep
1089665e31 Add attribute expansion options
This commit adds attribute expansion statements to the policy
language allowing compiler defaults to be overridden.

Always expands an attribute example:
expandattribute { foo } true;
CIL example:
(expandtypeattribute (foo) true)

Never expand an attribute example:
expandattribute { bar } false;
CIL example:
(expandtypeattribute (bar) false)

Adding the annotations directly to policy was chosen over other
methods as it is consistent with how targeted runtime optimizations
are specified in other languages. For example, in C the "inline"
command.

Motivation

expandattribute true:
Android has been moving away from a monolithic policy binary to
a two part split policy representing the Android platform and the
underlying vendor-provided hardware interface. The goal is a stable
API allowing these two parts to be updated independently of each
other. Attributes provide an important mechanism for compatibility.
For example, when the vendor provides a HAL for the platform,
permissions needed by clients of the HAL can be granted to an
attribute. Clients need only be assigned the attribute and do not
need to be aware of the underlying types and permissions being
granted.

Inheriting permissions via attribute creates a convenient mechanism
for independence between vendor and platform policy, but results
in the creation of many attributes, and the potential for performance
issues when processes are clients of many HALs. [1] Annotating these
attributes for expansion at compile time allows us to retain the
compatibility benefits of using attributes without the performance
costs. [2]

expandattribute false:
Commit 0be23c3f15 added the capability to aggresively remove unused
attributes. This is generally useful as too many attributes assigned
to a type results in lengthy policy look up times when there is a
cache miss. However, removing attributes can also result in loss of
information used in external tests. On Android, we're considering
stripping neverallow rules from on-device policy. This is consistent
with the kernel policy binary which also did not contain neverallows.
Removing neverallow rules results in a 5-10% decrease in on-device
policy build and load and a policy size decrease of ~250k. Neverallow
rules are still asserted at build time and during device
certification (CTS). If neverallow rules are absent when secilc is
run, some attributes are being stripped from policy and neverallow
tests in CTS may be violated. [3] This change retains the aggressive
attribute stripping behavior but adds an override mechanism to
preserve attributes marked as necessary.

[1] https://github.com/SELinuxProject/cil/issues/9
[2] Annotating all HAL client attributes for expansion resulted in
    system_server's dropping from 19 attributes to 8. Because these
    attributes were not widely applied to other types, the final
    policy size change was negligible.
[3] data_file_type and service_manager_type are stripped from AOSP
    policy when using secilc's -G option. This impacts 11 neverallow
    tests in CTS.

Test: Build and boot Marlin with all hal_*_client attributes marked
    for expansion. Verify (using seinfo and sesearch) that permissions
    are correctly expanded from attributes to types.
Test: Mark types being stripped by secilc with "preserve" and verify
    that they are retained in policy and applied to the same types.

Signed-off-by: Jeff Vander Stoep <jeffv@google.com>
2017-05-09 12:09:46 -04:00
Nicolas Iooss
b63eb892f9 libsepol: cil: check cil_fill_list return value
cil_gen_default() and cil_gen_defaultrange() call cil_fill_list()
without checking its return value. If it failed, propagate the return
value to the caller.

This issue has been found using clang's static analyzer. It reported
"warning: Value stored to 'rc' is never read" four times.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2017-04-12 14:40:16 -04:00
James Carter
0be23c3f15 libsepol/cil: Add ability to expand some attributes in binary policy
Originally, all type attributes were expanded when building a binary
policy. As the policy grew, binary policy sizes became too large, so
changes were made to keep attributes in the binary policy to minimize
policy size.

Keeping attributes works well as long as each type does not have too
many attributes. If an access check fails for types t1 and t2, then
additional checks must be made for every attribute that t1 is a member
of against t2 and all the attributes that t2 is a member of. This is
O(n*m) behavior and there are cases now where this is becoming a
performance issue.

Attributes are more aggressively removed than before. An attribute
will now be removed if it only appears in rules where attributes are
always expanded (typetransition, typechange, typemember, roletransition,
rangetransition, roletype, and AV Rules with self).

Attributes that are used in constraints are always kept because the
attribute name is stored for debugging purposes in the binary policy.

Attributes that are used in neverallow rules, but not in other AV rules,
will be kept unless the attribute is auto-generated.

Attributes that are only used in AV rules other than neverallow rules
are kept unless the number of types assigned to them is less than the
value of attrs_expand_size in the CIL db. The default is 1, which means
that any attribute that has no types assigned to it will be expanded (and
the rule removed from the policy), which is CIL's current behavior. The
value can be set using the function cil_set_attrs_expand_size().

Auto-generated attributes that are used only in neverallow rules are
always expanded. The rest are kept by default, but if the value of
attrs_expand_generated in the CIL db is set to true, they will be
expanded. The function cil_set_attrs_expand_generated() can be used
to set the value.

When creating the binary policy, CIL will expand all attributes that
are being removed and it will expand all attributes with less members
than the value specified by attrs_expand_size. So even if an attribute
is used in a constraint or neverallow and the attribute itself will be
included in the binary policy, it will be expanded when writing AV
rules if it has less members than attrs_expand_size.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2017-04-12 14:33:49 -04:00
James Carter
af0ce03ec7 libsepol/cil: Add hexadecimal support for Xen ioportcon statements
Add hexadecimal support for Xen ioportcon statements which was
left out of commit c408c70.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2017-03-28 13:33:05 -04:00
James Carter
da2f2316a3 libsepol/cil: Use hexadecimal numbers when writing Xen rules
When writing a policy.conf file from CIL source, use hexadecimal
numbers in ioportcon, iomemcon, and pcidevicecon rules.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2017-03-21 14:22:42 -04:00
James Carter
c408c70b0a libsepol/cil: Allow hexadecimal numbers in Xen context rules
Allow the use of hexadecimal numbers in iomemcon, ioportcon, and
pcidevicecon statements. The use of hexadecimal numbers is often
the natural choice for these rules.

A zero base is now passed to strtol() and strtoull() which will
assume base 16 if the string has a prefix of "0x", base 8 if the
string starts with "0", and base 10 otherwise.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2017-03-21 14:22:34 -04:00
Nicolas Iooss
6707526f1f libsepol/cil: avoid freeing uninitialized values
cil_resolve_ast() begins by checking whether one of its parameters is
NULL and "goto exit;" when it is the case. As extra_args has not been
initialized there, this leads to calling cil_destroy_tree_node_stack(),
__cil_ordered_lists_destroy()... on garbage values.

In practise this cannot happen because cil_resolve_ast() is only called
by cil_compile() after cil_build_ast() succeeded. As the if condition
exists nonetheless, fix the body of the if block in order to silence a
warning reported by clang Static Analyzer.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2017-03-21 14:20:22 -04:00
Nicolas Iooss
0864814583 libsepol/cil: make reporting conflicting type transitions work
When compiling a CIL policy which defines conflicting type transitions,
secilc crashes when trying to format an error message with uninitialized
values. This is caused by __cil_typetransition_to_avtab() not
initializing the ..._str fields of its local variable "struct
cil_type_rule trans" before calling __cil_type_rule_to_avtab().

While at it, make the error report clearer about what is wrong by
showing the types and classes which got expanded in
__cil_type_rule_to_avtab(). Here is an example of the result:

    Conflicting type rules (scontext=testuser_emacs.subj
    tcontext=fs.tmpfs.fs tclass=dir
    result=users.generic_tmpfs.user_tmpfs_file),
    existing=emacs.tmpfs.user_tmpfs_file

    Expanded from type rule (scontext=ARG1 tcontext=fs tclass=ARG3
    result=ARG2)

Reported-By: Dominick Grift <dac.override@gmail.com>
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2017-03-21 14:20:17 -04:00
Nicolas Iooss
ddaf0afec7 libsepol/cil: do not dereference args before checking it was not null
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2017-03-01 10:42:23 -05:00
James Carter
a2d40aaeba libsepol/cil: Move initialization of bitmap in __cil_permx_to_bitmap()
Nicolas Iooss reports:
  When __cil_permx_to_bitmap() calls __cil_permx_str_to_int() on an
  invalid number, local variablt "bitmap" is left initialized when
  the function returns and its memory is leaked.

  This memory leak has been found by running clang's Address Sanitizer
  on a set of policies generated by American Fuzzy Lop.

Move the initialization of bitmap to right before ebitmap_set_bit()
and after the call to __cil_permx_str_to_int().

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2017-02-21 13:11:15 -05:00
Nicolas Iooss
95e5c103f3 libsepol/cil: free bitmaps in cil_level_equals()
cil_level_equals() builds two bitmap and compare them but does not
destroy them before returning the result.

This memory leak has been found by running clang's Address Sanitizer on
a set of policies generated by American Fuzzy Lop.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2017-02-21 13:09:49 -05:00
Nicolas Iooss
9feaf0380d libsepol/cil: do not leak left-hand side of an invalid constraint
__cil_fill_constraint_expr() does not destroy the list associated with
the first operand of a two-operand operation when the second operand is
invalid.

This memory leak can be reproduced with the following policy:

    (constrain (files (read))
        (not (or (and (eq t1 exec_t) (%q t2 bin_t)) (eq r1 r2))))

This memory leak has been found by running clang's Address Sanitizer on
a set of policies generated from secilc/test/policy.cil by American
Fuzzy Lop.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2017-02-21 13:09:44 -05:00
Nicolas Iooss
602385d70c libsepol/cil: free the first operand if the second one is invalid
When __cil_expr_to_bitmap() fails to parse the second operand of an
operation with two operands, it returns an error without destroying the
bitmap which has been created for the first operand. Fix this memory
leak.

This has been tested with the following policy:

    (class CLASS (PERM))
    (classorder (CLASS))
    (sid SID)
    (sidorder (SID))
    (user USER)
    (role ROLE)
    (type TYPE)
    (category CAT)
    (categoryorder (CAT))
    (sensitivity SENS)
    (sensitivityorder (SENS))
    (sensitivitycategory SENS (CAT))
    (allow TYPE self (CLASS (PERM)))
    (roletype ROLE TYPE)
    (userrole USER ROLE)
    (userlevel USER (SENS))
    (userrange USER ((SENS)(SENS (CAT))))
    (sidcontext SID (USER ROLE TYPE ((SENS)(SENS))))

    (permissionx ioctl_test (ioctl CLASS
        (and (range 0x1600 0x19FF) (.ot (range 0x1750 0x175F)))))

This memory leak has been found by running clang's Address Sanitizer on
a set of policies generated from secilc/test/policy.cil by American
Fuzzy Lop.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2017-02-21 13:09:39 -05:00
Nicolas Iooss
7fe9a7be31 libsepol/cil: use __cil_ordered_lists_destroy() to free unordered_classorder_lists
In cil_resolve_ast, unordered_classorder_lists is a list of
cil_ordered_list. It needs to be destroyed with
__cil_ordered_lists_destroy() to free all associated memory.

This has been tested with the following policy:

    (class CLASS1 ())
    (class CLASS2 ())
    (classorder (unordered CLASS1))
    (classorder (CLASS2))

This memory leak has been found by running clang's Address Sanitizer on
a set of policies generated by American Fuzzy Lop.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2017-02-21 13:09:22 -05:00
James Carter
9edcf28a04 libsepol/cil: Destroy cil_tree_node stacks when finished resolving AST
CIL uses separate cil_tree_node stacks for optionals and blocks to
check for statements not allowed in optionals or blocks and to know
which optional to disable when necessary. But these stacks were not
being destroyed when exiting cil_resolve_ast(). This is not a problem
normally because the stacks will be empty, but this is not the case
when exiting with an error.

Destroy both tree node stacks when exiting to ensure that they are
empty.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2017-02-17 10:53:52 -05:00
Nicolas Iooss
eeafde1351 libsepol/cil: fix type confusion in cil_copy_ast
When running secilc on the following CIL file, the program tries to free
the data associated with type X using cil_destroy_typeattribute():

    (macro sys_obj_type ((user ARG1)) (typeattribute X))

    (block B
        (type X)
        (call sys_obj_type (Y))
    )

By adding some printf statements to cil_typeattribute_init(),
cil_type_init() and cil_destroy_typeattribute(), the error message I get
when using gcc's address sanitizer is:

$ secilc -o /dev/null -f /dev/null test.cil -vvvvvv
creating TYPE 0x60400000dfd0
Parsing 2017-02-02_crashing_nulptrderef_cil.cil
Building AST from Parse Tree
creating TYPEATTR 0x60600000e420
creating TYPE 0x60400000df50
Destroying Parse Tree
Resolving AST
Failed to resolve call statement at 2017-02-02_crashing_nulptrderef_cil.cil:5
Problem at 2017-02-02_crashing_nulptrderef_cil.cil:5
Pass 8 of resolution failed
Failed to resolve ast
Failed to compile cildb: -2
Destroying TYPEATTR 0x60600000e420, types (nil) name X
Destroying TYPEATTR 0x60400000df50, types 0xbebebebe00000000 name X
ASAN:DEADLYSIGNAL
=================================================================
==30684==ERROR: AddressSanitizer: SEGV on unknown address
0x000000000000 (pc 0x7fc0539d114a bp 0x7ffc1fbcb300 sp
0x7ffc1fbcb2f0 T0)
    #0 0x7fc0539d1149 in ebitmap_destroy /usr/src/selinux/libsepol/src/ebitmap.c:356
    #1 0x7fc053b96201 in cil_destroy_typeattribute ../cil/src/cil_build_ast.c:2370
    #2 0x7fc053b42ea4 in cil_destroy_data ../cil/src/cil.c:616
    #3 0x7fc053c595bf in cil_tree_node_destroy ../cil/src/cil_tree.c:235
    #4 0x7fc053c59819 in cil_tree_children_destroy ../cil/src/cil_tree.c:201
    #5 0x7fc053c59958 in cil_tree_subtree_destroy ../cil/src/cil_tree.c:172
    #6 0x7fc053c59a27 in cil_tree_destroy ../cil/src/cil_tree.c:165
    #7 0x7fc053b44fd7 in cil_db_destroy ../cil/src/cil.c:299
    #8 0x4026a1 in main /usr/src/selinux/secilc/secilc.c:335
    #9 0x7fc0535e5290 in __libc_start_main (/usr/lib/libc.so.6+0x20290)
    #10 0x403af9 in _start (/usr/src/selinux/DESTDIR/usr/bin/secilc+0x403af9)

AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: SEGV /usr/src/selinux/libsepol/src/ebitmap.c:356 in ebitmap_destroy
==30684==ABORTING

When copying the AST tree in cil_resolve_call1(),
__cil_copy_node_helper() calls cil_copy_typeattribute() to grab type X
in the symbol table of block B, and creates a node with the data of X
but with CIL_TYPEATTRIBUTE flavor.

This example is a "type confusion" bug between cil_type and
cil_typeattribute structures. It can be generalized to any couple of
structures sharing the same symbol table (an easy way of finding other
couples is by reading the code of cil_flavor_to_symtab_index()).

Fix this issue in a "generic" way in __cil_copy_node_helper(), by
verifying that the flavor of the found data is the same as expected and
triggering an error when it is not.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2017-02-08 10:48:40 -05:00
Nicolas Iooss
d6b5b037f9 libsepol: fix -Wwrite-strings warnings
When compiling with -Wwrite-strings, clang reports some warnings like:

    module_to_cil.c:784:13: error: assigning to 'char *' from 'const
    char [5]' discards qualifiers
    [-Werror,-Wincompatible-pointer-types-discards-qualifiers]
                    statement = "type";
                              ^ ~~~~~~
    module_to_cil.c:787:13: error: assigning to 'char *' from 'const
    char [5]' discards qualifiers
    [-Werror,-Wincompatible-pointer-types-discards-qualifiers]
                    statement = "role";
                              ^ ~~~~~~

Add a const type attribute to local variables which only handle constant
strings.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2017-02-06 11:05:33 -05:00
Nicolas Iooss
69ec21ce6a libsepol: remove useless assignments
There is no point in initializing a variable which gets
almost-immediately assigned an other value.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2017-01-19 08:48:36 -05:00
Nicolas Iooss
fd9e5ef7b7 libsepol: use constant keys in hashtab functions
Even though "hashtab_key_t" is an alias for "char *", "const
hashtab_key_t" is not an alias for "(const char) *" but means "(char *)
const".

Introduce const_hashtab_key_t to map "(const char) *" and use it in
hashtab_search() and hashtab key comparison functions.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2017-01-19 08:46:19 -05:00
Gary Tierney
af18b86e0b libsepol/cil: remove avrules with no affected types
Adds a check for avrules with type attributes that have a bitmap cardinality
of 0 (i.e., no types in their set) before adding them to the libsepol policy in
__cil_avrule_to_avtab().  Also adds an exception for neverallow rules to
prevent breaking anything from AOSP mentioned in
f9927d9370.

Signed-off-by: Gary Tierney <gary.tierney@gmx.com>
2016-12-13 10:56:59 -05:00
James Carter
3fe4499f7d libsepol/cil: Add ability to write policy.conf file from CIL AST
The ability to create a policy.conf file from the CIL AST has been
a desire from the beginning to assist in debugging and for general
flexibility. Some work towards this end was started early in CIL's
history, but cil_policy.c has not been remotely functional in a long
time. Until now.

The function cil_write_policy_conf() will write a policy.conf file
from a CIL AST after cil_build_ast(), cil_resolve_ast(),
cil_fqn_qualify(), and cil_post_process() have been called.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2016-11-30 10:18:12 -05:00
Stephen Smalley
8fdb225521 libsepol,checkpolicy: convert rangetrans and filenametrans to hashtabs
range transition and name-based type transition rules were originally
simple unordered lists.  They were converted to hashtabs in the kernel
by commit 2f3e82d694d3d7a2db019db1bb63385fbc1066f3 ("selinux: convert range
transition list to a hashtab") and by commit
2463c26d50adc282d19317013ba0ff473823ca47 ("SELinux: put name based
create rules in a hashtable"), but left unchanged in libsepol and
checkpolicy. Convert libsepol and checkpolicy to use the same hashtabs
as the kernel for the range transitions and name-based type transitions.

With this change and the preceding one, it is possible to directly compare
a policy file generated by libsepol/checkpolicy and the kernel-generated
/sys/fs/selinux/policy pseudo file after normalizing them both through
checkpolicy.  To do so, you can run the following sequence of commands:

checkpolicy -M -b /etc/selinux/targeted/policy/policy.30 -o policy.1
checkpolicy -M -b /sys/fs/selinux/policy -o policy.2
cmp policy.1 policy.2

Normalizing the two files via checkpolicy is still necessary to ensure
consistent ordering of the avtab entries.  There may still be potential
for other areas of difference, e.g. xperms entries may lack a well-defined
order.

Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
2016-11-28 13:10:59 -05:00
dcashman
4750ec2ed5 libsepol: cil: remove double-free.
Test: Untested patch.
Bug: https://code.google.com/p/android/issues/detail?id=226519
Change-Id: Icaf992ba1487098f2c4f16ac1017012f611281e9
Signed-off-by: Daniel Cashman <dcashman@android.com>
2016-11-15 10:48:26 -05:00
James Carter
2eefb20d8f libsepol/cil: Exit with an error for an unknown map permission
Nicholas Iooss discovered that using an unknown permission with a
map class will cause a segfault.

CIL will only give a warning when it fails to resolve an unknown
permission to support the use of policy module packages that use
permissions that don't exit on the current system. When resolving
the unknown map class permission an empty list is used to represent
the unknown permission. When it is evaluated later the list is
assumed to be a permission and a segfault occurs.

There is no reason to allow unknown class map permissions because
the class maps and permissions are defined by the policy.

Exit with an error when failing to resolve a class map permission.

Reported-by: Nicolas Iooss <nicolas.iooss@m4x.org>
Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2016-11-02 12:14:21 -04:00
Jason Zaman
2d1380f811 libsepol: Add symver with explicit version to build with ld.gold
The blank default symver fails to compile with ld.gold. This updates the
symver from blank to LIBSEPOL_1.0. The dynamic linker will first look
for the symbol with the explicit version specified. If there is none, it
will pick the first listed symbol so there is no breakage.
This also matches how symvers are defined in libsemanage.

Signed-off-by: Jason Zaman <jason@perfinion.com>
2016-10-31 12:50:24 -04:00
dcashman
d7cb38ff87 libsepol: cil: cil_strpool: Allow multiple strpool users.
cil_strpool currently provides an interface to a statically stored
global data structure.  This interface does not accomodate multiple
consumers, however, as two calls to cil_strpool_init() will lead to a
memory leak and a call to cil_strpool_destroy() by one consumer will
remove data from use by others, and subsequently lead to a segfault on
the next cil_strpool_destroy() invocation.

Add a reference counter so that the strpool is only initialized once and
protect the exported interface with a mutex.

Tested by calling cil_db_init() on two cil_dbs and then calling
cil_db_destroy() on each.

Signed-off-by: Daniel Cashman <dcashman@android.com>
2016-10-19 10:17:03 -04:00
James Carter
410634d650 libsepol/cil: Verify neither child nor parent in a bounds is an attribute
Nicolas Iooss found while fuzzing secilc with AFL that using an attribute
as a child in a typebounds statement will cause a segfault.

This happens because the child datum is assumed to be part of a cil_type
struct when it is really part of a cil_typeattribute struct. The check to
verify that it is a type and not an attribute comes after it is used.

This bug effects user and role bounds as well because they do not check
whether a datum refers to an attribute or not.

Add checks to verify that neither the child nor the parent datum refer
to an attribute before using them in user, role, and type bounds.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2016-10-19 10:08:15 -04:00
James Carter
0fcc430add libsepol/cil: Verify alias in aliasactual statement is really an alias
Nicolas Iooss found while fuzzing secilc with AFL that the statement
"(sensitivityaliasactual SENS SENS)" will cause a segfault.

The segfault occurs because when the aliasactual is resolved the first
identifier is assumed to refer to an alias structure, but it is not.

Add a check to verify that the datum retrieved is actually an alias
and exit with an error if it is not.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2016-10-19 10:08:09 -04:00
James Carter
166b260d75 libsepol/cil: Check that permission is not an empty list
Nicolas Iooss found while fuzzing secilc with AFL that the statement
"(class C (()))" will cause a segfault.

CIL expects a list of permissions in the class declaration and "(())"
is a valid list. Each item of the list is expected to be an identifier
and as the list is processed each item is checked to see if it is a
list. An error is given if it is a list, otherwise the item is assumed
to be an identifier. Unfortunately, the check only works if the list
is not empty. In this case, the item passes the check and is assumed
to be an identifier and a NULL is passed as the string for name
verification. If name verification assumes that a non-NULL value will
be passed in, a segfault will occur.

Add a check for an empty list when processing a permission list and
improve the error handling for permissions when building the AST.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2016-10-19 10:08:02 -04:00
James Carter
3aa292620c libsepol/cil: Check if identifier is NULL when verifying name
Nicolas Iooss found while fuzzing secilc with AFL that the statement
"(class C (()))" will cause a segfault.

When CIL checks the syntax of the class statement it sees "(())" as a
valid permission list, but since "()" is not an identifier a NULL is
passed as the string for name verification. A segfault occurs because
name verification assumes that the string being checked is non-NULL.

Check if identifier is NULL when verifying name.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2016-10-19 10:07:51 -04:00
James Carter
da51020d6f libsepol/cil: Use an empty list to represent an unknown permission
Nicolas Iooss found while fuzzing secilc with AFL that the statement
"(classpermissionset CPERM (CLASS (and unknow PERM)))" will cause a
segfault.

In order to support a policy module package using a permission that
does not exist on the system it is loaded on, CIL will only give a
warning when it fails to resolve an unknown permission. CIL itself will
just ignore the unknown permission. This means that an expression like
"(and UNKNOWN p1)" will look like "(and p1)" to CIL, but, since syntax
checking has already been done, CIL won't know that the expression is not
well-formed. When the expression is evaluated a segfault will occur
because all expressions are assumed to be well-formed at evaluation time.

Use an empty list to represent an unknown permission so that expressions
will continue to be well-formed and expression evaluation will work but
the unknown permission will still be ignored.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2016-10-19 10:07:43 -04:00
James Carter
1b3b36aeec libsepol/cil: Use empty list for category expression evaluated as empty
Nicolas Iooss found while fuzzing secilc with AFL that the following
policy will cause a segfault.

(category c0)
(category c1)
(categoryorder (c0 c1))
(sensitivity s0)
(sensitivitycategory s0 (not (all)))

The expression "(not (all))" is evaluated as containing no categories.
There is a check for the resulting empty list and the category datum
expression is set to NULL. The segfault occurs because the datum
expression is assumed to be non-NULL after evaluation.

Assign the list to the datum expression even if it is empty.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2016-10-19 10:07:36 -04:00
James Carter
1fc2f2f5ca libsepol/cil: Check for improper category range
Nicolas Iooss found while fuzzing secilc with AFL that the following
policy will cause a segfault.

(category c0)
(category c1)
(categoryorder (c0 c1))
(sensitivity s0)
(sensitivitycategory s0 (range c1 c0))

The category range "(range c1 c0)" is invalid because c1 comes after c0
in order.

The invalid range is evaluated as containing no categories. There is a
check for the resulting empty list and the category datum expression is
set to NULL. The segfault occurs because the datum expression is assumed
to be non-NULL after evaluation.

Add a check for an invalid range when evaluating category ranges.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2016-10-19 10:07:22 -04:00
William Roberts
e71e9891e4 libsepol/cil: disable symver on Mac builds
symver does not work on Mac, so like Android, just
disable it.

Signed-off-by: William Roberts <william.c.roberts@intel.com>
2016-10-18 13:48:53 -04:00
Nicolas Iooss
ac12826c11 libsepol/cil: fix memory leak in __cil_fill_expr()
__cil_fill_expr() initializes 'cil_list *sub_expr' but does not destroy
it when __cil_fill_expr_helper() fails. This list is therefore leaked
when __cil_fill_expr() returns.

This occurs when secilc compiles the following policy:

    (class CLASS (PERM))
    (classorder (CLASS))
    (sid SID)
    (sidorder (SID))
    (user USER)
    (role ROLE)
    (type TYPE)
    (category CAT)
    (categoryorder (CAT))
    (sensitivity SENS)
    (sensitivityorder (SENS))
    (sensitivitycategory SENS (CAT))
    (allow TYPE self (CLASS (PERM)))
    (roletype ROLE TYPE)
    (userrole USER ROLE)
    (userlevel USER (SENS))
    (userrange USER ((SENS)(SENS (CAT))))
    (sidcontext SID (USER ROLE TYPE ((SENS)(SENS))))

    (categoryset cats (not (range unknown)))

This bug has been found using gcc address sanitizer.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2016-10-04 10:28:27 -04:00
Nicolas Iooss
81c9ca5f96 libsepol/cil: fix double-free in cil categories parser
When cil_fill_cats() fails to parse an expression and destroys a
category set, it fails to reset *cats to NULL. This makes this object be
destroyed again in cil_destroy_catset().

This bug can be triggered by the following policy:

    (class CLASS (PERM))
    (classorder (CLASS))
    (sid SID)
    (sidorder (SID))
    (user USER)
    (role ROLE)
    (type TYPE)
    (category CAT)
    (categoryorder (CAT))
    (sensitivity SENS)
    (sensitivityorder (SENS))
    (sensitivitycategory SENS (CAT))
    (allow TYPE self (CLASS (PERM)))
    (roletype ROLE TYPE)
    (userrole USER ROLE)
    (userlevel USER (SENS))
    (userrange USER ((SENS)(SENS (CAT))))
    (sidcontext SID (USER ROLE TYPE ((SENS)(SENS))))

    (categoryset cats (range unknown))

This bug has been found by fuzzing secilc with american fuzzy lop.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2016-10-04 10:28:27 -04:00
Nicolas Iooss
f1ba58a199 libsepol/cil: make cil_resolve_name() fail for '.'
This CIL policy makes secilc crash with a NULL pointer dereference:

    (class CLASS (PERM))
    (classorder (CLASS))
    (sid SID)
    (sidorder (SID))
    (user USER)
    (role ROLE)
    (type TYPE)
    (category CAT)
    (categoryorder (CAT))
    (sensitivity SENS)
    (sensitivityorder (SENS))
    (sensitivitycategory SENS (CAT))
    (allow TYPE self (CLASS (PERM)))
    (roletype ROLE TYPE)
    (userrole USER ROLE)
    (userlevel USER (SENS))
    (userrange USER ((SENS)(SENS (CAT))))
    (sidcontext SID (USER ROLE TYPE ((SENS)(SENS))))

    (allow . self (CLASS (PERM)))

Using "." in the allow statement makes strtok_r() return NULL in
cil_resolve_name() and this result is then used in a call to
cil_symtab_get_datum(), which is thus invalid.

Instead of crashing, make secilc fail with an error message.

This bug has been found by fuzzing secilc with american fuzzy lop.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2016-10-04 10:28:18 -04:00
Gary Tierney
48965c602c libsepol/cil: create user and role caches when building binary policy
Pre-expands the role and user caches used in context validation when
conerting a cildb to a binary policydb.  This is currently only done
when loading a binary policy and prevents context validation from
working correctly with a newly built policy (i.e., when semanage builds
a new policy and then runs genhomedircon).

Also adds declarations for the hashtable mapping functions used:
policydb_role_cache and policydb_user_cache().

Signed-off-by: Gary Tierney <gary.tierney@gmx.com>
2016-10-03 14:59:23 -04:00
James Carter
c303ca910a libsepol/cil: Check for too many permissions in classes and commons
Fixes bug found by Nicolas Iooss as described below in the way suggested by Steve Lawrence.

Nicolass reported:

When compiling a CIL policy with more than 32 items in a class (e.g. in
(class capability (chown ...)) with many items),
cil_classorder_to_policydb() overflows perm_value_to_cil[class_index]
array. As this array is allocated on the heap through
calloc(PERMS_PER_CLASS+1, sizeof(...)), this makes secilc crash with the
following message:

    *** Error in `/usr/bin/secilc': double free or corruption (!prev): 0x000000000062be80 ***
    ======= Backtrace: =========
    /usr/lib/libc.so.6(+0x70c4b)[0x7ffff76a7c4b]
    /usr/lib/libc.so.6(+0x76fe6)[0x7ffff76adfe6]
    /usr/lib/libc.so.6(+0x777de)[0x7ffff76ae7de]
    /lib/libsepol.so.1(+0x14fbda)[0x7ffff7b24bda]
    /lib/libsepol.so.1(+0x152db8)[0x7ffff7b27db8]
    /lib/libsepol.so.1(cil_build_policydb+0x63)[0x7ffff7af8723]
    /usr/bin/secilc[0x40273b]
    /usr/lib/libc.so.6(__libc_start_main+0xf1)[0x7ffff7657291]
    /usr/bin/secilc[0x402f7a]

This bug has been found by fuzzing secilc with american fuzzy lop.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2016-09-29 13:59:45 -04:00
Guido Trentalancia
e7fbb8b401 Produce more meaningful error messages when conflicting type rules are found by libsepol.
Fixes Debian bug #832331 (https://bugs.debian.org/832331).

Signed-off-by: Guido Trentalancia <guido@trentalancia.net>
2016-09-06 13:46:32 -04:00
James Carter
f9927d9370 libsepol: Change which attributes CIL keeps in the binary policy
The removal of attributes that are only used in neverallow rules is
hindering AOSP adoption of the CIL compiler. This is because AOSP
extracts neverallow rules from its policy.conf for use in the Android
compatibility test suite. These neverallow rules are applied against
the binary policy being tested to check for a violation. Any neverallow
rules with an attribute that has been removed cannot be checked.

Now attributes are kept unless they are not used in any allow rule and
they are auto-generated or named "cil_gen_require" or do not have any
types associated with them.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2016-08-19 15:13:32 -04:00
James Carter
46e157b470 libsepol/cil: Warn instead of fail if permission is not resolve
If a policy module package has been created with a policy that contains
a permission and then is used on a system without that permission CIL
will fail with an error when it cannot resolve the permission.

This will prevent the installation on policy and the user will not
know that the policy has not been installed.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2016-07-28 10:51:38 -04:00
Steve Lawrence
7a137eb75f libsepol/cil: Ignore object_r in userrole mappings when creating policy binary
Commit 77779d2ca, which added support for userattributes in CIL,
accidentally removed code that ignored object_r when adding userrole
mappings to the policydb. This meant that running commands like
`semanage user -l` would incorrectly show object_r. This patch adds that
code back in. Note that CIL requires that these mappings exist to
properly validate file contexts, so pp2cil's behavior of creating these
mappings is not modified.

Signed-off-by: Steve Lawrence <slawrence@tresys.com>
2016-07-26 13:41:43 -04:00
Thomas Petazzoni
0635cd495b Add missing <stdarg.h> include
Add missing <stdarg.h> include

This is needed to fix the build on uClibc, due to the usage of
va_list.

Signed-off-by: Thomas Petazzoni <thomas.petazzoni@free-electrons.com>
2016-07-01 13:02:15 -04:00
James Carter
67560cc7ac libsepol/cil: Remove path field from cil_tree_node struct
Remove path field from cil_tree_node struct and all references
to it in CIL. This will reduce memory usage by 5%.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2016-05-05 16:32:07 -04:00
James Carter
46b3a55598 libsepol/cil: Replace cil_log() calls with cil_tree_log()
Replace all calls to cil_log() that print path information with a
call to cil_tree_log() which will also print information about any
high-level sources.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2016-05-05 16:23:36 -04:00
James Carter
73aac8fc1e libsepol/cil: Add cil_tree_log() and supporting functions
Provide more detailed log messages containing all relevant CIL and
high-level language source file information through cil_tree_log().

cil_tree_log() uses two new functions: cil_tree_get_next_path() and
cil_tree_get_cil_path().

cil_tree_get_next_path() traverses up the parse tree or AST until
it finds the next CIL or high-level language source information nodes.
It will return the path and whether or not the path is for a CIL file.

cil_tree_get_cil_path() uses cil_tree_get_next_path() to return
the CIL path.

Example cil_tree_log() message:
    Problem at policy.cil:21 from foo.hll:11 from bar.hll:2

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2016-05-05 16:19:45 -04:00
James Carter
681341f2f4 libsepol/cil: Store CIL filename in parse tree and AST
Use some of the functionality recently added to support high-level
language line marking to track the CIL filename.

The goal is to eventually remove the path field from the tree node
struct and offset the addtion of the hll_line field.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2016-05-05 16:15:23 -04:00
James Carter
875a6bcbe8 libsepol/cil: Add high-level language line marking support
Adds support for tracking original file and line numbers for
better error reporting when a high-level language is translated
into CIL.

This adds a field called "hll_line" to struct cil_tree_node which
increases memory usage by 5%.

Syntax:

;;* lm(s|x) LINENO FILENAME
(CIL STATEMENTS)
;;* lme

lms is used when each of the following CIL statements corresponds
to a line in the original file.

lmx is used when the following CIL statements are all expanded
from a single high-level language line.

lme ends a line mark block.

Example:

;;* lms 1 foo.hll
(CIL-1)
(CIL-2)
;;* lme
;;* lmx 10 bar.hll
(CIL-3)
(CIL-4)
;;* lms 100 baz.hll
(CIL-5)
(CIL-6)
;;* lme
(CIL-7)
;;* lme

CIL-1 is from line   1 of foo.hll
CIL-2 is from line   2 of foo.hll
CIL-3 is from line  10 of bar.hll
CIL-4 is from line  10 of bar.hll
CIL-5 is from line 100 of baz.hll
CIL-6 is from line 101 of baz.hll
CIL-7 is from line  10 of bar.hll

Based on work originally done by Yuli Khodorkovskiy of Tresys.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2016-05-05 16:13:49 -04:00
Laurent Bigonville
8586ee56be Fix multiple spelling errors
Thanks to the lintian utility from Debian
2016-05-02 08:45:45 -04:00
James Carter
74bde7fa16 libsepol/cil: Do not add an attribute as a type in the attr_type_map
The attribute to type map is used to get all of the types that are
asociated with an attribute. To make neverallow and bounds checking
easier it was convienent to map a type to itself. However, CIL was
wrongly mapping an attribute to itself in addition to the types
associated with it. This caused type bounds checking to fail if the
parent was granted a permission through one attribute while the child
was granted the permission through another attribute.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2016-04-29 13:23:07 -04:00
Richard Haines
aac9360581 selinux: Build policy on systems not supporting DCCP protocol
Commit 3895fbbe0c ("selinux: Add support
for portcon dccp protocol") added support for the (portcon dccp ..)
statement. This fix will allow policy to be built on platforms
(see [1]) that do not have DCCP support by defining the IANA
assigned IP Protocol Number 33 to IPPROTO_DCCP.

[1] https://android-review.googlesource.com/#/c/219568/

Signed-off-by: Richard Haines <richard_c_haines@btinternet.com>
2016-04-25 15:31:45 -04:00
James Carter
acd61984df libsepol/cil: Cleanup neverallow checking and fail if bounds checking fails
For both neverallow and bounds checking keep neverallow and bounds
failures separate from program faults.

Have secilc exit with an error (and fail to build a binary policy)
when bounds checks fail.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2016-04-13 15:13:41 -04:00
James Carter
a7604ba7eb libsepol/cil: Improve type bounds check reporting
There are three improvements.

When calling cil_find_matching_avrule_in_ast(), one parameter specifies
whether to return a match of the exact same (not a duplicate) rule.
Since the target passed in is created and not actually in the tree
by making this parameter true an extra comparison can be avoided.

Currently, when printing a bounds violation trace, every match except
for the last one has only the parents of the rule printed. Only the
last rule has both its parents and the actual rule printed. Now the
parents and rule are printed for each match. This has the additional
benefit that if a match is not found (there should always be a match)
a seg fault will not occur.

To reduce the amount of error reporting, only print a trace of a
matching rule if it is different from the previous one.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2016-04-13 15:13:33 -04:00
James Carter
7abbda3326 libsepol/cil: Fixed bug in cil_type_match_any()
An attribute that has no types associated with it should still match
with itself, but ebitmap_match_any() will return false if there are
no bits set in either bitmap. The solution is to check to see if the
two datums passed into cil_type_match_any() are the same. This has
the additional advantage of providing a quick match anytime the
attributes are the same.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2016-04-13 14:51:53 -04:00
Richard Haines
3895fbbe0c selinux: Add support for portcon dccp protocol
This adds CIL and checkpolicy support for the (portcon dccp ...)
statement. The kernel already handles name_bind and name_connect
permissions for the dccp_socket class.

Signed-off-by: Richard Haines <richard_c_haines@btinternet.com>
Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2016-04-06 10:14:27 -04:00
Steve Lawrence
4df9f89cb1 libsepol/cil: fix bug when resetting class permission values
During resolution of classcommon statements (cil_resolve_classcommon),
we add the number of class common permissions to the values of the class
permissions. This way, the internal CIL values of the common permission
go from 0 to N, and the values of class permissions start at N+1 (where
N is the number of common permissions). When we reset a class due to
reresolve (cil_reset_class), we must then reverse this process by
subtracting the number of common permissions from the class permission
values.

However, there is a bug when resetting classes in which we subtract the
number of common permissions from the common permissions value rather
than the class permissions value. This means that class permissions
could be too high (since they are not reduced on reset) and common
permissions underflowed (since they are reduced, but should not be).

In most cases, this didn't actually matter since these permission values
aren't used when creating the binary. Additionally, we always access the
permissions via a hash table lookup or map, and then use whatever value
they have to set bits in bitmaps. As long as the bits in the bitmap
match the values, things work as expected. However, the one case where
these values do matter is if you use 'all' in a class permission set. In
this case, we enable bits 0 through number of permissions in a bitmap.
But because our permission values are all mixed up, these enabled bits
do not correspond to the permission values. This results in making it
look like no permissions were set in a class permission set, and the
rule is essentially ignored.

This patch fixes the bug so that the values of class permissions are
properly reset, allowing one to use 'all' in class permission sets in a
policy that reresolves.

Signed-off-by: Steve Lawrence <slawrence@tresys.com>
Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2016-03-17 15:58:56 -04:00
Nicolas Iooss
172ce53ffa libsepol: fix __attribute__((unused)) annotations
clang warns about variables which are used in a function body even
though they were marked __attribute__((unused)).  For example:

    interfaces.c:129:2: error: 'handle' was marked unused but was used
    [-Werror,-Wused-but-marked-unused]
            handle = NULL;
            ^
    interfaces.c:233:2: error: 'handle' was marked unused but was used
    [-Werror,-Wused-but-marked-unused]
            handle = NULL;
            ^

Remove these warnings either by removing meaningless assigments or by
removing the attribute.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2016-02-11 08:32:15 -05:00
Nicolas Iooss
1bfb1a4ffd libsepol: cil: always initialize __cil_permx_to_sepol_class_perms() result
clang warns that __cil_permx_to_sepol_class_perms() return value, rc,
may be unitialized:

    ../cil/src/cil_binary.c:4188:9: error: variable 'rc' may be
    uninitialized when used here [-Werror,-Wconditional-uninitialized]
            return rc;
                   ^~
    ../cil/src/cil_binary.c:4148:8: note: initialize the variable 'rc'
    to silence this warning
            int rc;
                  ^
                   = 0

This theoretically happens when cil_expand_class(permx->obj) returns an
empty list.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2016-02-01 08:25:13 -05:00
Steve Lawrence
f610cac79a libsepol/cil: Validate extended avrules and permissionxs
Classes used in extended avrules and permissionxs must have an "ioctl"
permission. Add validation to ensure that is the case, or print an error
message otherwise.

Signed-off-by: Steve Lawrence <slawrence@tresys.com>
2015-12-07 16:21:35 -05:00