Block, macro, and optional names are all in stored in a block symtab. A
declarations fully-qualified name includes all of the block names from
the root node to the declaration separated by dots. Macro and optional
names are only used when trying to determine the block referred to by
an "in" block. An optional block name might be stored in a macro's
symtab, but optional blocks have no symtab and (*datum)->symtab just
refers to the symtab of the datum which would be the current symtab.
Since the assignment is not needed, remove it so the code is clearer.
Signed-off-by: James Carter <jwcart2@gmail.com>
When resolving names, the struct cil_args_resolve is passed to the
various resolve functions. The field last_resolved_name is not used.
Remove the last_resolved_name field from struct cil_args_resolve.
Signed-off-by: James Carter <jwcart2@gmail.com>
Since cil_gen_node() is only called from declarations, the check to
determine if the node is a declaration is not needed, so remove it.
Signed-off-by: James Carter <jwcart2@gmail.com>
The function cil_tree_walk() has an argument that can be used by
the process_node helper function to tell cil_tree_walk() to skip
the node's sub-tree or the rest of the current branch. The constants
CIL_TREE_SKIP_NOTHING, CIL_TREE_SKIP_NEXT and CIL_TREE_SKIP_HEAD are
defined to be used by that argument.
Fixed two instances in the function __cil_build_ast_node_helper()
where the value 1 is used instead of the more informative
CIL_TREE_SKIP_NEXT.
Signed-off-by: James Carter <jwcart2@gmail.com>
Both tunableif and booleanif use conditional blocks (either true or
false). No ordering is imposed, so a false block can be first (or even
the only) block. Checks are made to ensure that the first and second
(if it exists) blocks are either true or false, but no checks are made
to ensure that there is only one true and/or one false block. If there
are more than one true or false block, only the first will be used and
the other will be ignored.
Create a function, cil_verify_conditional_blocks(), that gives an error
along with a message if more than one true or false block is specified
and call that function when building tunableif and booleanif blocks in
the AST.
Signed-off-by: James Carter <jwcart2@gmail.com>
Acked-by: Ondrej Mosnacek <omosnace@redhat.com>
Versioned duplicate symbols cause problems for LTO. These symbols were
introduced during the CIL integration several releases ago and were only
consumed by other SELinux userspace components.
Fixes: https://github.com/SELinuxProject/selinux/issues/245
Signed-off-by: Petr Lautrbach <plautrba@redhat.com>
When compiling SELinux userspace tools with -ftrapv (this option
generates traps for signed overflow on addition, subtraction,
multiplication operations, instead of silently wrapping around),
semodule crashes when running the tests from
scripts/ci/fedora-test-runner.sh in a Fedora 32 virtual machine:
[root@localhost selinux-testsuite]# make test
make -C policy load
make[1]: Entering directory '/root/selinux-testsuite/policy'
# Test for "expand-check = 0" in /etc/selinux/semanage.conf
# General policy build
make[2]: Entering directory '/root/selinux-testsuite/policy/test_policy'
Compiling targeted test_policy module
Creating targeted test_policy.pp policy package
rm tmp/test_policy.mod.fc
make[2]: Leaving directory '/root/selinux-testsuite/policy/test_policy'
# General policy load
domain_fd_use --> off
/usr/sbin/semodule -i test_policy/test_policy.pp test_mlsconstrain.cil test_overlay_defaultrange.cil test_add_levels.cil test_glblub.cil
make[1]: *** [Makefile:174: load] Aborted (core dumped)
Using "coredumpctl gdb" leads to the following strack trace:
(gdb) bt
#0 0x00007f608fe4fa25 in raise () from /lib64/libc.so.6
#1 0x00007f608fe38895 in abort () from /lib64/libc.so.6
#2 0x00007f6090028aca in __addvsi3.cold () from /lib64/libsepol.so.1
#3 0x00007f6090096f59 in __avrule_xperm_setrangebits (low=30, high=30, xperms=0x8b9eea0)
at ../cil/src/cil_binary.c:1551
#4 0x00007f60900970dd in __cil_permx_bitmap_to_sepol_xperms_list (xperms=0xb650a30, xperms_list=0x7ffce2653b18)
at ../cil/src/cil_binary.c:1596
#5 0x00007f6090097286 in __cil_avrulex_ioctl_to_policydb (k=0xb8ec200 "@\023\214\022\006", datum=0xb650a30,
args=0x239a640) at ../cil/src/cil_binary.c:1649
#6 0x00007f609003f1e5 in hashtab_map (h=0x41f8710, apply=0x7f60900971da <__cil_avrulex_ioctl_to_policydb>,
args=0x239a640) at hashtab.c:234
#7 0x00007f609009ea19 in cil_binary_create_allocated_pdb (db=0x2394f10, policydb=0x239a640)
at ../cil/src/cil_binary.c:4969
#8 0x00007f609009d19d in cil_binary_create (db=0x2394f10, policydb=0x7ffce2653d30) at ../cil/src/cil_binary.c:4329
#9 0x00007f609008ec23 in cil_build_policydb_create_pdb (db=0x2394f10, sepol_db=0x7ffce2653d30)
at ../cil/src/cil.c:631
#10 0x00007f608fff4bf3 in semanage_direct_commit () from /lib64/libsemanage.so.1
#11 0x00007f608fff9fae in semanage_commit () from /lib64/libsemanage.so.1
#12 0x0000000000403e2b in main (argc=7, argv=0x7ffce2655058) at semodule.c:753
(gdb) f 3
#3 0x00007f6090096f59 in __avrule_xperm_setrangebits (low=30, high=30, xperms=0x8b9eea0)
at ../cil/src/cil_binary.c:1551
1551 xperms->perms[i] |= XPERM_SETBITS(h) - XPERM_SETBITS(low);
A signed integer overflow therefore occurs in XPERM_SETBITS(h):
#define XPERM_SETBITS(x) ((1 << (x & 0x1f)) - 1)
This macro is expanded with h=31, so "(1 << 31) - 1" is computed:
* (1 << 31) = -0x80000000 is the lowest signed 32-bit integer value
* (1 << 31) - 1 overflows the capacity of a signed 32-bit integer and
results in 0x7fffffff (which is unsigned)
Using unsigned integers (with "1U") fixes the crash, as
(1U << 31) = 0x80000000U has no overflowing issues.
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
Acked-by: Petr Lautrbach <plautrba@redhat.com>
When classmaps used in a neverallow were being expanded during CIL
neverallow checking, an empty classmapping in the list of
classmappings for a classmap would cause the classmap expansion to
stop and the rest of the classmapping of the classmap to be ignored.
This would mean that not all of the classes and permissions associated
with the classmap would be used to check for a neverallow violation.
Do not end the expansion of a classmap when one classmapping is empty.
Reported-by: Jonathan Hettwer <j2468h@gmail.com>
Signed-off-by: James Carter <jwcart2@gmail.com>
Acked-by: Stephen Smalley <stephen.smalley.work@gmail.com>
CIL was not correctly determining the depth of conditional expressions
which prevented it from giving an error when the max depth was exceeded.
This allowed invalid policy binaries to be created.
Validate the conditional expression using the same logic that is used
when evaluating a conditional expression. This includes checking the
depth of the expression.
Signed-off-by: James Carter <jwcart2@gmail.com>
Acked-by: Stephen Smalley <stephen.smalley.work@gmail.com>
CIL was not correctly determining the depth of constraint expressions
which prevented it from giving an error when the max depth was exceeded.
This allowed invalid policy binaries with constraint expressions exceeding
the max depth to be created.
Validate the constraint expression using the same logic that is used
when reading the binary policy. This includes checking the depth of the
the expression.
Reported-by: Jonathan Hettwer <j2468h@gmail.com>
Signed-off-by: James Carter <jwcart2@gmail.com>
Acked-by: Stephen Smalley <stephen.smalley.work@gmail.com>
In preparation to support a new policy format with a more optimal
representation of filename transition rules, this patch applies an
equivalent change from kernel commit c3a276111ea2 ("selinux: optimize
storage of filename transitions").
See the kernel commit's description [1] for the rationale behind this
representation. This change doesn't bring any measurable difference of
policy build performance (semodule -B) on Fedora.
[1] https://git.kernel.org/pub/scm/linux/kernel/git/pcmoore/selinux.git/commit/?id=c3a276111ea2572399281988b3129683e2a6b60b
Signed-off-by: Ondrej Mosnacek <omosnace@redhat.com>
CIL allows a type to be redeclared when using the multiple declarations
option ("-m" or "--muliple-decls"), but make it an error for an identifier
to be declared as both a type and an attribute.
Change the error message so that it always gives the location and flavor
of both declarations. The flavors will be the same in all other cases,
but in this case they explain why there is an error even if multiple
declartions are allowed.
Fixes: Commit fafe4c212b ("libsepol: cil: Add ability to redeclare types[attributes]")
Reported-by: Topi Miettinen <toiwoton@gmail.com>
Signed-off-by: James Carter <jwcart2@gmail.com>
Acked-by: Stephen Smalley <stephen.smalley.work@gmail.com>
Initialize the multiple_decls field when intializing the structure
cil_db.
Fixes: fafe4c212b ("libsepol: cil: Add ability to redeclare types[attributes]")
Reported-by: Topi Miettinen <toiwoton@gmail.com
Acked-by: Stephen Smalley <stephen.smalley.work@gmail.com>
Signed-off-by: James Carter <jwcart2@gmail.com>
This reverts commit 692716fc5f.
Other parts of the SELinux userspace depend on certain attributes,
such as node_type, exisiting and this change breaks those parts.
Before this patch can be reapplied, we need to identify the attributes
that must never be expanded and create a CIL module with the needed
expandtypeattribute statements (or something similar).
Signed-off-by: James Carter <jwcarter@gmail.com>
Fix issues like:
<inline asm>:1:1: error: unknown directive
.symver cil_build_policydb_pdb, cil_build_policydb@LIBSEPOL_1.0
Which was caused by the DISABLE_SYMVER define not being defined
for static, Mac or Android builds.
Acked-by: Joshua Brindle <joshua.brindle@crunchydata.com>
Signed-off-by: William Roberts <william.c.roberts@intel.com>
libsepol carried its own (outdated) copy of flask.h with the generated
security class and initial SID values for use by the policy
compiler and the forked copy of the security server code
leveraged by tools such as audit2why. Convert libsepol and
checkpolicy entirely to looking up class values from the policy,
remove the SECCLASS_* definitions from its flask.h header, and move
the header with its remaining initial SID definitions private to
libsepol. While we are here, fix the sepol_compute_sid() logic to
properly support features long since added to the policy and kernel,
although there are no users of it other than checkpolicy -d (debug)
and it is not exported to users of the shared library. There
are still some residual differences between the kernel logic and
libsepol.
Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
Acked-by: Petr Lautrbach <plautrba@redhat.com>
The value attrs_expand_size == 1 removes all empty attributes, but it
also makes sense to expand all attributes that have only one type. This
removes some redundant rules (there is sometimes the same rule for the
type and the attribute) and reduces the number of attributes that the
kernel has to go through when looking up rules.
Signed-off-by: Ondrej Mosnacek <omosnace@redhat.com>
Acked-by: James Carter <jwcart2@gmail.com>
A parameter of a macro was only considered to be a duplicate if it
matched both the name and flavor of another parameter. While it is
true that CIL is able to differentiate between those two parameters,
there is no reason to use the same name for two macro parameters and
it is better to return an error for what is probably an error.
Remove the check of the flavors when checking for duplicate parameters.
Signed-off-by: James Carter <jwcart2@gmail.com>
Acked-by: Ondrej Mosnacek <omosnace@redhat.com>
Type transition file names are stored in a symbol table. Before the
name is added, the symbol table is searched to see if the name had
already been inserted. If it has, then the already existing datum is
returned. If it has not, then the name is added if either the
typetransition rule does not occur in a macro or the name is not one
of the macro parameters.
Checking for a previous insertion before checking if the name is a
macro parameter can cause a macro parameter to be treated as the
actual name if a previous type transition file name is the same as
the parameter.
Now check the name to see if it a macro paramter before checking for
its existence in the symbol table.
Signed-off-by: James Carter <jwcart2@gmail.com>
Acked-by: Ondrej Mosnacek <omosnace@redhat.com>
The filename_- and range_trans_table ancillary hash tables in
cil_binary.c just duplicate the final policydb content and can be simply
removed.
Signed-off-by: Ondrej Mosnacek <omosnace@redhat.com>
The classperms associated with each map class permission and with each
classpermissionset are verified in __cil_verify_classperms() which had
multiple problems with how it did the verification.
1) Verification was short-circuited when the first normal class is found.
The second classpermissionset statement below would not have been
verified.
(classpermission cp1)
(classpermissionset cp1 (CLASS (PERM)))
(classpermissionset cp1 cp2)
2) The classperms of a map class permission and classpermissionset were
not checked for being NULL before the function recursively called itself.
This would result in a segfault if the missing map or set was referred to
before the classmap or classpermission occured. This error was reported by
Dominick Grift (dominick.grift@defensec.nl).
These rules would cause a segfault.
(classmap cm1 (mp1))
(classmapping cm1 mp1 (cm2 (mp2)))
(classmap cm2 (mp2))
But an error would be produced for these rules.
(classmap cm1 (mp1))
(classmap cm2 (mp2))
(classmapping cm2 mp2 (cm1 (mp1)))
3) The loop detection logic was incomplete and could only detect a loop
with a certain statement ordering.
These rules would cause a stack overflow.
(classmap cm1 (mp1))
(classmapping cm1 mp1 (cm2 (mp2)))
(classmap cm2 (mp2))
(classmapping cm2 mp2 (cm3 (mp3)))
(classmap cm3 (mp3))
(classmapping cm3 mp3 (cm2 (mp2)))
Rewrote __cil_verify_classperms() to fix these errors.
Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
Remove restrictions in libsepol and checkpolicy that required all
declared initial SIDs to be assigned a context. With this patch,
it is possible to build and load a policy that drops the sid <sidname>
<context> declarations for the unused initial SIDs. It is still
required to retain the sid <sidname> declarations (in the flask
definitions) in order to preserve the initial SID ordering/values.
The unused initial SIDs can be renamed, e.g. to add an unused_
prefix or similar, if desired, since the names used in the policy
are not stored in the kernel binary policy.
In CIL policies, the (sid ...) and (sidorder (...)) statements
must be left intact for compatibility but the (sidcontext ...)
statements for the unused initial SIDs can be omitted after this change.
With current kernels, if one removes an unused initial SID context
from policy, builds policy with this change applied and loads the
policy into the kernel, cat /sys/fs/selinux/initial_contexts/<sidname>
will show the unlabeled context. With the kernel patch to remove unused
initial SIDs, the /sys/fs/selinux/initial_contexts/<sidname>
file will not be created for unused initial SIDs in the first place.
NB If an unused initial SID was assigned a context different from
the unlabeled context in existing policy, then it is not safe to
remove that initial SID context from policy and reload policy on
the running kernel that was booted with the original policy. This
is because that kernel may have assigned that SID to various kernel
objects already and those objects will then be treated as having
the unlabeled context after the removal. In refpolicy, examples
of such initial SIDs are the "fs" SID and the "sysctl" SID. Even
though these initial SIDs are not directly used (in code) by the current
kernel, their contexts are being applied to filesystems and sysctl files by
policy and therefore the SIDs are being assigned to objects.
NB The "sysctl" SID was in use by the kernel up until
commit 8e6c96935fcc1ed3dbebc96fddfef3f2f2395afc ("security/selinux:
fix /proc/sys/ labeling) circa v2.6.39. Removing its context from
policy will cause sysctl(2) or /proc/sys accesses to end up
performing permission checks against the unlabeled context and
likely encounter denials for kernels < 2.6.39.
Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
- 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>
- 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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
__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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
__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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
If a userlevel or userrange statement is missing from a policy,
evaluate_level_expression() and evaluate_levelrange_expression, respectively
will have a NULL pointer dereference caused by a missing level in a user.
Add cil_pre_verify() which verifies users have a valid level. Also, move loop
checking in classpermissions into cil_pre_verify().
This fixes https://github.com/SELinuxProject/cil/issues/1.
Signed-off-by: Yuli Khodorkovskiy <ykhodorkovskiy@tresys.com>
Libraries such as libqpol that link with libsepol statically do not understand
the symbolic versioning in libsepol. This patch disables the symbolic versioning
in libsepol if building the static library or building for Android.
Signed-off-by: Yuli Khodorkovskiy <ykhodorkovskiy@tresys.com>
Acked-by: Stephen Smalley <sds@tycho.nsa.gov>
Acked-by: Steve Lawrence <slawrence@tresys.com>
The Android build does not like the symbol versioning introduced
by commit 8147bc7; the build fails with:
host SharedLib: libsepol (out/host/linux-x86/obj/lib/libsepol.so)
prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.15-4.8//x86_64-linux/bin/ld: error: symbol cil_build_policydb has undefined version
prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.15-4.8//x86_64-linux/bin/ld: error: symbol cil_build_policydb has undefined version LIBSEPOL_1.1
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Omit the versioned symbols and simply use the current interfaces
when building on Android.
Commit 36f62b7 also broke the Android build by moving secilc out of
libsepol, because the libsepol headers were not installed by the Android.mk
file.
Export the required libsepol headers for use by secilc and adjust secilc
to pick them up from the right location on Android.
Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
Since the secilc compiler is independent of libsepol, move secilc out of
libsepol. Linke secilc dynamically rather than statically with libsepol.
- Move secilc source, test policies, docs, and secilc manpage to secilc
directory.
- Remove unneeded Makefile from libsepol/cil. To build secilc, run make
in the secilc directory.
- Add target to install the secilc binary to /usr/bin/.
- Create an Android makefile for secilc and move secilc out of libsepol
Android makefile.
- Add cil_set_mls to libsepol public API as it is needed by secilc.
- Remove policy.conf from testing since it is no longer used.
Signed-off-by: Yuli Khodorkovskiy <ykhodorkovskiy@tresys.com>
Problems fixed:
1) Fix core dump when building CIL policy (corrupted double-linked list)
by Steve Lawrence <slawrence@tresys.com>
2) Binary policy failed to read with devicetreecon statement.
3) Free path name - With a Xen policy running secilc/valgrind
there are no memory errors.
Also added devicetreecon statement to CIL policy.cil and updated the CIL
Reference Guide.
Signed-off-by: Richard Haines <richard_c_haines@btinternet.com>
In Xen on ARM, device tree nodes identified by a path (string) need to
be labeled by the security policy.
Signed-off-by: Daniel De Graaf <dgdegra@tycho.nsa.gov>
This expands IOMEMCON device context entries to 64 bits. This change is
required to support static I/O memory range labeling for systems with
over 16TB of physical address space. The policy version number change
is shared with the next patch.
While this makes no changes to SELinux policy, a new SELinux policy
compatibility entry was added in order to avoid breaking compilation of
an SELinux policy without explicitly specifying the policy version.
Signed-off-by: Daniel De Graaf <dgdegra@tycho.nsa.gov>
- No longer require the caller to create a sepol_policydb. CIL is now
responsible for that
- Since the user is no longer responsible for creating the policydb, two
functions are added to let CIL know how it should configure the
policydb, to set the policy version and the target platform
- Some functions, like cil_compile, do not need a policydb. Additionally
some functions, like cil_filecons_to_string use the policydb, but could
be rewritten to not require it. In these cases, remove the policydb
from the API, and rewrite functions so they don't depend on it. The
only function that uses a policydb is cil_build_policydb
- Add functions and symbolic versioning to maintain binary backwards
compatability. API backwards compatability is not maintained
Signed-off-by: Steve Lawrence <slawrence@tresys.com>
Reformat secilc(8) man page for readability and correct url
Remove unused/obsolete info and correct portcon statement in the
Reference Guide.
Signed-off-by: Richard Haines <richard_c_haines@btinternet.com>