Add support for reading, writing, and copying Infiniband Pkey ocontext
data. Also add support for querying a Pkey sid to checkpolicy.
Signed-off-by: Daniel Jurgens <danielj@mellanox.com>
Add checkpolicy support for scanning and parsing ibpkeycon labels. Also
create a new ocontext for Infiniband Pkeys and define a new policydb
version for infiniband support.
Signed-off-by: Daniel Jurgens <danielj@mellanox.com>
When allocating an array with calloc(), the first argument usually is
the number of items and the second one the size of an item. Doing so
silences a warning reported by clang's static analyzer:
kernel_to_cil.c:2050:14: warning: Call to 'calloc' has an allocation
size of 0 bytes.
cond_data = calloc(sizeof(struct cond_data), num);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
When common_to_cil() or class_to_cil() fail to allocate an array to map
a permissions hashtable (for example when permissions.nprim is too big),
class_perm_to_array() gets called on a NULL pointer. Fix this.
This issue has been found while fuzzing hll/pp with the American Fuzzy
Lop.
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
Since commit 58962eb3d8 ("libsepol,checkpolicy: add binary module
support for xperms") function avrule_read() has been using its "p"
argument even though it was previously marked unused. This makes clang
report:
policydb.c:3276:7: error: 'p' was marked unused but was used
[-Werror,-Wused-but-marked-unused].
if (p->policyvers < MOD_POLICYDB_VERSION_XPERMS_IOCTL) {
^
Remove the attribute to make the code consistent again.
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
Presently we support xperms rules in source policy and in CIL modules.
The binary policy module format however was never extended for xperms.
This limitation inhibits use of xperms in refpolicy-based policy modules
(including the selinux-testsuite policy). Update libsepol to support
linking, reading, and writing a new binary policy module version that
supports xperms rules. Update dismod to display xperms rules in binary
policy modules.
Also, to support use of a non-base binary policy module with a newer
version on a system using a base policy module with an older version,
automatically upgrade the version during module linking. This facilitates
usage of newer features in non-base modules without requiring rebuilding
the base module.
Tests:
1. Add an allowxperms rule to the selinux-testsuite policy and
confirm that it is properly written to the binary policy module
(displayed by dismod), converted to CIL (the latter was already supported),
and included in the kernel policy (via dispol and kernel test).
2. Use semodule_link and semodule_expand to manually link and expand
all of the .pp files via libsepol, and confirm that the allowxperms rule
is correctly propagated to the kernel policy. This test is required to
exercise the legacy link/expand code path for binary modules that predated
CIL.
Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
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>
s6_addr32 is not portable; use s6_addr instead.
This obviates the need for #ifdef __APPLE__ conditionals in these cases.
Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
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>
fcb5d5c removed ../include from CFLAGS from libsepol/utils/Makefile so
that a build tool can't find sepol/sepol.h when only libsepol is built
and a system is without sepol.h in standard paths. It should use its own
sepol.h file during build. `oveeride` needs to be used in order not to
be overridden by values provided on a command line. Same problem applies
to LDFLAGS.
Fixes:
$ make CFLAGS="" LDFLAGS=""
make[1]: Entering directory '/root/selinux/libsepol/utils'
cc chkcon.c -lsepol -o chkcon
chkcon.c:1:25: fatal error: sepol/sepol.h: No such file or directory
#include <sepol/sepol.h>
$ make CFLAGS="" LDFLAGS=""
...
make -C utils
make[1]: Entering directory '/root/selinux/libsepol/utils'
cc -I../include chkcon.c -lsepol -o chkcon
/usr/bin/ld: cannot find -lsepol
collect2: error: ld returned 1 exit status
Signed-off-by: Petr Lautrbach <plautrba@redhat.com>
When compiling with -Wwrite-strings, the compiler complains about
calling strs_add with a const char* value for a char* parameter
(DEFAULT_OBJECT is defined to "object_r"). Silence this warning by
casting the literal string to char*.
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
The toolchain automatically handles them and they break cross compiling.
LDFLAGS should also come before object files, some flags (eg,
-Wl,as-needed) can break things if they are in the wrong place)
Gentoo-Bug: https://bugs.gentoo.org/500674
Signed-off-by: Jason Zaman <jason@perfinion.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>
name_list_to_string() and constraint_expr_to_string() both define an
exit label to clean-up dynamically-allocated memory when an error
occurs, but they miss some variables. Free the missing ones too.
This issue has been found using clang's static analyzer.
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
When set_to_names() fails to allocate *names, it frees variable
attr_name even though it either came from attr_list or was newly created
and added to attr_list. By doing so, the name is freed a second time
when attr_list is destroyed (with "attr_list_destroy(&attr_list)").
Avoid this double free by not freeing attr_name when it belongs to
attr_list.
This issue has been found using clang's static analyzer.
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
Some invalid policies might have p->p_types.nprim = 0. When parsing
such a policy, "i > p->p_types.nprim - 1" is always false even though
reading p->type_val_to_struct[i] triggers a segmentation fault.
Make type_set_expand() return an error when parsing such a policy by
handling correctly when p->p_types.nprim is zero.
This issue has been found while fuzzing semodule_package with the
American Fuzzy Lop.
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
Some functions assumes that p->global is not NULL. For example
range_read() contains:
p->global->enabled->range_tr_rules = rtr;
However p->global may currently be NULL when loading a policy module
with no avrule block. Avoid a NULL pointer dereference by making such a
policy invalid.
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
sepol_*_key_free(NULL) should just be a no-op just like
free(NULL). Fix several instances that did not handle this
correctly and would seg fault if called with NULL.
Test: setsebool -P zebra_write_config=1 while non-root
Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
CIL does not allow type or role sets in certain rules (such as allow
rules). It does, however, allow sets in typeattributeset and
roleattributeset statements. Because of this, when module_to_cil
translates a policy into CIL, it creates a new attribute for each
set that it encounters. But often the same set is used multiple times
which means that more attributes are created then necessary. As the
number of attributes increases the time required for the kernel to
make each policy decision increases which can be a problem.
To help reduce the number of attributes in a kernel policy,
when module_to_cil encounters a role or type set search to see if the
set was encountered already and, if it was, use the previously
generated attribute instead of creating a new one.
Testing on Android and Refpolicy policies show that this reduces the
number of attributes generated by about 40%.
Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
It would sometimes be helpful for debugging or verification purposes
to be able to convert a binary policy to a human-readable form.
Create new function, sepol_kernel_policydb_to_conf(), that takes a
policydb created from a binary policy and writes a policy.conf file
to the provided FILE pointer.
Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
It would sometimes be helpful for debugging or verification purposes
to be able to convert a binary policy to a human-readable form.
Create new function, sepol_kernel_policydb_to_cil(), that takes a
policydb created from a binary policy and writes CIL policy to the
provided FILE pointer.
Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
When sepol_user_add_role() fails to allocate memory for role_cp but
succeeds in reallocating user->roles memory, it frees this reallocated
memory, thus leaving user->roles referencing a free memory block. When
sepol_user_clone() calls sepol_user_free(new_user) because the
allocation failure made sepol_user_add_role() fail, the following code
is executed:
for (i = 0; i < user->num_roles; i++)
free(user->roles[i]);
free(user->roles);
As user->roles has been freed, this code frees pointers which may be
invalid and then tries to free user->roles again.
Fix this flaw by returning right after strdup() failed in
sepol_user_add_role().
This issue has been found using clang's static analyzer.
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
When load_booleans() calls process_boolean() to parse a boolean
definition, process_boolean() returns a successful value when it fails
to use strtok_r() (e.g. when there is no "=" in the parsed line). This
leads load_booleans() to use uninitialized name and/or val when setting
the boolean into the policy.
Rework process_boolean() in order to report errors when a boolean
definition is incorrect.
This issue has been found using clang's static analyzer.
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
In cond_expr_to_cil() when stack_init(&stack) fails, stack is set to
NULL and the execution flow jumps to label "exit". This triggers a call
to stack_pop(stack) which dereferences a NULL pointer in "if (stack->pos
== -1)".
This issue has been found using clang's static analyzer.
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
When list_init() fails to allocate a list with calloc(), it calls
list_destroy(&l) with l = NULL. This functions starts by dereferencing
its argument ("(*list)->head"), which does not work well when it is
NULL.
This bug can be fixed by returning directly in list_init() when calloc()
fails. Doing so allows making list_init() implementation shorter by
removing label "exit" and local variable "rc".
This issue has been found using clang's static analyzer.
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
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>
Define the new cgroup_seclabel policy capability used to
enable userspace setting of security labels on cgroup files
via setfscreatecon() aka /proc/self/attr/fscreate and/or
setfilecon() aka setxattr().
Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
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>
Since fd9e5ef7b7 ("libsepol: use constant keys in hashtab functions")
it is possible to call hashtab_search() with a const char* key value.
Doing so fixes compiler warnings about non-const char* string literals
(-Wwrite-strings flag).
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>
A check is made in symtab_insert() for the case when an identifier
had already been declared and was now being required. This meant
that a declaration followed by a require was treated differently
from a require followed by a declaration.
Remove that check and treat both cases the same (which means
returning +1).
Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
Policy modules do not have the concept of named IP addresses like CIL
does. So when converting nodecode statements from pp policy modules to
CIL, we need to wrap the IP address and mask parameters in parentheses
so that the CIL compiler does not try to resolve them as named
addresses, but instead treats them as anonymous.
Signed-off-by: Steve Lawrence <slawrence@tresys.com>
ln on macOS doesn't support --relative, so use the gnu version by default.
Also document how to build on macOS.
Signed-off-by: Karl MacMillan <karlwmacmillan@gmail.com>
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>
When sepol_polcap_getname() is called with a negative capnum, it
dereferences polcap_names[capnum] which produces a segmentation fault
most of the time.
For information, here is a gdb session when hll/pp loads a policy module
which has been mutated by American Fuzzy Lop:
Program received signal SIGSEGV, Segmentation fault.
sepol_polcap_getname (capnum=capnum@entry=-4259840) at polcaps.c:34
34 return polcap_names[capnum];
=> 0x00007ffff7a8da07 <sepol_polcap_getname+135>: 48 8b 04 f8 mov
(%rax,%rdi,8),%rax
(gdb) bt
#0 sepol_polcap_getname (capnum=capnum@entry=-4259840) at
polcaps.c:34
#1 0x00007ffff7a7c440 in polcaps_to_cil (pdb=0x6042e0) at
module_to_cil.c:2492
#2 sepol_module_policydb_to_cil (fp=fp@entry=0x7ffff79c75e0
<_IO_2_1_stdout_>, pdb=0x6042e0, linked=linked@entry=0) at
module_to_cil.c:4039
#3 0x00007ffff7a7e695 in sepol_module_package_to_cil
(fp=fp@entry=0x7ffff79c75e0 <_IO_2_1_stdout_>, mod_pkg=0x604280) at
module_to_cil.c:4087
#4 0x0000000000401acc in main (argc=<optimized out>,
argv=<optimized out>) at pp.c:150
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
When running "make test" with the Address Sanitizer (by adding
-fsanitize=address to compiler flags), a lot of memory leaks are
reported from checkpolicy. Anyway some leaks come from the tests and it
seems cleaner to start fixing these ones.
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
When compiling libsepol tests, clang complains about some uninitialized
variables:
test-common.c:171:14: error: variable 'my_primary' is used
uninitialized whenever 'if' condition is false
[-Werror,-Wsometimes-uninitialized]
} else if (my_flavor == TYPE_ALIAS) {
^~~~~~~~~~~~~~~~~~~~~~~
test-common.c:179:30: note: uninitialized use occurs here
CU_ASSERT(type->primary == my_primary);
^~~~~~~~~~
/usr/include/CUnit/CUnit.h:123:30: note: expanded from macro
'CU_ASSERT'
{ CU_assertImplementation((value), __LINE__, #value, __FILE__, "", CU_...
^
test-common.c:171:10: note: remove the 'if' if its condition is
always true
} else if (my_flavor == TYPE_ALIAS) {
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
test-common.c:153:25: note: initialize the variable 'my_primary' to
silence this warning
unsigned int my_primary, my_flavor, my_value;
^
= 0
test-common.c:171:14: error: variable 'my_value' is used
uninitialized whenever 'if' condition is false
[-Werror,-Wsometimes-uninitialized]
} else if (my_flavor == TYPE_ALIAS) {
^~~~~~~~~~~~~~~~~~~~~~~
test-common.c:181:30: note: uninitialized use occurs here
CU_ASSERT(type->s.value == my_value);
^~~~~~~~
/usr/include/CUnit/CUnit.h:123:30: note: expanded from macro
'CU_ASSERT'
{ CU_assertImplementation((value), __LINE__, #value, __FILE__, "", CU_...
^
test-common.c:171:10: note: remove the 'if' if its condition is
always true
} else if (my_flavor == TYPE_ALIAS) {
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
test-common.c:153:46: note: initialize the variable 'my_value' to
silence this warning
unsigned int my_primary, my_flavor, my_value;
^
= 0
This is because the call to CU_FAIL("not an alias") is not fatal in
test_alias_datum(), and variables my_primary and my_value are indeed
used uninitialized in a CU_ASSERT statement later.
Silent the warning by moving the elseif condition to a CU_ASSERT
statement which replaces the CU_FAIL.
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>
Define the extended_socket_class policy capability used to enable
the use of separate socket security classes for all network address
families rather than the generic socket class. This also enables
separate security classes for ICMP and SCTP sockets, which were previously
mapped to the rawip_socket class.
The legacy redhat1 policy capability that was only ever used in testing
within Fedora for ptrace_child is reclaimed for this purpose; as far as
I can tell, this policy capability is not enabled in any supported distro
policy.
Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
self is included in a target type set.
When neverallow checking was refactored in commit 9e6840e, self
was not handled correctly. The assumption was made that self only
appeared by itself as a target type, when it may appear in a list of
types. Because of this, if self appears in a target type set of a
neverallow, the other types in the type set are not checked.
Example:
allow TYPE1 TYPE2:CLASS1 { PERM1 };
neverallow TYPE1 {TYPE2 self}:CLASS1 { PERM1 };
The old assertion checking would not find a violation in the rules
above because the target type TYPE2 would be ignored.
This fix will cause all of the types in a target list that includes
self to be checked.
Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
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>
Teach audit2why to recognize type bounds failures. This required
updating libsepol sepol_compute_av_reason() to identify bounds
failures, and updating libsepol context_struct_compute_av() to
include the type bounds logic from the kernel.
This could potentially be further augmented to provide more detailed
reporting via the reason buffer to include information similar to
what security_dump_masked_av() reports in the kernel. However, it
is unclear if this is needed. It is already possible to get type
bounds checking at policy build time by enabling expand-check=1
in /etc/selinux/semanage.conf (or by default when compiling
monolithic policy).
Before:
type=AVC msg=audit(1480451925.038:3225): avc: denied { getattr } for pid=7118 comm="chmod" path="/home/sds/selinux-testsuite/tests/bounds/bounds_file_blue" dev="dm-2" ino=23337697 scontext=unconfined_u:unconfined_r:test_bounds_child_t:s0-s0:c0.c1023 tcontext=unconfined_u:object_r:test_bounds_file_blue_t:s0 tclass=file permissive=0
Was caused by:
Unknown - would be allowed by active policy
Possible mismatch between this policy and the one under which the audit message was generated.
Possible mismatch between current in-memory boolean settings vs. permanent ones.
After:
type=AVC msg=audit(1480451925.038:3225): avc: denied { getattr } for pid=7118 comm="chmod" path="/home/sds/selinux-testsuite/tests/bounds/bounds_file_blue" dev="dm-2" ino=23337697 scontext=unconfined_u:unconfined_r:test_bounds_child_t:s0-s0:c0.c1023 tcontext=unconfined_u:object_r:test_bounds_file_blue_t:s0 tclass=file permissive=0
Was caused by:
Typebounds violation.
Add an allow rule for the parent type.
Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
chenxiaolong reported this via
https://github.com/SELinuxProject/selinux/issues/23
A nicer fix would be to rework the interface to be more
like security_av_string() in libselinux, but that requires
updating all callers.
Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
Tools like lcov (for code coverage) does not like files named
"<stdout>". For example it reports errors like:
genhtml: ERROR: cannot read
/usr/src/selinux/libsemanage/src/<stdout>
When using flex -o option, the output file name gets written in the
generated C code, which solves this issue.
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
A valid policy would not have two symbols (classes, roles, users...)
sharing the same unique identifier. Make policydb_read() rejects such
policy files.
When ..._val_to_name translation tables were allocated with malloc(),
change to calloc() in order to initialize the tables with NULLs.
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
When loading an invalid module which uses a declaration ID 0,
semodule_package crashes in policydb_index_decls():
p->decl_val_to_struct[decl->decl_id - 1] = decl;
gdb shows the following stack trace:
#0 0x00007ffff7aa1bbd in policydb_index_decls (p=p@entry=0x605360)
at policydb.c:1034
#1 0x00007ffff7aaa9fc in policydb_read (p=<optimized out>,
fp=fp@entry=0x605090, verbose=verbose@entry=0) at policydb.c:3958
#2 0x00007ffff7ab4764 in sepol_policydb_read (p=<optimized out>,
pf=pf@entry=0x605090) at policydb_public.c:174
#3 0x0000000000401d33 in main (argc=<optimized out>,
argv=0x7fffffffdc88) at semodule_package.c:220
Change policydb_index_decls() to report an error instead:
libsepol.policydb_index_decls: invalid decl ID 0
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
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>
Originally object_r's types bitmap was empty since we exempt
object_r from the normal user-role and role-type checks. CIL
however sets object_r's types to all types to avoid special case
logic. However, the kernel does not load object_r types from the
policy file; it predefines object_r and merely validates that the
object_r definition in the policy has the expected value. Thus,
the actual policy file and the /sys/fs/selinux/policy file were
differing in their object_r entry. Fix this by not writing object_r's
types to the policy file, since they are ignored by the kernel
anyway.
Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
Currently ebitmap_load() accepts loading a bitmap with highbit=192 and
one node {startbit=0, map=0x2}. When iterating over the bitmap,
ebitmap_for_each_bit() is expected to only yield "1" but it gives the
following bits: 1, 65, 129.
This is due to two facts in ebitmap_for_each_bit() implementation:
* ebitmap_next() stays on the first (and only) node of the bitmap
instead of stopping the iteration.
* the end condition of the for loop consists in comparing the bit with
ebitmap_length() (ie. the bitmap highbit), which is above the limit of
the last node here.
These are not bugs when the bitmap highbit is equals to
l->startbit+MAPSIZE, where l is the last node (this is how
ebitmap_set_bit() sets it). So a simple fix consists in making
ebitmap_load() reject bitmaps which are loaded with an invalid highbit
value.
This issue has been found while fuzzing semodule_package with the
American Fuzzy Lop.
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
Commit 02a7d77ef2 ("libsepol: make parsing symbol table headers more
robust") broke refpolicy build, because checkmodule generates avrule
decl blocks with "decl->symtab[i].nprim = 0" for all possible i, even
when decl->symtab[SYM_ROLES] and decl->symtab[SYM_TYPES] are not
empty.
More precisely, decl->symtab[i].nprim seems to be only updated in
libsepol/src/link.c (in *_copy_callback() functions).
Revert the buggy part of commit 02a7d77ef2 to fix this regression.
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
There is no reason to modify the number of roles defined in a policy
when no role is being inserted.
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
When running hll/pp on some invalid policy module, it can output:
libsepol.sepol_module_package_read: unknown magic number at section
1, offset: 251, number: 0x
The last number looks funny and was caused by using "%ux". "u" is not a
prefix like "l", "h", "z"... and "%x" already expects an unsigned
integer (cf. http://man7.org/linux/man-pages/man3/printf.3.html).
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
When fuzzing hll/pp, the fuzzer created a policy module with a block
which has no declaration. With block->branch_list = NULL,
typealias_list_create() triggered a NULL pointer dereference when
computing max_decl_id.
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
When hll/pp reads an invalid policy module where some scopes use
required symbols which are not defined, the program crashes with a
segmentation fault in required_scopes_to_cil():
Program received signal SIGSEGV, Segmentation fault.
required_scopes_to_cil (decl_stack=0x6040b0, block=0x607780,
pdb=0x6042e0, indent=0) at module_to_cil.c:3479
3479 for (j = 0; j < scope_datum->decl_ids_len; j++)
{
=> 0x00007ffff7a7b1a8 <block_to_cil+5224>: 44 8b 58 10 mov
0x10(%rax),%r11d
(gdb) bt
#0 required_scopes_to_cil (decl_stack=0x6040b0, block=0x607780,
pdb=0x6042e0, indent=0) at module_to_cil.c:3479
#1 block_to_cil (pdb=pdb@entry=0x6042e0,
block=block@entry=0x607780, stack=stack@entry=0x6040b0,
indent=indent@entry=0) at module_to_cil.c:3622
#2 0x00007ffff7a85a18 in global_block_to_cil (stack=0x6040b0,
block=0x607780, pdb=0x6042e0) at module_to_cil.c:3738
#3 blocks_to_cil (pdb=0x6042e0) at module_to_cil.c:3764
#4 sepol_module_policydb_to_cil (fp=fp@entry=0x7ffff79d05e0
<_IO_2_1_stdout_>, pdb=0x6042e0, linked=linked@entry=0) at
module_to_cil.c:4051
#5 0x00007ffff7a86b55 in sepol_module_package_to_cil
(fp=fp@entry=0x7ffff79d05e0 <_IO_2_1_stdout_>, mod_pkg=0x604280) at
module_to_cil.c:4080
#6 0x0000000000401acc in main (argc=<optimized out>,
argv=<optimized out>) at pp.c:150
(gdb) p scope_datum
$1 = (struct scope_datum *) 0x0
Detect such errors and exit with an error return value.
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
When hll/pp operates on an invalid policy module which defines blocks
with non-empty decl->symtab[SYM_COMMONS], additive_scopes_to_cil_map()
calls func_to_cil[SYM_COMMONS], which is NULL.
In additive_scopes_to_cil(), filter out NULL elements of func_to_cil
before calling additive_scopes_to_cil_map().
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
1. Use the new helper to convert from AVRULE to AVTAB values.
2. Only check once for invalid AVRULE specified parameter.
3. Drop assert and just return error on invalid specification.
Signed-off-by: William Roberts <william.c.roberts@intel.com>
General clean up for expand_avrule_helper:
1. Minimize the conversions of AVRULE specification to AVTAB specification,
they are almost the same, the one exception is AVRULE_DONTAUDIT.
2. Clean up the if/else logic, collapse with a switch.
3. Move xperms allocation and manipulation to its own helper.
4. Only write avkey for values that change.
5. Return error rather than assert on invalid specification.
Signed-off-by: William Roberts <william.c.roberts@intel.com>
Rather than having multiple copies of the AVTAB and AVRULE
defines, consolidate them.
This makes it clear that AVRULE to AVTAB conversion no longer
need to occur.
Signed-off-by: William Roberts <william.c.roberts@intel.com>
When hll/pp loads a policy file which has been modified so that the
nprim field of one of its non-empty symbol table was changed to zero, it
crashes with a segmentation fault. A quick analysis leads to
"p->sym_val_to_name[i] = (char **)alloc(p->symtab[i].nprim, sizeof(char
*));" in policydb_index_others(), which is not executed when
p->symtab[i].nprim is zero even though there are items in
p->symtab[i].table.
Detect such an oddity in the policy file early to exit with a clean
error message.
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
While fuzzing hll/pp, the fuzzer (AFL) crafted a policy which triggered
the following message without making the policy loading fail (the
program crashed with a segmentation fault later):
security: ebitmap: map size 192 does not match my size 64 (high bit
was 0)
This is because ebitmap_read() returned -EINVAL and this value was
handled as a successful return value by scope_index_read() because it
was not -1.
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
When fuzzing hll/pp inputs, a policy module where the value of
scope->decl_ids_len has been modified to zero makes the program abort
(when it has been compiled without -DNDEBUG).
Change the behavior to report an error message instead. This eases
fuzzing functions like policydb_read().
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
The combining logic for dontaudit rules was wrong, causing
a dontaudit A B:C *; rule to be clobbered by a dontaudit A B:C p;
rule.
This is a reimplementation of:
commit 6201bb5e25 ("libsepol:
fix checkpolicy dontaudit compiler bug")
that avoids the cumbersome pointer assignments on alloced.
Reported-by: Nick Kralevich <nnk@google.com>
Signed-off-by: William Roberts <william.c.roberts@intel.com>
The flex skeleton often triggers compiler warnings; make these
non-fatal for building. We already do likewise for checkpolicy.
Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
The combining logic for dontaudit rules was wrong, causing
a dontaudit A B:C *; rule to be clobbered by a dontaudit A B:C p;
rule.
Reported-by: Nick Kralevich <nnk@google.com>
Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
The sepol_{bool|iface|user}_key_create() functions were not
copying the name. This produces a use-after-free in the
swig-generated code for python3 bindings. Copy the name
in these functions, and free it upon sepol_{bool|iface|user}_key_free().
Reported-by: Nicolas Iooss <nicolas.iooss@m4x.org>
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>
Correct the build issues on mac, mostly flags for tools.
libsepol and cil now build completley on Mac with a
simple make command.
Signed-off-by: William Roberts <william.c.roberts@intel.com>
The local: * entry should only be in the base entry, not in each of them.
This is part of resolving gold linker build failures reported by
Jason Zaman.
Reported-by: Jason Zaman <jason@perfinion.com>
Signed-off-by: Stephen Smalley <sds@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>
Checkpolicy has an option to produce CIL output and is dependent on
the policydb-to-CIL conversion in libsepol for that option. Add
support for converting extended permissions to CIL so that checlpolicy
can generate CIL.
Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
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>
Commit 915fa8f08f moves the xperm specified value directly from
avrule to avtab. The mapping between them is currently the same,
but may not always be. Instead these values should be mapped using
values defined in av_extended_perms_t and avtab_extended_perms_t.
Fixes: 915fa8f08f ("checkpolicy: switch operations to extended perms")
Change-Id: Ic9f4031c9381b2ff6cc46043fb1602758ef4c224
Signed-off-by: Jeff Vander Stoep <jeffv@google.com>
Fix this:
genusers.c:63:14: warning: variable 'nread' is uninitialized when used here [-Wuninitialized]
if (buffer[nread - 1] == '\n')
^~~~~
genusers.c:40:15: note: initialize the variable 'nread' to silence this warning
ssize_t nread;
^
= 0
Signed-off-by: William Roberts <william.c.roberts@intel.com>
Fix this on Mac build:
genbools.c:71:9: warning: unused variable 'size' [-Wunused-variable]
size_t size = 0;
^
Signed-off-by: William Roberts <william.c.roberts@intel.com>
Even though g_b_role_2 is used both in
tests/policies/test-linker/small-base.conf and
tests/policies/test-linker/module1.conf, it seems to only exists in the
scope of the base policy.
This fixes the following failure of "make -C libsepol test":
./libsepol-tests
CUnit - A unit testing framework for C - Version 2.1-3
http://cunit.sourceforge.net/
Suite: cond
Test: cond_expr_equal ...passed
Suite: linker
Test: linker_indexes ...passed
Test: linker_types ...passed
Test: linker_roles ...sym g_b_role_2 has 1 decls, 2 expected
FAILED
1. test-common.c:43 - scope->decl_ids_len == len
2. test-common.c:52 - found == 1
Test: linker_cond ...passed
Suite: expander
Test: expander_indexes ...passed
Test: expander_attr_mapping ...passed
Test: expander_role_mapping ...passed
Test: expander_user_mapping ...passed
Test: expander_alias ...passed
Suite: deps
Test: deps_modreq_global ...passed
Test: deps_modreq_opt ...passed
Suite: downgrade
Test: downgrade ...passed
Run Summary: Type Total Ran Passed Failed Inactive
suites 5 5 n/a 0 0
tests 13 13 12 1 0
asserts 1274 1274 1272 2 n/a
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
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>
Rather than duplicating the following sequence:
1. Read len from file
2. alloc up space based on 1
3. read the contents into the buffer from 2
4. null terminate the buffer from 2
Use the str_read() function that is in the kernel, which
collapses steps 2 and 4. This not only reduces redundant
code, but also has the side-affect of providing a central
check on zero_or_saturated lengths from step 1 when
generating string values.
Signed-off-by: William Roberts <william.c.roberts@intel.com>
The usage patterns between these structures seem similair
to role_val_to_struct usages. Calloc these up to prevent
any unitialized usages.
Signed-off-by: William Roberts <william.c.roberts@intel.com>
Throughout libsepol, values taken from sepolicy are used in
places where length == 0 or length == <saturated> matter,
find and fix these.
Also, correct any type mismatches noticed along the way.
Signed-off-by: William Roberts <william.c.roberts@intel.com>
When initializing role_datum_t array, initialize the array.
This corrects this issue:
==25766== Conditional jump or move depends on uninitialised value(s)
==25766== at 0x40ABFE: context_is_valid (context.c:59)
==25766== by 0x40AAED: policydb_context_isvalid (context.c:19)
==25766== by 0x43CBF4: context_read_and_validate (policydb.c:1881)
==25766== by 0x43E7B3: ocontext_read_selinux (policydb.c:2631)
==25766== by 0x43EC4D: ocontext_read (policydb.c:2729)
==25766== by 0x442019: policydb_read (policydb.c:3937)
==25766== by 0x442F15: sepol_policydb_read (policydb_public.c:174)
==25766== by 0x407ED4: init (check_seapp.c:885)
==25766== by 0x408D83: main (check_seapp.c:1230)
Also, check for NULL when determining if a role can be associated
with a type.
Signed-off-by: William Roberts <william.c.roberts@intel.com>
The newc variable is calloc'd and assigned to a new
owner during a loop. After the first assignment of newc
to newgenfs->head, the subsequent iteration could fail
before the newc is reseated with a new heap allocation
pointer. When the subsequent iteration fails, the
newc variable is freed. Later, an attempt it made to
free the same pointer assigned to newgenfs->head.
To correct this, clear newc after every loop iteration.
Signed-off-by: William Roberts <william.c.roberts@intel.com>
When count is 0 and the highbit is not zero, the ebitmap is not
valid and the internal node is not allocated. This causes issues
when routines, like mls_context_isvalid() attempt to use the
ebitmap_for_each_bit() and ebitmap_node_get_bit() as they assume
a highbit > 0 will have a node allocated.
Signed-off-by: William Roberts <william.c.roberts@intel.com>
In type_set_expand:
When nprim, the table index counter, is greater than the value of initizalized
entries in the type_val_to_struct[] array, detect this as invalid
and return an error.
Signed-off-by: William Roberts <william.c.roberts@intel.com>
ebitmap_set_bit() can possible allocate nodes, however, the bail early
style of type_set_expand() could leave internal ebitmaps allocated
but not free'd.
Modify type_set_expand() so that it free's all allocated ebitmaps
before returning the error code to the calling routine.
Signed-off-by: William Roberts <william.c.roberts@intel.com>
AFL Found this bug:
==6523== Invalid read of size 8
==6523== at 0x4166B4: type_set_expand (expand.c:2508)
==6523== by 0x43A0B8: policydb_role_cache (policydb.c:790)
==6523== by 0x41CD70: hashtab_map (hashtab.c:235)
==6523== by 0x43AC9E: policydb_index_others (policydb.c:1103)
==6523== by 0x441B14: policydb_read (policydb.c:3888)
==6523== by 0x442A1F: sepol_policydb_read (policydb_public.c:174)
==6523== by 0x407ED4: init (check_seapp.c:885)
==6523== by 0x408D97: main (check_seapp.c:1231)
This occurs when the type_val_to_struct[] mapping array
doesn't contain the type indicated in the ebitmap.
Signed-off-by: William Roberts <william.c.roberts@intel.com>
Correct errors like these reported by gcc:
module_to_cil.c: In function ‘block_to_cil’:
module_to_cil.c:229:20: error: ‘attr_list’ may be used uninitialized in this function [-Werror=maybe-uninitialized]
struct list_node *curr = (*attr_list)->head;
Usages of attr_list_destroy() were called when list_init()
fails.
stack_init() and stack_destroy() also suffered from the
aforementioned issue.
To correct the issue, initialize stack and list variables to
NULL.
Signed-off-by: William Roberts <william.c.roberts@intel.com>
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>
Bail before running off the end of the class index
Change-Id: I47c4eaac3c7d789f8d85047e34e37e3f0bb38b3a
Signed-off-by: Joshua Brindle <brindle@quarksecurity.com>
This patch is part of the Debian effort to make the build reproducible
Thank to Reiner Herrmann <reiner@reiner-h.de> for the patches
Signed-off-by: Laurent Bigonville <bigon@bigon.be>
The following test incorrectly asserts a neverallowxperm failure.
attribute test1_attr1;
attribute test1_attr2;
type test1_type1, test1_attr1, test1_attr2;
allow test1_type1 test1_attr1:socket ioctl;
allowxperm test1_type1 test1_attr2:socket ioctl { 1 };
neverallowxperm test1_attr1 test1_attr1:socket ioctl { 0 }
To handle attributes correctly, the neverallowxperm checking has been
modified. Now when the ioctl permission is granted on an avtab entry
that matches an avrule neverallowxperm entry, the assertion checking
first determines the matching source/target/class sets between the
avtab entry and the neverallowxperm entry. Only the matching sets are
enumerated over to determine if the neverallowed extended permissions
exist and if they are granted. This is similar to how
report_assertion_avtab_matches() reports neverallow failures.
Signed-off-by: Jeff Vander Stoep <jeffv@google.com>
When converting pp files to CIL or generating CIL using checkpolicy
or checkmodule use CIL's HLL line mark annotations to record the
original file and line numbers for neverallow rules so that CIL can
produce more informative error messages. (Unfortunately, the original
line number information is not saved in pp files, so there is no benefit
for policy modules.)
This is only done for neverallow rules currently.
Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
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>
Change logic of bounds checking to match kernel's bound checking.
The following explanation is taken from Stephen Smalley's kernel
patch.
Under the new logic, if the source type and target types are both
bounded, then the parent of the source type must be allowed the same
permissions to the parent of the target type. If only the source
type is bounded, then the parent of the source type must be allowed
the same permissions to the target type.
Examples of the new logic and comparisons with the old logic:
1. If we have:
typebounds A B;
then:
allow B self:process <permissions>;
will satisfy the bounds constraint iff:
allow A self:process <permissions>;
is also allowed in policy.
Under the old logic, the allow rule on B satisfies the
bounds constraint if any of the following three are allowed:
allow A B:process <permissions>; or
allow B A:process <permissions>; or
allow A self:process <permissions>;
However, either of the first two ultimately require the third to satisfy
the bounds constraint under the old logic, and therefore this degenerates
to the same result (but is more efficient - we only need to perform
one compute_av call).
2. If we have:
typebounds A B;
typebounds A_exec B_exec;
then:
allow B B_exec:file <permissions>;
will satisfy the bounds constraint iff:
allow A A_exec:file <permissions>;
is also allowed in policy.
This is essentially the same as #1; it is merely included as
an example of dealing with object types related to a bounded domain
in a manner that satisfies the bounds relationship. Note that
this approach is preferable to leaving B_exec unbounded and having:
allow A B_exec:file <permissions>;
in policy because that would allow B's entrypoints to be used to
enter A. Similarly for _tmp or other related types.
3. If we have:
typebounds A B;
and an unbounded type T, then:
allow B T:file <permissions>;
will satisfy the bounds constraint iff:
allow A T:file <permissions>;
is allowed in policy.
The old logic would have been identical for this example.
4. If we have:
typebounds A B;
and an unbounded domain D, then:
allow D B:unix_stream_socket <permissions>;
is not subject to any bounds constraints under the new logic
because D is not bounded. This is desirable so that we can
allow a domain to e.g. connectto a child domain without having
to allow it to do the same to its parent.
The old logic would have required:
allow D A:unix_stream_socket <permissions>;
to also be allowed in policy.
Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
As per discussion in https://android-review.googlesource.com/#/c/221980,
we should be using #ifdef __APPLE__ rather than our own custom-defined
DARWIN for building on MacOS X.
Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
The current bounds checking of both source and target types
requires allowing any domain that has access to the child domain
to also have the same permissions to the parent, which is undesirable.
Drop the target bounds expansion and checking.
Making this change fully functional requires a corresponding kernel
change; this change only allows one to build policies that would
otherwise violate the bounds checking on target type. The kernel
change is required to allow the permissions at runtime.
Based on patch by Stephen Smalley.
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>
Commit 99fc177b "Add neverallow support for ioctl extended permissions"
first checks to see if the ioctl permission is granted, then checks to
see if the same source/target violates a neverallowed ioctl command.
Unfortunately this does not address the case where the ioctl permission
and extended permissions are granted on different attributes. Example,
the following will incorrectly cause a neverallow violation.
allow untrusted_app self:tcp_socket ioctl;
allowxperm domain domain:tcp_socket unpriv_sock_ioctls;
neverallowxperm untrusted_app domain:tcp_socket ~unpriv_sock_ioctls;
The fix is to enumerate over the source and target attributes when
looking for extended permission violations.
Note: The bug this addresses incorrectly asserts that a violation has
occurred. Actual neverallow violations are always caught.
Signed-off-by: Jeff Vander Stoep <jeffv@google.com>
Tested-by: William Roberts <william.c.roberts@intel.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>