Commit graph

65 commits

Author SHA1 Message Date
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
Steve Lawrence
f5602f5ff9 libsepol/cil: Add support for neverallowx
Add a new statement, neverallowx, which has the same syntax as allowx:

  (neverallowx foo bar (ioctl file (range 0x2000 0x20FF)))
  (allowx foo bar (ioctl file (0x20A0))) ; this fails

Much of the changes just move functions around or split functions up to
ease the sharing of avrule and avrulex comparisons with neverallows.
This refactoring also modifies the avrule struct to include a union of
either class permission information for standard avrules or extended
permission information for extended avrules, also done to support
sharing code.

This also changes assertion.c and avtab.c to allow
check_assertion_avtab_match to work with extended avrules.

Signed-off-by: Steve Lawrence <slawrence@tresys.com>
2015-12-02 15:15:03 -05:00
Steve Lawrence
b41468cd9d libsepol/cil: Remove duplicated 'if' condition in cil_tree
David Binderman wrote:
> Hello there,
>
> ./cil/src/cil_tree.c:1279:36: warning: duplicated 'if' condition [-Wduplicated-cond]
>
> Source code is
>
>             if (filecon->context_str != NULL) {
>                 cil_log(CIL_INFO, " %s", filecon->context_str);
>             } else if (filecon->context != NULL) {
>                 cil_tree_print_context(filecon->context);
>             } else if (filecon->context_str != NULL) {
>                 cil_log(CIL_INFO, " %s", filecon->context_str);
>             }
>
> Two mentions of filecon->context_str. Suggest code rework.

Reported-by: David Binderman <dcb314@hotmail.com>
Signed-off-by: Steve Lawrence <slawrence@tresys.com>
2015-12-01 15:40:28 -05:00
Yuli Khodorkovskiy
71dd7b7133 secilc: Add support for unordered classes
Resolves https://github.com/SELinuxProject/cil/issues/3

An 'unordered' keyword provides the ability to append classes to the current
list of ordered classes. This allows users to not need knowledge of existing
classes when creating a class and fixes dependencies on classes when removing a
module. This enables userspace object managers with custom objects to be
modularized.

If a class is declared in both an unordered and ordered statement, then the
ordered statement will supercede the unordered declaration.

Example usage:

    ; Appends new_class to the existing list of classes
    (class new_class ())
    (classorder (unordered new_class))

Signed-off-by: Yuli Khodorkovskiy <ykhodorkovskiy@tresys.com>
Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2015-11-10 13:26:52 -05:00
Steve Lawrence
551d834c39 libsepol/cil: improve recursion detection
Add support for detecting recursive blockinherits, and print a trace of
the detected loop. Output will look something like this upon detection:

  Recursive blockinherit found:
    test.cil:42: block a
    test.cil:43: blockinherit b
    test.cil:36: block b
    test.cil:37: blockinherit c
    test.cil:39: block c
    test.cil:40: blockinherit a

Additionally, improve support for detecting recursive macros/calls. Due
to the way calls are copied, the existing code only detected recursion
with call depth of three or more. Smaller depths, like

  (macro m ()
    (call m))

were not detected and caused a segfault. The callstack that was used for
this was not sufficient, so that is removed and replaced with a method
similar to the block recursion detection. A similar trace is also
displayed for recursive macros/calls.

Also, cleanup sidorder, classorder, catorder, sensorder, and in lists at
the end of resolve, fixing a potential memory leak if errors occur
during resolve.

Signed-off-by: Steve Lawrence <slawrence@tresys.com>
Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2015-09-15 12:40:09 -04:00
Yuli Khodorkovskiy
2ee9377b6b libsepol/cil: Fix uninitialized false positive in cil_binary
On older versions of gcc, an error is incorrectly given about
uninitialized variables. This will initialize the culprits.

Signed-off-by: Yuli Khodorkovskiy <ykhodorkovskiy@tresys.com>
Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2015-09-11 11:02:53 -04:00
Yuli Khodorkovskiy
de4c95f9c8 libsepol/cil: Provide error if classperms are empty
Fixes https://github.com/SELinuxProject/cil/issues/7.

This fixes a bug where cil_verify_classperms was executed on NULL
classperms lists. A check is now performed when verifying
classpermissions and classmap to ensure the classperms lists are not
empty.

Signed-off-by: Yuli Khodorkovskiy <ykhodorkovskiy@tresys.com>
Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2015-09-11 11:02:37 -04:00
Yuli Khodorkovskiy
77779d2ca5 libsepol/cil: Add userattribute{set} functionality
This adds a userattribute statement that may be used in userroles and
constraints. The syntax is the same as typeattributset.

Also, disallow roleattributes where roles are accepted in contexts.

Specify a userattribute

    (userattribute foo)

Add users to the set foo

    (userattributeset foo (u1 u2))

Signed-off-by: Yuli Khodorkovskiy <ykhodorkovskiy@tresys.com>
Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2015-09-11 09:07:46 -04:00
Steve Lawrence
b6e519e542 libsepol/cil: fix blockinherit copying segfault and add macro restrictions
When we copy a blockinherit statement, we perform actions that assume
the blockinherit statement was already resolved. However, this isn't the
case if the statement was copied from a tunableif or an in-statement,
since those are resolve before blockinherits and blocks.  So when
copying a blockinherit that hasn't been resolved, ignore the code that
associates blocks with the blockinherit; that will all be handled when
the copied blockinherit is actually resolved later.

Additionally, restrict block, blockabstract, and blockinherit statements
from appearing in macros. These statements are all resolved before
macros due to ordering issues, so they must not appear inside macros.
Note that in addition to doing the checks in build_ast, they are also
done in resolve_ast. This is because an in-statement could copy a block
statement into a macro, which we would not know about until after the
in-statement was resolved.

Signed-off-by: Steve Lawrence <slawrence@tresys.com>
Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2015-09-10 10:05:16 -04:00
Steve Lawrence
1fe89056ea libsepol/cil: fix NULL pointer dereference when copying classpermission/set
When copying classpermission or classpermissionset statements, we did
not properly initialize the new structs. This would cause a segfault
when one used either of these statements inside a tunableif block, e.g.

  (tunableif foo
    (true
      (classpermissionset cps (cls (perm1 perm2))))
    (false
      (classpermissionset cps (cls (perm1)))))

Reported-by: Dominick Grift <dac.override@gmail.com>
Signed-off-by: Steve Lawrence <slawrence@tresys.com>
Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2015-09-09 15:31:14 -04:00
Steve Lawrence
ef93dfe039 libsepol/cil: add ioctl whitelist support
Add three new extended avrule statements with the following syntax:

  (allowx source_type target_type permissionx)
  (auditallowx source_type target_type permissionx)
  (dontauditx source_type target_type permissionx)

source_type - type, typeattribute, or typealias
target_type - type, typeattribute, typealias, or "self" keyword
permissionx - named or anonymous permissionx statement, which has the syntax:

  (permissionx name (kind object expression))

name - unique identifier of the permissionx statement
kind - must be "ioctl"; could be extended in the future
object - class or classmap
expression - standard CIL expression containing hexadecimal values,
  prefixed with '0x', and the expression keywords 'or', 'xor', 'and',
  'not', 'range', or 'all'. Values must be between 0x0000 and 0xFFFF.
  Values may also be provided in decimal, or in octal if starting with '0'.

For example:

 (allowx src_t tgt_t (ioctl cls (0x1111 0x1222 0x1333)))
 (allowx src_t tgt_t (ioctl cls (range 0x1400 0x14FF)))
 (allowx src_t tgt_t (ioctl cls (and (range 0x1600 0x19FF) (not (range 0x1750 0x175F)))))

 (permissionx ioctl_nodebug (ioctl cls (not (range 0x2010 0x2013))))
 (allowx src_t tgt_t ioctl_nodebug)

Signed-off-by: Steve Lawrence <slawrence@tresys.com>
Acked-by: James Carter <jwcart2@tycho.nsa.gov>
2015-09-02 16:03:07 -04:00
Steve Lawrence
5eae956abf libsepol/cil: Improve resolution error messages
In some cases, if a statement failed to resolve inside an optional, we
would still log a failed to resolve error message, even though the
optional was disabled and everything successfully compiled. This was
confusing. Additionally, if a resolution failure occurred outside of an
optional, the error message did not include the actual name that could
not be resolved--it only logged the statement type (e.g. allow,
booleanif, etc.) and file/line number.

This patch removes resolution error messages which should not always be
printed, as well as improves the resolution failure message to also
print the last name that was attempted to be resolved. Also makes some
less important error messages INFO rather than WARN, which tended to
just clutter things and hide actual error messages.

Signed-off-by: Steve Lawrence <slawrence@tresys.com>
2015-07-22 11:02:16 -04:00
James Carter
3e4a902010 libsepol/cil: Add CIL bounds checking and reporting.
Use the libsepol bounds checking to check for and report user and
role bounds violations.

For type bounds checking, use libsepol bounds checking to determine
if there is a violation for a given type. For each violation display
an error message that includes the CIL AST from the root node to the
node of the rule causing the violation.

Example error report:
Child type b_t3_c exceeds bounds of parent b_t3
  (allow b_t3_c b_tc (file (write)))
    <root>
    booleanif at line 148633 of cil.conf.bounds
    true at line 148634 of cil.conf.bounds
    allow at line 148636 of cil.conf.bounds
      (allow b_t3_c b_tc (file (read write)))

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2015-06-22 10:03:16 -04:00
James Carter
bea07710d0 libsepol/cil: Track number of classes and number of types and attributes.
These values are stored in the CIL db so they can be used to
determine how much memory is needed for mapping libsepol values
to CIL data.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2015-06-22 10:03:16 -04:00
James Carter
beb01ceb49 libsepol/cil: Refactored CIL neverallow checking and reporting.
Use the libsepol neverallow checking to determine if a given neverallow
rule is violated. If a violation is found, use the function
cil_find_matching_avrule_in_ast() to find the AST node of the particular
rule that violates the neverallow. This allows CIL to provide a more
informative error message that includes the file and line number of the
node and all of its parents.

Example error report:
Neverallow check failed at line 31285 of cil.conf.neverallow
  (neverallow typeset4 self (memprotect (mmap_zero)))
    <root>
    booleanif at line 152094 of cil.conf.neverallow
    true at line 152095 of cil.conf.neverallow
    allow at line 152096 of cil.conf.neverallow
      (allow ada_t self (memprotect (mmap_zero)))

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2015-06-22 10:03:16 -04:00
James Carter
f9bdf580b8 libsepol/cil: Add function to search the CIL AST for an AV rule.
The search will be considered a success if any rule is found that
at least partially matches all parts (src type, tgt type, and class-
perms) of the target rule.

For example, for a target of (allow domain file_type (file (read write)
the rule (allow init_t init_exec_t (file (read exec)) will match.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2015-06-22 10:03:07 -04:00
Yuli Khodorkovskiy
1e2b2e57e5 libsepol/cil: Do not allow categories/sensitivities inside blocks
Fixes https://github.com/SELinuxProject/cil/issues/2.

Sensitivities and categories generated from blocks use dots to indicate
namespacing. This could result in categories that contain ambiguous
ranges with categories declared in blocks.

Example:

    (category c0)
    (category c2)
    (block c0
        (category (c2))
        (filecon ... (s0 (c2)))
    )

The above policy results in the filecontext: ... s0:c0.c2. The categories c0.c2
could be interpreted as a range between c0 and c2 or it could be the namespaced
category c0.c2. Therefore, categories are no longer allowed inside blocks to
eliminate this ambiguity.

This patch also disallows sensitivites in blocks for consistency with category
behavior.

Signed-off-by: Yuli Khodorkovskiy <ykhodorkovskiy@tresys.com>
2015-05-27 14:00:01 -04:00