• Home
  • History
  • Annotate
  • only in /external/selinux/libsepol/src/
History log of /external/selinux/libsepol/src/
Revision Date Author Comments (<<< Hide modified files) (Show modified files >>>)
4da8fcc21a3240345c727ab8207225d76f12fc7d 23-Oct-2017 Jan Zarsky <jzarsky@redhat.com> libsepol: free ibendport device names

When reading policy, ibendport device names are allocated in
ocontext_read_selinux() but they are not freed when calling
sepol_policydb_free();

Fix this by freeing them in ocontext_selinux_free().

Signed-off-by: Jan Zarsky <jzarsky@redhat.com>
olicydb.c
77059c39e8a06743de9a15fb4501dac85ae0f889 13-Sep-2017 Jan Zarsky <jzarsky@redhat.com> libsepol: fix memory leak in sepol_bool_query()

When sepol_bool_query() returns NULL response, variable name is not
freed. Fix this by calling free() before returning.

Signed-off-by: Jan Zarsky <jzarsky@redhat.com>
ooleans.c
51bc21036ce3368506cf9db2b319ab42eb355515 03-Sep-2017 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: use IN6ADDR_ANY_INIT to initialize IPv6 addresses

When compiling libsepol with clang and some warning flags, the compiler
complains about the way IPv6 addresses are initialized:

kernel_to_cil.c:2795:35: error: suggest braces around initialization
of subobject [-Werror,-Wmissing-braces]
struct in6_addr subnet_prefix = {0};
^
{}

When replacing the initializer as suggested, gcc 4.8.4 complains:

kernel_to_cil.c: In function ‘write_selinux_ibpkey_rules_to_cil’:
kernel_to_cil.c:2795:9: error: missing initializer for field
‘__in6_u’ of ‘struct in6_addr’ [-Werror=missing-field-initializers]
struct in6_addr subnet_prefix = {};
^

Thankfully netinet/in.h provides a macro to initialize struct in6_addr
variables:

#define IN6ADDR_ANY_INIT { { { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } } }

Both clang and gcc no longer report warnings when using this macro.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
ernel_to_cil.c
ernel_to_conf.c
odule_to_cil.c
fafe4c212bf6c32c3021d7b69bcc0cf219e71608 29-Aug-2017 Dan Cashman <dcashman@android.com> libsepol: cil: Add ability to redeclare types[attributes]

Modify cil_gen_node() to check to see if the cil_db supports multiple
declarations, and if so, to check whether or not the
repeated symbol is eligible to share the existing, already-stored datum. The
only types considered so far are CIL_TYPE and CIL_TYPEATTRIBUTE, both of
which intall empty datums during AST building, so they automatically return
true.

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

Signed-off-by: Dan Cashman <dcashman@android.com>
Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
ibsepol.map.in
53bb2a11c23b774f096701bab759c6ab9ec52ea1 17-Aug-2017 Stephen Smalley <sds@tycho.nsa.gov> checkpolicy,libselinux,libsepol,policycoreutils: Update my email address

Update my email address since epoch.ncsc.mil no longer exists.

Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
vtab.c
bitmap.c
ashtab.c
ls.c
ls.h
olicydb.c
ervices.c
idtab.c
ymtab.c
rite.c
ae1cd1207605fbe57a895151039e3c3d7c98b2b8 14-Jul-2017 Stephen Smalley <sds@tycho.nsa.gov> libsepol: Define nnp_nosuid_transition policy capability

Define the nnp_nosuid_transition policy capability used to enable
SELinux domain transitions under NNP or nosuid if the
nnp_transition permission or nosuid_transition permission is
allowed between the old and new contexts. When this capability is not
enabled, such transitions remain limited to bounded transitions as they
were prior to the introduction of this capability.

Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
olcaps.c
f2b5aae4aa70e192a26fbf8f8cb0e621db19a25d 09-Jun-2017 James Carter <jwcart2@tycho.nsa.gov> libsepol: Fix neverallow bug when checking conditional policy

Commit 9e6840e refactored neverallow checking. In the process a bug
was introduced that causes enabled conditional rules to be skipped.
The bug is that the avtab key is checked by comparing the specified
field of the key to the value AVTAB_ALLOWED. Since enabled conditional
rules have an additional bit set as well, these rules are not
considered to match.

The fix is to use a bitwise AND (&) to only check the desired bit.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
ssertion.c
f6f4876dfce648e94cded4666ec5231f947e50b5 11-Jun-2017 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: destroy the expanded level when mls_semantic_level_expand() fails

In mls_semantic_range_expand(), when a call to
mls_semantic_level_expand() fails, the function destroys the semantic
level instead of the expanded one. This leads to a use-after-free which
is reported by gcc's Address Sanitizer:

libsepol.mls_semantic_level_expand: mls_semantic_level_expand: invalid sensitivity level found 128/0.
libsepol.sepol_module_package_read: invalid module in module package (at section 0)
Failed to read policy package
=================================================================
==24456==ERROR: AddressSanitizer: heap-use-after-free on address 0x60200000ee58 at pc 0x7fe6c4fb96b4 bp 0x7fffa5ea6b70 sp 0x7fffa5ea6b60
READ of size 8 at 0x60200000ee58 thread T0
#0 0x7fe6c4fb96b3 in mls_semantic_level_destroy /usr/src/selinux/libsepol/src/mls.c:755
#1 0x7fe6c4fb9b88 in mls_semantic_range_destroy /usr/src/selinux/libsepol/src/mls.c:802
#2 0x7fe6c500e8ab in user_datum_destroy /usr/src/selinux/libsepol/src/policydb.c:535
#3 0x7fe6c500e980 in user_destroy /usr/src/selinux/libsepol/src/policydb.c:1390
#4 0x7fe6c4f36c48 in hashtab_map /usr/src/selinux/libsepol/src/hashtab.c:235
#5 0x7fe6c50152da in symtabs_destroy /usr/src/selinux/libsepol/src/policydb.c:1595
#6 0x7fe6c5015433 in policydb_destroy /usr/src/selinux/libsepol/src/policydb.c:1503
#7 0x7fe6c5040e0d in sepol_policydb_free /usr/src/selinux/libsepol/src/policydb_public.c:82
#8 0x7fe6c4fbc503 in sepol_module_package_free /usr/src/selinux/libsepol/src/module.c:143
#9 0x7fe6c4fefefb in sepol_ppfile_to_module_package /usr/src/selinux/libsepol/src/module_to_cil.c:4293
#10 0x401e51 in main /usr/src/selinux/policycoreutils/hll/pp/pp.c:124
#11 0x7fe6c4add510 in __libc_start_main (/usr/lib/libc.so.6+0x20510)
#12 0x402589 in _start (/usr/src/selinux/DESTDIR/usr/libexec/selinux/hll/pp+0x402589)

0x60200000ee58 is located 8 bytes inside of 16-byte region [0x60200000ee50,0x60200000ee60)
freed by thread T0 here:
#0 0x7fe6c5537ae0 in __interceptor_free /build/gcc-multilib/src/gcc/libsanitizer/asan/asan_malloc_linux.cc:45
#1 0x7fe6c4fb969b in mls_semantic_level_destroy /usr/src/selinux/libsepol/src/mls.c:757
#2 0x7fe6c4f02a57 in mls_semantic_range_expand /usr/src/selinux/libsepol/src/expand.c:948
#3 0x7fe6c5007a98 in policydb_user_cache /usr/src/selinux/libsepol/src/policydb.c:939
#4 0x7fe6c4f36c48 in hashtab_map /usr/src/selinux/libsepol/src/hashtab.c:235
#5 0x7fe6c5013859 in policydb_index_others /usr/src/selinux/libsepol/src/policydb.c:1286
#6 0x7fe6c5020b65 in policydb_read /usr/src/selinux/libsepol/src/policydb.c:4342
#7 0x7fe6c4fc0cdb in sepol_module_package_read /usr/src/selinux/libsepol/src/module.c:618
#8 0x7fe6c4ff008d in sepol_ppfile_to_module_package /usr/src/selinux/libsepol/src/module_to_cil.c:4276
#9 0x401e51 in main /usr/src/selinux/policycoreutils/hll/pp/pp.c:124
#10 0x7fe6c4add510 in __libc_start_main (/usr/lib/libc.so.6+0x20510)

previously allocated by thread T0 here:
#0 0x7fe6c5537e40 in __interceptor_malloc /build/gcc-multilib/src/gcc/libsanitizer/asan/asan_malloc_linux.cc:62
#1 0x7fe6c5004efc in mls_read_semantic_level_helper /usr/src/selinux/libsepol/src/policydb.c:1976
#2 0x7fe6c500f596 in mls_read_semantic_range_helper /usr/src/selinux/libsepol/src/policydb.c:2010
#3 0x7fe6c500f596 in user_read /usr/src/selinux/libsepol/src/policydb.c:3258
#4 0x7fe6c502055b in policydb_read /usr/src/selinux/libsepol/src/policydb.c:4286
#5 0x7fe6c4fc0cdb in sepol_module_package_read /usr/src/selinux/libsepol/src/module.c:618
#6 0x7fe6c4ff008d in sepol_ppfile_to_module_package /usr/src/selinux/libsepol/src/module_to_cil.c:4276
#7 0x401e51 in main /usr/src/selinux/policycoreutils/hll/pp/pp.c:124
#8 0x7fe6c4add510 in __libc_start_main (/usr/lib/libc.so.6+0x20510)

SUMMARY: AddressSanitizer: heap-use-after-free /usr/src/selinux/libsepol/src/mls.c:755 in mls_semantic_level_destroy
Shadow bytes around the buggy address:
0x0c047fff9d70: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c047fff9d80: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c047fff9d90: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c047fff9da0: fa fa fa fa fa fa fa fa fa fa 01 fa fa fa 01 fa
0x0c047fff9db0: fa fa 01 fa fa fa 01 fa fa fa 01 fa fa fa 01 fa
=>0x0c047fff9dc0: fa fa 00 00 fa fa 00 00 fa fa fd[fd]fa fa fd fd
0x0c047fff9dd0: fa fa fd fd fa fa fd fd fa fa fd fa fa fa fd fd
0x0c047fff9de0: fa fa 04 fa fa fa 00 01 fa fa fd fd fa fa fd fd
0x0c047fff9df0: fa fa fd fd fa fa fd fd fa fa 00 00 fa fa fd fd
0x0c047fff9e00: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c047fff9e10: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
Shadow byte legend (one shadow byte represents 8 application bytes):
Addressable: 00
Partially addressable: 01 02 03 04 05 06 07
Heap left redzone: fa
Heap right redzone: fb
Freed heap region: fd
Stack left redzone: f1
Stack mid redzone: f2
Stack right redzone: f3
Stack partial redzone: f4
Stack after return: f5
Stack use after scope: f8
Global redzone: f9
Global init order: f6
Poisoned by user: f7
Container overflow: fc
Array cookie: ac
Intra object redzone: bb
ASan internal: fe
Left alloca redzone: ca
Right alloca redzone: cb
==24456==ABORTING

This issue has been found while fuzzing hll/pp with the American Fuzzy
Lop.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
xpand.c
f9ae34a40440d194b60fbd1ce570b8b094f1a94d 09-May-2017 James Carter <jwcart2@tycho.nsa.gov> libsepol: Expand attributes with TYPE_FLAGS_EXPAND_ATTR_TRUE set

Commit 1089665e31a647a5f0ba2eabe8ac6232b384bed9 (Add attribute
expansion options) adds an expandattribute rule to the policy.conf
language which sets a type_datum flag. Currently the flag is used
only when writing out CIL policy from a policy.conf.

Make use of the flag when expanding policy to expand policy rules
and remove all type associations for an attribute that has
TYPE_FLAGS_EXPAND_ATTR_TRUE set. (The attribute will remain in the
policy, but have no types associated with it.)

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
xpand.c
ink.c
22ac4f9bd388dc3b36d17194fe697987e49325e8 31-May-2017 Stephen Smalley <sds@tycho.nsa.gov> libsepol: Fix alloc-size-larger-than warning from gcc 7

Fixes the following warning from gcc 7:

In function ‘name_list_to_string’,
inlined from ‘constraint_expr_to_string’ at module_to_cil.c:1790:8:
module_to_cil.c:1135:6: warning: argument 1 range [18446744071562067968, 18446744073709551615] exceeds maximum object size 9223372036854775807 [-Walloc-size-larger-than=]
str = malloc(len);
~~~~^~~~~~~~~~~~~
In file included from module_to_cil.c:36:0:
module_to_cil.c: In function ‘constraint_expr_to_string’:
/usr/include/stdlib.h:443:14: note: in a call to allocation function ‘malloc’ declared here
extern void *malloc (size_t __size) __THROW __attribute_malloc__ __wur;
^~~~~~

While we are here, fix a few other issues too.
The usage of snprintf was wrong and unnecessary; we just allocated
the string to be the right size, so we should just fill it.

Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
odule_to_cil.c
187a44d05884c2cc06c32aa010a4af4b76945a65 30-May-2017 James Carter <jwcart2@tycho.nsa.gov> libsepol: Fix module_to_cil's handling of type aliases

Type aliases present a problem for module_to_cil because they are not
in the sym_val_to_name table that it uses to write declarations. Type
aliases are gathered by going through the decl_ids list and then
the alias declaration is written out when the block with that scope
id is handled. This doesn't work if a type alias appears in a require
block, since the require cannot be distinguished from the declaration.
The result is two declarations of the alias and an error when secilc
compiles the policy.

Because of the work cleaning up scope handling, the alias declaration
will always be at the end of the decl_ids list, so now only gather
the last scope id.

Also, when an alias is used in a module it is required as a type and
it will appear in the sym_val_to_name table. When that occurs, just
skip the alias when writing out types.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
odule_to_cil.c
c8a7edc614ee3abe63d6f4a8d7fa9c0d342599b7 30-May-2017 James Carter <jwcart2@tycho.nsa.gov> libsepol: Clean up scope handling

Currently, when checking if an identifier is enabled, each scope in
the decl_ids list is checked. This means that if any block that
requires the identifier is enabled, then the identifier will be treated
as being declared.

Now, declarations will be kept at the end of the decl_ids list and
when checking if an identifier is enabled, only the last scope will
be checked (Except for roles and users which allow multiple declarations,
they will have to keep the old behavior.)

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
vrule_block.c
olicydb.c
a522d5765d38e6377ccd64b86d6148bb78fcf7b5 31-May-2017 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: do not use handle when it is marked unused

Assigning NULL to handle does not perform anything useful and clang
complains about this:

ibendports.c:122:2: error: 'handle' was marked unused but was used
[-Werror,-Wused-but-marked-unused]
handle = NULL;
^
ibpkeys.c:115:2: error: 'handle' was marked unused but was used
[-Werror,-Wused-but-marked-unused]
handle = NULL;
^

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
bendports.c
bpkeys.c
914691cc2a8d2bffe5e31a292b90936b2b76f543 22-May-2017 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: make role_list_destroy() do nothing when role_list is NULL

When a function called by sepol_module_policydb_to_cil() fails before
role_list_create() has been called, role_list is still NULL but is
dereferenced in role_list_destroy(). Here is a gdb session on hll/pp:

Unknown value for handle-unknown: 6

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7a68a37 in role_list_destroy () at module_to_cil.c:215
215 struct list_node *curr = role_list->head;

(gdb) bt
#0 0x00007ffff7a68a37 in role_list_destroy () at
module_to_cil.c:215
#1 sepol_module_policydb_to_cil (fp=fp@entry=0x7ffff79925e0
<_IO_2_1_stdout_>, pdb=<optimized out>, linked=linked@entry=0) at
module_to_cil.c:4060
#2 0x00007ffff7a6ac75 in sepol_module_package_to_cil
(fp=fp@entry=0x7ffff79925e0 <_IO_2_1_stdout_>, mod_pkg=0x604280) at
module_to_cil.c:4080
#3 0x0000000000401a58 in main (argc=<optimized out>,
argv=<optimized out>) at pp.c:150

This issue has been found while fuzzing hll/pp with the American Fuzzy
Lop.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
odule_to_cil.c
9a3d2c7a9b78f7ca04977a4c5a6bda4c8875c89c 22-May-2017 Daniel Jurgens <danielj@mellanox.com> semanage: Update semanage to allow runtime labeling of ibendports

Update libsepol and libsemanage to work with ibendport records. Add local
storage for new and modified ibendport records in ibendports.local.
Update semanage to parse the ibendport command options to add, modify,
and delete them.

Signed-off-by: Daniel Jurgens <danielj@mellanox.com>
bendport_internal.h
bendport_record.c
bendports.c
6a7a5aafe52aa7dbd2daab1645829fd9821e716f 22-May-2017 Daniel Jurgens <danielj@mellanox.com> semanage: Update semanage to allow runtime labeling of Infiniband Pkeys

Update libsepol and libsemanage to work with pkey records. Add local
storage for new and modified pkey records in pkeys.local. Update semanage
to parse the pkey command options to add, modify, and delete pkeys.

Signed-off-by: Daniel Jurgens <danielj@mellanox.com>
bpkey_internal.h
bpkey_record.c
bpkeys.c
118c0cd1038efb8d869db70753d2ac449f4fda9b 22-May-2017 Daniel Jurgens <danielj@mellanox.com> libsepol: Add ibendport ocontext handling

Add support for reading, writing, and copying IB end port ocontext data.
Also add support for querying a IB end port sid to checkpolicy.

Signed-off-by: Daniel Jurgens <danielj@mellanox.com>
xpand.c
ernel_to_cil.c
ernel_to_common.c
ernel_to_conf.c
ibsepol.map.in
odule_to_cil.c
olicydb.c
ervices.c
rite.c
9fbb3112769a7931777f30894156d981b6933415 22-May-2017 Daniel Jurgens <danielj@mellanox.com> libsepol: Add ibpkey ocontext handling

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>
xpand.c
ernel_to_cil.c
ernel_to_common.c
ernel_to_conf.c
ibsepol.map.in
odule_to_cil.c
olicydb.c
ervices.c
rite.c
bfd61a3ec70b7d614f7d778e0959560f79fd7c4a 20-May-2017 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: use the number of elements in calloc first argument

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>
ernel_to_cil.c
d00cc134837c36b47c374414668b29c4489b2725 20-May-2017 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: propagate calloc() failure

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>
odule_to_cil.c
8fe362f0121ab6d82f646ae51948a8df4a8834c6 17-May-2017 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: remove unused attribute on a used argument

Since commit 58962eb3d847 ("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>
olicydb.c
58962eb3d847bd4bfd37c6790d13f361bbe543f9 15-May-2017 Stephen Smalley <sds@tycho.nsa.gov> libsepol,checkpolicy: add binary module support for xperms

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>
ink.c
olicydb.c
rite.c
c3118041df74124c5b8b8d769354bb0ca4c5ac19 10-May-2017 Stephen Smalley <sds@tycho.nsa.gov> checkpolicy,libsepol: drop unnecessary usage of s6_addr32

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>
ode_record.c
1089665e31a647a5f0ba2eabe8ac6232b384bed9 04-May-2017 Jeff Vander Stoep <jeffv@google.com> Add attribute expansion options

This commit adds attribute expansion statements to the policy
language allowing compiler defaults to be overridden.

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

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

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

Motivation

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

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

expandattribute false:
Commit 0be23c3f15fd 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>
odule_to_cil.c
1dc95dd5588bee62a39a96fb8ba5e57ace94051a 03-May-2017 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: silence false-positive -Wwrite-strings warning

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>
ernel_to_cil.c
0be23c3f15fdbef35a57d8586aeeae9b1f7606cc 12-Apr-2017 James Carter <jwcart2@tycho.nsa.gov> libsepol/cil: Add ability to expand some attributes in binary policy

Originally, all type attributes were expanded when building a binary
policy. As the policy grew, binary policy sizes became too large, so
changes were made to keep attributes in the binary policy to minimize
policy size.

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

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

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

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

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

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

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

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
ibsepol.map.in
473753f21a44496107e491dc265cf2236599766c 10-Apr-2017 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: correct spelling errors in module_to_cil.c comments

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
odule_to_cil.c
d88657bc4d3407208d4f37665d12715368810561 10-Apr-2017 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: do not leak memory when an error occurs

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>
odule_to_cil.c
8ccd0db8609cc372eaf96beb48f09decd3106b6a 10-Apr-2017 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: do not free attr_name twice

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>
odule_to_cil.c
3e7fd1daba5d3d8c861606ab8d706269634022ad 07-Apr-2017 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: do not wrap integers when checking bound

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>
xpand.c
42e32227da3db728ca8ead4690a1147183fb223c 07-Apr-2017 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: refuse to load policies with no block

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>
olicydb.c
e6edc424555d4f8d1d6a968072e137a77656d480 07-Apr-2017 Stephen Smalley <sds@tycho.nsa.gov> libsepol: do not seg fault on sepol_*_key_free(NULL)

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>
oolean_record.c
face_record.c
ser_record.c
92f22e193a7e78702178bf9960f03167ba3ea1df 29-Mar-2017 James Carter <jwcart2@tycho.nsa.gov> libsepol: In module_to_cil create one attribute for each unique set

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>
odule_to_cil.c
0a08fd1e69797d6ab315ee17d797ef12dae25ce9 21-Mar-2017 James Carter <jwcart2@tycho.nsa.gov> libsepol: Add ability to convert binary policy to policy.conf file

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>
ernel_to_conf.c
ibsepol.map.in
70a480bfcd46214a1cc0fc2cc6c13b72f567480a 21-Mar-2017 James Carter <jwcart2@tycho.nsa.gov> libsepol: Add ability to convert binary policy to CIL

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>
ernel_to_cil.c
ernel_to_common.c
ernel_to_common.h
ibsepol.map.in
b251dbba9845e36b93b59b7489ddfd9113009283 28-Mar-2017 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: fix use-after-free in sepol_user_clone()

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>
ser_record.c
b6579d262e20e3ac82218abf3a2ce153e15f86a0 28-Mar-2017 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: constify sepol_genbools()'s boolpath parameter

This allows removing an unnecessary cast to (char *) in libselinux.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
enbools.c
76f8c04c197f1e53610cd68d372daafab11f82b7 28-Mar-2017 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: make process_boolean() fail on invalid lines

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>
enbools.c
a83f1cfd7e3513896d95828326d45362f53268d2 28-Mar-2017 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: do not dereference a NULL pointer when stack_init() fails

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>
odule_to_cil.c
6e3c3595b15d8656780af24b37e0efd68a32abf5 25-Mar-2017 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol/cil: do not dereference a NULL pointer when calloc() fails

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>
odule_to_cil.c
526d0dadb844d022bc10e0c30c0a0c639ded6105 20-Mar-2017 James Carter <jwcart2@tycho.nsa.gov> libsepol: Update module_to_cil to output hexadecimal for Xen rules

When generating CIL, use hexadecimal numbers in ioportcon,
iomemcon, and pcidevicecon statements.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
odule_to_cil.c
43b24f0132bc7e48044af062b25cf009c6f136d7 28-Feb-2017 Stephen Smalley <sds@tycho.nsa.gov> libsepol: Define cgroup_seclabel policy capability

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>
olcaps.c
d6b5b037f913e2770967f480f66b06a13a72a4cd 05-Feb-2017 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: fix -Wwrite-strings warnings

When compiling with -Wwrite-strings, clang reports some warnings like:

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

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

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
odule_to_cil.c
8adbd615c19cfa0fd5e9b857e5ffcbfd263af82d 31-Jan-2017 James Carter <jwcart2@tycho.nsa.gov> libsepol: Return +1 when declaration is followed by a require

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>
olicydb.c
1ef665cb92a59f66563addb317541be986e11169 25-Jan-2017 Steve Lawrence <slawrence@tresys.com> libsepol: fix pp module to cil nodecon statement

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>
odule_to_cil.c
4a05e95f196604495642978993bbc90766ec42f6 20-Jan-2017 Karl MacMillan <karlwmacmillan@gmail.com> libsepol compilation fixes for macOS.

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>
akefile
69ec21ce6a530a34044793609b2378c8ceda8db0 15-Jan-2017 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: remove useless assignments

There is no point in initializing a variable which gets
almost-immediately assigned an other value.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
rite.c
ebe24ad20bfd5b071f0ea4c0802608f9c2392ccf 15-Jan-2017 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: verify the right variable after calling calloc()

After "otype = calloc(1, sizeof(*otype))", it is reasonable to check the
value of otype, not ft.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
olicydb.c
fd9e5ef7b78b34a7bd3ffc786bdd785f4fa29beb 15-Jan-2017 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: use constant keys in hashtab functions

Even though "hashtab_key_t" is an alias for "char *", "const
hashtab_key_t" is not an alias for "(const char) *" but means "(char *)
const".

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

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
ashtab.c
olicydb.c
oles.c
ymtab.c
sers.c
d4923b49b4dbe7bf2af02cd0429c61e522c3a7de 04-Jan-2017 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: make capability index an unsigned int

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>
olcaps.c
d479baa82d67c9ac56c1a6fa041abfb9168aa4b3 01-Dec-2016 Stephen Smalley <sds@tycho.nsa.gov> libsepol: Define extended_socket_class policy capability

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>
olcaps.c
9e81e611c7717384e5cbe4e0d149167bc4fd4d2d 29-Nov-2016 James Carter <jwcart2@tycho.nsa.gov> libsepol: Fix neverallow checking to also check the other types when
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>
ssertion.c
3fe4499f7d554fee8d1f474fd7f0aec646ea403a 28-Nov-2016 James Carter <jwcart2@tycho.nsa.gov> libsepol/cil: Add ability to write policy.conf file from CIL AST

The ability to create a policy.conf file from the CIL AST has been
a desire from the beginning to assist in debugging and for general
flexibility. Some work towards this end was started early in CIL's
history, but cil_policy.c has not been remotely functional in a long
time. Until now.

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

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
ibsepol.map.in
7e09f584e1f7b315abc4f55023234e3225ab9fa0 29-Nov-2016 Stephen Smalley <sds@tycho.nsa.gov> libsepol,libselinux,audit2allow: teach audit2why about type bounds failures

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>
ervices.c
fff90bd22b68274630a7b7448b5a0fed1578c551 29-Nov-2016 Stephen Smalley <sds@tycho.nsa.gov> libsepol: sepol_av_to_string: clear static buffer

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>
til.c
ab270850998191a41abb47d929ab816259d3428e 28-Nov-2016 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol,libsemanage: write file name in flex output

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>
akefile
fb237459c84ef843828988a953e06826435dfcae 28-Nov-2016 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: detect duplicated symbol IDs

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>
onditional.c
olicydb.c
9872b04a8020417664143e35925f81d4ecc5ee96 28-Nov-2016 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: check decl_id bounds before using it

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>
olicydb.c
8fdb2255215a1f1488b613737b5fbffb873d8376 23-Nov-2016 Stephen Smalley <sds@tycho.nsa.gov> libsepol,checkpolicy: convert rangetrans and filenametrans to hashtabs

range transition and name-based type transition rules were originally
simple unordered lists. They were converted to hashtabs in the kernel
by commit 2f3e82d694d3d7a2db019db1bb63385fbc1066f3 ("selinux: convert range
transition list to a hashtab") and by commit
2463c26d50adc282d19317013ba0ff473823ca47 ("SELinux: put name based
create rules in a hashtable"), but left unchanged in libsepol and
checkpolicy. Convert libsepol and checkpolicy to use the same hashtabs
as the kernel for the range transitions and name-based type transitions.

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

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

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

Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
xpand.c
ls.c
olicydb.c
rite.c
2e47b69c534457c66f007b345f81a2e9c220dc2d 23-Nov-2016 Stephen Smalley <sds@tycho.nsa.gov> libsepol: do not write object_r types to policy file

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>
rite.c
75b14a5de10a825348128bcca6c47fe5a29b8d31 23-Nov-2016 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: ebitmap: reject loading bitmaps with incorrect high bit

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>
bitmap.c
73313a752859c7fda03d3bd091985606b592ff05 23-Nov-2016 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: do not check decl->symtab[i].nprim

Commit 02a7d77ef2bf ("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 02a7d77ef2bf to fix this regression.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
olicydb.c
86bad3dbf981b7d645d41e4c93649dcf782b1a6f 23-Nov-2016 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: do not modify p->p_roles.nprim in role_set_expand

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>
xpand.c
2907caa33cbb722ecf423aa47e43f4f5053c2723 22-Nov-2016 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: fix unknown magic section number error message

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>
odule.c
d10725649ecdc522506e8c4f640e6118502f66f0 22-Nov-2016 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: make scope_index_destroy() more robust

When scope_index_read() fails while attempting to allocate memory for
scope_index->class_perms_map, scope_index_destroy() gets called with
scope->class_perms_len != 0 and scope->class_perms_map == NULL. This
triggers the following segmentation fault (in semodule_package):

Program received signal SIGSEGV, Segmentation fault.
ebitmap_destroy (e=0x10) at ebitmap.c:362
362 n = e->node;
=> 0x00007ffff79ff7f6 <ebitmap_destroy+134>: 48 8b 3f mov
(%rdi),%rdi

(gdb) bt
#0 ebitmap_destroy (e=0x10) at ebitmap.c:362
#1 0x00007ffff79e2c37 in scope_index_destroy (scope=0x608860) at
avrule_block.c:87
#2 avrule_decl_destroy (x=0x608830) at avrule_block.c:103
#3 0x00007ffff7aae99c in avrule_block_read (fp=0x605090,
num_scope_syms=8, block=0x6054e8, p=0x605360) at policydb.c:3598
#4 policydb_read (p=0x605360, fp=fp@entry=0x605090,
verbose=verbose@entry=0) at policydb.c:3946
#5 0x00007ffff7ab4ab4 in sepol_policydb_read (p=<optimized out>,
pf=pf@entry=0x605090) at policydb_public.c:174
#6 0x0000000000401d33 in main (argc=<optimized out>,
argv=0x7fffffffdc88) at semodule_package.c:220

(gdb) f 1

(gdb) p *scope
$1 = {scope = {{node = 0x0, highbit = 0}, {node = 0x0, highbit = 0},
{node = 0x0, highbit = 0}, {node = 0x0, highbit = 0}, {node = 0x0,
highbit = 0}, {node = 0x0, highbit = 0}, {node = 0x0, highbit = 0},
{node = 0x0, highbit = 0}}, class_perms_map = 0x0, class_perms_len =
4294934272}

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
vrule_block.c
8d31f8053ca83af7266fed71a11b7a52b16cc13a 22-Nov-2016 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: do not crash when block->branch_list is NULL

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>
odule_to_cil.c
6675e12cc17345834f14a52d260fd0bf4437d03c 22-Nov-2016 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: do not crash when a symbol does not exist

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>
odule_to_cil.c
52b3b625b653923f3994de8e84248ba1b1614422 22-Nov-2016 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: do not call a NULL function in additive_scopes_to_cil()

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>
odule_to_cil.c
4129eb499db070a001b9bb4d5286f5699db7d85f 17-Nov-2016 William Roberts <william.c.roberts@intel.com> expand_terule_helper: cleanups

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>
xpand.c
dcd473d5ae0a9f81c272a30e9e39a28cda8fc586 17-Nov-2016 William Roberts <william.c.roberts@intel.com> expand_avrule_helper: cleanup

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>
xpand.c
02a7d77ef2bf8e9be5df04d647b39e2ddbf6af6e 16-Nov-2016 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: make parsing symbol table headers more robust

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>
olicydb.c
0a32f3b169d7fd8ae3d569cbd21cb67f6f019f98 16-Nov-2016 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: test for ebitmap_read() negative return value

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>
olicydb.c
784b43b2ae04bbd8a689f6c32086d4c43bc2c89e 16-Nov-2016 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: replace an assert with an error message

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>
olicydb.c
be96f05182ffd934eb20776c52a88df6e51fe6df 16-Nov-2016 William Roberts <william.c.roberts@intel.com> libsepol: fix checkpolicy dontaudit compiler bug

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 6201bb5e258e2b5bcc04d502d6fbc05c69d21d71 ("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>
xpand.c
5862ac5dfe3bcfc5ff1aa40b5585899b993ae446 15-Nov-2016 William Roberts <william.c.roberts@intel.com> Revert "libsepol: fix checkpolicy dontaudit compiler bug"

This reverts commit 6201bb5e258e2b5bcc04d502d6fbc05c69d21d71.
xpand.c
7a4db1566a970788e6e83a5f083a2ffb96b66a76 15-Nov-2016 Stephen Smalley <sds@tycho.nsa.gov> libsepol: cil_lexer: make warnings non-fatal for building

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>
akefile
6201bb5e258e2b5bcc04d502d6fbc05c69d21d71 14-Nov-2016 Stephen Smalley <sds@tycho.nsa.gov> libsepol: fix checkpolicy dontaudit compiler bug

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>
xpand.c
eac6f1f1b5125fde76dedb2f3e806a69f8a3e9ff 08-Nov-2016 Stephen Smalley <sds@tycho.nsa.gov> libsepol: sepol_{bool|iface|user}_key_create: copy name

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>
oolean_record.c
face_record.c
ser_record.c
3340d851dfcb2c803fe470b116c5f1dff909308f 17-Oct-2016 William Roberts <william.c.roberts@intel.com> libsepol: build on mac

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>
akefile
b514885063d7e052c1cd1b4e4e6a8f668ac45e7b 05-Oct-2016 Stephen Smalley <sds@tycho.nsa.gov> libsepol, libsemanage: fix linker scripts / map files

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>
ibsepol.map.in
5694d2683916d4b3c3f5d65fc1c0aa6a45d43fa9 30-Sep-2016 James Carter <jwcart2@tycho.nsa.gov> libsepol: Add support for converting extended permissions to CIL

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>
odule_to_cil.c
6ccfa46ad4b8776fc4ade4e8d4db5ecb45154185 29-Sep-2016 Jeff Vander Stoep <jeffv@google.com> libsepol: fix xperm mapping between avrule and avtab

Commit 915fa8f08f4f 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: 915fa8f08f4f ("checkpolicy: switch operations to extended perms")

Change-Id: Ic9f4031c9381b2ff6cc46043fb1602758ef4c224
Signed-off-by: Jeff Vander Stoep <jeffv@google.com>
xpand.c
d97cd6a2033c7f77c0cb5d9dfd77bdd2c7754a5b 23-Sep-2016 William Roberts <william.c.roberts@intel.com> libsepol: fix unitialized variable 'nread' on mac build

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>
enusers.c
87c5afdad247ddc458cd0d9343bd5b03793b958c 23-Sep-2016 William Roberts <william.c.roberts@intel.com> libsepol: fix unused variable 'len' on mac build

Fix this:
genusers.c:39:9: warning: unused variable 'len' [-Wunused-variable]
size_t len = 0;

Signed-off-by: William Roberts <william.c.roberts@intel.com>
enusers.c
e729fbe9b4dae01b9895f361307ffdae9664b5c5 23-Sep-2016 William Roberts <william.c.roberts@intel.com> libsepol: fix unused variable 'size' on mac build

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>
enbools.c
f9927d9370f90bd9d975ff933fe107ec4f93a9ac 19-Aug-2016 James Carter <jwcart2@tycho.nsa.gov> libsepol: Change which attributes CIL keeps in the binary policy

The removal of attributes that are only used in neverallow rules is
hindering AOSP adoption of the CIL compiler. This is because AOSP
extracts neverallow rules from its policy.conf for use in the Android
compatibility test suite. These neverallow rules are applied against
the binary policy being tested to check for a violation. Any neverallow
rules with an attribute that has been removed cannot be checked.

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

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
odule_to_cil.c
fbf77104c30f51ed927de2493730c8f1fbd4cb33 19-Aug-2016 William Roberts <william.c.roberts@intel.com> libsepol: port str_read from kernel

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>
onditional.c
odule.c
olicydb.c
rivate.h
ervices.c
fb0cc0cc649a12edf1dc846841a5d026b1cc20ec 19-Aug-2016 William Roberts <william.c.roberts@intel.com> libsepol: calloc all the *_to_val_structs

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>
ls.c
olicydb.c
sers.c
8673854fb8b7006e92a4b1ce338ed229b0e1a9f6 16-Aug-2016 William Roberts <william.c.roberts@intel.com> libsepol: fix overflow and 0 length allocations

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>
onditional.c
ontext.c
ontext_record.c
odule.c
odule_to_cil.c
olicydb.c
rivate.h
02081779f3bbae034f9b4c2450a28c519460ae9e 16-Aug-2016 William Roberts <william.c.roberts@intel.com> libsepol: fix unitialized jmp and invalid dereference

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>
ontext.c
olicydb.c
d13bff623b8cee1dd299c224ab3ba367be978076 16-Aug-2016 William Roberts <william.c.roberts@intel.com> libsepol: bound attr_type_map access by nprim

Correct an invalid memory access when attr_type_map array
indexing is outside of bounds.

Signed-off-by: William Roberts <william.c.roberts@intel.com>
olicydb.c
305986f58c23941243f75fa0ff9e6733695451aa 16-Aug-2016 William Roberts <william.c.roberts@intel.com> genfs_read: fix use heap-use-after-free

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>
olicydb.c
33de30a2844f8486bbf288fc36e50f4b09860b02 16-Aug-2016 William Roberts <william.c.roberts@intel.com> ebitmap: detect invalid bitmap

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>
bitmap.c
b612314bf3cae7652330dbf41000940048237412 16-Aug-2016 William Roberts <william.c.roberts@intel.com> libsepol: ensure key is valid before doing search

Signed-off-by: William Roberts <william.c.roberts@intel.com>
ls.c
8b4ad4fde577548a286a7c571ba4585cc11cfcd8 16-Aug-2016 William Roberts <william.c.roberts@intel.com> libsepol: fix invalid access of NULL on type_val_to_struct

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>
xpand.c
8e8a648e92ce1cd0c254459fcabb9dfa381a15bd 08-Aug-2016 William Roberts <william.c.roberts@intel.com> libsepol: fix memory leak in expand.c

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>
xpand.c
6e7d04ac0b01f34716941736f356d88a6f4ea6a1 08-Aug-2016 William Roberts <william.c.roberts@intel.com> libsepol: fix invalid read when policy file is corrupt

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>
xpand.c
ca3ec93ad01a0475ba669203e38446cca31717c5 04-Aug-2016 William Roberts <william.c.roberts@intel.com> module_to_cil: fix possible use of uninitialized value

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>
odule_to_cil.c
747a440fdd5b32c16739ecbd76367eb2a582fe82 11-Jul-2016 Petr Lautrbach <plautrba@redhat.com> libsepol: Add missing return to sepol_node_query()

Due to the missing return in sepol_node_query(), the function always
set *response to NULL whenever a protocol was SEPOL_PROTO_IP6

Fixes:
sudo semanage node -a -M ::1 -p ipv6 -t node_t ::1
sudo semanage node -m -M ::1 -p ipv6 -t node_t ::1
[1] 12968 segmentation fault (core dumped) semanage node -m -M ::1 -p ipv6 -t node_t ::1

Signed-off-by: Petr Lautrbach <plautrba@redhat.com>
odes.c
28e92c5325cea83d4fb15225754b277d997c629f 20-Jun-2016 Stephen Smalley <sds@tycho.nsa.gov> libsepol: rewrite sepol_string_to_security_class to use hashtab_search

Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
ervices.c
94df3f7d24935d12ab96d095fca3c4ed2ad3155c 03-Jun-2016 Joshua Brindle <brindle@quarksecurity.com> Correctly detect unknown classes in sepol_string_to_security_class

Bail before running off the end of the class index

Change-Id: I47c4eaac3c7d789f8d85047e34e37e3f0bb38b3a
Signed-off-by: Joshua Brindle <brindle@quarksecurity.com>
ervices.c
fb85e5cc95c327bab89d0592b67291b200717792 02-Jun-2016 Laurent Bigonville <bigon@bigon.be> Sort object files for deterministic linking order

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>
akefile
44c359aa0504fabe3d9427a95133379234f7d74e 18-May-2016 Jeff Vander Stoep <jeffv@google.com> Fix neverallowxperm checking on attributes

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>
ssertion.c
2c2c81dcdc2719c73a19b01b692b31c8e903965f 05-May-2016 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: remove libsepol.map when cleaning

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
akefile
175aba387b2606d82cf80b3d5edfe7693eac18d7 05-May-2016 James Carter <jwcart2@tycho.nsa.gov> libsepol: When generating CIL use HLL line mark for neverallows

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>
odule_to_cil.c
5cd5ffcc50037e40ef8eb424d0d3ef63b2249644 03-May-2016 James Carter <jwcart2@tycho.nsa.gov> libsepol: Change logic of bounds checking

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>
ierarchy.c
bedef7d12493e5785537c1f8e46ce32c3e34bf32 03-May-2016 Stephen Smalley <sds@tycho.nsa.gov> libsepol,checkpolicy,secilc: Replace #ifdef DARWIN with __APPLE__.

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>
enbools.c
enusers.c
ode_record.c
rivate.h
3cf8669135cd821030984e91b2a8270113df10b4 29-Apr-2016 James Carter <jwcart2@tycho.nsa.gov> libsepol: Only apply bounds checking to source types in rules

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>
ierarchy.c
aac9360581ba8894ac90d88e094dabca510f8266 24-Apr-2016 Richard Haines <richard_c_haines@btinternet.com> selinux: Build policy on systems not supporting DCCP protocol

Commit 3895fbbe0cf2ec52d6b6eda66084b6e9f8d88fb2 ("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>
odule_to_cil.c
orts.c
1beb818f109fcbcc3b5581f712e85c4a1945c026 20-Apr-2016 Jeff Vander Stoep <jeffv@google.com> Fix extended permissions neverallow checking

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>
ssertion.c
3895fbbe0cf2ec52d6b6eda66084b6e9f8d88fb2 06-Apr-2016 Richard Haines <richard_c_haines@btinternet.com> selinux: Add support for portcon dccp protocol

This adds CIL and checkpolicy support for the (portcon dccp ...)
statement. The kernel already handles name_bind and name_connect
permissions for the dccp_socket class.

Signed-off-by: Richard Haines <richard_c_haines@btinternet.com>
Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
odule_to_cil.c
ort_record.c
orts.c
172ce53ffa793e69632923b5323fc8c2220b3294 05-Feb-2016 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: fix __attribute__((unused)) annotations

clang warns about variables which are used in a function body even
though they were marked __attribute__((unused)). For example:

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

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

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
ooleans.c
ebug.c
ierarchy.c
nterfaces.c
odes.c
olicydb.c
orts.c
oles.c
sers.c
f5602f5ff980435ee2aefed35ba643310ceeac25 01-Dec-2015 Steve Lawrence <slawrence@tresys.com> libsepol/cil: Add support for neverallowx

Add a new statement, neverallowx, which has the same syntax as allowx:

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

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

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

Signed-off-by: Steve Lawrence <slawrence@tresys.com>
ssertion.c
vtab.c
0ca5562e9782cd078030d486be9e8dc3190a8ccf 21-Nov-2015 Richard Haines <richard_c_haines@btinternet.com> libsepol: Fully expand neverallowxperm rules

Currently neverallowxperm rules will be resolved correctly when
building policy, however they are not detectable when using tools
such as an updated version of setools. This patch will allow
these to be viewed in the same way as neverallow rules are in a
text based kernel policy file (e.g. policy.conf).

Signed-off-by: Richard Haines <richard_c_haines@btinternet.com>
Acked-by: Jeff Vander Stoep <jeffv@google.com>
xpand.c
99fc177b5af4e1e8855d42d2d01cb93ac7f9d14b 18-Sep-2015 Jeff Vander Stoep <jeffv@google.com> Add neverallow support for ioctl extended permissions

Neverallow rules for ioctl extended permissions will pass in two
cases:
1. If extended permissions exist for the source-target-class set
the test will pass if the neverallow values are excluded.
2. If extended permissions do not exist for the source-target-class
set the test will pass if the ioctl permission is not granted.

Signed-off-by: Jeff Vander Stoep <jeffv@google.com>
Acked-by: Nick Kralevich <nnk@google.com>
Acked-by: Stephen Smalley <sds@tycho.nsa.gov>
ssertion.c
xpand.c
til.c
011da992da63f5a11eb43309f40aeeb085957bcf 28-Aug-2015 Steve Lawrence <slawrence@tresys.com> libsepol: fix memory leak when destroying avtab containing extended avrules

Signed-off-by: Steve Lawrence <slawrence@tresys.com>
Acked-by: Stephen Smalley <sds@tycho.nsa.gov>
vtab.c
6ea58f548b87e52e13aee4c14d56031062280747 28-Jul-2015 Yuli Khodorkovskiy <ykhodorkovskiy@tresys.com> libsepol: Replace sscanf in module_to_cil

Some platforms do not have %ms support in sscanf. This adds a tokenize()
function to be used instead of sscanf. tokenize() has the ability to split on any
delimiter. All whitespace delimiters will be squashed.

Signed-off-by: Yuli Khodorkovskiy <ykhodorkovskiy@tresys.com>
odule_to_cil.c
til.c
14eb8acb1a9779002f258f04016c1eba7369b229 16-Jul-2015 Stephen Smalley <sds@tycho.nsa.gov> libsepol: fix policydb_read for policy versions < 24

Policy versions < 24 did not include type attributes in the types symtab,
so there can be holes in the type_val_to_struct array. Fixes a segfault
during the downgrade test performed by a make test in libsepol.

Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
olicydb.c
798faf12274dacf6165a7e25ad933abb0e98efc5 10-Jun-2015 James Carter <jwcart2@tycho.nsa.gov> libsepol: Refactored bounds (hierarchy) checking code

The largest change to the user and role bounds checking was to put
them in their own functions, so they could be called independently.

The type bounds checking was changed to check one type bounds at
a time. An expanded avtab is still created, but now only the rules
of the parent type are expanded. If violations are discovered,
a list of avtab_ptr_t's provides details. This list is used to
display error messages for backwards compatibility and will be
used by CIL to provide a more detailed error message.

Memory usage is reduced from 9,355M to 126M and time is reduced
from 9 sec to 2 sec.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
ierarchy.c
9e6840e6a24533d5fac24c6001bfaaca5ad121fc 10-Jun-2015 James Carter <jwcart2@tycho.nsa.gov> libsepol: Refactored neverallow checking.

Instead of creating an expanded avtab, generating all of the avtab
keys corresponding to a neverallow rule and searching for a match,
walk the nodes in the avtab and use the attr_type_map and ebitmap
functions to find matching rules.

Memory usage is reduced from 370M to 125M and time is reduced from
14 sec to 2 sec. (Bounds checking commented out in both cases.)

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
ssertion.c
88d09b69795de11401355d2fcc6459bdc3f8a8a6 09-Jun-2015 James Carter <jwcart2@tycho.nsa.gov> libsepol: Treat types like an attribute in the attr_type_map.

Types are treated as attributes that contain only themselves. This
is how types are already treated in the type_attr_map.

Treating types this way makes finding rules that apply to a given
type much easier. This simplifies the implementation of neverallow
checking in assertion.c and bounds checking in hierarchy.c.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
xpand.c
olicydb.c
49f7ebb04c086f84a3a6a85a96b84e42c757f4e1 09-Jun-2015 James Carter <jwcart2@tycho.nsa.gov> libsepol: Add new ebitmap function named ebitmap_match_any()

This function returns true if there is a common bit that is set
in both bitmaps.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
bitmap.c
915fa8f08f4f9a4c437ee8280a4e641872ea59dd 12-Jun-2015 Jeff Vander Stoep <jeffv@google.com> checkpolicy: switch operations to extended perms

The ioctl operations code is being renamed to the more generic
"extended permissions." This commit brings the policy compiler
up to date with the kernel patch.

Signed-off-by: Jeff Vander Stoep <jeffv@google.com>
vtab.c
xpand.c
olicydb.c
rite.c
11fccc48cdeab2946042165819362ae1c2f1eaab 22-May-2015 Steve Lawrence <slawrence@tresys.com> libsepol: with pp to CIL, always write auditadm_r and secadm_r roles
to the base module

In fedora and refpolicy, the auditadm_r and secadm_r roles can be in
either the base module or a non-base module, or they could be in both.
This means that it is possible for duplicate role declarations to exist.
CIL does not allow duplicate declarations of anything, but there is no
way for the pp compiler to know if the roles are declared in which
module, or if they are in both when compiling a single module. This
means we cannot use the same hack that we use for user_r, staff_r, etc.,
to generate CIL role declarations (i.e. only create role declarations
for these when defined in base).

So only for these two roles, always declare them as part of base,
regardless of where or if they are defined. This means that turning off
the auditadm module will never remove the auditamd_r role (likewise for
secadm), whereas right now, in some cases it would. This also means that
role allow rules will still exist for these roles even with the modules
removed. However, this is okay because the roles would not have any
types associated with them so no access would be allowed.

Signed-off-by: Steve Lawrence <slawrence@tresys.com>
Reported-by: Miroslav Grepl <mgrepl@redhat.com>
odule_to_cil.c
54b3e9b946aba293bcbf165433d8199063e26530 22-May-2015 Steve Lawrence <slawrence@tresys.com> libsepol: with pp to CIL, only associate declared roleattributes with
in-scope types

When a roleattribute is in a declared scope, CIL roletype statements are
generated for all types associated with it. This incorrectly includes
types that are associated with the roleattribute in optional blocks,
which can result in CIL resolution failures if the optional block is
turned off due to a missing type. So, change the roletype CIL statement
generation with roleattributes to mimic the behavior of roles, ensuring
declared roleattributes are only associated with in-scope types.

Signed-off-by: Steve Lawrence <slawrence@tresys.com>
Reported-by: Miroslav Grepl <mgrepl@redhat.com>
odule_to_cil.c
8ebb97d0be79f8bdb6765fa26505140d081d1c50 08-May-2015 James Carter <jwcart2@tycho.nsa.gov> Replace fmemopen() with internal function in libsepol.

Created a new function, get_line(), to replace the use of fmemopen()
and getline() in module_to_cil.c since fmemopen() is not available
on Darwin.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
odule_to_cil.c
7c912dbc7c926629474387f39f9b86cf94477cd7 24-Apr-2015 Stephen Smalley <sds@tycho.nsa.gov> libsepol: Binary modules do not support ioctl rules.

Prevent writing a binary policy module if the source
included an ioctl operation rule because we do not support ioctl
operation rules in the binary module format. It doesn't seem
worthwhile to introduce a new binary policy module version since
CIL is now merged and we will have to implement the support in CIL
regardless; might as well only support it in CIL modules.

Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
rite.c
80bc7ee8faaddfa7a650994fa82a57f41a9e7475 22-Apr-2015 Jeff Vander Stoep <jeffv@google.com> Add support for ioctl command whitelisting

Adds support for new policy statements whitelisting individual ioctl
commands. Ioctls provide many of the operations necessary for driver control.
The typical driver supports a device specific set of operations accessible
by the ioctl system call and specified by the command argument. SELinux
provides per operation access control to many system operations e.g. chown,
kill, setuid, ipc_lock, etc. Ioclts on the other hand are granted on a per
file descriptor basis using the ioctl permission, meaning that the set of
operations provided by the driver are granted on an all-or-nothing basis.
In some cases this may be acceptable, but often the same driver provides a
large and diverse set of operations such as benign and necessary functionality
as well as dangerous capabilities or access to system information that should
be restricted.

Example policy:
allow <source> <target>:<class> { 0x8900-0x8905 0x8910 }
auditallow <source> <target>:<class> 0x8901

The ioctl permission is still required in order to make an ioctl call. If no
individual ioctl commands are specified, only the ioctl permission is
checked by the kernel - i.e. status quo. This allows ioctl whitelisting to
done in a targeted manner, protecting desired drivers without requiring every
ioctl command to be known and specified before use and otherwise allowing
existing policy to be used as-is.

This only implements ioctl whitelisting support for monolithic kernel policies
built via checkpolicy. Support for modules and CIL remains to be done.

Bug: 19419509
Change-Id: I198e8c9279b94d8ce4ae5625018daa99577ee970
Signed-off-by: Jeff Vander Stoep <jeffv@google.com>
Acked-by: Stephen Smalley <sds@tycho.nsa.gov>
vtab.c
xpand.c
olicydb.c
rite.c
16796d8dc19cffe55896b75e4a88832f2a25450b 15-Apr-2015 Yuli Khodorkovskiy <ykhodorkovskiy@tresys.com> libsepol: Don't use symbol versioning for static object files

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>
so.h
4514332550765aecd7e78964173142a31e92a540 01-Apr-2015 James Carter <jwcart2@tycho.nsa.gov> libsepol: add function to generate CIL from a module policydb

Add a new function, sepol_module_policydb_to_cil, that generates
CIL from a module (not kernel) policydb. Refactor
sepol_module_package_to_cil() to use the new function.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
ibsepol.map.in
odule_to_cil.c
758a7fe501586f0f952f6790304ac0f343a64518 01-Apr-2015 James Carter <jwcart2@tycho.nsa.gov> libsepol, policycoreutils: Move functions to convert a module package to CIL

Move code to convert a policy module to CIL from the policy package to
CIL conversion tool, pp, in policycoreutils to libsepol. The only changes
to the code are the additions of the prefix "sepol_" to the functions
sepol_module_package_to_cil() and sepol_ppfile_to_module_package(). This
code is being changed from GPL to LGPL with permission from Tresys.

Convert pp to use the renamed functions in libsepol.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
ibsepol.map.in
odule_to_cil.c
36f62b78f1e008aaf3d8b6d60a30895beacd17d3 31-Mar-2015 Yuli Khodorkovskiy <ykhodorkovskiy@tresys.com> libsepol: Move secilc out of libsepol

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>
ibsepol.map.in
d03e9373e82d143c396401adf4912ed0ea490ecf 23-Mar-2015 Richard Haines <richard_c_haines@btinternet.com> libsepol: Fix building Xen policy with devicetreecon

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>
olicydb.c
c046d974c5513c5bc1c29f964177e2fac4004544 19-Mar-2015 Thomas Hurd <thurd@tresys.com> libsepol: bool_copy_callback set state on creation

Boolean states are only written on a declaration.
If a module is turned off which includes a tunable declaration that
is required in another module, the state is never set. This patch
sets the state when the booldatum is created so that an uninitialized
memory read does not occur in cond_write_bool and write garbage to
the link binary. This can cause a failure in cond_read_bool when
running semodule_expand.

Signed-off-by: Thomas Hurd <thurd@tresys.com>
ink.c
f0290677091e7eee4a3724a2a86ede9e11f93802 17-Mar-2015 Daniel De Graaf <dgdegra@tycho.nsa.gov> libsepol, checkpolicy: add device tree ocontext nodes to Xen policy

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>
xpand.c
olicydb.c
rite.c
82030de5dc8d08a9417842156293c65fef9dc70c 17-Mar-2015 Daniel De Graaf <dgdegra@tycho.nsa.gov> libsepol, checkpolicy: widen Xen IOMEM ocontext entries

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>
olicydb.c
rite.c
8147bc762241b899444e43557c45f7f79c707502 13-Feb-2015 Steve Lawrence <slawrence@tresys.com> libsepol: clean up the CIL API

- 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>
ibsepol.map.in
e7694874c20efaf6670f6639b0383077015b8d0c 22-Feb-2015 Chris PeBenito <cpebenito@tresys.com> libsepol: Fix error path in mls_semantic_level_expand().

If the level contains a category that is not associated with a sensitivity,
the code correctly detects the condition, but does not return an error.

Signed-off-by: Chris PeBenito <cpebenito@tresys.com>
Acked-by: Steve Lawrence <slawrence@tresys.com>
xpand.c
ed7a6ba24ad3241e696fa7bc9bb56bb4f373147b 16-Dec-2014 dcashman <dcashman@google.com> Allow libsepol C++ static library on device.

Change-Id: I7da601767c3a4ebed7274e33304d8b589a9115fe
Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
ssertion.c
xpand.c
ink.c
olicydb.c
rite.c
acb2a9beded6bd29471ffaa517316c0497f24e15 15-Jan-2015 John Brooks <john.brooks@jolla.com> Tweak avtab hash table parameters for better performance

Using the Fedora 20 targeted policy, running check_assertions requires
an avtab with around 22 million elements. With the default limit of 4096
buckets, performance is abysmal: it takes more than an hour to populate
the hash. Profiling shows most of that time under avtab_search_node.

This patch increases the hash from 13 to 20 bits and to a maximum of
1048576 buckets. The time for check_assertions on that policy is reduced
to about 3 minutes, which is enough to re-enable those checks as part of
the build process.

A full size table will allocate 4-8 MB of memory, up from 16-32 KB. In a
cursory review, these tables are usually short-lived and only 1-3 are
allocated together. Compared to the cost of entries in this table (up to
1 GB using the same policy), this isn't a significant increase.

Signed-off-by: John Brooks <john.brooks@jolla.com>
vtab.c
798950e055e04cbea0464fb83cab406ee8d35154 15-Jan-2015 John Brooks <john.brooks@jolla.com> Use a better hash function for libsepol's avtab

This function, based on murmurhash3, has much better distribution than
the original. Using the current default of 4096 buckets, there are many
fewer collisions:

Before:
2893000 entries and 4096/4096 buckets used, longest chain length 1649
After:
2732000 entries and 4096/4096 buckets used, longest chain length 764

The difference becomes much more significant when buckets are increased.
A naive attempt to expand the current function to larger outputs doesn't
yield any significant improvement; so this function is a prerequisite
for increasing the bucket size.

Signed-off-by: John Brooks <john.brooks@jolla.com>
vtab.c
76ea9f898747bc11f27ad4598700e8f81cbc76e7 15-Jan-2015 John Brooks <john.brooks@jolla.com> Build libsepol with -O2

libsepol contains performance sensitive code; in particular, compiler
optimizations save a few minutes off of the optimized policydb hash
tables.

Signed-off-by: John Brooks <john.brooks@jolla.com>
akefile
678ec5df790b0ff3c9dbb041be670a5916838e29 24-Nov-2014 Stephen Smalley <sds@tycho.nsa.gov> Fix expand logic for policy versions older than 24.

This was broken for older policy versions when we updated to
version 24.

Broken by commit 787f2f00f5d8ed6f5f.

Change-Id: I4063334c5c0462ef5c3706611c7dff5c60c612aa
Reported-by: William Roberts <bill.c.roberts@gmail.com>
Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
xpand.c
9da070f7004c4ad92fbda50de4a84935af6ee301 14-Oct-2014 Stephen Smalley <sds@tycho.nsa.gov> libsepol: Report all neverallow violations.

Switch libsepol check_assertions() from only reporting the first violation
to reporting them all.

Change-Id: I45b3502ff96b1d093574e1fecff93a582f8d00bd
Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
Acked-by: Steve Lawrence <slawrence@tresys.com>
ssertion.c
71393a181d63c9baae5fe8dcaeb9411d1f253998 20-Oct-2014 Steve Lawrence <slawrence@tresys.com> libselinux: libsepol: use ln --relative to create .so symlinks

The current build system assumes SHLIBDIR is ../../ relative to LIBDIR.
However, this isn't always the case. For example, Arch Linux sets both
LIBDIR and SHLIBDIR to /usr/lib, which results in broken symlinks.

Instead of making that assumption, create .so symlinks using ln
--relative so that the correct relative paths are used. Note that this
adds a dependency for the build system to use coretuils-8.16 or later.

Fixes #2

Reported-by: Nicolas Iooss <nicolas.iooss@m4x.org>
Signed-off-by: Steve Lawrence <slawrence@tresys.com>
akefile
14c0564641e6c8be386f117c2b0f09434121226f 14-Sep-2014 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: fix most gcc -Wwrite-strings warnings

gcc puts literal strings lie in read-only memory. On x86_64, trying to
write to them triggers a segmentation fault.

To detect such issues at build time, variables holding a pointer to such
strings should be "const char*". "gcc -Wwrite-strings" warns when using
non-const pointers to literal strings.

Remove gcc warnings by adding const to local variables and argumens of
internal functions.

This does *not* fix this warning:

policydb_public.c:208:10: warning: passing argument 2 of 'hashtab_search' discards 'const' qualifier from pointer target type
return (hashtab_search(p->p.p_classes.table, PACKET_CLASS_NAME) ==
^
In file included from ../include/sepol/policydb/symtab.h:16:0,
from ../include/sepol/policydb/policydb.h:60,
from policydb_public.c:4:
../include/sepol/policydb/hashtab.h:98:24: note: expected 'hashtab_key_t' but argument is of type 'const char *'
extern hashtab_datum_t hashtab_search(hashtab_t h, const hashtab_key_t k);
^

Moreover the "const" word in hashtab_search prototype does not make the
second parameter "const char*" but "char* const".

Acked-by: Steve Lawrence <slawrence@tresys.com>
ink.c
olicydb.c
olicydb_internal.h
ervices.c
rite.c
278ae562d6ce19dffbebe7995b4c62f16b3fd8c7 14-Sep-2014 Nicolas Iooss <nicolas.iooss@m4x.org> libsepol: fix potential free of uninitialized pointer

When using "gcc -O2 -Wall -Werror" to compile libsepol, the following
error happens:

services.c: In function 'constraint_expr_eval_reason':
services.c:820:2: error: 'answer_list' may be used uninitialized in this
function [-Werror=maybe-uninitialized]
free(answer_list);
^

Indeed, because of a goto statement in constraint_expr_eval_reason
function, "free(answer_list)" can be called before answer_list has been
initialized.

Fix this error by moving the definition of answer_list to the beginning
of constraint_expr_eval_reason.

Acked-by: Steve Lawrence <slawrence@tresys.com>
ervices.c
416f150f1a56589839ef000fd9dfa021d567a1c7 14-Oct-2011 Steve Lawrence <slawrence@tresys.com> libsepol: build cil into libsepol

Set DISABLE_CIL=y to build libsepol without CIL support, e.g

make DISABLE_CIL=y

To enable CIL support in libsepol, set DISABLE_CIL=n. This is the default
if not specified.

Signed-off-by: Steve Lawrence <slawrence@tresys.com>
akefile
ibsepol.map
ibsepol.map.in
44a65ed816ea05e3f04872eb78f09c44ec695b21 14-Oct-2011 Steve Lawrence <slawrence@tresys.com> libsepol: add function to libsepol for setting target_platform

With pp modules, the target platform information comes form the base
module. However, CIL modules have no concept of target platform. So it
must come from somewhere else. This adds an API function that allows
setting the target platform.

Signed-off-by: Steve Lawrence <slawrence@tresys.com>
olicydb_public.c
9e746d6a693c2090694407c218300cfa4b8469a0 16-Apr-2014 Stephen Smalley <sds@tycho.nsa.gov> Improve error message for name-based transition conflicts.

Quote the component name.
Reorder the arguments to more closely align with the rule syntax.
Use a more descriptive text that will more clearly correspond to the original rule.

Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
xpand.c
e910cf6e62d94d09e810bd173c14c5c4afb72242 15-Apr-2014 Stephen Smalley <sds@tycho.nsa.gov> Revert "libsepol: filename_trans: use some better sorting to compare and merge"

This change was incorrect and can yield duplicate file name transition rules.
Revert it and look at converting the filename_trans list to a hashtab
as has already been done in the kernel in the future.

This reverts commit a29f6820c52b60b9028298cde9962dd140bbf9ea.

Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
xpand.c
a80a48cb1907162b1fce8f0af38d062fca39a635 24-Mar-2014 Stephen Smalley <sds@tycho.nsa.gov> Fix for binary policy modules.

They do not retain the neverallow source information so we must
not assume that source_filename is set. Either need a new binary
module format if we want to propagate this information for modular
builds or get rid of binary modules.

Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
xpand.c
ink.c
ef24ade029329a6e9981bd1de2ba7b9ea48e1c79 05-Mar-2014 Stephen Smalley <sds@tycho.nsa.gov> Report source file and line information for neverallow failures.

Change-Id: I0def97a5f2f6097e2dad7bcd5395b8fa740d7073
Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
ssertion.c
xpand.c
ink.c
olicydb.c
733ea081476299614e4f358a2ff5f87194be3865 03-Nov-2013 Richard Haines <richard_c_haines@btinternet.com> libsepol: Fix valgrind errors in constraint_expr_eval_reason

Running valgrind flagged up three "definitely lost" malloc/realloc errors
when checking constraints.

Signed-off-by: Richard Haines <richard_c_haines@btinternet.com>
ervices.c
e1551b91af5660f690dfeb1b7f9a333853dcc524 03-Nov-2013 Richard Haines <richard_c_haines@btinternet.com> libsepol: Add sepol_validate_transition_reason_buffer function

This will return mls/validatetrans constraint information for each
expression in a buffer. If POLICY_KERN version is >=
POLICYDB_VERSION_CONSTRAINT_NAMES then the policy defined types/attributes
will be returned.

Signed-off-by: Richard Haines <richard_c_haines@btinternet.com>
ervices.c
4bc2cd49d4bb5cfb54c8133a9e9881e8f18f45cd 28-Oct-2013 Dan Walsh <dwalsh@redhat.com> Update version of policy file to match what was shipped since Fedora 19
olicydb.c
9eefe11b3a94307a3f5432316a59d1f8e3268429 28-Oct-2013 Richard Haines <richard_c_haines@btinternet.com> libsepol: V1 Allow constraint denials to be determined.

Adds policy source defined 'type' or 'typeattribute' names to
constraints by adding additional structures (->type_names->types) to a
binary policy.
Before this change all typeattributes were expanded to lists of types
and added to the constraint under ->names. This made it difficult for
system admins to determine from the policy source what attribute
needed to be updated. To facilitate analysis of constraint failures
a new function has also been added, see sepol_compute_av_reason_buffer.

As additional structures have been added to policy, the policy version
is also updated (POLICYDB_VERSION_CONSTRAINT_NAMES). There is also a
corresponding kernel patch to handle the additional structures.

sepol_compute_av_reason_buffer is an extended version of
sepol_compute_av_reason. This will return a buffer with constraint
expression information, containing the constrain type, class, perms,
keywords etc.. It will also contain which constraint expr failed plus
the final outcome. The buffer MUST be free'd with free(3).

The type information output by sepol_compute_av_reason_buffer depends on
the policy version:
If >= POLICYDB_VERSION_CONSTRAINT_NAMES, then the output will be
whatever was in the original policy (type or attribute names).
If < POLICYDB_VERSION_CONSTRAINT_NAMES, then the output will be
the types listed in the constraint (as no attribute information is
available in these versions).
For users and roles whatever policy version, only the names are listed
(as role attributes are not currently held in the constraint).

Also added are two functions that obtain the class and permissions
from a binary policy file that has been loaded for testing:
sepol_string_to_security_class
sepol_string_to_av_perm

Signed-off-by: Richard Haines <richard_c_haines@btinternet.com>
xpand.c
olicydb.c
ervices.c
rite.c
56258807ea4b33cf3c7a1dbf1b574ab77c91f899 25-Oct-2013 Stephen Smalley <sds@tycho.nsa.gov> Revert "Richard Haines patch that allows us discover constraint violation information"

This reverts commit 56b49ab7114f367f46b70e41d84dc7e6d52d5209.

Conflicts:
libselinux/src/audit2why.c
xpand.c
olicydb.c
ervices.c
rite.c
3b44fe10e5961ec5ef6a9a7037dbc3b9840ca1a9 11-Oct-2013 Dan Walsh <dwalsh@redhat.com> Patch from Sven Vermeulen to use RANLIB.

This will allow users to specify alternal ranlib commands.
akefile
a8b3340288cb5252b2a8844e4892c066d5b8fdf5 09-Oct-2013 Dan Walsh <dwalsh@redhat.com> Laurent Bigonville patch to allow overriding PATH Definitions in Makefiles
akefile
56b49ab7114f367f46b70e41d84dc7e6d52d5209 09-Oct-2013 Dan Walsh <dwalsh@redhat.com> Richard Haines patch that allows us discover constraint violation information

Basically we need this information to allow audit2allow/audit2why to better
describe which constraint is being broken.
xpand.c
olicydb.c
ervices.c
rite.c
92788715dc793f805b0ae56844216b844a34ea22 10-Jan-2013 Alice Chu <alice.chu@sta.samsung.com> libsepol: Fix memory leak issues found by Klocwork

Signed-off-by: Eric Paris <eparis@redhat.com>
xpand.c
ierarchy.c
ink.c
olicydb.c
olicydb_convert.c
ervices.c
ymtab.c
693f5241fdd5ae7e89d4312b85443c0fc1b1a57d 18-Dec-2012 Eric Paris <eparis@redhat.com> checkpolicy: libsepol: implement default type policy syntax

We currently have a mechanism in which the default user, role, and range
can be picked up from the source or the target object. This implements
the same thing for types. The kernel will override this with type
transition rules and similar. This is just the default if nothing
specific is given.

Signed-off-by: Eric Paris <eparis@redhat.com>
Acked-by: Dan Walsh <dwalsh@redhat.com>
xpand.c
ink.c
olicydb.c
rite.c
afe88d8c69543b2ebd6e25efdaab76f40ea4d3c7 11-Dec-2012 Eric Paris <eparis@redhat.com> libsepol: coverity fixes

Signed-off-by: Eric Paris <eparis@redhat.com>
Acked-by: Dan Walsh <dwalsh@redhat.com>
vrule_block.c
xpand.c
enbools.c
enusers.c
ink.c
odule.c
olicydb.c
rite.c
a29f6820c52b60b9028298cde9962dd140bbf9ea 25-May-2012 Adam Tkac <atkac@redhat.com> libsepol: filename_trans: use some better sorting to compare and merge

The expand_filename_trans() function consumed vast majority of time by comparsion
of two lists with dumb algorithm with O(n^2) complexity.

Now it chunks one list by it's filename_trans->stype value to limit length of
elements which needs to be walked when comparing filename_trans_t element with
this chunked list.

This change speeds-up se* commands by 80%.

Signed-off-by: Adam Tkac <atkac@redhat.com>
Signed-off-by: Eric Paris <eparis@redhat.com>
Acked-by: Dan Walsh <dwalsh@redhat.com>
xpand.c
2ef297d4c80b7e55d9a33e20b44c540ffc6ad351 25-Feb-2012 Harry Ciao <qingtao.cao@windriver.com> libsepol: role_fix_callback skips out-of-scope roles during expansion.

If a role identifier is out of scope it would be skipped over during
expansion, accordingly, be it a role attribute, it should be skipped
over as well when role_fix_callback tries to propagate its capability
to all its sub-roles.

Signed-off-by: Harry Ciao <qingtao.cao@windriver.com>
Signed-off-by: Eric Paris <eparis@redhat.com>
xpand.c
01723ac2ce03443e8c89a47c53072dfa6debcb00 06-Jun-2012 Chris PeBenito <cpebenito@tresys.com> libsepol: Add always_check_network policy capability

Currently the packet class in SELinux is not checked if there are no
SECMARK rules in the security or mangle netfilter tables. Similarly, the
peer class is not checked if there is no NetLabel or labeled IPSEC. Some
systems prefer that these classes are always checked, for example, to
protect the system should the netfilter rules fail to load or if the
nefilter rules were maliciously flushed.

Add the always_check_network policy capability which, when enabled, treats
these mechanisms as enabled, even if there are no labeling rules.

Signed-off-by: Chris PeBenito <cpebenito@tresys.com>
Signed-off-by: Eric Paris <eparis@redhat.com>
olcaps.c
1f3bca77e04687afb87a7a4e034298c9c955919b 12-Jun-2012 Chris PeBenito <cpebenito@tresys.com> libsepol: check for missing initial SID labeling statement.

If an initial SID is missing a labeling statement, the compiler will
segfault when trying to copy the context during expand. Check for this
situation to handle it gracefully.

This fixes ocontext_copy_selinux() and ocontext_copy_xen().

Signed-off-by: Chris PeBenito <cpebenito@tresys.com>
Signed-off-by: Eric Paris <eparis@redhat.com>
xpand.c
e26b58b08e92f823ff2f7e20ffd3124b7c5f8ccf 12-Jun-2012 Chris PeBenito <cpebenito@tresys.com> libsepol: Move context_copy() after switch block in ocontext_copy_*().

If an initial SID is missing a labeling statement, the compiler will
segfault on the context_copy(). Move the context copy after the
switch block so that the existance of the initial SID label can be checked
before trying to copy the context.

This fixes both ocontext_copy_selinux() and ocontext_copy_xen().

Signed-off-by: Chris PeBenito <cpebenito@tresys.com>
Signed-off-by: Eric Paris <eparis@redhat.com>
xpand.c
4a33c78ca572598ff76976a41d8b456293dfaebc 30-Aug-2012 Stephen Smalley <sds@tycho.nsa.gov> libsepol: fix neverallow checking on attributes

Ole Kliemann reported that allow rules written using type attributes were
not being detected by neverallow assertions in the policy. I think that
this was broken in policy.24 and later due to changes in the type datum.
Fix the expand logic to correctly distinguish type attributes from types.

Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
Signed-off-by: Eric Paris <eparis@redhat.com>
xpand.c
84f6ac246f5980f831a5777d53c0a0bd6ad17d3c 23-Feb-2012 Stephen Smalley <sds@tycho.nsa.gov> libsepol: Android/MacOS X build support

Android/MacOS X build support for libsepol.
Create a Android.mk file for Android build integration.
Introduce DARWIN ifdefs for building on MacOS X.

Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
Signed-off-by: Eric Paris <eparis@redhat.com>
Acked-by: Dan Walsh <dwalsh@redhat.com>
enbools.c
enusers.c
ode_record.c
rivate.h
d21ec5a5605f708b70e0b685b76f03a978f2008c 25-May-2012 Adam Tkac <atkac@redhat.com> libsepol: prepend instead of append to filename_trans list

Currently expand_filename_trans() function use much CPU time to find
end of the state->out->filename_trans list. This is not needed because
data can be prepended instead of appended to the list.

This ends with 10% speed-up of various se* commands (semodule, setsebool).

Signed-off-by: Adam Tkac <atkac@redhat.com>
Signed-off-by: Eric Paris <eparis@redhat.com>
Acked-by: Dan Walsh <dwalsh@redhat.com>
xpand.c
c43f5b1d34d9cbdc767254046d9b7e0ab47b866d 29-May-2012 Eric Paris <eparis@redhat.com> libsepol: cosmetic changes to make the source easier to read

strict adherense to 80 characters means that we split stuff in stupid
places. Screw 80 characters. Buy a bigger monitor.

Signed-off-by: Eric Paris <eparis@redhat.com>
Acked-by: Dan Walsh <dwalsh@redhat.com>
xpand.c
7a1e3e1fef1d90832507ecd13d764258ea4fe14c 15-Jun-2012 Eric Paris <eparis@redhat.com> libsepol: reserve policycapability for redhat testing of ptrace child

Red Hat is testing ptrace_child in the wild. reserve this policy
capability so we don't have conflicts.

Signed-off-by: Eric Paris <eparis@redhat.com>
olcaps.c
8720c8e576671c7b7c1d65392fcb7fc3cdbc3fbd 23-Apr-2012 Eric Paris <eparis@redhat.com> libsepol: allocate enough space to hold filename in trans rules

There is an off by one bug in which the filename length stored with
filename_trans_rules is stored as strlen (aka, no nul) however the
code to allocate space and read the name back in from policy only
allocates len, and not the len + 1 needed to hold the nul. Allocate
enough space for the nul.

Signed-off-by: Eric Paris <eparis@redhat.com>
Acked-by: Dan Walsh <dwalsh@redhat.com>
olicydb.c
09c783c9a36cd47216df827c5d2c21ec8cd613e2 05-Dec-2011 Eric Paris <eparis@redhat.com> libsepol: checkpolicy: implement new default labeling behaviors

We would like to be able to say that the user, role, or range of a newly
created object should be based on the user, role, or range of either the
source or the target of the creation operation. aka, for a new file
this could be the user of the creating process or the user or the parent
directory. This patch implements the new language and the policydb
support to give this information to the kernel.

Signed-off-by: Eric Paris <eparis@redhat.com>
Acked-by: Dan Walsh <dwalsh@redhat.com>
xpand.c
ink.c
olicydb.c
rite.c
0a778ba601d68ef91304f90c101b5dc67d433e04 31-Oct-2011 Eric Paris <eparis@redhat.com> libsepol: expand: do filename_trans type comparison on mapped representation

The filename_trans code had a bug where duplicate detection was being
done between the unmapped type value of a new rule and the type value of
rules already in policy. This meant that duplicates were not being
silently dropped and were instead outputting a message that there was a
problem. It made things hard because the message WAS using the mapped
type to convert to the string representation, so it didn't look like a
dup!

Signed-off-by: Eric Paris <eparis@redhat.com>
Acked-by: Dan Walsh <dwalsh@redhat.com>
xpand.c
2f68def6338d072ae13328cf6357a4468408ce1b 18-Oct-2011 Steve Lawrence <slawrence@tresys.com> libsepol: Move ebitmap_* functions from mcstrans to libsepol

This patches moves some ebitmap functions (and, xor, not, etc.) from
mcstrans into libsepol, where they really belong and could be used by
other applications (e.g. CIL)

Signed-off-by: Eric Paris <eparis@redhat.com>
Acked-by: Dan Walsh <dwalsh@redhat.com>
bitmap.c
rivate.h
c81a43c753efbda6f2106dbf0a291005683474f8 28-Sep-2011 Eric Paris <eparis@redhat.com> libselinux: libsemanage: libsepol: regenerate .pc on VERSION change

The makefile which generated the package config files did not have the
VERSION file as a dependancy. Thus if you updated a tree you have
previously build the .pc file wouldn't be rebuilt and the old version
would be reinstalled.

Signed-off-by: Eric Paris <eparis@redhat.com>
Acked-by: Dan Walsh <dwalsh@redhat.com>
akefile
b10ff76086a4065b3aa29e6c2f83c54923ebef74 02-Sep-2011 Dan Walsh <dwalsh@redhat.com> libsepol: setools expects expand_module_avrules to be an exported interface of libsepol

This is needed in order to build setools, although I think setools
still will not fully build. It would be good if someone from setools
would diagnose what is breaking.

Signed-off-by: Eric Paris <eparis@redhat.com>
Acked-by: Dan Walsh <dwalsh@redhat.com>
ibsepol.map
9f709e6bab863036950644a7dd470d50663b558b 01-Sep-2011 Harry Ciao <qingtao.cao@windriver.com> libsepol: Preserve tunables when required by semodule program.

If the "-P/--preserve_tunables" option is set for the semodule program,
the preserve_tunables flag in sepol_handle_t would be set, then all tunables
would be treated as booleans by having their TUNABLE flag bit cleared,
resulting in all tunables if-else conditionals preserved for raw policy.

Note, such option would invalidate the logic to double-check if tunables
ever mix with booleans in one expression, so skip the call to assert()
when this option is passed.

Signed-off-by: Harry Ciao <qingtao.cao@windriver.com>
Signed-off-by: Eric Paris <eparis@redhat.com>
Acked-by: Dan Walsh <dwalsh@redhat.com>
xpand.c
e4bc1b223debcc6747fef4d7a2a0a320c0208a88 01-Sep-2011 Harry Ciao <qingtao.cao@windriver.com> libsepol: libsemanage: policycoreutils: Create a new preserve_tunables flag in sepol_handle_t.

By default only the effective branch of a tunable conditional would be
expanded and written to raw policy, while all needless unused branches
would be discarded.

Add a new option '-P' or "--preserve_tunables" to the semodule program.
By default it is 0, if set to 1 then the above preserve_tunables flag
in the sepol_handle_t would be set to 1 accordingly.

Signed-off-by: Harry Ciao <qingtao.cao@windriver.com>
Signed-off-by: Eric Paris <eparis@redhat.com>
Acked-by: Dan Walsh <dwalsh@redhat.com>
andle.c
andle.h
ibsepol.map
5722d765c756ac8dc52c52077f9311b8886fe8da 01-Sep-2011 Harry Ciao <qingtao.cao@windriver.com> libsepol: Skip tunable identifier and cond_node_t in expansion.

The effective branch of a tunable has been appended to its home
decl->avrules list during link, in expansion we should just skip tunables
from expanding their rules into te_cond_avtab hashtab and adding to the
out->cond_list queue.

Signed-off-by: Harry Ciao <qingtao.cao@windriver.com>
Signed-off-by: Eric Paris <eparis@redhat.com>
Acked-by: Dan Walsh <dwalsh@redhat.com>
xpand.c
ad5951fcb142cf9c2e899d3d99ce35b729b66b4c 01-Sep-2011 Harry Ciao <qingtao.cao@windriver.com> libsepol: Permanently discard disabled branches of tunables in expansion.

For a cond_node_t in one decl->cond_list queue, append its
avtrue_list or avfalse_list to the avrules list of its home decl
depending on its state value, so that these effective rules would
be permanently added to te_avtab hashtab.

On the other hand, the rules on the disabled unused list won't be
expanded and written to the raw policy at all.

Signed-off-by: Harry Ciao <qingtao.cao@windriver.com>
Signed-off-by: Eric Paris <eparis@redhat.com>
Acked-by: Dan Walsh <dwalsh@redhat.com>
xpand.c
d9d583759595e522a0ebfb56f74ee2a274d48d19 01-Sep-2011 Harry Ciao <qingtao.cao@windriver.com> libsepol: Copy and check the cond_bool_datum_t.flags during link.

Copy the TUNABLE flag for cond_bool_datum_t during link, and check
if there is a mismatch between boolean/tunable declaration and
usage among modules. If this is the case, bail out with errors.

Signed-off-by: Harry Ciao <qingtao.cao@windriver.com>
Signed-off-by: Eric Paris <eparis@redhat.com>
Acked-by: Dan Walsh <dwalsh@redhat.com>
ink.c
b0be2a06b7b377cfc3134bb7ebadc9cf9d070992 01-Sep-2011 Harry Ciao <qingtao.cao@windriver.com> libsepol: Write and read TUNABLE flags in related data structures.

All flags in cond_bool_datum_t and cond_node_t structures are written
or read for policy modules which version is no less than
MOD_POLICYDB_VERSION_TUNABLE_SEP.

Note, for cond_node_t the TUNABLE flag bit would be used only at expand,
however, it won't hurt to read/write this field for modules(potentially
for future usage).

Signed-off-by: Harry Ciao <qingtao.cao@windriver.com>
Signed-off-by: Eric Paris <eparis@redhat.com>
Acked-by: Dan Walsh <dwalsh@redhat.com>
onditional.c
rite.c
80f26c5ee865993264ef638480c6a05ab574f7c0 01-Sep-2011 Harry Ciao <qingtao.cao@windriver.com> checkpolicy: Separate tunable from boolean during compile.

Both boolean and tunable keywords are processed by define_bool_tunable(),
argument 0 and 1 would be passed for boolean and tunable respectively.
For tunable, a TUNABLE flag would be set in cond_bool_datum_t.flags.

Note, when creating an if-else conditional we can not know if the
tunable identifier is indeed a tunable(for example, a boolean may be
misused in tunable_policy() or vice versa), thus the TUNABLE flag
for cond_node_t would be calculated and used in expansion when all
booleans/tunables copied during link.

Signed-off-by: Harry Ciao <qingtao.cao@windriver.com>
Signed-off-by: Eric Paris <eparis@redhat.com>
Acked-by: Dan Walsh <dwalsh@redhat.com>
onditional.c
f87ae538256eff759cb67c448416dc14031849a1 01-Sep-2011 Harry Ciao <qingtao.cao@windriver.com> libsepol: Indicate when boolean is indeed a tunable.

Add flags to cond_bool_datum_t and cond_node_t structures to differentiate
the tunables' identifiers and conditionals from those of booleans.

Signed-off-by: Harry Ciao <qingtao.cao@windriver.com>
Signed-off-by: Eric Paris <eparis@redhat.com>
Acked-by: Dan Walsh <dwalsh@redhat.com>
olicydb.c
0299119625fe0067998fffdff9bdf721379f3131 16-Aug-2011 Harry Ciao <qingtao.cao@windriver.com> libsepol: Skip writing role attributes for policy.X and downgraded pp.

Role attributes are redundant for policy.X, their destiny has been
fulfilled in the expand phase when their types.types ebitmap have
been populated to that of their sub regular roles.

When pp is downgraded, role_datum_t's the flavor flag and roles
ebitmap would be discarded, resulting in role attributes useless
at all. So for such case they should also be skipped.

Deduct the number of role attributes from p_roles.table->nel when
they are skipped.

Last, uncount attributes number before converting endianness.

Signed-off-by: Harry Ciao <qingtao.cao@windriver.com>
Signed-off-by: Eric Paris <eparis@redhat.com>
Acked-by: Dan Walsh <dwalsh@redhat.com>
rite.c
dbc9a61819ea9a6b61bb29a2765b319ac974a775 02-Aug-2011 Harry Ciao <qingtao.cao@windriver.com> libsepol: Only call role_fix_callback for base.p_roles during expansion.

expand_role_attributes() would merge the sub role attribute's roles
ebitmap into that of the parent, then clear it off from the parent's
roles ebitmap. This supports the assertion in role_fix_callback() that
any role attribute's roles ebitmap contains just regular roles.

expand_role_attribute() works on base.p_roles table but not any
block/decl's p_roles table, so the above assertion in role_fix_callback
could fail when it is called for block/decl and some role attribute is
added into another.

Since the effect of get_local_role() would have been complemented by
the populate_roleattributes() at the end of the link phase, there is
no needs(and wrong) to call role_fix_callback() for block/decl in the
expand phase.

Signed-off-by: Harry Ciao <qingtao.cao@windriver.com>
Signed-off-by: Eric Paris <eparis@redhat.com>
Acked-by: Dan Walsh <dwalsh@redhat.com>
xpand.c
1867652e5424e867cea542a9311ccdc5fa9ec835 20-Apr-2011 Eric Paris <eparis@redhat.com> libsepol: use mapped role number instead of module role number

When expanding a module which includes role transitions we were
comparing the numeric value of the base policy role with the numberic
value of the unmapped role in the module. Comparisions between
role values need to both be in terms of the mapped role in the base
module.

Signed-off-by: Eric Paris <eparis@redhat.com>
Acked-by: Harry Ciao <qingtao.cao@windriver.com>
xpand.c
7190ed6020e061ccb204fd7b6e7f16bd22fdca82 20-Apr-2011 Eric Paris <eparis@redhat.com> libsepol: store all filename transition rules when parsing a policy

The kernel policy parsing logic was incorrectly believing the list of
filename transition rules was always empty because we never updated the
tail pointer when we added to the list. This patch updates the pointer
to the last entry when a new entry is added.

Signed-off-by: Eric Paris <eparis@redhat.com>
Acked-by: Dan Walsh <dwalsh@redhat.com>
olicydb.c
c3f5d75c3234ea2b03c7eba9eb18b550efcc1605 25-Jul-2011 Harry Ciao <qingtao.cao@windriver.com> Support adding one role attribute into another.

When the link process is completed, the types type_set_t and roles
ebitmap in a role attribute are settled, then we could go on to scan
all role attributes in the base->p_roles.table checking if any non-zero
bit in its roles ebitmap is indeed another role attribute.

If this is the case, then we need to escalate the roles ebitmap of
the sub role attribute into that of the parent, and remove the sub role
attribute from parent's roles ebitmap.

Since sub-attribute's roles ebitmap may further contain other role
attributes, we need to re-scan the updated parent's roles ebitmap.

Also if a loop dependency is detected, no escalation of sub-attribute's
roles ebitmap is needed.

Note, although in the link stage all role identifiers defined in any
block/decl of any module would be copied into the base->p_roles.table,
the role-attribute relationships could still be recorded in the decl's
local symtab[SYM_ROLES] table(see get_local_role()), so before all above
escalation of sub role attribute's roles ebitmap into that of parent ever
happens, all decl in the base->global list except the global block would
have to be traversed so as to populate potential role-attribute
relationships from decl up to the base module.

Signed-off-by: Harry Ciao <qingtao.cao@windriver.com>
Signed-off-by: Steve Lawrence <slawrence@tresys.com>
ink.c
3592ebea1a5beb390a520c09747d3699867af9de 25-Jul-2011 Harry Ciao <qingtao.cao@windriver.com> Add role attribute support when expanding role_set_t.

When the rolemap and pointer to the base module are available, if
a non-zero bit in role_set_t.roles is a role attribute, expand it
before remap.

Note, during module compile the rolemap may not be available, the
potential duplicates of a regular role and the role attribute that
the regular role belongs to could be properly handled by
copy_role_allow() and copy_role_trans() during module expansion.

Take advantage of the role_val_to_struct[] of the base module, since
when role_set_expand() is invoked, the role_val_to_struct[] of the
out module may have not been established yet.

Also cleanup the error handling of role_set_expand().

Signed-off-by: Harry Ciao <qingtao.cao@windriver.com>
Signed-off-by: Steve Lawrence <slawrence@tresys.com>
xpand.c
olicydb.c
sers.c
d4d90eceeba902874252fd7c1b9384fc5b1605d4 25-Jul-2011 Harry Ciao <qingtao.cao@windriver.com> Add role attribute support when expanding role_datum_t.

1. Copy the flavor flag into its counterpart in the out module;

2. Fix all role attributes in the base module:
2.1 remap the roles ebitmap and merge into its counterpart in the
out module;
2.2 escalate the types.types ebitmap of its counterpart in the out
module, to the counterparts for all the regular roles that belongs
to the current role attribute.

The role_fix_callback() must be called after role_copy_callback()
so that state->rolemap[] is available.

Signed-off-by: Harry Ciao <qingtao.cao@windriver.com>
Signed-off-by: Steve Lawrence <slawrence@tresys.com>
xpand.c
bff13595230dbd41692a98482ff3323078ae7d03 25-Jul-2011 Harry Ciao <qingtao.cao@windriver.com> Add role attribute support when linking modules.

Make the flavor flag and the roles ebitmap in role_datum_t structure
properly handled during module link process:

1. the flavor flag is copied into the base module;

2. if both the current module and the base module have defined or
required the same role, check if there is a discrepency in flavor;

3. remap the roles ebitmap and merge into its counterpart in the
base module;

Signed-off-by: Harry Ciao <qingtao.cao@windriver.com>
Signed-off-by: Steve Lawrence <slawrence@tresys.com>
ink.c
8072dba146b213a3f12a394596537e73f1b9339c 25-Jul-2011 Harry Ciao <qingtao.cao@windriver.com> Add role attribute support when generating pp files.

Add support to read/write the flavor flag and roles ebitmap in the
role_datum_t structure from/to policy module, if its version is no less
than MOD_POLICYDB_VERSION_ROLEATTRIB.

Since the role ebitmap would be expanded and won't be written into
policy.X, neither is the flavor flag, kernel SELinux security server
needs no change, the maximum version number for policy.X needs no bump.

Signed-off-by: Harry Ciao <qingtao.cao@windriver.com>
Signed-off-by: Steve Lawrence <slawrence@tresys.com>
olicydb.c
rite.c
16675b7f96b7a61ac64180b1824ec04984b72b3b 25-Jul-2011 Harry Ciao <qingtao.cao@windriver.com> Add role attribute support when compiling modules.

1. Add a uint32_t "flavor" field and an ebitmap "roles" to the
role_datum_t structure;

2. Add a new "attribute_role" statement and its handler to declare
a role attribute;

3. Modify declare_role() to setup role_datum_t.flavor according
to the isattr argument;

4. Add a new "roleattribute" rule and its handler, which will record
the regular role's (policy value - 1) into the role attribute's
role_datum_t.roles ebitmap;

5. Modify the syntax for the role-types rule only to define the
role-type associations;

6. Add a new role-attr rule to support the declaration of a single
role, and optionally the role attribute that the role belongs to;

7. Check if the new_role used in role-transition rule is a regular role;

8. Support to require a role attribute;

9. Modify symtab_insert() to allow multiple declarations only for
the regular role, while a role attribute can't be declared more than once
and can't share a same name with another regular role.

Signed-off-by: Harry Ciao <qingtao.cao@windriver.com>
Signed-off-by: Steve Lawrence <slawrence@tresys.com>
olicydb.c
30c3a6e4c3abe5e3202344591768aa4666b66f76 02-May-2011 Steve Lawrence <slawrence@tresys.com> libsepol: warn if filename_trans rules are dropped

Signed-off-by: Steve Lawrence <slawrence@tresys.com>
rite.c
58fef61e7350d64049a04c9a4b21c86ce35c35de 13-Apr-2011 Steve Lawrence <slawrence@tresys.com> libsepol: use the correct number of roletrans rules when not supported

When writing the roletrans rules, rules are dropped when not supported,
but the number of rules is not decreased. This sets the number of
elements to the actual number of rules that will be written.

Signed-off-by: Steve Lawrence <slawrence@tresys.com>
rite.c
34df32ab85a914c2bb7430e40716be7cbfa0a6bb 12-Apr-2011 Eric Paris <eparis@redhat.com> libsepol: support policy modules when roletrans rules not supported

Although the role trans code had support to handle the kernel policy
when the version was less that roletrans such support was not in the
module read/write code. This patch adds proper support for role trans
in modules.

Signed-off-by: Eric Paris <eparis@redhat.com>
Signed-off-by: Steve Lawrence <slawrence@tresys.com>
olicydb.c
rite.c
6eeb71538ea29b639ac7549831cd1aa4da32722a 12-Apr-2011 Eric Paris <eparis@redhat.com> libsepol: add support for filenametrans rule

This patch adds libsepol support for filename_trans rules. These rules
allow one to make labeling decisions for new objects based partially on
the last path component. They are stored in a list. If we find that
the number of rules grows to an significant size I will likely choose to
store these in a hash, both in libsepol and in the kernel. But as long
as the number of such rules stays small, this should be good.

Signed-off-by: Eric Paris <eparis@redhat.com>
Signed-off-by: Steve Lawrence <slawrence@tresys.com>
vrule_block.c
xpand.c
ink.c
olicydb.c
rite.c
6db9b74210197f792a52038abbd10e946e99e49d 25-Mar-2011 Harry Ciao <qingtao.cao@windriver.com> Userspace: handle the class in role_trans_rule

Add class support to various functions to handle role_trans_rule_t
structures.

Signed-off-by: Harry Ciao <qingtao.cao@windriver.com>
Signed-off-by: Steve Lawrence <slawrence@tresys.com>
xpand.c
ink.c
olicydb.c
rite.c
93417dfa28606d48dc3e37e05d5a3aeaa1488870 25-Mar-2011 Harry Ciao <qingtao.cao@windriver.com> Userspace: handle the class field in role_trans struct

Add the class support to various functions that handle role_trans
structure.

Signed-off-by: Harry Ciao <qingtao.cao@windriver.com>
Signed-off-by: Steve Lawrence <slawrence@tresys.com>
olicydb.c
rite.c
45b2e6ec2340d698db506dff8c3df947b6e29452 25-Mar-2011 Harry Ciao <qingtao.cao@windriver.com> Userspace: add class to role_trans & role_trans_rule

Introduce the class support to role_trans and role_trans_rule
structures, which could be the subject class("process") or the
class that the newly created object belongs to.

Signed-off-by: Harry Ciao <qingtao.cao@windriver.com>
Signed-off-by: Steve Lawrence <slawrence@tresys.com>
olicydb.c
033959726bf32ab59a52201e0696f269c0810609 09-Dec-2010 Justin P. Mattock <justinmattock@gmail.com> Author: "Justin P. Mattock"
Email: justinmattock@gmail.com
Subject: libsepol
Date: Tue, 6 Jul 2010 15:23:29 -0700

Going through these warning messages Im getting:
(example 1 of many)
booleans.c: In function 'sepol_bool_count':
booleans.c:106:39: error: parameter 'handle' set but not used
cc1: all warnings being treated as errors

seems most of these go to NULL; Which tells me that these are here for
future use and/or need to be there for some other reason.
The biggest problem I have is Im getting errors out of these as opposed
to just a warning(-Werror) so marking the variable with a GCC
__attribute__ ((unused)) gets things going.

Signed-off-by: Justin P. Mattock <justinmattock@gmail.com>
Signed-off-by: Chad Sellers <csellers@tresys.com>
ooleans.c
ebug.c
nterfaces.c
odes.c
olicydb.c
orts.c
oles.c
ervices.c
sers.c
7420787817c4949276d7947202b49d78eba37c13 24-Feb-2010 Daniel J Walsh <dwalsh@redhat.com> updated libselinux pkgconfig does not work correctly on lib64 machines.

On 02/24/2010 02:24 PM, Daniel J Walsh wrote:
>
Ignore the first patch it was missing pc.in files.

Acked-by: Eamon Walsh <ewalsh@tycho.nsa.gov>
Signed-off-by: Joshua Brindle <method@manicmethod.com>
akefile
ibsepol.pc.in
8627ab66a7136f1a84fe2a4d83f04e196b09ea7b 18-Nov-2009 Manoj Srivastava <srivasta@debian.org> Author: Manoj Srivastava
Email: srivasta@debian.org
Subject: cannnot -> cannot and suport -> support
Date: Tue, 17 Nov 2009 10:27:57 -0600

This was reported after a lintian check found this on any package
linked with libsepol. Closes: #556390

Signed-off-by: Manoj Srivastava <srivasta@debian.org>
Signed-off-by: Chad Sellers <csellers@tresys.com>
rite.c
12777502c638698a9e1dd6748a2309cb87946a65 21-Oct-2009 Eamon Walsh <ewalsh@tycho.nsa.gov> Add pkgconfig files for libsepol, libselinux, and libsemanage.

Having a pkgconfig files allows the pkg-config tool to be used to
query the presence of the library (or a particular version of it),
and to obtain the C flags and linker arguments to build with it.

Based on Debian patches by Manoj Srivastava <srivasta@debian.org>.

Signed-off-by: Eamon Walsh <ewalsh@tycho.nsa.gov>
akefile
ibsepol.pc.in
505c75aad7f16e0db9ccfeb04eaa70f242e6b060 29-Sep-2009 Paul Nuzzi <pjnuzzi@tycho.ncsc.mil> libsepol: Add support for multiple target OSes

On Wed, 2009-09-16 at 09:58 -0400, Joshua Brindle wrote:
> I'd rather have separate ocontext structs for each system. That way it
> is very easy to understand which ones apply to which system and you
> don't get a crazy out of context ocontext struct.
>

I looked into having separate ocontext structs but that would involve
changing a lot of files making the patch much larger and more intrusive.

> > } u;
> > union {
> > uint32_t sclass; /* security class for genfs */
> > @@ -313,6 +323,17 @@ typedef struct genfs {
> > #define OCON_NODE6 6 /* IPv6 nodes */
> > #define OCON_NUM 7
> >
> > +/* object context array indices for Xen */
> > +#define OCON_ISID 0 /* initial SIDs */
> > +#define OCON_PIRQ 1 /* physical irqs */
> > +#define OCON_IOPORT 2 /* io ports */
> > +#define OCON_IOMEM 3 /* io memory */
> > +#define OCON_DEVICE 4 /* pci devices */
> > +#define OCON_DUMMY1 5 /* reserved */
> > +#define OCON_DUMMY2 6 /* reserved */
> > +#define OCON_NUM 7
> > +
> > +
> >
> Should these be namespaced? What if <random other system> has io port
> objects? You'd have to align them with each other and you have a mess of
> keeping the numbers the same (you already do this with OCON_ISID)

Variables have been namespaced and there is no more overlap with
OCON_ISID.

> Also we are relying on having the same number of OCON's which isn't good
> I don't think. As much as I hate the policydb_compat_info (read: alot)
> why aren't we using that to say how many ocons a xen policy really has?

OCON_NUM is now dynamically read through policydb_compat_info.

> This is messy, why not an ocontext_selinux_free() and
> ocontext_xen_free() (note: I realize the xen_free() one won't do
> anything except freep the ocontext_t)
>

done.

> >
> > len = buf[1];
> > - if (len != strlen(target_str)&&
> > - (!alt_target_str || len != strlen(alt_target_str))) {
> > - ERR(fp->handle, "policydb string length %zu does not match "
> > - "expected length %zu", len, strlen(target_str));
> > + if (len> 32) {
> >
>
> magic number 32?

#defined.

Thanks for your input. Below is the updated patch for libsepol.

----

libsepol/include/sepol/policydb/policydb.h | 28 ++
libsepol/src/expand.c | 85 +++++++-
libsepol/src/policydb.c | 295
+++++++++++++++++++++++------
libsepol/src/policydb_internal.h | 1
libsepol/src/private.h | 4
libsepol/src/write.c | 93 ++++++++-
6 files changed, 443 insertions(+), 63 deletions(-)

Signed-off-by: Joshua Brindle <method@manicmethod.com>
xpand.c
olicydb.c
olicydb_internal.h
rivate.h
rite.c
a0440a66c3418842f309fc4f78f2aad87ba6c96f 31-Aug-2009 Stephen Smalley <sds@tycho.nsa.gov> Unchecked input leades to integer underflow

On Mon, 2009-08-31 at 08:55 -0500, Manoj Srivastava wrote:
> On Mon, Aug 31 2009, Stephen Smalley wrote:
>
> > On Sun, 2009-08-30 at 10:19 -0500, Manoj Srivastava wrote:
> >> Hi,
> >>
> >> This bug was discovered, and the analysis done, buy Max
> >> Kellermann. I have never been able to replicate the problem, so I can't
> >> help debug this error.
> >>
> >> Strace:
> >> --8<---------------cut here---------------start------------->8---
> >> brk(0x3233000) = 0x3233000
> >> mmap(NULL, 18446744073703178240, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = -1 ENOMEM (Cannot allocate memory)
> >> mmap(NULL, 18446744073703313408, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = -1 ENOMEM (Cannot allocate memory)
> >> mmap(NULL, 134217728, PROT_NONE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_NORESERVE, -1, 0) = 0x7fdfda316000
> >> --8<---------------cut here---------------end--------------->8---
> >>
> >> > 0xffffffffff9ec000 == 18446744073703178240 (the size of the first
> >> > large allocation). It's also equal to -6373376. This just looks like
> >> > an integer underflow, doesn't it?
> >>
> >> --8<---------------cut here---------------start------------->8---
> >> Breakpoint 4, 0x00007f9bc4c05400 in mmap64 () from /lib/libc.so.6
> >> (gdb) p $rsi
> >> $25 = -6373376
> >> (gdb) bt
> >> #0 0x00007f9bc4c05400 in mmap64 () from /lib/libc.so.6
> >> #1 0x00007f9bc4baf6bb in _int_malloc () from /lib/libc.so.6
> >> #2 0x00007f9bc4bb0a78 in malloc () from /lib/libc.so.6
> >> #3 0x00007f9bc5301a8e in sepol_module_package_read (mod=0xb1d170, spf=0xb202e0, verbose=0) at module.c:533
> >> #4 0x00007f9bc4ea7838 in ?? () from /lib/libsemanage.so.1
> >>
> >> (gdb) frame 3
> >> #3 0x00007f9bc5301a8e in sepol_module_package_read (mod=0xb1d170, spf=0xb202e0, verbose=0) at module.c:533
> >> 533 module.c: No such file or directory.
> >> in module.c
> >> (gdb) p len
> >> $26 = 18446744073703176358
> >> (gdb) p i
> >> $27 = 3
> >> (gdb) p nsec
> >> $30 = 4
> >> (gdb) p offsets[i+1]
> >> $28 = 8192
> >> (gdb) p offsets[i]
> >> $29 = 6383450
> >> --8<---------------cut here---------------end--------------->8---
> >>
> >> > line 456:
> >> > len = offsets[i + 1] - offsets[i];
> >>
> >> > Voila, integer underflow. The function module_package_read_offsets()
> >> > reads the offsets from the input file, but does not verify them.
> >> > off[nsec] = policy_file_length(file);
> >> > Here, the check is missing.
> >>
> >> We should probably have:
> >> --8<---------------cut here---------------start------------->8---
> >> off[nsec] = policy_file_length(file);
> >> if (off[nsec] < off[nsec-1]) {
> >> ERR(file->handle, "file size smaller than previous offset (at %u, "
> >> "offset %zu -> %zu", nsec, off[nsec - 1],
> >> off[nsec]);
> >> return -1;
> >> }
> >> --8<---------------cut here---------------end--------------->8---
> >
> > Perhaps I am missing something, but module_package_read_offsets()
> > already checks that the offsets are increasing and aborts if not.
>
> Well, almost. It does check for most of the offsets:
> --8<---------------cut here---------------start------------->8---
>
> 406 for (i = 0; i < nsec; i++) {
> 407 off[i] = le32_to_cpu(buf[i]);
> 408 if (i && off[i] < off[i - 1]) {
> 409 ERR(file->handle, "offsets are not increasing (at %u, "
> 410 "offset %zu -> %zu", i, off[i - 1],
> 411 off[i]);
> 412 return -1;
> 413 }
> 414 }
> --8<---------------cut here---------------end--------------->8---
> So far, so good.
> --8<---------------cut here---------------start------------->8---
> 415
> 416 free(buf);
> 417 off[nsec] = policy_file_length(file);
> 418 *offsets = off;
> 419 return 0;
> --8<---------------cut here---------------end--------------->8---
>
> The problem is line 417, where there is no check; and in the
> case reported, the file length was less than the previous offset, and
> this resulted in a negative number passed to the memory allocator,
> which resulted in a huge allocation request.
>
> Above, I just propose adding a check after line 417.

Check the last offset against the file size, and ensure that we free the
buffer and offset array in the error cases.

Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
odule.c
86a2f899cb031036892f85c679ab6802bce15c43 06-Jul-2009 Christopher Pardy <cpardy@redhat.com> libsepol: method to check disable dontaudit flag.

This patch adds the ability to check on the value of the disable_dontaudit flag in the sepol handle. In the past the only way to know the value of this was to directly read the values from the handle. The get function provides a setter-getter symmetry similar to other functions found in libsepol.

Signed-off-by: Christopher Pardy <cpardy@redhat.com>
Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
andle.c
ibsepol.map
3df79fc5ebf08a35aaa095b2ee3fd24b3ece6ae5 21-Mar-2009 Joshua Brindle <method@manicmethod.com> Author: Joshua Brindle
Email: method@manicmethod.com
Subject: libsepol: fix boolean state smashing
Date: Wed, 18 Mar 2009 10:47:34 -0400

If a boolean is encountered in a require block before the place where it is
declared it currently gets created with the state set to false no matter what
the declared state was. This only affects booleans in modules where the boolean
was also required in another module. Patch below:

Signed-off-by: Joshua Brindle <method@manicmethod.com>
ink.c
f7917ea9cf6af752de98a1e742152d813028c669 10-Feb-2009 Caleb Case <ccase@tresys.com> aliases for the boundry format

The boundry format mapped the primary field to a boolean in the
properties bitmap. This is appropriate for the kernel policy, but in
modular policy the primary field may be an integer that indicates the
primary type that is being aliased. In this case, the primary value cannot
be assumed to be boolean.

This patch creates a new module format that writes out the primary value
as was done before the boundry format.

Signed-off-by: Caleb Case <ccase@tresys.com>
Signed-off-by: Joshua Brindle <method@manicmethod.com>
olicydb.c
rite.c
a73248ba8184e152c752310ac1cb649c7a292ebb 09-Oct-2008 Joshua Brindle <method@manicmethod.com> remove reject file
xpand.c.rej
f470207454f5f6ce539aa543e5168a07d667254b 08-Oct-2008 Joshua Brindle <method@manicmethod.com> Author: KaiGai Kohei
Email: kaigai@ak.jp.nec.com
Subject: Thread/Child-Domain Assignment (rev.6)
Date: Tue, 07 Oct 2008 15:39:45 +0900

>> Hmm....
>> It seems to me what you pointed out is a bug of my patch. It prevents to deliver
>> actual number of type/attribute symbols to policy file, but it is unclear why does
>> it makes libsepol ignore the policyvers.
>> (I guess it may be a separated matter.)
>>
>>> Rather than trying to calculate the length without attributes I just removed
>>> the attribute check. This causes attributes to be written for all versions,
>>> but this should not cause any problems at all.
>> The reason why I injected such an ad-hoc code is that we cannot decide the policy
>> version written when type_attr_remove() is invoked.
>> Is it impossible to move it to policydb_write()?
>> It is invoked after the policyvers is fixed by caller.
>
> It isn't impossible. You are going to have to make it walk to type
> symbol table to calculate the length without attributes, then write
> that length instead of the total symtab length.

The attached patch enables to fixup the number of type/attribute entries
to be written. The type_attr_uncount() decrements the number of attribute
entries skipped at type_write().

At first, I had a plan to invoke type_attr_remove() with
hashtab_map_remove_on_error(), but it means the given policydb structure
is modified at policydb_write() and implicit changes to external interface.

Differences from the previous version are here:

Signed-off-by: Joshua Brindle <method@manicmethod.com>
xpand.c
ierarchy.c
ink.c
olicydb.c
rite.c
e61b36a5c78852c5d30d9512e0c69546d23ea25c 07-Oct-2008 Joshua Brindle <method@manicmethod.com> Author: Joshua Brindle
Email: method@manicmethod.com
Subject: BUGREPORT: A type alias of invisible primary one
Date: Mon, 22 Sep 2008 16:43:04 -0400

KaiGai Kohei wrote:
> Joshua Brindle wrote:
>> KaiGai Kohei wrote:
>>> I found a strange type_datum_t object which has 0 for its s.value
>>> during development of new type hierarchy checks.
>>>
>>> The strange one is "xguest_javaplugin_default_xproperty_t" which
>>> is an alias type of "xguest_javaplugin_xproperty_t".
>>>
>>> I doubted my patch at first, but it can be reproduced on the normal
>>> libsepol. It seems to me an original matter which is not exposed yet,
>>> and I am innocence. :-)
>>>
>>> During tracing the matter, I noticed the primary type is invisible
>>> at expand_module(), but the aliased one is visible. It can make the
>>> strange type_datum_t object.
>>>
>>> * at the expand_module()
>>> 1. The expand_state_t which includes typemap is initialized.
>>>
>>> 2. The type_copy_callback is invoked for any types via hashtab_map.
>>> It only copies primary and visible types into newer hashtab,
>>> and set up typemap to translate between old and new s.value.
>>> Thus, the given primary type is invisible, its slot of typemap
>>> is kept to zero.
>>> (*) is_id_enabled() for "xguest_javaplugin_xproperty_t" returned false.
>>>
>>> 3. The alias_copy_callback is invoked for any types via hashtab_map.
>>> It only copies alias and visible types into newer hashtab.
>>> Here is no check whether the primary side is visible, or not.
>>> A copied type_datum_t object for the given alias has new s.value
>>> which is picked up from state->typemap.
>>>
>>> 4. However, the target slot of state->typemap was zero, because
>>> its primary one is invisible. The aliased type has a strange
>>> s.value.
>>>
>>> 5. Type hierarchy checks got a segmentation fault, due to
>>> "p->type_val_to_name[datum->s.value - 1]".
>>> ^^^^^^^^^^^^^^^^^^ == -1
>>> Yes, we can identify cause of the matter.
>> Do you have a policy that can be used to reproduce this?
>
> Yes, the following policy can reproduce the matter.
> - - - - [ cut here ] - - - -
> policy_module(baz, 1.0)
>
> optional_policy(`
> gen_require(`
> type invisible_primary_t;
> ')
> typealias invisible_primary_t alias visible_alias_t;
> ')
> - - - - - - - - - - - - - - -
>
> The attached patch can inject some of printf()'s.
> You can see that invisible_primary_t is skipped at type_copy_callback()
> and an incorrect s.value is assigned at alias_copy_callback().
>
> Thanks,
>

This should fix it. I tested with and without your patchset on a few policies. Let me know if it doesn't work for you:
xpand.c
xpand.c.rej
eeb520a0453ccc3d51770c4281125086e91c4ff7 30-Sep-2008 Joshua Brindle <method@manicmethod.com> Revert "Subject: remove expand_rule function"

This reverts commit 45e94541ecbe3594482975018e4ceb0fadacd92a.
xpand.c
45e94541ecbe3594482975018e4ceb0fadacd92a 12-Aug-2008 Joshua Brindle <method@manicmethod.com> Subject: remove expand_rule function

Send again with the right date and time ;)

This removes the (apparently) unused expand_rule function

Signed-off-by: Joshua Brindle <method@manicmethod.com>
xpand.c
13cd4c8960688af11ad23b4c946149015c80d549 19-Aug-2008 Joshua Brindle <method@manicmethod.com> initial import from svn trunk revision 2950
akefile
ssertion.c
v_permissions.h
vrule_block.c
vtab.c
oolean_internal.h
oolean_record.c
ooleans.c
onditional.c
onstraint.c
ontext.c
ontext.h
ontext_internal.h
ontext_record.c
ebug.c
ebug.h
so.h
bitmap.c
xpand.c
enbools.c
enusers.c
andle.c
andle.h
ashtab.c
ierarchy.c
face_internal.h
face_record.c
nterfaces.c
ibsepol.map
ink.c
ls.c
ls.h
odule.c
odule_internal.h
ode_internal.h
ode_record.c
odes.c
olcaps.c
olicydb.c
olicydb_convert.c
olicydb_internal.h
olicydb_public.c
ort_internal.h
ort_record.c
orts.c
rivate.h
oles.c
ervices.c
idtab.c
ymtab.c
ser_internal.h
ser_record.c
sers.c
til.c
rite.c