Commit graph

70 commits

Author SHA1 Message Date
Christian Göttsche
5570c2e394 checkpolicy: enclose macro argument in parentheses
Found by clang-tidy

Signed-off-by: Christian Göttsche <cgzones@googlemail.com>
2021-09-15 10:13:48 -04:00
Christian Göttsche
1711757378
checkpolicy: mark read-only parameters in policy define const
Make it more obvious which parameters are read-only and not being
modified and allow callers to pass const pointers.

Signed-off-by: Christian Göttsche <cgzones@googlemail.com>
2021-07-13 21:02:10 +02:00
Christian Göttsche
4e3d0990c6
checkpolicy: drop redundant cast to the same type
Found by clang-tidy.

Signed-off-by: Christian Göttsche <cgzones@googlemail.com>
2021-07-13 21:02:09 +02:00
Christian Göttsche
5a10f05f53
checkpolicy: check before potential NULL dereference
policy_define.c: In function ‘define_te_avtab_extended_perms’:
    policy_define.c:1946:17: error: potential null pointer dereference [-Werror=null-dereference]
     1946 |         r->omit = omit;
          |                 ^

In the case of `r` being NULL, avrule_read_ioctls() would return
with its parameter `rangehead` being a pointer to NULL, which is
considered a failure in its caller `avrule_ioctl_ranges`.
So it is not necessary to alter the return value.

Found by GCC 11 with LTO enabled.

Signed-off-by: Christian Göttsche <cgzones@googlemail.com>
2021-07-13 21:02:08 +02:00
Christian Göttsche
79e7724930
checkpolicy: follow declaration-after-statement
Follow the project style of no declaration after statement.

Found by the GCC warning -Wdeclaration-after-statement.

Signed-off-by: Christian Göttsche <cgzones@googlemail.com>
2021-07-13 21:02:07 +02:00
Christian Göttsche
db674bf218
checkpolicy: drop dead condition
The variable `id` is guaranteed to be non-NULL due to the preceding
while condition.

    policy_define.c:1171:7: style: Condition '!id' is always false [knownConditionTrueFalse]
      if (!id) {
          ^
    policy_define.c:1170:13: note: Assuming that condition 'id=queue_remove(id_queue)' is not redundant
     while ((id = queue_remove(id_queue))) {
                ^
    policy_define.c:1171:7: note: Condition '!id' is always false
      if (!id) {
          ^

Found by Cppcheck.

Signed-off-by: Christian Göttsche <cgzones@googlemail.com>
2021-07-13 21:02:05 +02:00
James Carter
dcd07fdcbf
libsepol/checkpolicy: Set user roles using role value instead of dominance
Roles in an optional block have two datums, one in the global block
and one in the avrule_decl where it is declared. The datum in the
global block does not have its dominace set. This is a problem because
the function set_user_role() sets the user's roles based on the global
datum's dominance ebitmap. If a user is declared with an associated role
that was declared in an optional block, then it will not have any roles
set for it because the dominance ebitmap is empty.

Example/
  # handle_unknown deny
  class CLASS1
  sid kernel
  class CLASS1 { PERM1 }
  type TYPE1;
  allow TYPE1 self:CLASS1 PERM1;
  role ROLE1;
  role ROLE1 types { TYPE1 };
  optional {
    require {
      class CLASS1 { PERM1 };
    }
    role ROLE1A;
    user USER1A roles ROLE1A;
  }
  user USER1 roles ROLE1;
  sid kernel USER1:ROLE1:TYPE1

In this example, USER1A would not have ROLE1A associated with it.

Instead of using dominance, which has been deprecated anyway, just
set the bit corresponding to the role's value in the user's roles
ebitmap in set_user_role().

Signed-off-by: James Carter <jwcart2@gmail.com>
Acked-by: Nicolas Iooss <nicolas.iooss@m4x.org>

[N.I: added spaces around "-" operator]
2021-03-15 21:50:58 +01:00
Nicolas Iooss
b320291888 libsepol/cil: fix memory leak when a constraint expression is too deep
When __cil_validate_constrain_expr() fails,
cil_constrain_to_policydb_helper() does not destroy the constraint
expression. This leads to a memory leak reported by OSS-Fuzz with the
following CIL policy:

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

    (constrain
        (CLASS (PERM))
        (or
            (eq t1 TYPE)
            (or
                (eq t1 TYPE)
                (or
                    (eq t1 TYPE)
                    (or
                        (eq t1 TYPE)
                        (or
                            (eq t1 TYPE)
                            (eq t1 TYPE)
                        )
                    )
                )
            )
        )
    )

Add constraint_expr_destroy(sepol_expr) to destroy the expression.

Moreover constraint_expr_destroy() was not freeing all items of an
expression. Code in libsepol/src and checkpolicy contained while loop to
free all the items of a constraint expression, but not the one in
libsepol/cil. As freeing only the first item of an expression is
misleading, change the semantic of constraint_expr_destroy() to iterate
the list of constraint_expr_t and to free all items.

Fixes: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=28938
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
Acked-by: James Carter <jwcart2@gmail.com>
2021-02-03 09:28:39 +01:00
Nicolas Iooss
521e6a2f47 libsepol/cil: fix signed overflow caused by using (1 << 31) - 1
When compiling SELinux userspace tools with -ftrapv (this option
generates traps for signed overflow on addition, subtraction,
multiplication operations, instead of silently wrapping around),
semodule crashes when running the tests from
scripts/ci/fedora-test-runner.sh in a Fedora 32 virtual machine:

    [root@localhost selinux-testsuite]# make test
    make -C policy load
    make[1]: Entering directory '/root/selinux-testsuite/policy'
    # Test for "expand-check = 0" in /etc/selinux/semanage.conf
    # General policy build
    make[2]: Entering directory '/root/selinux-testsuite/policy/test_policy'
    Compiling targeted test_policy module
    Creating targeted test_policy.pp policy package
    rm tmp/test_policy.mod.fc
    make[2]: Leaving directory '/root/selinux-testsuite/policy/test_policy'
    # General policy load
    domain_fd_use --> off
    /usr/sbin/semodule -i test_policy/test_policy.pp test_mlsconstrain.cil test_overlay_defaultrange.cil test_add_levels.cil test_glblub.cil
    make[1]: *** [Makefile:174: load] Aborted (core dumped)

Using "coredumpctl gdb" leads to the following strack trace:

    (gdb) bt
    #0  0x00007f608fe4fa25 in raise () from /lib64/libc.so.6
    #1  0x00007f608fe38895 in abort () from /lib64/libc.so.6
    #2  0x00007f6090028aca in __addvsi3.cold () from /lib64/libsepol.so.1
    #3  0x00007f6090096f59 in __avrule_xperm_setrangebits (low=30, high=30, xperms=0x8b9eea0)
        at ../cil/src/cil_binary.c:1551
    #4  0x00007f60900970dd in __cil_permx_bitmap_to_sepol_xperms_list (xperms=0xb650a30, xperms_list=0x7ffce2653b18)
        at ../cil/src/cil_binary.c:1596
    #5  0x00007f6090097286 in __cil_avrulex_ioctl_to_policydb (k=0xb8ec200 "@\023\214\022\006", datum=0xb650a30,
        args=0x239a640) at ../cil/src/cil_binary.c:1649
    #6  0x00007f609003f1e5 in hashtab_map (h=0x41f8710, apply=0x7f60900971da <__cil_avrulex_ioctl_to_policydb>,
        args=0x239a640) at hashtab.c:234
    #7  0x00007f609009ea19 in cil_binary_create_allocated_pdb (db=0x2394f10, policydb=0x239a640)
        at ../cil/src/cil_binary.c:4969
    #8  0x00007f609009d19d in cil_binary_create (db=0x2394f10, policydb=0x7ffce2653d30) at ../cil/src/cil_binary.c:4329
    #9  0x00007f609008ec23 in cil_build_policydb_create_pdb (db=0x2394f10, sepol_db=0x7ffce2653d30)
        at ../cil/src/cil.c:631
    #10 0x00007f608fff4bf3 in semanage_direct_commit () from /lib64/libsemanage.so.1
    #11 0x00007f608fff9fae in semanage_commit () from /lib64/libsemanage.so.1
    #12 0x0000000000403e2b in main (argc=7, argv=0x7ffce2655058) at semodule.c:753

    (gdb) f 3
    #3  0x00007f6090096f59 in __avrule_xperm_setrangebits (low=30, high=30, xperms=0x8b9eea0)
        at ../cil/src/cil_binary.c:1551
    1551     xperms->perms[i] |= XPERM_SETBITS(h) - XPERM_SETBITS(low);

A signed integer overflow therefore occurs in XPERM_SETBITS(h):

    #define XPERM_SETBITS(x) ((1 << (x & 0x1f)) - 1)

This macro is expanded with h=31, so "(1 << 31) - 1" is computed:

* (1 << 31) = -0x80000000 is the lowest signed 32-bit integer value
* (1 << 31) - 1 overflows the capacity of a signed 32-bit integer and
  results in 0x7fffffff (which is unsigned)

Using unsigned integers (with "1U") fixes the crash, as
(1U << 31) = 0x80000000U has no overflowing issues.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
Acked-by: Petr Lautrbach <plautrba@redhat.com>
2020-10-15 19:25:05 +02:00
Ondrej Mosnacek
42ae834a74 libsepol,checkpolicy: optimize storage of filename transitions
In preparation to support a new policy format with a more optimal
representation of filename transition rules, this patch applies an
equivalent change from kernel commit c3a276111ea2 ("selinux: optimize
storage of filename transitions").

See the kernel commit's description [1] for the rationale behind this
representation. This change doesn't bring any measurable difference of
policy build performance (semodule -B) on Fedora.

[1] https://git.kernel.org/pub/scm/linux/kernel/git/pcmoore/selinux.git/commit/?id=c3a276111ea2572399281988b3129683e2a6b60b

Signed-off-by: Ondrej Mosnacek <omosnace@redhat.com>
2020-08-03 08:52:12 -04:00
Stephen Smalley
f8c110c8a6 libsepol,checkpolicy: remove use of hardcoded security class values
libsepol carried its own (outdated) copy of flask.h with the generated
security class and initial SID values for use by the policy
compiler and the forked copy of the security server code
leveraged by tools such as audit2why.  Convert libsepol and
checkpolicy entirely to looking up class values from the policy,
remove the SECCLASS_* definitions from its flask.h header, and move
the header with its remaining initial SID definitions private to
libsepol.  While we are here, fix the sepol_compute_sid() logic to
properly support features long since added to the policy and kernel,
although there are no users of it other than checkpolicy -d (debug)
and it is not exported to users of the shared library.  There
are still some residual differences between the kernel logic and
libsepol.

Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
Acked-by: Petr Lautrbach <plautrba@redhat.com>
2020-03-12 07:50:55 +01:00
Nicolas Iooss
b550c0e202
Fix many misspellings
Use codespell (https://github.com/codespell-project/codespell) in order
to find many common misspellings that are present in English texts.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2019-09-18 22:47:35 +02:00
Ondrej Mosnacek
3e506bda3b libsepol: add ebitmap_for_each_set_bit macro
Most of the users of ebitmap_for_each_bit() macro only care for the set
bits, so introduce a new ebitmap_for_each_positive_bit() macro that
skips the unset bits. Replace uses of ebitmap_for_each_bit() with the
new macro where appropriate.

Signed-off-by: Ondrej Mosnacek <omosnace@redhat.com>
2019-05-20 14:00:32 -04:00
liwugang
98a951fa76
checkpolicy: check the result value of hashtable_search
Signed-off-by: liwugang <liwugang@xiaomi.com>
2018-09-19 20:43:39 +02:00
Tri Vo
ea8d689b53 Resolve conflicts in expandattribute.
This commit resolves conflicts in values of expandattribute statements
in policy language and expandtypeattribute in CIL.

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

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

A warning will be issued on this conflict.

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

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

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

Signed-off-by: Richard Haines <richard_c_haines@btinternet.com>
2018-03-19 12:34:29 -04:00
Stephen Smalley
53bb2a11c2 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>
2017-08-17 14:17:12 -04:00
Daniel Jurgens
5bc05dd2a5 checkpolicy: Add support for ibendportcon labels
Add checkpolicy support for scanning and parsing ibendportcon labels.
Also create a new ocontext for IB end ports.

Signed-off-by: Daniel Jurgens <danielj@mellanox.com>
2017-05-23 16:20:55 -04:00
Daniel Jurgens
5b203145fd checkpolicy: Add support for ibpkeycon labels
Add checkpolicy support for scanning and parsing ibpkeycon labels. Also
create a new ocontext for Infiniband Pkeys and define a new policydb
version for infiniband support.

Signed-off-by: Daniel Jurgens <danielj@mellanox.com>
2017-05-23 16:20:54 -04:00
Stephen Smalley
c3118041df 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>
2017-05-10 10:25:56 -04:00
Jeff Vander Stoep
1089665e31 Add attribute expansion options
This commit adds attribute expansion statements to the policy
language allowing compiler defaults to be overridden.

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

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

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

Motivation

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

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

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

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

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

Signed-off-by: Jeff Vander Stoep <jeffv@google.com>
2017-05-09 12:09:46 -04:00
Nicolas Iooss
9087bb9c5a checkpolicy: dereference rangehead after checking it was not NULL
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2017-03-21 14:20:28 -04:00
Nicolas Iooss
7da9bc00f2 checkpolicy: do not leak memory when a class is not found in an avrule
While checkmodule tries to compile the following policy file and fails
because class "process" is not found, it does not free some allocated
memory:

    module ckpol_leaktest 1.0.0;
    require {type TYPE1;}
    allow TYPE1 self:process fork;

clang memory sanitier output is:

=================================================================
==16050==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 136 byte(s) in 1 object(s) allocated from:
    #0 0x7f8bd8127608 in malloc (/usr/lib/clang/3.9.1/lib/linux/libclang_rt.asan-x86_64.so+0xf6608)
    #1 0x41a620 in define_te_avtab_helper /usr/src/selinux/checkpolicy/policy_define.c:2450:24
    #2 0x41b6c8 in define_te_avtab /usr/src/selinux/checkpolicy/policy_define.c:2621:6
    #3 0x40522b in yyparse /usr/src/selinux/checkpolicy/policy_parse.y:470:10
    #4 0x411816 in read_source_policy /usr/src/selinux/checkpolicy/parse_util.c:64:6
    #5 0x7f8bd7cb3290 in __libc_start_main (/usr/lib/libc.so.6+0x20290)

Direct leak of 8 byte(s) in 1 object(s) allocated from:
    #0 0x7f8bd8127608 in malloc (/usr/lib/clang/3.9.1/lib/linux/libclang_rt.asan-x86_64.so+0xf6608)
    #1 0x411c87 in insert_id /usr/src/selinux/checkpolicy/policy_define.c:120:18

Indirect leak of 24 byte(s) in 1 object(s) allocated from:
    #0 0x7f8bd8127608 in malloc (/usr/lib/clang/3.9.1/lib/linux/libclang_rt.asan-x86_64.so+0xf6608)
    #1 0x43133c in ebitmap_set_bit /usr/src/selinux/libsepol/src/ebitmap.c:321:27

Indirect leak of 18 byte(s) in 1 object(s) allocated from:
    #0 0x7f8bd80b5eb0 in __interceptor___strdup (/usr/lib/clang/3.9.1/lib/linux/libclang_rt.asan-x86_64.so+0x84eb0)
    #1 0x41a6e5 in define_te_avtab_helper /usr/src/selinux/checkpolicy/policy_define.c:2460:28
    #2 0x41b6c8 in define_te_avtab /usr/src/selinux/checkpolicy/policy_define.c:2621:6
    #3 0x40522b in yyparse /usr/src/selinux/checkpolicy/policy_parse.y:470:10
    #4 0x411816 in read_source_policy /usr/src/selinux/checkpolicy/parse_util.c:64:6
    #5 0x7f8bd7cb3290 in __libc_start_main (/usr/lib/libc.so.6+0x20290)

SUMMARY: AddressSanitizer: 186 byte(s) leaked in 4 allocation(s).

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2017-01-23 11:26:44 -05:00
Nicolas Iooss
42658e729f checkpolicy: add a missing free(id) in define_roleattribute()
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2017-01-23 11:26:40 -05:00
Nicolas Iooss
0a0d055283 checkpolicy: fix memory leaks in define_filename_trans()
When parsing type_transition statements with names, the memory allocated
by the type set bitmaps of variable stypes and ttypes was never freed.

Call type_set_destroy() to free this memory and, while at it, make the
function exits without leaking memory when exiting with an error.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2017-01-23 11:26:34 -05:00
Nicolas Iooss
aa1a8a3c84 checkpolicy: always free id in define_type()
In function define_type(), some error conditions between "id =
queue_remove(id_queue)" and "get_local_type(id, attr->s.value, 1)"
returned without freeing id. Fix theses memory leaks.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2017-01-23 11:26:30 -05:00
Nick Kralevich
908898846a policy_define.c: don't free memory returned from queue_head()
Unlike queue_remove(), queue_head() does not modify the queue, but
rather, returns a pointer to an element within the queue. Freeing the
memory associated with a value returned from that function corrupts
subsequent users of the queue, who may try to reference this
now-deallocated memory.

This causes the following policy generation errors on Android:

  FAILED:
  out/target/product/bullhead/obj/ETC/plat_sepolicy.cil_intermediates/plat_policy_nvr.cil
  /bin/bash -c "out/host/linux-x86/bin/checkpolicy -M -C -c 30 -o
  out/target/product/bullhead/obj/ETC/plat_sepolicy.cil_intermediates/plat_policy_nvr.cil
  out/target/product/bullhead/obj/ETC/plat_sepolicy.cil_intermediates/plat_policy.conf"
  system/sepolicy/public/app.te:241:ERROR 'only ioctl extended permissions
  are supported' at token ';' on line 6784:
  #line 241
  } };
  checkpolicy:  error(s) encountered while parsing configuration

because the value of "id" in:

  id = queue_remove(id_queue);
  if (strcmp(id,"ioctl") == 0) {
    ...
  } else {
    yyerror("only ioctl extended permissions are supported");
    ...
  }

is now garbage.

This is a partial revert of the following commit:

  c1ba8311 checkpolicy: free id where it was leaked

Signed-off-by: Nick Kralevich <nnk@google.com>
2017-01-13 14:43:38 -05:00
Nicolas Iooss
d7b0941eed checkpolicy: fix memory usage in define_bool_tunable()
In an error path of define_bool_tunable(), variable id is freed after
being used by a successful call to declare_symbol(). This may cause
trouble as this pointer may have been used as-is in the policy symtab
hash table.

Moreover bool_value is never freed after being used. Fix this memory
leak too. This leak has been detected with gcc Address Sanitizer.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2017-01-09 15:01:33 -05:00
Nicolas Iooss
c1ba831122 checkpolicy: free id where it was leaked
Several functions in policy_define.c do not free id after handling it.
Add the missing free(id) statements.

The places where free(id) was missing were found both with gcc Address
Sanitizer and manual code inspection.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2017-01-06 13:43:21 -05:00
Nicolas Iooss
6ef96094d3 checkpolicy: fix memory leaks in genfscon statements parsing
When parsing several genfscon statements for the same filesystem, the
content of local variable "fstype" is never freed. Moreover variable
"type" is never freed when define_genfs_context_helper() succeeds.

Fix these leaks by calling free() appropriately.

These leaks have been detected with gcc Address Sanitizer.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2017-01-06 13:28:23 -05:00
Nicolas Iooss
da00246827 checkpolicy: free id in define_port_context()
Variable id is almost never freed in define_port_context().

This leak has been detected with gcc Address Sanitizer.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2017-01-06 13:22:38 -05:00
Stephen Smalley
8fdb225521 libsepol,checkpolicy: convert rangetrans and filenametrans to hashtabs
range transition and name-based type transition rules were originally
simple unordered lists.  They were converted to hashtabs in the kernel
by commit 2f3e82d694d3d7a2db019db1bb63385fbc1066f3 ("selinux: convert range
transition list to a hashtab") and by commit
2463c26d50adc282d19317013ba0ff473823ca47 ("SELinux: put name based
create rules in a hashtable"), but left unchanged in libsepol and
checkpolicy. Convert libsepol and checkpolicy to use the same hashtabs
as the kernel for the range transitions and name-based type transitions.

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

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

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

Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
2016-11-28 13:10:59 -05:00
Stephen Smalley
49bfee8562 checkpolicy: treat -self as an error
checkpolicy wrongly handles "-self". At the least, it should handle it as
an error. At best, it should support it correctly (which would involve
libsepol support as well). At present, it looks like it will end up
negating (-) the next type/attribute in the list after self, or if
there are no entries after self, ignoring it entirely.

This originally was raised by the Android team, which wanted to support
something like the following:
neverallow domain { domain -self }:dir search;
to prohibit cross domain access to some resource but allow access within
the same domain.

This change just makes it a fatal error during compilation.
Implementing real support for -self is left as future work.

Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
2016-11-18 11:09:38 -05:00
Nicolas Iooss
112f86d489 checkpolicy: add types associated to a role in the current scope when parsing
This fixes most of the errors reported in "make -C libsepol test":

    ./libsepol-tests
         CUnit - A unit testing framework for C - Version 2.1-3
         http://cunit.sourceforge.net/
    Suite: cond
      Test: cond_expr_equal ...passed
    Suite: linker
      Test: linker_indexes ...passed
      Test: linker_types ...passed
      Test: linker_roles ...
    role o1_b_role_1 has 0 types, 1 expected
    role o1_b_role_1 has 0 types, 1 expected
    role o1_m1_role_1 has 0 types, 1 expected
    sym g_b_role_2 has 1 decls, 2 expected
    Role o1_b_role_2 had type o1_b_type_1 not in types array
    role o1_b_role_2 has 0 types, 1 expected
    Role g_b_role_4 had type g_m1_type_2 not in types array
    role g_b_role_4 has 0 types, 1 expected
    role o3_b_role_1 has 0 types, 1 expected
    role o3_b_role_1 has 0 types, 1 expected
    role o4_b_role_1 has 0 types, 1 expected
    Role o4_b_role_1 had type g_m1_type_1 not in types array

    FAILED
        1. test-common.c:216  - found == len
        2. test-common.c:216  - found == len
        3. test-common.c:216  - found == len
        4. test-common.c:43  - scope->decl_ids_len == len
        5. test-common.c:52  - found == 1
        6. test-common.c:213  - new == 1
        7. test-common.c:216  - found == len
        8. test-common.c:213  - new == 1
        9. test-common.c:216  - found == len
        10. test-common.c:216  - found == len
        11. test-common.c:216  - found == len
        12. test-common.c:216  - found == len
        13. test-common.c:213  - new == 1
      Test: linker_cond ...passed
    Suite: expander
      Test: expander_indexes ...passed
      Test: expander_attr_mapping ...passed
      Test: expander_role_mapping ...passed
      Test: expander_user_mapping ...passed
      Test: expander_alias ...passed
    Suite: deps
      Test: deps_modreq_global ...passed
      Test: deps_modreq_opt ...passed
    Suite: downgrade
      Test: downgrade ...passed

    Run Summary:    Type  Total    Ran Passed Failed Inactive
                  suites      5      5    n/a      0        0
                   tests     13     13     12      1        0
                 asserts   1269   1269   1256     13      n/a

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2016-09-06 10:49:56 -04:00
Stephen Smalley
bedef7d124 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>
2016-05-03 11:54:20 -04:00
Richard Haines
aac9360581 selinux: Build policy on systems not supporting DCCP protocol
Commit 3895fbbe0c ("selinux: Add support
for portcon dccp protocol") added support for the (portcon dccp ..)
statement. This fix will allow policy to be built on platforms
(see [1]) that do not have DCCP support by defining the IANA
assigned IP Protocol Number 33 to IPPROTO_DCCP.

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

Signed-off-by: Richard Haines <richard_c_haines@btinternet.com>
2016-04-25 15:31:45 -04:00
Richard Haines
3895fbbe0c selinux: Add support for portcon dccp protocol
This adds CIL and checkpolicy support for the (portcon dccp ...)
statement. The kernel already handles name_bind and name_connect
permissions for the dccp_socket class.

Signed-off-by: Richard Haines <richard_c_haines@btinternet.com>
Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
2016-04-06 10:14:27 -04:00
Jeff Vander Stoep
99fc177b5a 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>
2015-09-22 10:52:47 -04:00
Stephen Smalley
a3691b87be checkpolicy: fix double free on name-based type transitions
checkpolicy was directly assigning type sets rather than using
type_set_cpy() and therefore creating pointer aliases to the
same type set from multiple filename-based type transition rules
if they specified multiple classes.  This would then yield a double
free when destroying the rules afterward and a segmentation fault.
Fix it to use type_set_cpy().

Reported-by: William C Roberts <william.c.roberts@intel.com>
Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
2015-07-31 08:57:32 -04:00
Jeff Vander Stoep
915fa8f08f 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>
2015-06-15 09:21:20 -04:00
Nick Kralevich
de0a3bd18d policy_define.c: fix compiler warnings
Fixes compiler warnings all similar to the following:

host C: checkpolicy <= external/selinux/checkpolicy/policy_define.c
external/selinux/checkpolicy/policy_define.c:1572:2: warning: comparison of integers of different signs: 'int' and 'uint32_t' (aka 'unsigned int') [-Wsign-compare]
        ebitmap_for_each_bit(&tclasses, node, i) {
        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
external/selinux/checkpolicy/../libsepol/include/sepol/policydb/ebitmap.h:76:39: note: expanded from macro 'ebitmap_for_each_bit'
        for (bit = ebitmap_start(e, &n); bit < ebitmap_length(e); bit = ebitmap_next(&n, bit)) \
                                             ^ ~~~~~~~~~~~~~~~~~

Signed-off-by: Nick Kralevich <nnk@google.com>
2015-06-15 09:14:34 -04:00
Jeff Vander Stoep
80bc7ee8fa 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>
2015-04-23 08:30:33 -04:00
Daniel De Graaf
f029067709 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>
2015-03-18 08:16:44 -04:00
Daniel De Graaf
82030de5dc 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>
2015-03-18 08:16:18 -04:00
dcashman
ed7a6ba24a Allow libsepol C++ static library on device.
Change-Id: I7da601767c3a4ebed7274e33304d8b589a9115fe
Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
2015-01-20 10:31:15 -05:00
Nicolas Iooss
5af8c5adb2 checkpolicy: fix gcc -Wunused-variable warnings
Add __attribute__ ((unused)) to unused function parameters.

Acked-by: Steve Lawrence <slawrence@tresys.com>
2014-10-02 09:56:41 -04:00
Nicolas Iooss
7dcb7a5946 checkpolicy: fix most gcc -Wwrite-strings warnings
Acked-by: Steve Lawrence <slawrence@tresys.com>
2014-10-02 09:56:28 -04:00
Nicolas Iooss
581d3eb128 checkpolicy: fix gcc -Wsign-compare warnings
Acked-by: Steve Lawrence <slawrence@tresys.com>
2014-10-02 09:56:13 -04:00
Nicolas Iooss
832e7017f8 checkpolicy: constify the message written by yyerror and yywarn
Acked-by: Steve Lawrence <slawrence@tresys.com>
2014-10-02 09:56:06 -04:00
Nicolas Iooss
8db96d0cb4 checkpolicy: add printf format attribute to relevant functions
Once __attribute__ ((format(printf, 1, 2))) is added to yyerror2,
"gcc -Wformat -Wformat-security" shows some issues.  Fix them.

Acked-by: Steve Lawrence <slawrence@tresys.com>
2014-10-02 09:56:03 -04:00