Commit graph

1242 commits

Author SHA1 Message Date
Christian Göttsche
782fa6ea38 libselinux: context_new(): drop dead assignment
The variable `i` is not used inside this loop, and it later
unconditionally set to 0.

Found by clang-analyzer.

Signed-off-by: Christian Göttsche <cgzones@googlemail.com>
2021-05-18 10:06:22 +02:00
Christian Göttsche
319429ba33 libselinux: exclude_non_seclabel_mounts(): drop unused variable
The variable `num` is never read from.

Found by clang-analyer.

Signed-off-by: Christian Göttsche <cgzones@googlemail.com>
2021-05-18 10:06:22 +02:00
Christian Göttsche
d0e16077d4 libselinux: getconlist: free memory on multiple level arguments
Do not leak memory if the program argument `l` got passed more than
once.

Found by clang-analyzer.

Signed-off-by: Christian Göttsche <cgzones@googlemail.com>
2021-05-18 10:06:22 +02:00
Christian Göttsche
d0c02882b7 libselinux: selabel_get_digests_all_partial_matches: free memory after FTS_D block
Free all memory from `selabel_get_digests_all_partial_matches()` in case
of success and failure.

Found by clang-analyzer.

Signed-off-by: Christian Göttsche <cgzones@googlemail.com>
2021-05-18 10:06:22 +02:00
Christian Göttsche
7464272caa libselinux: selinux_restorecon: mark local variable static
The variable `dir_xattr_list` is only used inside `selinux_restorecon.c`.

selinux_restorecon.c:65:19: warning: no previous extern declaration for non-static variable 'dir_xattr_list' [-Wmissing-variable-declarations]
struct dir_xattr *dir_xattr_list;
                  ^
selinux_restorecon.c:65:1: note: declare 'static' if the variable is not intended to be used outside of this translation unit
struct dir_xattr *dir_xattr_list;
^

Signed-off-by: Christian Göttsche <cgzones@googlemail.com>
2021-05-18 10:06:22 +02:00
Christian Göttsche
533e9d6ce0 libselinux: avcstat: use standard length modifier for unsigned long long
The format width specifier `L` is only standardized for floating point
types. Use `ll` for fixed-width data types.

Signed-off-by: Christian Göttsche <cgzones@googlemail.com>
2021-05-18 10:06:22 +02:00
Christian Göttsche
11194b982b libselinux: sefcontext_compile: mark local variable static
The variable `policy_file` is only used in sefcontext_compile.c.

Signed-off-by: Christian Göttsche <cgzones@googlemail.com>
2021-05-18 10:06:22 +02:00
Christian Göttsche
7ca82e0db4 libselinux: Sha1Finalise(): do not discard const qualifier
Mark the argument `Buffer` of `Sha1Update()` const, since it is not
modified.

sha1.c: In function ‘Sha1Finalise’:
sha1.c:208:25: warning: cast discards ‘const’ qualifier from pointer target type [-Wcast-qual]
  208 |     Sha1Update(Context, (uint8_t*)"\x80", 1);
      |                         ^
sha1.c:211:29: warning: cast discards ‘const’ qualifier from pointer target type [-Wcast-qual]
  211 |         Sha1Update(Context, (uint8_t*)"\0", 1);
      |                             ^

Signed-off-by: Christian Göttsche <cgzones@googlemail.com>
2021-05-18 10:06:22 +02:00
Christian Göttsche
3950b1afed libselinux: label_common(): do not discard const qualifier
As the const qualifier is discarded in label_common(), do not return a
const qualified pointer pointer from the local function `lookup_all()`.

label_file.c: In function ‘lookup_common’:
label_file.c:994:24: warning: cast discards ‘const’ qualifier from pointer target type [-Wcast-qual]
  994 |  struct spec *result = (struct spec*)matches[0];
      |                        ^

Signed-off-by: Christian Göttsche <cgzones@googlemail.com>
2021-05-18 10:06:22 +02:00
Christian Göttsche
d23421c65a libselinux: selinux_file_context_cmp(): do not discard const qualifier
matchpathcon.c: In function ‘selinux_file_context_cmp’:
matchpathcon.c:487:18: warning: cast discards ‘const’ qualifier from pointer target type [-Wcast-qual]
  487 |  rest_a = strchr((char *)a, ':');
      |                  ^
matchpathcon.c:488:18: warning: cast discards ‘const’ qualifier from pointer target type [-Wcast-qual]
  488 |  rest_b = strchr((char *)b, ':');
      |                  ^

Signed-off-by: Christian Göttsche <cgzones@googlemail.com>
2021-05-18 10:06:22 +02:00
Christian Göttsche
ae34b3ca3c libselinux: sidtab_hash(): do not discard const qualifier
Do not discard the const qualifier of the function argument, and drop
the redundant local variable `keyp`.

avc_sidtab.c: In function ‘sidtab_hash’:
avc_sidtab.c:23:9: warning: cast discards ‘const’ qualifier from pointer target type [-Wcast-qual]
   23 |  keyp = (char *)key;
      |         ^

Signed-off-by: Christian Göttsche <cgzones@googlemail.com>
2021-05-18 10:06:22 +02:00
Nicolas Iooss
f1bc162cc2 libselinux: silence -Wstringop-overflow warning from gcc 10.3.1
When building libselinux on Fedora 33 with gcc 10.3.1, the compiler
reports:

    label_file.c: In function ‘lookup_all.isra’:
    label_file.c:940:4: error: ‘strncpy’ specified bound depends on the
    length of the source argument [-Werror=stringop-overflow=]
      940 |    strncpy(clean_key, key, len - 1);
          |    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    label_file.c:927:8: note: length computed here
      927 |  len = strlen(key);
          |        ^~~~~~~~~~~
    cc1: all warnings being treated as errors

As clean_key is the result of malloc(len), there is no issue here. But
using strncpy can be considered as strange, because the size of the
string is already known and the NUL terminator is always added later, in
function ‘lookup_all.isra.

Replace strncpy with memcpy to silence this gcc false-positive warning.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
Acked-by: Petr Lautrbach <plautrba@redhat.com>
2021-05-12 09:35:50 +02:00
Christian Göttsche
a88d24522f libselinux: selinux_check_passwd_access_internal(): respect deny_unknown
`selinux_check_passwd_access_internal()`, and thereby
`checkPasswdAccess(3)` and `selinux_check_passwd_access(3)`, does not
respect the policy defined setting of `deny_unknown`, like
`selinux_check_access(3)` does.
This means in case the security class `passwd` is not defined, success
is returned instead of failure, i.e. permission denied.

Most policies should define the `passwd` class and the two affected
public functions are marked deprecated.

Align the behavior with `selinux_check_access(3)` and respect
the deny_unknown setting in case the security class is not defined.

Signed-off-by: Christian Göttsche <cgzones@googlemail.com>
2021-05-12 09:34:58 +02:00
lijiazi
e99ee4904d selinux: remove last slash in CE dirs macro
With this slash, in selinux_android_restorecon_common while loop,
fts_read need to traverse to "/data/system_ce/0" to satisfy the
conditions of skip CE.
If this dir's hash changed in this OTA, new hash will update to
xattr of dir's inode without restorecon for this dir.
When vold installed CE key, and want to restorecon for this dir,
hash match check return true, and dir will be skipped again.
This results in this dir cannot get correct context.

Remove last slash will make skip CE condition satisfy when traverse
"data/system_ce", without update "data/system_ce/0" hash.
Vold can check not match and correct restorecon "data/system_ce/0".

Test: OTA with CE dir contexts changed.

Change-Id: If6aacbe782636acac6cde1517619d8da85143436
Signed-off-by: lijiazi <lijiazi@xiaomi.com>
2021-05-04 08:37:24 +00:00
Nicolas Iooss
f63263c2d0
libselinux: do not duplicate make target when going into subdirectory
When running "make install-pywrap", make displays:

    make[1]: Entering directory '/root/selinux/libselinux'
    make -C src install-pywrap install-pywrap
    make[2]: Entering directory '/root/selinux/libselinux/src'

The duplicated "install-pywrap" is not expected. Remove it from the
Makefile.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2021-04-30 21:09:22 +02:00
Colin Cross
0c40b2bbcf Replace llndk_library with llndk clause in cc_library
Remove the vestigial llndk_library modules and replace them with
properties in the llndk clause of the implementation cc_library.

Bug: 170784825
Test: m checkbuild
Test: compare out/soong/build.ninja
Change-Id: I1353f630e5a3f4649a13ce8c21bf6be65067716c
2021-04-21 18:55:08 -07:00
Joel Galenson
f30e6ff376 Use the new more inclusive command-line options.
Test: Compile
Change-Id: Ie54fb0dafda0a6167e95b32d0a6b4f762162ae1d
2021-04-19 09:46:07 -07:00
Petr Lautrbach
cf853c1a0c
Update VERSIONs to 3.2 for release.
Signed-off-by: Petr Lautrbach <plautrba@redhat.com>
2021-03-04 16:42:59 +01:00
Petr Lautrbach
d4d1f4ba7e
Update VERSIONs to 3.2-rc3 for release.
Signed-off-by: Petr Lautrbach <plautrba@redhat.com>
2021-02-24 15:49:59 +01:00
Petr Lautrbach
142826a38e libselinux: fix segfault in add_xattr_entry()
When selabel_get_digests_all_partial_matches(), resp
get_digests_all_partial_matches() doesn't find a match,
calculated_digest is not initialized and followup memcmp() could
segfault. Given that calculated_digest and xattr_digest are already
compared in get_digests_all_partial_matches() and the function returns
true or false based on this comparison, it's not necessary to compare
these values again.

Fixes:
    # cd /root
    # mkdir tmp
    # restorecon -D -Rv tmp  # create security.sehash attribute
    # restorecon_xattr -d -v tmp
    specfiles SHA1 digest: afc752f47d489f3e82ac1da8fd247a2e1a6af5f8
    calculated using the following specfile(s):
    /etc/selinux/targeted/contexts/files/file_contexts.subs_dist
    /etc/selinux/targeted/contexts/files/file_contexts.subs
    /etc/selinux/targeted/contexts/files/file_contexts.bin
    /etc/selinux/targeted/contexts/files/file_contexts.homedirs.bin
    /etc/selinux/targeted/contexts/files/file_contexts.local.bin

    Segmentation fault (core dumped)

Signed-off-by: Petr Lautrbach <plautrba@redhat.com>
2021-02-24 10:52:52 +01:00
Nicolas Iooss
398d2ceef9 libselinux: rename gettid() to something which never conflicts with the libc
Musl recently added a wrapper for gettid() syscall. There is no way to
detect this new version in a reliable way, so rename our gettid()
wrapper to a non-conflicting name.

Introduce a new function which, when using a libc known to provide a
wrapper for gettid(), calls it, and which, otherwise, performs the
syscall directly.

Anyway this function is only used on systems where /proc/thread-self
does not exist, which are therefore running Linux<3.17.

Fixes: https://github.com/SELinuxProject/selinux/issues/282
Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
Acked-by: Petr Lautrbach <plautrba@redhat.com>
2021-02-19 15:19:31 +01:00
Vit Mojzis
8f0f0a28aa selinux(8,5): Describe fcontext regular expressions
Describe which type of regular expression is used in file context
definitions and which flags are in effect.

Explain how local file context modifications are processed.

Signed-off-by: Vit Mojzis <vmojzis@redhat.com>
Acked-by: Petr Lautrbach <plautrba@redhat.com>
2021-02-19 15:18:05 +01:00
Christian Göttsche
9cc6b5cf40 libselinux/getconlist: report failures
Check the given context a priori, to print a more user friendly message,
opposed to a generic following get_ordered_context_list/_with_level
failure.

Notify the user about failures of get_ordered_context_list/_with_level,
so no-context-found and a failure results are distinguishable.

Signed-off-by: Christian Göttsche <cgzones@googlemail.com>
2021-02-19 15:15:11 +01:00
Treehugger Robot
6275ba5a60 Merge "Symbol files describing APIs across updatable components are reviewed" 2021-02-09 14:16:26 +00:00
Bob Badour
57866d006b [LSC] Add LOCAL_LICENSE_KINDS to external/selinux
Added SPDX-license-identifier-Apache-2.0 to:
  libselinux/fuzzers/Android.bp

Added SPDX-license-identifier-Apache-2.0 SPDX-license-identifier-BSD
    SPDX-license-identifier-GPL SPDX-license-identifier-GPL-2.0
    SPDX-license-identifier-LGPL SPDX-license-identifier-LGPL-2.1
    SPDX-license-identifier-LGPL-3.0 SPDX-license-identifier-Zlib
    legacy_unencumbered
to:
  Android.bp

Added SPDX-license-identifier-Apache-2.0 SPDX-license-identifier-GPL-2.0
    legacy_unencumbered
to:
  libselinux/Android.bp

Added SPDX-license-identifier-BSD
to:
  secilc/Android.bp

Added SPDX-license-identifier-BSD SPDX-license-identifier-GPL
    SPDX-license-identifier-LGPL SPDX-license-identifier-LGPL-2.1
    SPDX-license-identifier-LGPL-3.0 SPDX-license-identifier-Zlib
    legacy_unencumbered
to:
  libsepol/Android.bp

Added SPDX-license-identifier-GPL SPDX-license-identifier-GPL-2.0
    SPDX-license-identifier-LGPL
to:
  checkpolicy/Android.bp

Bug: 68860345
Bug: 151177513
Bug: 151953481

Test: m all

Exempt-From-Owner-Approval: janitorial work
Change-Id: I3859438c836077d59ed424d04659213c3018f5fe
2021-02-05 01:27:52 -08:00
Jiyong Park
b755a86d07 Symbol files describing APIs across updatable components are reviewed
The build system will soon require that symbol files describing APIs
across updatable components (e.g. across APEXes or across sytem/vendor)
have the ".map.txt" suffix. This will trigger the NDK API review in the
gerrit so that backwards incompatible changes are prevented.

Bug: N/A
Test: m nothing
Change-Id: I1aacf8eea317ac1e7cf0dea3689ff8ef3e315dc0
2021-02-04 21:05:36 +09:00
Petr Lautrbach
2c7c4a84c3
Update VERSIONs to 3.2-rc2 for release.
Signed-off-by: Petr Lautrbach <plautrba@redhat.com>
2021-02-03 11:26:28 +01:00
Christian Göttsche
156dd0de5c
libselinux: update getseuser
- Bail out if not running on a SELinux enabled system
- Check whether the passed context is valid
- Do not report a get_ordered_context_list_with_level failure on zero
  found contexts

Signed-off-by: Christian Göttsche <cgzones@googlemail.com>
2021-01-20 16:53:37 +01:00
Christian Göttsche
e2dca5df40
libselinux: accept const fromcon in get_context API
Rework the APIs in <selinux/get_context_list.h> to take a constant
string as from context.

The passed string is not modified currently but not declared const,
which restricting callers (who care about const-correctness).

Signed-off-by: Christian Göttsche <cgzones@googlemail.com>
2021-01-20 16:53:34 +01:00
Petr Lautrbach
c534d4e2ce
Update VERSIONs and Python bindings version to 3.2-rc1 for release
Signed-off-by: Petr Lautrbach <plautrba@redhat.com>
2021-01-20 12:40:14 +01:00
Petr Lautrbach
da4829d0be libselinux: Always close status page fd
According to mmap(2) after the mmap() call has returned, the file
descriptor, fd, can be closed immediately without invalidating the
mapping.

Signed-off-by: Petr Lautrbach <plautrba@redhat.com>
2021-01-18 07:37:28 -06:00
Alan Stokes
ec6a9c94b2 Don't restorecon profile root.
Since commit be3db7b7aeb10adf51b34a681d73d5c5bbd59623 vold has been
responsible for labeling the user profile data root directories. So we
should skip those in a recursive restorecon, as we do for
e.g. /data/data, to avoid having the correct label overridden by an
incorrect one. Unlike /data/data the subdirectories should still be
restored.

Bug: 141677108
Bug: 175311045
Test: Manual. Root dir is not re-labeled, subdir is.
Change-Id: I7ffec8ed95d49e8d08fdb90e8f7e164f1d76f422
2020-12-15 09:40:48 +00:00
Bram Bonné
f68a36b119 Null-terminate libselinux seinfo in fuzzer.
Bug: 172338832
Test: make and run libselinux_android_setcontext_fuzzer on device
Test: Run testcase 5652118323200000
Change-Id: Ib619679e89f10a5f58cb8ac17ba2b67d35b1b606
2020-11-24 10:29:18 +01:00
Bram Bonné
0e8eccd069 Merge "Null-terminate libselinux context name in fuzzer." 2020-11-16 14:21:50 +00:00
Bram Bonné
c7c88d9701 Null-terminate libselinux context name in fuzzer.
Test: make and run libselinux_context_fuzzer on host
Fix: 171997120
Fix: 172338832
Change-Id: I23ed5b8c695a8dc2dd18f1a08d18590f4d8dd1e3
2020-11-13 10:08:57 +01:00
Ondrej Mosnacek
45b15c2216
selinux(8): explain that runtime disable is deprecated
Update the main SELinux manpage to explain that runtime disable (i.e.
disabling SELinux using SELINUX=Disabled) is deprecated and recommend
disabling SELinux only via the kernel boot parameter.

Signed-off-by: Ondrej Mosnacek <omosnace@redhat.com>
2020-11-11 20:42:22 +01:00
Ondrej Mosnacek
3c16aaefbf
selinux(8): mark up SELINUX values
Mark up the possible values of SELINUX (disabled, permissive, enforcing)
for better readability.

Signed-off-by: Ondrej Mosnacek <omosnace@redhat.com>
2020-11-11 20:42:21 +01:00
Treehugger Robot
14de5345d4 Merge "Add more fuzzers" 2020-11-10 15:14:08 +00:00
Joel Galenson
21bd55b760 Add more fuzzers
Test: Run fuzzers
Change-Id: Ia4e459821d9f5d20a238cb27f5a2589897b96e24
2020-11-09 15:12:29 -08:00
Treehugger Robot
673604a02a Merge "Add another SELinux fuzz target" 2020-11-03 21:01:55 +00:00
Joel Galenson
17dfcdf899 Add another SELinux fuzz target
Test: Build and run the fuzzer
Change-Id: I9f6057f93defc4e1b81bce7e105a7bd89c808ee4
2020-11-03 10:31:35 -08:00
Yifan Hong
e149732597 Merge "Make {vendor_,}ramdisk_available." 2020-11-02 18:33:33 +00:00
Björn Bidar
c2a58cc525 libselinux: LABEL_BACKEND_ANDROID add option to enable
Add option to just enable the android label backend without disabling
anything else eg. using ANDROID_HOST. Enable by default when using ANDROID_HOST.

Signed-off-by: Björn Bidar <bjorn.bidar@jolla.com>
2020-11-01 20:47:15 -06:00
Yifan Hong
175a3e4479 Make {vendor_,}ramdisk_available.
Making libselinux available to ramdisk and vendor_ramdisk
modules. Ramdisk and vendor_ramdisk modules are typically
used by first stage init.

This is the prerequisite to make toybox available to ramdisk
and vendor_ramdisk, so that first stage console can use shell
utilities.

Test: pass
Bug: 156098440

Change-Id: I8289eb12ce5a90fc68fcd432a2eef4240c87a7d2
2020-10-29 10:58:38 -07:00
Joel Galenson
7cb28c7f7a Add more fuzz targets for SELinux
Test: Build and run the fuzzers
Change-Id: I6b6a0e19cc56276ea43a989432a2ac6f6beb482f
2020-10-29 07:35:47 -07:00
Jeffrey Vander Stoep
14e430c1aa Merge "Add fuzz targets for SELinux." 2020-10-29 10:34:28 +00:00
Bram Bonné
76636da2d8 Add fuzz targets for SELinux.
Test: m libselinux_android_setcontext_fuzzer
Test: m libselinux_context_fuzzer
Change-Id: I82e82ff41b1d969e6756658955dbbdbb6330eb43
2020-10-29 10:01:54 +01:00
Björn Bidar
db0f2f382e libselinux: Add build option to disable X11 backend
Signed-off-by: Björn Bidar <bjorn.bidar@jolla.com>
2020-10-23 09:50:02 -05:00
Colin Cross
c2846a38dc Make the connection between implementation and llndk_library explicit
Instead of assuming a module with the .llndk suffix exists, add an
llndk_stubs property to every cc_library module that has a
corresponding llndk_library.  Also rename the llndk_library to have
an explicit .llndk suffix.

Bug: 170784825
Test: no changes to build.ninja (excluding comments) or Android-${TARGET_PRODUCT}.mk
Change-Id: Iaf4ffe2dc7459715c97d8083e39b367b128f1b55
2020-10-19 13:37:53 -07:00
Petr Lautrbach
4a142ac46a
libsepol: Bump libsepol.so version
Previous commits removed some symbols and broke ABI, therefore we need to change
SONAME.

See the following quotes from distribution guidelines:

https://www.debian.org/doc/debian-policy/ch-sharedlibs.html#run-time-shared-libraries

Every time the shared library ABI changes in a way that may break
binaries linked against older versions of the shared library, the SONAME
of the library and the corresponding name for the binary package
containing the runtime shared library should change.

https://docs.fedoraproject.org/en-US/packaging-guidelines/#_downstream_so_name_versioning

When new versions of the library are released, you should use an ABI
comparison tool to check for ABI differences in the built shared
libraries. If it detects any incompatibilities, bump the n number by
one.

Signed-off-by: Petr Lautrbach <plautrba@redhat.com>
2020-10-19 22:11:39 +02:00
Nicolas Iooss
d23342a9de libselinux: convert matchpathcon to selabel_lookup()
Function matchpathcon() is deprecated in favor of selabel_lookup() but
program "matchpathcon" is much easier to use than "selabel_loopkup" to
find the file context which would be applied to some files and
directories.

More precisely:

    matchpathcon /path/to/my/file

is easier to type and remember than:

    selabel_lookup -b file -k /path/to/my/file

It also allows performing multiple context searches in one command,
where selabel_lookup cannot use multiple -k options.

Migrate matchpathcon to the preferred API.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
Acked-by: Petr Lautrbach <plautrba@redhat.com>
2020-10-14 17:57:26 +02:00
Tom Cherry
68c10fa51a Use libcutils_headers for android_filesystem_config.h
android_filesystem_config.h is found since system/core/include is on
the include path for all projects and contains a symlink to the real
android_filesystem_config.h.  This is fragile and the below bug seeks
to remove this symlink and have users correctly depend on
libcutils_headers.

Bug: 165825252
Test: build
Change-Id: I173a275366051aec3e941870e6dbebaab6bea6d0
2020-09-18 15:45:16 -07:00
Chris PeBenito
7ef5b1854f libselinux: Change userspace AVC setenforce and policy load messages to audit format.
Signed-off-by: Chris PeBenito <chpebeni@linux.microsoft.com>
Acked-by: Stephen Smalley <stephen.smalley.work@gmail.com>
2020-09-15 17:19:32 -04:00
Chris PeBenito
f5d644c7e6 libselinux: Add additional log callback details in man page for auditing.
Add additional information about the log callback message types.  Indicate
which types could be audited and the relevant audit record types for them.

Signed-off-by: Chris PeBenito <chpebeni@linux.microsoft.com>
Acked-by: Stephen Smalley <stephen.smalley.work@gmail.com>
2020-09-15 17:19:32 -04:00
Chris PeBenito
075f9cfe7a libselinux: Fix selabel_lookup() for the root dir.
9e4480b921 ("Remove trailing slash on selabel_file lookups.") introduced
a bug which turns the root directory lookup "/" into an empty string.

Signed-off-by: Chris PeBenito <chpebeni@linux.microsoft.com>
Acked-by: Stephen Smalley <stephen.smalley.work@gmail.com>
2020-09-15 09:22:08 -04:00
Chris PeBenito
a4149e0eab libselinux: Add new log callback levels for enforcing and policy load notices.
This will enable userspace object managers to send proper audits for policy
loads and setenforce messages generated by the userspace AVC code.

Signed-off-by: Chris PeBenito <chpebeni@linux.microsoft.com>
Acked-by: Stephen Smalley <stephen.smalley.work@gmail.com>
2020-08-31 10:27:46 -04:00
Christian Göttsche
a63f93d83b libselinux: initialize last_policyload in selinux_status_open()
If not initialized to the current policyload count, an enforcing change
will trigger policyload-callbacks in selinux_status_updated().

Signed-off-by: Christian Göttsche <cgzones@googlemail.com>
Acked-by: Stephen Smalley <stephen.smalley.work@gmail.com>
2020-08-31 10:23:51 -04:00
Christian Göttsche
ef902db9c8 libselinux: safely access shared memory in selinux_status_updated()
Access the shared nenory safe in regard to consistent view of the SELinux
kernel status page - not in regard to thread-safety.

Signed-off-by: Christian Göttsche <cgzones@googlemail.com>
Acked-by: Stephen Smalley <stephen.smalley.work@gmail.com>
2020-08-31 10:23:51 -04:00
Chris PeBenito
9e4480b921 libselinux: Remove trailing slash on selabel_file lookups.
Having a trailing slash on a file lookup, e.g. "/some/path/", can
cause a different result, for example,  when file contexts are written to have
the directory have a different label than the contents.  This is inconsistent
with normal Linux behaviors where trailing slashes are ignored.

Many callers already strip the trailing slash before the lookup or users
revise the file contexts to work around this.  This fixes it comprehensively.

v2: fix length issues

Signed-off-by: Chris PeBenito <chpebeni@linux.microsoft.com>
Acked-by: Stephen Smalley <stephen.smalley.work@gmail.com>
2020-08-26 14:25:45 -04:00
Christian Göttsche
21fb5f20da libselinux: use full argument specifiers for security_check_context in man page
The argument for security_check_context(_raw) is defined as `const char *`.

Say so in the man page.

Signed-off-by: Christian Göttsche <cgzones@googlemail.com>
Acked-by: Stephen Smalley <stephen.smalley.work@gmail.com>
2020-08-26 14:21:54 -04:00
Stephen Smalley
e7abd802d4 libselinux: fix build order
We need to install the include files before we try to build the source.
Otherwise, make DESTDIR=~/obj install can fail if there are older
headers under /usr/include.

Signed-off-by: Stephen Smalley <stephen.smalley.work@gmail.com>
2020-08-17 11:54:16 -04:00
Mike Palmiotto
05bdc03130 libselinux: use kernel status page by default
Commit bc2a8f418e ("libselinux: add selinux_status_* interfaces for
/selinux/status") introduced the sestatus mechanism, which allows for
mmap()'ing of the kernel status page as a replacement for avc_netlink.

The mechanism was initially intended for userspace object managers that
were calculating access decisions within their application and did not
rely on the libselinux AVC implementation. In order to properly make use
of sestatus within avc_has_perm(), the status mechanism needs to
properly set avc internals during status events; else, avc_enforcing is
never updated upon sestatus changes.

This commit gets rid of the default avc_netlink_open() in
avc_init_internal(), replacing it with selinux_status_open(). In the
event that the kernel status page cannot be mapped, the netlink fallback
will be used. By default, avc_has_perm_noaudit() and
selinux_check_access() will now attempt to read the kernel status page,
which removes a system call from two critical code paths.

Since the AVC thread create/stop callbacks were intended to avoid a
system call in the critical code path, they no longer need to be created
by default. In the event that the kernel status page is successfully
mapped, threads will not be created. Threads will still be
created/stopped for the sestatus fallback codepaths.

Userspace object managers that still need a netlink socket can call
avc_netlink_acquire_fd() to open and/or obtain one.

Update the manpage to reflect the new avc_netlink_acquire_fd()
functionality.

Signed-off-by: Mike Palmiotto <mike.palmiotto@crunchydata.com>
Acked-by: Stephen Smalley <stephen.smalley.work@gmail.com>
2020-08-11 08:11:40 -04:00
Stephen Crane
ed5407a024 Pass individual arguments in bindgen flags
Bindgen flags are now shell escaped, so we can't pass multiple distinct
arguments in the same argument string. Bindgen will parse each element
of the bindgen_flags list as an argument and fails to parse the flag if
it is separated from the value by whitespace. Bindgen accepts
--flag=value forms for its arguments, so we use these instead.

Test: m libselinux_bindgen
Change-Id: Ic0ca26b8a93547d8dc23087d9f7d414dfab341d6
2020-08-05 00:33:50 -07:00
Ivan Lozano
be230956fb Update rust_bindgen module with new property names.
The stem property has changed to source_stem, flags has changed to
bindgen_flags, and crate_name is now required.

Bug: 159064919
Test: mma
Change-Id: Ib4c0dbe98231cdd70c041d5b0a001238ae6c0cc7
2020-08-03 20:55:32 -04:00
Janis Danisevskis
3a9d35cc84 Add rust_bindgen target for libselinux.
Generate rust bindings for libselinux.

Bug: 159466840
Test: system_security_keystore_selinux_rust_test
Change-Id: I5c360b2b92faaffe6e66942559e7c97a48d9d4a9
2020-07-30 15:35:09 -07:00
Kunal
3ab0dbf47f libselinux android: Add keystore2_key label module.
This patch adds a new Android specific module for keystore2 key
namespace lookup. It assumes the presence of keystore_contexts files
mapping numeric namespace identifiers to SELinux labels. Keystore 2.0
uses this module to exert more granular access control and allow system
and vendor components to share explicit key namespaces.

Bug: 158500146
Test: N/A
Change-Id: Ic6c186cb4c2fb1e6e5ddd8494e89f72cfb3119ba
2020-07-30 11:01:32 -07:00
Petr Lautrbach
7df27b78e9 Update VERSIONs and Python bindings version to 3.1 for release
Signed-off-by: Petr Lautrbach <plautrba@redhat.com>
2020-07-10 17:17:15 +02:00
Alan Stokes
468cc0e990 Expose ability to set level from uid.
Extract the existing level computation into a helper function.

Add selinux_android_context_with_level() to take a context string and
return a new one with appropriate level based on user and/or app id.

Test: builds
Bug: 141677108
Change-Id: I4618d4c74d1a2b94de9e934a8caf2e24049f0477
2020-07-07 16:46:25 +01:00
Petr Lautrbach
b3d8b99f0c Update VERSIONs to 3.1-rc2 for release.
Signed-off-by: Petr Lautrbach <plautrba@redhat.com>
2020-06-19 13:02:31 +02:00
Ji Qin
08f5e30177 libselinux: Fix NULL pointer use in selinux_restorecon_set_sehandle
error occur when selinux_restorecon_default_handle return NULL in
restorecon_init.

fixes: https://github.com/SELinuxProject/selinux/issues/249

Signed-off-by: Ji Qin <jiqin.ji@huawei.com>
Acked-by: Stephen Smalley <stephen.smalley.work@gmail.com>
2020-06-18 19:32:52 +02:00
Stephen Smalley
ab2cf74685 libselinux: fix selinux_restorecon() statfs bug
As reported in https://github.com/SELinuxProject/selinux/issues/248,
setfiles -r (rootpath) fails when the alternate root contains a symlink
that is correct relative to the alternate root but not in the current root.
This is a regression introduced by commit e016502c0a ("libselinux: Save
digest of all partial matches for directory").  Do not call statfs(2) here
if acting on a symbolic link.  Unfortunately there is no lstatfs() call.
Ensure that we initialize the statfs buffer always.  If the supplied
file is a symlink, then we don't need to worry about the later tests of
filesystem type because we wouldn't be setting the digest anyway and
we are not performing a full sysfs relabel.  While here, fix the earlier
test for a directory to use the correct test.

Reproducer:
$ mkdir /root/my-chroot && echo foo > /root/my-chroot/link-target && ln -s /link-target /root/my-chroot/symlink
$ echo "/root/my-chroot/symlink" | setfiles -vFi -r /root/my-chroot -f - /etc/selinux/targeted/contexts/files/file_contexts

Before:
setfiles: statfs(/root/my-chroot/symlink) failed: No such file or directory

After:
Relabeled /root/my-chroot/symlink from unconfined_u:object_r:admin_home_t:s0 to system_u:object_r:default_t:s0

Fixes: https://github.com/SELinuxProject/selinux/issues/248
Fixes: e016502c0a ("libselinux: Save digest of all partial matches for directory")
Signed-off-by: Stephen Smalley <stephen.smalley.work@gmail.com>
Tested-by: Jonathan Lebon <jlebon@redhat.com>
Acked-by: Petr Lautrbach <plautrba@redhat.com>
2020-06-18 19:25:27 +02:00
Petr Lautrbach
c554c3d88a Update VERSIONs to 3.1-rc1 for release.
Signed-off-by: Petr Lautrbach <plautrba@redhat.com>
2020-05-15 15:54:08 +02:00
Christian Göttsche
7c73601d54 tree-wide: introduce PYTHON_SETUP_ARGS to customize setup.py calls on Debian
On Debian the `distutils` module is patched, so `get_python_lib()`
returns by default `/usr/lib/python3/dist-packages` (no minor version)

But `setuptools` affecting setup.py is not patched to create the library
directory at `/usr/lib/python3/dist-packages` by default, rather than a
command line argument `--install-layout deb` is added

Add PYTHON_SETUP_ARGS as argument to affected setup.py calls and add a
note in the global README.md

See https://www.debian.org/doc/packaging-manuals/python-policy/packaging_tools.html
Section B.1

Fixes: https://github.com/SELinuxProject/selinux/issues/187

Signed-off-by: Christian Göttsche <cgzones@googlemail.com>
Acked-by: Petr Lautrbach <plautrba@redhat.com>
2020-05-06 16:12:35 +02:00
Richard Filo
7ce2d865df libselinux: Add missing errno setup
Errno is not set to ENOENT when lookup_all() doesn't find any match.

fixes: https://src.fedoraproject.org/tests/selinux/issue/51

Signed-off-by: Richard Filo <rfilo@redhat.com>
Acked-by: Ondrej Mosnacek <omosnace@redhat.com>
2020-05-06 16:08:24 +02:00
Topi Miettinen
7eaea214a0 libselinux: mount selinuxfs noexec and nosuid
Mount selinuxfs with mount flags noexec and nosuid. It's not likely
that this has any effect, but it's visually more pleasing.

Option nodev can't be used because of /sys/fs/selinux/null device,
which is used by Android.

Signed-off-by: Topi Miettinen <toiwoton@gmail.com>
Acked-by: Stephen Smalley <stephen.smalley.work@gmail.com>
2020-05-04 09:51:03 +02:00
Christian Göttsche
7a124ca275 libselinux: mark security_context_t typedef as deprecated
Follow-up of: 9eb9c93275 ("Get rid of security_context_t and fix const declarations.")

Acked-by: William Roberts <william.c.roberts@intel.com>
Signed-off-by: Christian Göttsche <cgzones@googlemail.com>
2020-05-01 10:48:19 -05:00
William Roberts
4465a807c7 Makefile: swig build allow deprecated functions
The SWIG C build should allow deprecated functions and not warn on them
because it is exposing the full interface including deprecated routines.

Signed-off-by: William Roberts <william.c.roberts@intel.com>
2020-04-30 09:13:25 -05:00
William Roberts
c7020954ca utils: matchpathcon add deprecated warning
Add a deprecated warning to matchpathcon encouraging users to switch to
selabel_lookup.

Signed-off-by: William Roberts <william.c.roberts@intel.com>
2020-04-30 09:13:25 -05:00
William Roberts
327ec8eb18 matchpathcon: allow use of deprecated routines
Utility matchpathcon uses the matchpathcon interface which has been
deprectaed. However, this tool will continue to live on, so allow it to
use the deprecated interface.

Signed-off-by: William Roberts <william.c.roberts@intel.com>
2020-04-30 09:13:25 -05:00
William Roberts
afd45fe70a selinux_check_passwd_access: annotate deprecated
Update the one internal tree caller in the same file to
call selinux_check_passwd_access_internal.

Signed-off-by: William Roberts <william.c.roberts@intel.com>
2020-04-30 09:13:25 -05:00
William Roberts
efe21d7fb1 matchpathcon: create internal matchpathcon_fini interface
Now that matchpathcon_fini is marked deprecated, create an
matchpathcon_fini_internal interface for internal users. We create
a new header file for matchpathcon_internal interfaces.

Signed-off-by: William Roberts <william.c.roberts@intel.com>
2020-04-30 09:13:25 -05:00
William Roberts
e14ead8936 avc: create internal avc_init interface
Now that avc_init is marked deprecated, create an avc_init_internal interface
for internal users.

Signed-off-by: William Roberts <william.c.roberts@intel.com>
2020-04-30 09:13:25 -05:00
William Roberts
ce798241c7 avc_init: annotate deprecated
Signed-off-by: William Roberts <william.c.roberts@intel.com>
2020-04-30 09:13:25 -05:00
William Roberts
124b1d8a7c matchpathcon: annotate deprecated
Signed-off-by: William Roberts <william.c.roberts@intel.com>
2020-04-30 09:13:25 -05:00
William Roberts
bcb39e6451 matchpathcon_fini: annotate deprecated
Signed-off-by: William Roberts <william.c.roberts@intel.com>
2020-04-30 09:13:25 -05:00
William Roberts
708c2d9ca6 matchpathcon_init: annotate deprecated
Signed-off-by: William Roberts <william.c.roberts@intel.com>
2020-04-30 09:13:25 -05:00
William Roberts
c4a362b899 checkPasswdAccess: annotate deprecated
Signed-off-by: William Roberts <william.c.roberts@intel.com>
2020-04-30 09:13:25 -05:00
William Roberts
8c6b40137b sidput: annotate deprecated
Signed-off-by: William Roberts <william.c.roberts@intel.com>
2020-04-30 09:13:25 -05:00
William Roberts
ff51f0c528 sidget: annotate deprecated
Signed-off-by: William Roberts <william.c.roberts@intel.com>
2020-04-30 09:13:25 -05:00
William Roberts
81822ece1f rpm_execcon: annotate deprecated
Signed-off-by: William Roberts <william.c.roberts@intel.com>
2020-04-30 09:13:25 -05:00
William Roberts
d2d4353c97 selinux_users_path: annotate deprecated
Signed-off-by: William Roberts <william.c.roberts@intel.com>
2020-04-30 09:13:25 -05:00
William Roberts
39fc7a9991 selinux_booleans_path: annotate deprecated
Signed-off-by: William Roberts <william.c.roberts@intel.com>
2020-04-30 09:13:25 -05:00
William Roberts
2e03962b56 security_load_booleans: annotate deprecated
Signed-off-by: William Roberts <william.c.roberts@intel.com>
2020-04-30 09:13:25 -05:00
William Roberts
63bb1b303a security_load_booleans: update return comment
The code returns -1 not 0, correct it.

Signed-off-by: William Roberts <william.c.roberts@intel.com>
2020-04-30 09:13:25 -05:00
Nicolas Iooss
417aff7266 libselinux,libsemanage: remove double blank lines
This looks cleaner.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2020-04-22 16:40:34 -05:00
Nicolas Iooss
65c82cccf9 libselinux/utils: remove unneeded variable in Makefile
LD_SONAME_FLAGS is not used when building libselinux utils.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2020-04-22 16:40:34 -05:00
Nicolas Iooss
091549b2d0 libselinux: make context_*_set() return -1 when an error occurs
In libselinux, most functions set errno and return -1 when an error
occurs. But some functions return 1 instead, such as context_type_set(),
context_role_set(), etc. This increases the difficulty of writing Python
bindings of these functions without much benefit.

Return -1 instead (errno was already set).

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2020-04-17 15:49:37 -05:00
Nicolas Iooss
164f437b19 libselinux: copy the reason why selinux_status_open() returns 1
The function comment of selinux_status_open() states:

    It returns 0 on success, or -1 on error.

However the implementation of this function can also return 1. This is
documented in its manpage (libselinux/man/man3/selinux_status_open.3) as
intended. Copy the reason near the function definition in order to make
the code more auditable.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2020-04-17 15:49:37 -05:00
Nicolas Iooss
0bcaba30d7 libselinux: add missing glue code to grab errno in Python bindings
The Python bindings for libselinux expose functions such as
avc_has_perm(), get_ordered_context_list(), etc. When these functions
encounter an error, they set errno accordingly and return a negative
value. In order to get the value of errno from Python code, it needs to
be "forwarded" in a way. This is achieved by glue code in
selinuxswig_python_exception.i, which implement raising an OSError
exception from the value of errno.

selinuxswig_python_exception.i was only generating glue code from
functions declared in selinux.h and not in other headers. Add other
headers.

selinuxswig_python_exception.i is generated by "bash exception.sh". Mark
the fact that exception.sh is a Bash script by adding a shebang. This
makes "shellcheck" not warn about the Bash array which is used to list
header files.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
Acked-by: William Roberts <william.c.roberts@intel.com>
2020-04-17 15:49:37 -05:00
Christian Göttsche
21f50e94b9
tree-wide: use python module importlib instead of the deprecated imp
Replace

python3 -c 'import imp;print([s for s,m,t in imp.get_suffixes() if t == imp.C_EXTENSION][0])'
<string>:1: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses
.cpython-38-x86_64-linux-gnu.so

with

python3 -c 'import importlib.machinery;print(importlib.machinery.EXTENSION_SUFFIXES[0])'
.cpython-38-x86_64-linux-gnu.so

Signed-off-by: Christian Göttsche <cgzones@googlemail.com>
2020-04-16 18:50:43 +02:00
Chris PeBenito
ec85260057
libselinux: Add selinux_restorecon option to treat conflicting specifications as an error.
Signed-off-by: Chris PeBenito <chpebeni@linux.microsoft.com>
2020-04-14 18:22:17 +02:00
Adam Duskett
aa40067b7b Fix building against musl and uClibc libc libraries.
Currently, the src/Makefile provides the FTS_LDLIBS when building against musl
or uClibc. However, this is missing from utils/Makefile, which causes linking
to fail.

Add the FTS_LDLIBS variable to the LDLIBS variable in utils/Makefile to fix
compiling against uClibc and musl.

Signed-off-by: Adam Duskett <Aduskett@gmail.com>
2020-04-10 16:44:08 -05:00
Jiyong Park
1ea855ee67 libselinux is LLNDK, not VNDK-core
libselinux has stable C APIs and therefore provides a stub library for
Mainline clients. It is not copied into any Mainline modules and the
only instance of the lib in /system/lib serves all of them.

However for vendors, we still had another copy of libselinux in VNDK
(e.g. in the VNDK APEX that is served via the path /system/lib/vndk).
Since the library is guaranteed to have stable C APIs, there is no
reason to keep the vendor variant of the library in VNDK. Keeping it in
VNDK would be just a waste of storage space.

This change removes libselinux from VNDK and marks it as LLNDK. The
single instance of if in /system/lib serves vendor processes as well as
Mainline modules.

Bug: 151303316
Test: m
Change-Id: Ibb3e125c1bf4ef7873ae8df0795e781f64d743f1
2020-03-31 15:26:07 +09:00
Jiyong Park
8949cc0b79 Make libselinux symbols versioned
Since R, stub variants of libselinux are created. They are used when
libselinux is requested from APEXes. Depending on the min_sdk_version
requirement of the APEX, we need to use different versions of libselinux
stubs. For example, an APEX that started with Android R should be linked
with R stub of libselinux, even it's built in Android S source tree
which might have a few more APIs. Otherwise, the APEX built in S won't
be able to work on R devices.

The stub generator (build/soong/cc/gen_stub_libs.py) uses symbol version
for identifying which version of Android the symbol was first
introduced. So, in this change, the existing symbols are all assigned
with a symbol version LIBSELINUX_R. For the symbols that will be added
for S should be assigned with a different symbol version, e.g.

LIBSELINUX_S { # introduced=S
   new_symbol;
   new_symbol2;
};

Bug: 151053366
Bug: 150999716
Test: m
Change-Id: I2d5966fbc9d255cc6a12aede88ee5f89987b5089
2020-03-12 14:33:15 +09:00
Jiyong Park
8cd9475631 Make libseliux a stub library
libselinux is currently being copied to APEXes. This is risky because
the library is not designed to be portable; part of it is tied to the
specific version of the Android that it was developed for.

This change fixes the problem by declaring that the library supports
a stub with the list of C APIs that are included in the stub. Then there
is only one copy of libselinux in /system/lib and other APEXes use the
copy by dynamically linking to it.

Bug: 151053366
Test: m com.android.adbd. It doesn't include libselinux in it.
Test: m com.android.adbd-deps-info. then inspect
out/soong/com.android.adbd-deps-info.txt. The dependency to libselinux
is shown as '(external)'.

Change-Id: I8faf344f3984437e313745e5eda5fdb8e75ce8ab
2020-03-11 13:54:27 +09:00
William Roberts
fc093ad757 libselinux: drop symbols from map
Previously, libselinux was exporting the following symbols:
  - dir_xattr_list;
  - map_class;
  - map_decision;
  - map_perm;
  - myprintf_compat;
  - unmap_class;
  - unmap_perm;

However, these appear to be unused and can safely be dropped.

This is done as a seperate commit to so it can easily be reverted
seperately for any reasons.

Signed-off-by: William Roberts <william.c.roberts@intel.com>
2020-03-05 13:07:34 -06:00
William Roberts
3eb91bec55 Makefile: add linker script to minimize exports
Add a linker script that exports only what was previosly exported by
libselinux.

This was checked by generating an old export map (from master):
nm --defined-only -g ./src/libselinux.so | cut -d' ' -f 3-3 | grep -v '^_' > old.map

Then creating a new one for this library after this patch is applied:
nm --defined-only -g ./src/libselinux.so | cut -d' ' -f 3-3 | grep -v '^_' > new.map

And diffing them:
diff old.map new.map

Fixes: #179

Signed-off-by: William Roberts <william.c.roberts@intel.com>
2020-03-05 13:07:34 -06:00
William Roberts
7f9edee769 Makefile: add -fno-semantic-interposition
Add -fno-semantic-interposition to CFLAGS. This will restore
the DSO infrastructures protections to insure internal callers
of exported symbols call into libselinux and not something laoding first
in the library list.

Clang has this enabled by default.

Signed-off-by: William Roberts <william.c.roberts@intel.com>
2020-03-05 13:07:34 -06:00
William Roberts
4246bb550d dso: drop hidden_proto and hidden_def
Signed-off-by: William Roberts <william.c.roberts@intel.com>
2020-03-05 13:07:34 -06:00
Stephen Smalley
a41dfeb55d libselinux: deprecate security_compute_user(), update man pages
commit 1f89c4e787 ("libselinux: Eliminate
use of security_compute_user()") eliminated the use of
security_compute_user() by get_ordered_context_list().  Deprecate
all use of security_compute_user() by updating the headers and man
pages and logging a warning message on any calls to it.  Remove
the example utility that called the interface. While here, also
fix the documentation of correct usage of the user argument to these
interfaces.

Fixes: https://github.com/SELinuxProject/selinux/issues/70
Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
Acked-by: Petr Lautrbach <plautrba@redhat.com>
2020-02-27 17:30:56 +01:00
Mikhail Novosyolov
8d3f5f7425 libselinux: Fix Ru translation of failsafe context
From failsafe_context(5):
"The failsafe_context file allows SELinux-aware applications such as
PAM(8) to obtain a known valid login context for an administrator if
no valid default entries can be found elsewhere."

"Надёжный" means "reliable", "резервный" means "reserve",
the last variant is much closer to what "failsafe" really does.

Discussed with and approved by previous translators:
https://github.com/SELinuxProject/selinux/pull/203

Signed-off-by: Mikhail Novosyolov <m.novosyolov@rosalinux.ru>
Acked-by: Petr Lautrbach <plautrba@redhat.com>
2020-02-21 09:12:23 +01:00
Petr Lautrbach
1f89c4e787 libselinux: Eliminate use of security_compute_user()
get_ordered_context_list() code used to ask the kernel to compute the complete
set of reachable contexts using /sys/fs/selinux/user aka
security_compute_user(). This set can be so huge so that it doesn't fit into a
kernel page and security_compute_user() fails. Even if it doesn't fail,
get_ordered_context_list() throws away the vast majority of the returned
contexts because they don't match anything in
/etc/selinux/targeted/contexts/default_contexts or
/etc/selinux/targeted/contexts/users/

get_ordered_context_list() is rewritten to compute set of contexts based on
/etc/selinux/targeted/contexts/users/ and
/etc/selinux/targeted/contexts/default_contexts files and to return only valid
contexts, using security_check_context(), from this set.

Fixes: https://github.com/SELinuxProject/selinux/issues/28

Signed-off-by: Petr Lautrbach <plautrba@redhat.com>
2020-02-20 09:47:23 -05:00
Christian Göttsche
4b33c9da64 libselinux: drop error return from is_selinux_enabled documentation
Since commit e3cab998b4 ("libselinux
mountpoint changing patch.") for version 20120216 is_selinux_enabled()
does never return -1; drop mentions in the man-page and header file.

Signed-off-by: Christian Göttsche <cgzones@googlemail.com>
Acked-by: Stephen Smalley <sds@tycho.nsa.gov>
2020-02-18 10:38:19 -05:00
Alan Stokes
8c9370e816 Delete unused selinux_android_setfilecon().
Test: Builds, device boots.
Change-Id: Ib01feb0bcaa7fdc8b951805bda82ec6e5cd3054c
2020-02-11 16:20:57 +00:00
Nick Kralevich
cfa868e4d3 label_file.c: Fix MAC build
On Android, the label_file.c file is compiled for all platforms,
including OSX. OSX has a slightly different prototype for the
getxattr function.

ssize_t getxattr(const char *path, const char *name, void *value, size_t size, u_int32_t position, int options);

which causes a compile error when compiling libselinux on OSX.

  ```
  external/selinux/libselinux/src/label_file.c:1038:37: error: too few arguments to function call, expected 6, have 4
                                       read_digest, SHA1_HASH_SIZE);
                                                                ^
  /Applications/Xcode9.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/sys/xattr.h:61:1: note: 'getxattr' declared here
  ssize_t getxattr(const char *path, const char *name, void *value, size_t size, u_int32_t position, int options);
  ^
  1 error generated.
  ```

On OSX builds, add the additional arguments so that the code compiles.

As both SELinux labels and the restorecon partial digest are stored in
extended attributes, it's theoretically possible that someone
could assign SELinux labels and hash digests on OSX filesystems.
Doing so would be extremely weird and completely untested, but
theoretically possible.

Signed-off-by: Nick Kralevich <nnk@google.com>
2020-02-11 09:47:41 -05:00
Nick Kralevich
74de00c108 label_file.c: Fix MAC build
On Android, the label_file.c file is compiled for all platforms,
including OSX. OSX has a slightly different prototype for the
getxattr function.

ssize_t getxattr(const char *path, const char *name, void *value, size_t size, u_int32_t position, int options);

which causes a compile error when compiling libselinux on OSX.

  ```
  external/selinux/libselinux/src/label_file.c:1038:37: error: too few arguments to function call, expected 6, have 4
                                       read_digest, SHA1_HASH_SIZE);
                                                                ^
  /Applications/Xcode9.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/sys/xattr.h:61:1: note: 'getxattr' declared here
  ssize_t getxattr(const char *path, const char *name, void *value, size_t size, u_int32_t position, int options);
  ^
  1 error generated.
  ```

On OSX builds, add the additional arguments so that the code compiles.

As both SELinux labels and the restorecon partial digest are stored in
extended attributes, it's theoretically possible that someone
could assign SELinux labels and hash digests on OSX filesystems.
Doing so would be extremely weird and completely untested, but
theoretically possible.

Fixes: 149060079
Test: compiles on both Linux and OSX
Change-Id: Ib80057ab09e48cc90dd37c2cc3c7046d0bdfdc9b
2020-02-07 12:59:12 -08:00
Nick Kralevich
3760c1e482 Merge remote-tracking branch 'aosp/upstream-master' into mymerge
Incorporate the latest upstream SELinux changes into the Android
build tree.

  % git merge aosp/upstream-master --no-ff

A followup commit will make Android specific changes to allow
this code to compile.

- Known issue: -

Multiple implementations of partial directory match digesting.

To fix bug 62302954 ("Investigate restorecon() / selabel_lookup()
performance"), Android implemented a number of patches, including
7d4a56f84d

The upstream SELinux community ended up writing their own variant of
Android's patch, which accomplishes the same thing. This patch is at
e016502c0a

This merge has the effect of having both patches in the tree at the same
time, which could be confusing. However, the new upstream code isn't
used by Android, so there's no impact (other than code bloat and
duplication).

Change-Id: I2bb804b71763c0c3ba77fe48d42787298f85a9d7
Test: treehugger
2020-02-03 13:00:08 -08:00
Nick Kralevich
263539011d Revert "Restorecon: factor out a lookup helper for context matches"
The upstream SELinux project has a variant of this patch.
Please see
5cff2813c5
for the replacement. This change deletes the local modification.
A future change will merge in the upstream branch,
incorporating the upstream changes.

This reverts commit f69947cffa.

Test: treehugger
2020-02-03 12:57:50 -08:00
Nick Kralevich
b0f301ae2e Revert "Restorecon: Ignore the stem when looking up all matches in file context"
The upstream SELinux project has a variant of this patch.
Please see
c00ed59281
for the replacement. This change deletes the local modification.
A future change will merge in the upstream branch,
incorporating the upstream changes.

This reverts commit ffb4432b9a.

Test: treehugger
2020-02-03 12:55:09 -08:00
Stephen Smalley
7bece3768b libselinux: export flush_class_cache(), call it on policyload
Rename flush_class_cache() to selinux_flush_class_cache(), export it
for direct use by userspace policy enforcers, and call it on all policy
load notifications rather than only when using selinux_check_access().
This ensures that policy reloads that change a userspace class or
permission value will be reflected by subsequent string_to_security_class()
or string_to_av_perm() calls.

Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
2020-01-24 08:28:37 -05:00
Stephen Smalley
784b029c3f libselinux: update man pages for userspace policy enforcers
Despite deprecating use of flask.h and av_permissions.h back in 2014,
the man pages for avc_has_perm(3) and security_compute_av(3) were not
updated to provide instructions on how to dynamically map class/permission
names nor to encourage use of selinux_check_access(3) instead of these
interfaces.  Also, while selinux_set_mapping(3) supports dynamic
class/perm mapping at initialization, it does not support changes to
the class/perm values at runtime upon a policy reload, and no
instructions were provided on how to set up a callback to support
this case.  Update the man pages accordingly.

Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
Acked-by: William Roberts <bill.c.roberts@gmail.com>
2020-01-21 14:32:42 -05:00
Stephen Smalley
89674c2ff7 libselinux: remove flask.h and av_permissions.h
The flask.h and av_permissions.h header files were deprecated and
all selinux userspace references to them were removed in
commit 76913d8adb ("Deprecate use of flask.h and av_permissions.h.")
back in 2014 and included in the 20150202 / 2.4 release.
All userspace object managers should have been updated
to use the dynamic class/perm mapping support since that time.
Remove these headers finally to ensure that no users remain and
that no future uses are ever introduced.

Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
Acked-by: Petr Lautrbach <plautrba@redhat.com>
2020-01-21 14:31:41 -05:00
Petr Lautrbach
dca7ce8195
Update VERSIONs to 3.0 for release.
Signed-off-by: Petr Lautrbach <plautrba@redhat.com>
2019-11-28 13:46:48 +01:00
Petr Lautrbach
6e187f8a2a Update VERSIONs to 3.0-rc2 for release.
Signed-off-by: Petr Lautrbach <plautrba@redhat.com>
2019-11-22 13:54:17 +01:00
Nicolas Iooss
91cd4600db
libselinux,libsemanage: check in python_exception.i files
Generating selinuxswig_python_exception.i and
semanageswig_python_exception.i requires gcc, which appears to be
unavailable on some platform. Work around this issue by adding the
generated files to the git repository.

While at it, remove a stray space in the generated
selinuxswig_python_exception.i.

Original thread: https://lore.kernel.org/selinux/20191012172357.GB19655@imap.altlinux.org/T/#ma78bd7fe71fb5784387a8c0cebd867d6c02ee6e4

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
Cc: Michael Shigorin <mike@altlinux.org>
2019-11-13 08:34:46 +01:00
Nicolas Iooss
dd9c70e0d7
libselinux,libsemanage: fix python_exception.i dependencies
selinuxswig_python_exception.i and semanageswig_python_exception.i need
to be regenerated when either an input header file changes or
exception.sh changes. Add the missing items to the respective Makefiles.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2019-11-13 08:34:42 +01:00
Nicolas Iooss
5815cc9843
libselinux,libsemanage: never create -.o in exception.sh
Files starting with "-" causes issues in commands such as "rm *.o". For
libselinux and libsemanage, when exception.sh fails to remove "-.o",
"make clean" fails with:

    rm: invalid option -- '.'
    Try 'rm ./-.o' to remove the file '-.o'.
    Try 'rm --help' for more information.

Fix this by making exception.sh create "temp.o" instead of "-.o".

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2019-11-13 08:34:35 +01:00
Petr Lautrbach
6d5f7f20bc Replace www.nsa.gov references by github.com/SELinuxProject
The original page doesn't exist anymore.

Fixes: https://github.com/SELinuxProject/selinux/issues/170

Signed-off-by: Petr Lautrbach <plautrba@redhat.com>
2019-11-08 09:20:29 -05:00
Ashwini Oruganti
4a0df6c499 Merge "Don't require seinfo for privapps" 2019-11-07 01:05:09 +00:00
Ashwini Oruganti
0c61ef8783 Don't require seinfo for privapps
Relax the requirement to have both seinfo and name specified for
privapps. The original reason for requiring both was because, normally,
a package can only be uniquely specified by both name and signature,
otherwise package squatting could occur. However, privapps are
pre-installed, so the concerns about the potential for package squatting
are eliminated. This change will drastically simplify sepolicy
configuration for priv-apps.

Bug: 142672293
Test: Flashed a device with this build and verified it boots.
Change-Id: I68e6245ae004888bdcc91df410ce15a8fd5da583
2019-11-06 08:31:44 -08:00
Thomas Petazzoni
0271bf4136
libselinux/src/Makefile: don't pass bogus -I and -L to python setup.py build_ext
Using $(DESTDIR) during the build does not follow the normal/standard
semantic of DESTDIR: it is normally only needed during the
installation. Therefore, a lot of build systems/environments don't
pass any DESTDIR at build time, which causes setup.py to be called
with -I /usr/include -L /usr/lib, which breaks cross-compilation.

Signed-off-by: Thomas Petazzoni <thomas.petazzoni@bootlin.com>
2019-11-02 17:32:20 +01:00
Marco Nelissen
cdeff9625d Remove unnecessary include and library
libselinux only linked with libcrypto so it could #include <openssl/sha.h>,
however it doesn't actually need that include, and so doesn't need
libcrypto either.

Test: build
Change-Id: Ic812274916aa3e63229e51027c615dc96611a13f
2019-10-31 13:46:19 -07:00
Petr Lautrbach
b3ed0a7a60 Update VERSIONs to 3.0-rc1 for release.
Signed-off-by: Petr Lautrbach <plautrba@redhat.com>
2019-10-28 13:06:11 +01:00
Nicolas Iooss
cfe4874093 libselinux: mark all exported function "extern"
Many functions are already marked "extern" in libselinux's public
headers and this will help using the content of the headers in order to
automatically generate some glue code for Python bindings.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2019-10-18 07:34:39 +13:00
Bowgo Tsai
e5b9766b3a Removing selinux_android_prop_context_handle
This function hasn't been used for near two years.
Removing it to prevent confusion.

The last usage is removed in
commit I27dd391fc06a3c78e88a65c7931c84de1699f157

Bug: 137712473
Bug: 141871131
Test: boot the device
Change-Id: I9d26ca7375b49b98a1fc6fda38f1ef9fd3c3f563
2019-10-02 13:31:12 +00:00
Bowgo Tsai
dc67d9ca5b libselinux: fix MAX_FILE_CONTEXT_SIZE
The value should be increased to five to accommodate 'system_ext'
context files.

Bug: 137712473
Test: boot crosshatch
Change-Id: I3d8e9a5b54438892d6133f56ce2dff0b1b771481
2019-09-30 00:34:16 +08:00
Treehugger Robot
9357d1441b Merge "libselinux: add /system_ext support." 2019-09-28 00:28:57 +00:00
Elliott Hughes
f2b58fb840 libselinux: stop loading libc++ and libm.
Part of the work to reduce toybox startup time (http://b/141555565).

Test: readelf
Change-Id: I78279f56e4b3069aa1557a4f056863530805b2f6
2019-09-24 12:16:34 -07:00
Nicolas Iooss
68b2e4416e libselinux: do not add rc to pos twice
In regex_format_error(), when error_data->error_offset is zero, rc is
not updated and should not be added to pos again.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2019-09-23 08:12:32 -04:00
Nicolas Iooss
340da085a5 libselinux: ensure strlen() is not called on NULL
When compile_regex() calls regex_prepare_data() and this function fails
in the following condition:

    *regex = regex_data_create();
    if (!(*regex))
        return -1;

... error_data has been zero-ed and compile_regex() calls:

    regex_format_error(&error_data,
        regex_error_format_buffer,
        sizeof(regex_error_format_buffer));

This leads to a call to strlen(error_data->error_buffer), where
error_data->error_buffer is NULL.

Avoid this by checking that error_data->error_buffer is not NULL before
trying to format it.

This issue has been found using clang's static analyzer:
https://337-118970575-gh.circle-artifacts.com/0/output-scan-build/2019-09-01-181851-6152-1/report-0b122b.html#EndPath

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2019-09-23 08:12:32 -04:00
Bowgo Tsai
5077059ae3 libselinux: add /system_ext support.
Adds libselinux support for:
system_ext_file_contexts
system_ext_property_contexts
system_ext_seapp_contexts
system_ext_service_contexts
system_ext_hwservice_contexts

Bug: 137712473
Test: boot crosshatch
Change-Id: Ia79aa070a5ce205e7fd487b79078d9124b59e4a1
2019-09-20 18:21:40 +08: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
Mike Palmiotto
86df2b27a7 libselinux: fix string conversion of unknown perms
Commit c19395d722 fixed some handling of unknown
classes/permissions, but missed the case where an unknown permission is loaded
and then subsequently logged, either via denial or auditallow. If a permission
set has some valid values mixed with unknown values, say `{ read write foo }`,
a check on `{ read write foo }` would fail to log the entire set.

To fix this, skip over the bad permissions/classes when expanding them to
strings. The unknowns should be logged during `selinux_set_mapping`, so
there is no need for further logging of the actual unknown permissions.

Signed-off-by: Mike Palmiotto <mike.palmiotto@crunchydata.com>
2019-09-18 08:20:30 -04:00
Vit Mojzis
26e83975d5 Fix mcstrans secolor examples
According to "check_dominance" function:
Range defined as "s15:c0.c1023" does not dominate any other range than
 "s15:c0.c1023" (does not dominate "s15", "s15:c0.c200", etc.).
While range defined as "s15-s15:c0.c1023" dominates all of the above.

This is either a bug, or "s15:c0.c1023" should not be used in the
examples.

Signed-off-by: Vit Mojzis <vmojzis@redhat.com>
2019-09-16 15:43:24 -04:00
Nicolas Iooss
f25d03d75d
libselinux: ensure that digest_len is not zero
In add_xattr_entry(), if selabel_get_digests_all_partial_matches()
returns with digest_len = 0, the code gets executed as:

    sha1_buf = malloc(digest_len * 2 + 1);  /* Allocate 1 byte */

    /* ... */

    for (i = 0; i < digest_len; i++)  /* Do not do anything */
        sprintf((&sha1_buf[i * 2]), "%02x", xattr_digest[i]);

    /* ... */

    new_entry->digest = strdup(sha1_buf);  /* use of uninitiliazed content */

This is reported by some static code analyzers, even though in practise
digest_len should never be zero, and the call to sprintf() ensures that
the content of sha1_buf is initialized and terminated by '\0'.

Make sure to never call strdup() on an uninitialized string by verifying
that digest_len != 0.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2019-09-01 18:44:48 +02:00
Richard Haines
2a1766f443
selinux: Update manpages after removing legacy boolean and user code
Remove and update all relevant manpages.

Signed-off-by: Richard Haines <richard_c_haines@btinternet.com>
2019-07-29 23:46:47 +02:00
Richard Haines
c3f9492d7f
selinux: Remove legacy local boolean and user code
Remove legacy local boolean and user code, and to preserve API/ABI
compatibility the following functions int values should be set to '0'
as they are no longer used:
  selinux_mkload_policy(int preservebools)
  security_set_boolean_list(.... int permanent)
and the following are now no-op and return '-1':
  security_load_booleans()
  sepol_genusers()
  sepol_set_delusers()
  sepol_genbools()
  sepol_genbools_array()
and these still return their paths for compatibility, however they are
marked as deprecated:
  selinux_booleans_path()
  selinux_users_path()

These have been removed as they are local functions only:
  sepol_genusers_policydb()
  sepol_genbools_policydb()

Also "SETLOCALDEFS" removed from SELinux config file and code.

Signed-off-by: Richard Haines <richard_c_haines@btinternet.com>
2019-07-29 23:46:24 +02:00
Richard Haines
e016502c0a
libselinux: Save digest of all partial matches for directory
We used to hash the file_context and skip the restorecon on the top
level directory if the hash doesn't change. But the file_context
might change after an OTA update; and some users experienced long
restorecon time as they have lots of files under directories like
/data/media.

This CL tries to hash all the partial match entries in the
file_context for each directory; and skips the restorecon if that
digest stays the same, regardless of the changes to the other parts
of file_context.

This is a version ported from Android that was originally written by:
xunchang <xunchang@google.com>

Signed-off-by: Richard Haines <richard_c_haines@btinternet.com>
2019-07-27 10:39:24 +02:00
xunchang
c00ed59281
libselinux: Ignore the stem when looking up all matches in file context
This is a follow up fix to the restorecon change in
commit 6ab5fbaabc84f7093b37c1afae855292e918090f This change has been
tested in android for a while.

The stem is a list of top level directory (without regex metachar)
covered in the file context. And it constructs from finding the
second '/' in the regex_string; and aims to speed up the lookup by
skipping unnecessary regex matches. More contexts in
https://lore.kernel.org/selinux/200309231522.25749.russell@coker.com.au/

However, this caused some issue when we try to find all the partial
matches for a root directory. For example, the path "/data" doesn't
have a stem while the regex "/data/misc/(/.*)?" has "/data" as the
stem. As a result, all the regex for the subdirs of /data will not
considered as a match for "/data". And the restorecon will wrongly
skip on top level "/data" when there's a context change to one of
subdir.

This CL always includes the stem when compiling the regex in all
circumstances. Also, it ignores the stem id check in the "match all"
case, while the behavior for the single match stays unchanged. I will
collect more data to find out if stem id check is still necessary at
all with the new restorecon logic.

Test: run restorecon on "/data"; change the context of one subdir and
run again, and the context is restored on that subdir; search the caller
of regex_match

Signed-off-by: Tianjie Xu <xunchang@google.com>
2019-07-27 10:39:24 +02:00
xunchang
5cff2813c5
Restorecon: factor out a lookup helper for context matches
We used to hash the file_context and skip the restorecon on the top
level directory if the hash doesn't change. But the file_context might
change after an update; and some users experienced long restorecon
time as they have lots of files under directories like /data/media.
Therefore, we try to skip unnecessary restores if the file context
relates to the given directory doesn't change.

This CL is the first step that factors out a lookup helper function
and returns an array of matched pointers instead of a single one.
The old loopup_common function is then modified to take the first
element in the array.

This change has already been submitted in android selinux branch. And
porting it upstream will make these two branches more consistent and
save some work for the future merges.

Signed-off-by: Tianjie Xu <xunchang@google.com>
2019-07-27 10:39:19 +02:00
Petr Lautrbach
2efa068575 libselinux: Use Python distutils to install SELinux python bindings
Follow officially documented way how to build C extension modules using
distutils - https://docs.python.org/3.8/extending/building.html#building

Fixes:

- selinux python module fails to load when it's built using SWIG-4.0:

>>> import selinux
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python3.7/site-packages/selinux/__init__.py", line 13, in <module>
    from . import _selinux
ImportError: cannot import name '_selinux' from 'selinux' (/usr/lib64/python3.7/site-packages/selinux/__init__.py)

SWIG-4.0 changed (again?) its behavior so that it uses: from . import _selinux
which looks for _selinux module in the same directory as where __init__.py is -
$(PYLIBDIR)/site-packages/selinux. But _selinux module is installed into
$(PYLIBDIR)/site-packages/ since a9604c30a5 ("libselinux: Change the location
of _selinux.so").

- audit2why python module fails to build with Python 3.8

cc -O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fexceptions -fstack-protector-strong -grecord-gcc-switches -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -specs=/usr/lib/rpm/redhat/redhat-annobin-cc1 -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -DOVERRIDE_GETTID=0 -I../include -D_GNU_SOURCE -DDISABLE_RPM -DNO_ANDROID_BACKEND -DUSE_PCRE2 -DPCRE2_CODE_UNIT_WIDTH=8  -Wl,-z,relro -Wl,--as-needed  -Wl,-z,now -specs=/usr/lib/rpm/redhat/redhat-hardened-ld -L. -shared -o python-3.8audit2why.so python-3.8audit2why.lo -lselinux -l:libsepol.a  -Wl,-soname,audit2why.so,--version-script=audit2why.map,-z,defs
/usr/bin/ld: python-3.8audit2why.lo: in function `finish':
/builddir/build/BUILD/libselinux-2.9/src/audit2why.c:166: undefined reference to `PyArg_ParseTuple'
/usr/bin/ld: python-3.8audit2why.lo: in function `_Py_INCREF':
/usr/include/python3.8/object.h:449: undefined reference to `_Py_NoneStruct'
/usr/bin/ld: /usr/include/python3.8/object.h:449: undefined reference to `_Py_NoneStruct'
/usr/bin/ld: python-3.8audit2why.lo: in function `check_booleans':
/builddir/build/BUILD/libselinux-2.9/src/audit2why.c:84: undefined reference to `PyExc_RuntimeError'
...

It's related to the following Python change
https://docs.python.org/dev/whatsnew/3.8.html#debug-build-uses-the-same-abi-as-release-build

Python distutils adds correct link options automatically.

- selinux python module doesn't provide any Python metadata

When selinux python module was built manually, it didn't provide any metadata.
distutils takes care about that so that selinux Python module is visible for
pip:

$ pip3 list | grep selinux
selinux              2.9

Signed-off-by: Petr Lautrbach <plautrba@redhat.com>
2019-07-26 18:15:46 +02:00
Richard Haines
ee8f7a870c
libselinux: Fix security_get_boolean_names build error
When running 'make' from libselinux on Fedora 30 (gcc 9.1.1) the
following error is reported:

bute=const -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=2 -Wstrict-overflow=5
-I../include -D_GNU_SOURCE  -DNO_ANDROID_BACKEND  -c -o booleans.o
booleans.c
booleans.c: In function ‘security_get_boolean_names’:
booleans.c:39:5: error: assuming signed overflow does not occur when
changing X +- C1 cmp C2 to X cmp C2 -+ C1 [-Werror=strict-overflow]
  39 | int security_get_boolean_names(char ***names, int *len)
      |    ^~~~~~~~~~~~~~~~~~~~~~~~~~
cc1: all warnings being treated as errors
make[1]: *** [Makefile:171: booleans.o] Error 1

This is caused by the '--i' in the: 'for (--i; i >= 0; --i)' loop.

Signed-off-by: Richard Haines <richard_c_haines@btinternet.com>
2019-07-21 22:59:37 +02:00
Nick Kralevich
97f1ad6591 Merge remote-tracking branch 'aosp/upstream-master' into mymege
Followed the following steps:
  # In repo client
  cd external/selinux
  repo sync .
  repo start mymerge .
  git merge aosp/upstream-master --no-ff # resolve any conflicts
  lunch && make -j
  repo upload .

Test: compiles and boots
Change-Id: Ia2dbf92e3127aa779bec3c46f171d3ef6c1cbfe5
2019-06-11 09:07:03 -07:00
Unto Sten
baf8a1de16 Check strdup() failure 2019-05-15 17:36:18 -07:00
Unto Sten
cd1ef4d64e another style fix 2019-05-15 17:35:43 -07:00
Unto Sten
e1a74396c7 Unify code style to preserve my sanity 2019-05-15 17:35:43 -07:00
Unto Sten
5d8f44e2c3 Global replace exit(0) with more readable exit(EXIT_SUCCESS) 2019-05-15 17:34:43 -07:00
Nick Kralevich
10c7956b29 Delay /data/vendor_ce restorecon
When Android boots after file_contexts has changed, the boot process
walks the entire /data partition, updating any changed SELinux labels as
appropriate. However, credential encrypted ("ce") directories are
deliberately excluded from this early boot directory walk. Files within
ce directories have their filenames encrypted, and as a result, cannot
match the file_contexts entries. Only after the user has unlocked their
device are the unencrypted filenames available and a restorecon
appropriate.

Exclude /data/vendor_ce from the early boot restorecon, like we do for
/data/system_ce and /data/misc_ce. This prevents init from
inappropriately relabeling these files with encrypted filenames.

(cherrypicked from commit 2d3cc3b458)

Bug: 132349934
Test: See bug 132349934 comment #12 for test procedure
Change-Id: I59171f11dc25d446fae3760c4aa538264944391d
2019-05-15 09:32:22 -07:00
liwugang
84cf5d7a34 No need to calculate the hash value of file_contexts
The file_contexts' hash value is no longer used. So remove it.

Test: compile
Change-Id: I6f2c59a712377bef698fd87ebf38cc4dfbf9ee0c
Signed-off-by: liwugang <liwugang@xiaomi.com>
2019-04-23 14:13:32 +08:00
Nick Kralevich
8c158034dd Remove isV2App
This selector is no longer used.

Bug: 123605817
Bug: 111314398
Test: compiles and boots
Change-Id: Ieb45a797706d3c274922b5b0aa48edf50b646f89
2019-04-16 17:29:42 -07:00
Nick Kralevich
04af6a3c5a Merge remote-tracking branch 'aosp/upstream-master' into mymerge
Followed the following steps:
  # In repo client
  cd external/selinux
  repo sync .
  repo start mymerge .
  git merge aosp/upstream-master --no-ff # resolve any conflicts
  lunch && make -j
  repo upload .

Test: compiles and boots
Change-Id: I39ccb9f0eb0003a2b35807e30cf7fa11354d5909
2019-04-12 14:56:16 -07:00
Joshua Brindle
25ce102907 Add security_validatetrans support
It seems validatetrans support was never added to libselinux, despite being added to
selinuxfs in kernel version 4.5

There is a utility to test, however the targeted policy has no validatetrans rules so some must be added:

$ cat validatetrans.cil
(mlsvalidatetrans db_table (and (or (or (or (eq l1 l2) (and (eq t3 unconfined_t) (domby l1 l2))) (and (eq t3 unconfined_t) (dom l1 l2))) (and (eq t3 unconfined_t) (incomp l1 l2))) (or (or (or (eq l1 h2) (and (eq t3 unconfined_t) (domby h1 h2))) (and (eq t3 unconfined_t) (dom h1 h2))) (and (eq t3 unconfined_t) (incomp h1 h2)))))

$ sudo semodule -i validatetrans.cil

$ ./validatetrans system_u:system_r:kernel_t:s0 system_u:system_r:init_t:s0:c0 db_table system_u:system_r: # invalid context here
opening /sys/fs/selinux/validatetrans
security_validatetrans returned -1 errno: Invalid argument

$ ./validatetrans system_u:system_r:kernel_t:s0 system_u:system_r:init_t:s0:c0 db_table system_u:system_r:init_t:s0
opening /sys/fs/selinux/validatetrans
security_validatetrans returned -1 errno: Operation not permitted

$ ./validatetrans system_u:system_r:kernel_t:s0 system_u:system_r:init_t:s0:c0 db_table system_u:system_r:unconfined_t:s0
opening /sys/fs/selinux/validatetrans
security_validatetrans returned 0 errno: Success

Signed-off-by: Joshua Brindle <joshua.brindle@crunchydata.com>
2019-04-09 06:51:02 -07:00
Nick Kralevich
3060b61d41 add SELINUX_ANDROID_RESTORECON_SKIP_SEHASH
Allow callers to indicate that they don't want to compute the sehash
value. Callers may not have CAP_SYS_ADMIN, so attempting to write the
sehash value will result in the following (harmless) errors:

  SELinux:  setxattr failed: /data/app/com.andromeda.androbench2-z5oLVfPATqQF35yGDuMUeA==:  Operation not permitted

TODO: It would be better if the default for restorecon was to suppress
the hash computation, since otherwise it encourages programs to be
overprivileged with CAP_SYS_ADMIN. I'll plan on doing that in a followup
commit.

Bugs where this error message has been called out:
Bug: 129766333
Bug: 129271240
Bug: 128700692
Bug: 129925723

Test: install an APK and ensure that no "SELinux:  setxattr failed"
    error messages are generated.

Change-Id: I396f036681abf106d48413a7a6126d4a6af2fa3a
2019-04-04 16:14:08 -07:00
Jeff Vander Stoep
3e334d0162 export seapp_context_init
Bug: 129704390
Test: ps -AZ; verify that apps have correct context
Test: with "#define DEBUG 1" to verify that
selinux_android_seapp_context_reload() is only called once
in zygote.

Change-Id: I8120f66ce77b472d9190647e13f6da6c6f52464a
(cherry picked from commit 5a26d140d6)
2019-04-04 12:49:14 -07:00
Nick Kralevich
781054cc2f Merge remote-tracking branch 'aosp/upstream-master' into mymerge
Followed the following steps:
  # In repo client
  cd external/selinux
  repo sync .
  repo start mymerge .
  git merge aosp/upstream-master --no-ff # resolve any conflicts
  lunch && make -j
  repo upload .

Test: compiles and boots
Change-Id: I75ccf5307012a2517c0fdf13bea806e10b8b8595
2019-03-29 10:15:37 -07:00
xunchang
ffb4432b9a Restorecon: Ignore the stem when looking up all matches in file context
The stem is a list of top level directory (without regex metachar)
covered in the file context. And it constructs from finding the
second '/' in the regex_string; and aims to speed up the lookup by
skipping unnecessary regex matches. More contexts in
https://lore.kernel.org/selinux/200309231522.25749.russell@coker.com.au/

However, this caused some issue when we try to find all the partial
matches for a root directory. For example, the path "/data" doesn't
have a stem while the regex "/data/misc/(/.*)?" has "/data" as the
stem. As a result, all the regex for the subdirs of /data will not
considered as a match for "/data". And the restorecon will wrongly
skip on top level "/data" when there's a context change to one of
subdir.

This CL always includes the stem when compiling the regex in all
circumstances. Also, it ignores the stem id check in the "match all"
case, while the behavior for the single match stays unchanged. I will
collect more data to find out if stem id check is still necessary at
all with the new restorecon logic.

Bug: 62302954
Bug: 127946548
Test: run restorecon on "/data"; change the context of one subdir and
run again, and the context is restored on that subdir; search the caller
of regex_match

Change-Id: I4d6e554bb6abe124055782769d2f95083ed6c3a1
2019-03-15 09:24:14 -07:00
Petr Lautrbach
891cfee44f Update VERSIONs to 2.9 for release.
Signed-off-by: Petr Lautrbach <plautrba@redhat.com>
2019-03-15 11:32:30 +01:00
Petr Lautrbach
707e4b8610 libselinux: Do not define gettid() if glibc >= 2.30 is used
Since version 2.30 glibc implements gettid() system call wrapper, see
https://sourceware.org/bugzilla/show_bug.cgi?id=6399

Fixes:
cc -O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fexceptions -fstack-protector-strong -grecord-gcc-switches -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -specs=/usr/lib/rpm/redhat/redhat-annobin-cc1 -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -I../include -D_GNU_SOURCE  -DNO_ANDROID_BACKEND   -c -o procattr.o procattr.c
procattr.c:28:14: error: static declaration of ‘gettid’ follows non-static declaration
   28 | static pid_t gettid(void)
      |              ^~~~~~
In file included from /usr/include/unistd.h:1170,
                 from procattr.c:2:
/usr/include/bits/unistd_ext.h:34:16: note: previous declaration of ‘gettid’ was here
   34 | extern __pid_t gettid (void) __THROW;
      |                ^~~~~~

Signed-off-by: Petr Lautrbach <plautrba@redhat.com>
2019-03-13 13:23:50 -04:00
Petr Lautrbach
486aa7d991 libselinux: Add security_reject_unknown(3) man page
Commit c19395d722 ("libselinux: selinux_set_mapping: fix handling of unknown
classes/perms") added a new interface security_reject_unknown() which needs to
be documented.

Signed-off-by: Petr Lautrbach <plautrba@redhat.com>
2019-03-11 11:47:36 -04:00
Treehugger Robot
de9339b298 Merge "Remove -Wno-pointer-bool-conversion" 2019-03-06 00:09:59 +00:00
Tianjie Xu
f797b5b327 Merge "Restorecon: save digest of all partial matches for directory" 2019-03-05 22:28:30 +00:00
Tianjie Xu
de42e97aa8 Merge "Restorecon: factor out a lookup helper for context matches" 2019-03-05 22:28:11 +00:00
xunchang
7d4a56f84d Restorecon: save digest of all partial matches for directory
We used to hash the file_context and skip the restorecon on the top
level directory if the hash doesn't change. But the file_context
might change after an OTA update; and some users experienced long
restorecon time as they have lots of files under directories like
/data/media.

This CL tries to hash all the partial match entries in the
file_context for each directory; and skips the restorecon if that
digest stays the same, regardless of the changes to the other parts
of file_context.

Bug: 62302954
Test: visited directory skips correctly during restorecon.
Change-Id: Ia0668629a260b9b7a049bb68f6a8cc901c6cc46b
2019-03-05 12:34:19 -08:00
xunchang
f69947cffa Restorecon: factor out a lookup helper for context matches
This is part of the effort to save digest for subdirectories.
Split out the non-android part to make the merge to upstream
branch easier.

Bug: 62302954
Test: build android, compile the upstream branch
Change-Id: I4df94ed381f26356c539d604f31a65daabafc1da
2019-03-05 10:36:03 -08:00
Nick Kralevich
373aaaa48f Remove -Wno-pointer-bool-conversion
This doesn't appear needed anymore.

Test: compiles.
Change-Id: I41b41ec67324051bbae0624735eb797ad60aaca2
2019-03-05 08:51:10 -08:00
Nick Kralevich
356091588a Merge remote-tracking branch 'aosp/upstream-master' into mymerge
Additionally, resolve build time errors due to

  c19395d722
  libselinux: selinux_set_mapping: fix handling of unknown classes/perm

Followed the following steps:
  # In repo client
  cd external/selinux
  repo sync .
  repo start mymerge .
  git merge aosp/upstream-master --no-ff # resolve any conflicts
  lunch && make -j
  repo upload .

Test: device boots and no obvious problems.
Change-Id: Ib3a6c086ceadaeaaaf35498d53b2b3e3ad5b8945
2019-03-04 17:18:15 -08:00
Petr Lautrbach
ee1809f453 Update VERSIONs to 2.9-rc2 for release.
Signed-off-by: Petr Lautrbach <plautrba@redhat.com>
2019-03-01 13:58:20 +01:00
Stephen Smalley
c19395d722 libselinux: selinux_set_mapping: fix handling of unknown classes/perms
The libselinux selinux_set_mapping() implementation was never updated
to handle unknown classes/permissions based on the policy handle_unknown
flag.  Update it and the internal mapping functions to gracefully
handle unknown classes/permissions.  Add a security_reject_unknown()
interface to expose the corresponding selinuxfs node and use it when
creating a mapping to decide whether to fail immediately or proceed.

This enables dbus-daemon and XSELinux, which use selinux_set_mapping(),
to continue working with the dummy policy or other policies that lack
their userspace class/permission definitions as long as the policy
was built with -U allow.

Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
2019-03-01 12:51:31 +01:00
Nick Kralevich
65c6846e1a Merge remote-tracking branch 'aosp/upstream-master' into mymerge
This really isn't needed, as we just rebased 5 days ago. However, I
wanted to minimize the diff in case anyone happens to look at
b/126376007 today.

Followed the following steps:
  # In repo client
  cd external/selinux
  repo sync .
  repo start mymerge .
  git merge aosp/upstream-master --no-ff # resolve any conflicts
  repo upload .

Test: device boots and no obvious problems.
Bug: 126376007
Change-Id: I290900ec5285ca98212b90d0ac536da9d27b16c9
2019-02-26 09:55:25 -08:00
Nick Kralevich
28cf7ea80d perfcrastination: Merge remote-tracking branch 'aosp/upstream-master' into mymerge
Followed the following steps:
  # In repo client
  cd external/selinux
  repo sync .
  repo start mymerge .
  git merge aosp/upstream-master --no-ff # resolve any conflicts
  repo upload .

Test: device compiles and boots
Change-Id: I2b5b1a201d43ee94fc909dd8bca5595bc7f0e522
2019-02-21 12:56:14 -08:00
Petr Lautrbach
1952be65dc Switch to python3 by default
- Python 2.7 is planned to be the last of the 2.x releases
- It's generally advised to use Python 3
- Majority of python/ scripts are already switched python3
- Users with python 2 only can still use:

$ make PYTHON=/usr/bin/python ....

Signed-off-by: Petr Lautrbach <plautrba@redhat.com>
2019-02-20 16:43:27 +01:00
Stephen Smalley
6b89b1f9c1 libselinux: fix selinux_restorecon() on non-SELinux hosts
The kernel only supports seclabel if it is >= 2.6.30 _and_
SELinux is enabled, since seclabel is generated by SELinux
based partly on policy (e.g. is the filesystem type configured in policy
with a labeling behavior that supports userspace labeling). For some
reason, when this logic was moved from setfiles to libselinux,
the test of whether SELinux was enabled was dropped.  Restore it.

This is necessary to enable use of setfiles on non-SELinux hosts
without requiring explicit use of the -m option.

Fixes: 602347c742 ("policycoreutils: setfiles - Modify to use selinux_restorecon")
Reported-by: sajjad ahmed <sajjad_ahmed782@yahoo.com>
Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
Cc: Richard Haines <richard_c_haines@btinternet.com>
Reported-by: sajjad ahmed &lt;<a href="mailto:sajjad_ahmed782@yahoo.com" target="_blank">sajjad_ahmed782@yahoo.com</a>&gt;<br>
Signed-off-by: Stephen Smalley &lt;<a href="mailto:sds@tycho.nsa.gov" target="_blank">sds@tycho.nsa.gov</a>&gt;<br>
2019-02-20 11:21:33 +01:00
Nick Kralevich
df5204a030 Merge remote-tracking branch 'aosp/upstream-master' into mymerge
Followed the following steps:
  # In repo client
  cd external/selinux
  repo sync .
  repo start mymerge .
  git merge aosp/upstream-master --no-ff # resolve any conflicts
  repo upload .

Test: device compiles and boots
Change-Id: If92a0b5e99e69ac0434197fa848b736b9cf0bf77
2019-02-14 12:11:20 -08:00
Petr Lautrbach
5d59284381
libselinux: Fix RESOURCE_LEAK defects reported by coverity scan
Fixes:

libselinux/src/checkAccess.c:93: leaked_storage: Variable "user_context" going out of scope leaks the storage it points to.
libselinux/src/label_db.c:286: leaked_storage: Variable "filp" going out of scope leaks the storage it points to.
libselinux/src/label_db.c:291: leaked_storage: Variable "filp" going out of scope leaks the storage it points to.
libselinux/src/label_file.c:405: leaked_storage: Variable "str_buf" going out of scope leaks the storage it points to.
libselinux/src/load_policy.c:266: leaked_storage: Variable "names" going out of scope leaks the storage it points to.
libselinux/src/selinux_config.c:183: leaked_storage: Variable "end" going out of scope leaks the storage it points to.
libselinux/src/selinux_config.c:184: overwrite_var: Overwriting "end" in "end = type + strlen(type) - 1" leaks the storage that "end" points to.
libselinux/src/selinux_restorecon.c:376: leaked_storage: Variable "new_entry" going out of scope leaks the storage it points to.
libselinux/src/selinux_restorecon.c:855: leaked_storage: Variable "xattr_value" going out of scope leaks the storage it points to.

Signed-off-by: Petr Lautrbach <plautrba@redhat.com>
2019-02-10 17:52:09 +01:00
Petr Lautrbach
347719d15f
libselinux/selinux_restorecon: Skip customized files also without -v
In the original code, customizable file contexts were not changed only if -v was
used. It lead to different behavior when selinux_restorecon was run with -v and
without it.

Based on an initial patch by Jan Zarsky <jzarsky@redhat.com>

Signed-off-by: Petr Lautrbach <plautrba@redhat.com>
2019-02-10 17:06:00 +01:00
Jooyung Han
9cb1372b72 Mark libselinux as double_loadable
libselinux is a VNDK lib and also used by LLNDK(libmediandk) which means
this lib can be double-loaded.
(deps: libmediandk -> libmedia_jni -> libandroid_runtime -> libselinux)

Bug: 121280180
Test: m -j
Change-Id: Ie7a583088a97cf68f7ae547b6d63f970efa559e8
2019-02-07 17:36:43 +09:00
Petr Lautrbach
fdb242ef1b
libselinux: Change matchpathcon usage to match with matchpathcon manpage
Signed-off-by: Petr Lautrbach <plautrba@redhat.com>
2019-02-04 22:11:22 +01:00
Petr Lautrbach
5689d82a44
libselinux: set an appropriate errno in booleans.c
Fixes:
$ mkdir booleans
$ sudo mount --bind ./booleans /sys/fs/selinux/booleans
$ sudo getsebool -a
getsebool:  Unable to get boolean names:  Success

Signed-off-by: Petr Lautrbach <plautrba@redhat.com>
2019-02-04 22:11:13 +01:00
Viktor Ashirov
474a09233c
python/restorecon: add force option
This adds 'force' keyword argument to selinux.restorecon() function
using SELINUX_RESTORECON_SET_SPECFILE_CTX flag.

Signed-off-by: Viktor Ashirov <vashirov@redhat.com>
2019-02-04 20:23:32 +01:00
Aleksei Nikiforov
0445e65d83 Allow installing translated man pages
Signed-off-by: Aleksei Nikiforov <darktemplar@basealt.ru>
2019-01-28 12:03:57 +01:00
Aleksei Nikiforov
e3e3873de7 Add man pages translation by Olesya Gerasimenko
Signed-off-by: Olesya Gerasimenko <gammaray@basealt.ru>
Signed-off-by: Aleksei Nikiforov <darktemplar@basealt.ru>
2019-01-28 12:03:57 +01:00
Nick Kralevich
1633b76f8a Merge remote-tracking branch 'aosp/upstream-master' into mymerge
Followed the following steps:
  # In repo client
  cd external/selinux
  repo sync .
  repo start mymerge .
  git merge aosp/upstream-master --no-ff # resolve any conflicts
  repo upload .

Test: device boots and no obvious problems.
Change-Id: I6beff804808e92d1002ead226c7d5c702f373cdc
2019-01-25 08:29:25 -08:00
Petr Lautrbach
53312c7d61 Update VERSIONs to 2.9-rc1 for release.
Signed-off-by: Petr Lautrbach <plautrba@redhat.com>
2019-01-25 11:48:54 +01:00
Petr Lautrbach
de5d5ede60 libselinux/audit2why.so: Filter out non-python related symbols
audit2why.so used to export libsepol.a symbols. We only need Python related
symbols:

- initaudit2why for python 2
- PyInit_audit2why for python3

Signed-off-by: Petr Lautrbach <plautrba@redhat.com>
2019-01-21 12:13:41 +01:00
Nicolas Iooss
689a6eb576 libselinux: do not dereference symlink with statfs in selinux_restorecon
When selinux_restorecon() is used to relabel symlinks, it performs the
following syscalls (as seen by running strace on restorecond):

    lstat("/root/symlink", {st_mode=S_IFLNK|0777, st_size=6, ...}) = 0
    statfs("/root/symlink", 0x7ffd6bb4d090) = -1 ENOENT (No such file or directory)
    lstat("/root/symlink", {st_mode=S_IFLNK|0777, st_size=6, ...}) = 0
    lgetxattr("/root/symlink", "security.selinux", "sysadm_u:object_r:user_home_t", 255) = 30

The second one triggers a SELinux check for lnk_file:read, as statfs()
dereferences symbolic links. This call to statfs() is only used to find
out whether "restoreconlast" xattr can be ignored, which is always the
case for non-directory files (the first syscall, lstat(), is actually
used to perform this check).

Skip the call to statfs() when setrestoreconlast is already false.

This silences an AVC denial that would otherwise be reported to
audit.log (cf. https://github.com/SELinuxProject/refpolicy/pull/22).

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2019-01-18 11:13:19 -05:00
Tri Vo
5fa62dd318 Merge "libselinux: Fix location of product_seapp_contexts" 2019-01-09 04:26:15 +00:00
Nick Kralevich
c3e8eef882 Merge remote-tracking branch 'aosp/upstream-master' into mymerge
Followed the following steps:
  # In repo client
  cd external/selinux
  repo sync .
  repo start mymerge .
  git merge aosp/upstream-master --no-ff # resolve any conflicts
  repo upload .

Test: android compiles and boots and no observed problems.
Change-Id: I9fedadcaad26aa01425b71b9897f2dd0aa53468d
2019-01-07 11:18:21 -08:00
Tri Vo
81f6f73416 libselinux: Fix location of product_seapp_contexts
Fixes a mistake made in aosp/851559. Actual location of
product_seapp_contexts is /product/etc/selinux/product_seapp_contexts

Bug: 119305624
Test: dataservice_app is correctly labeled on blueline
Change-Id: Ic25472d44efa57418fb38cf65f9726a7fda2b417
2019-01-02 13:56:36 -08:00
William Roberts
9fe430345a Makefile: add -Wstrict-overflow=5 to CFLAGS
Build with strict overflow checking enabled. If the compiler optimizes
code that could be removed due to undefined signed overflow, then the
compiler will issue a warning.

Signed-off-by: William Roberts <william.c.roberts@intel.com>
2018-12-31 08:06:29 -08:00
William Roberts
97edcebd1e build: set _FORTIFY_SOURCE=2 in libselinux
Use -D_FO0RTIFY_SOURCE=2 when building libselinux and it's util library.
Note that this can be overridden by setting CFLAGS during the build.

Signed-off-by: William Roberts <william.c.roberts@intel.com>
2018-12-31 08:06:29 -08:00
William Roberts
4f96b323b0 Makefile: fix _FORTIFY_SOURCE redefined build error
Certain builds of gcc enable _FORTIFY_SOURCE which results in the error:
<command-line>:0:0: warning: "_FORTIFY_SOURCE" redefined
<command-line>:0:0: note: this is the location of the previous definition

Correct this by undefining it first and redefining it. Also, the previous
command line option was using -Wp which is passing the value *AS IS* to the
pre-processor rather than to the compiler driver. The C pre-processor has
an undocumented interface subject to change per man 1 gcc. Just use the
-D option to specify this value.

Signed-off-by: William Roberts <william.c.roberts@intel.com>
2018-12-31 08:06:29 -08:00
Tri Vo
a1c6b50f9a libselinux: add /product support.
Adds libselinux support for:
product_file_contexts
product_property_contexts
product_seapp_contexts
product_service_contexts
product_hwservice_contexts

Bug: 119305624
Test: boot blueline
Change-Id: I1984ce4e32598db9d02441c426595db0484402eb
2018-12-18 14:51:40 -08:00
Nick Kralevich
b744f16fd2 Merge remote-tracking branch 'aosp/upstream-master' into mymerge
Followed the following steps:
  # In repo client
  cd external/selinux
  repo sync .
  repo start mymerge .
  git merge aosp/upstream-master --no-ff # resolve any conflicts
  repo upload .

Test: android compiles and boots and no observed problems.
Change-Id: Ibdc3617c75af6ba0d93756cec1ad5ae229e3d5e2
2018-11-18 08:46:50 -08:00
Nicolas Iooss
b4b0074294
libselinux: selinux_restorecon: fix printf format string specifier for uint64_t
fc_count is defined as uint64_t, which needs to be printed with PRIu64
(it is "llu" on x86 and "lu" on x86-64). Otherwise, building with
'CC="gcc -m32"' fails with:

    selinux_restorecon.c: In function ‘restorecon_sb’:
    selinux_restorecon.c:633:26: error: format ‘%lu’ expects argument of
    type ‘long unsigned int’, but argument 3 has type ‘uint64_t’ {aka
    ‘long long unsigned int’} [-Werror=format=]
         fprintf(stdout, "\r%luk", fc_count / STAR_COUNT);
                            ~~^
                            %llu

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2018-11-10 17:32:06 +01:00
Yabin Cui
0105497de0 Merge "libselinux: add fromRunAs input selector in seapp_contexts." 2018-11-08 17:55:30 +00:00
Yabin Cui
5fa9987e1b libselinux: add fromRunAs input selector in seapp_contexts.
It allows setting rules for setcontext requests from run-as.

Bug: 118737210
Test: boot marlin and run CtsSimpleperfTestCases.

Change-Id: I2616d624576e03107230a54ad021c0a8c6a071bd
2018-11-06 15:21:13 -08:00
Nick Kralevich
1ad3304eae Merge remote-tracking branch 'aosp/upstream-master' into mymerge
In particular, pulls in
3f99b14939
which is needed for b/118685852

Followed the following steps:
  # In repo client
  cd external/selinux
  repo sync .
  repo start mymerge .
  git merge aosp/upstream-master --no-ff # resolve any conflicts
  repo upload .

Bug: 118685852
Test: Android compiles and no obvious problems.
Change-Id: Ic8f1bb2b573a1491b733732653afd7dbe494c85f
2018-11-05 06:41:36 -08:00
Stephen Smalley
3f99b14939 libselinux: fix overly strict validation of file_contexts.bin
load_mmap and regex_load_mmap (in the !USE_PCRE2 case) were
incorrectly treating the absence of any fixed stems or study data
as an error, rejecting valid file_contexts.bin files.  Remove
the extraneous validation checks.

Test:
$ cat > file_contexts <<EOF
(/.*)?                u:object_r:system_file:s0
/lib                   u:object_r:system_dir:s0
EOF
$ sefcontext_compile file_contexts
$ selabel_lookup -b file -k /lib -f file_contexts.bin

Before:
ERROR: selabel_open - Could not obtain handle.

After:
Default context: u:object_r:system_dir:s0

Reported-by: Jiyong Park <jiyong@google.com>
Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
2018-11-05 09:31:45 -05:00
Elliott Hughes
ee87941ab7 Add more functions to the host libselinux.
I'd like to build the exact same toybox binary for the host as for the
device, with the aim of getting a more hermetic build without maintaining
two toyboxes.

Bug: N/A
Test: builds
Change-Id: Ib6a1775100e43722ddf1dcfcc13e85703c9986f1
2018-10-04 16:13:14 -07:00
Nick Kralevich
72ba6b4369 Merge remote-tracking branch 'aosp/upstream-master' into manualmerge
In particular, this merges in
https://github.com/SELinuxProject/selinux/pull/99 , which makes Android
builds quieter.

Followed the following steps:

  # In repo client
  cd external/selinux
  repo sync .
  repo start mymerge .
  git merge aosp/upstream-master --no-ff # resolve any conflicts
  repo upload .

Test: compiles/boots no problems.
Bug: 115998215
Change-Id: I0be55971cfc0c18722ff0ac755864b1b4b6657e0
2018-09-21 12:58:18 -07:00
Peter Collingbourne
0122099251 Export some additional symbols from libselinux.
This will allow certain other platform components to link against
libselinux dynamically instead of statically.
2018-09-13 14:34:12 -07:00
Steven Moreland
080ddd2df0 Fix vendor situation for selinux_log_callback.
Add a new function selinux_vendor_log_callback to support
    the non-VNDK vendor case (where /system/etc/event-log-tags
    isn't available for consistency of all PRODUCT_FULL_TREBLE
    devices whether they are VNDK or the legacy VNDK).

Bug: 113083310
Test: boot Pixel 1, use new APIs in vndservicemanager, check
      for denials.
Change-Id: I032dbb6e6fb5d9b825feab9dee0de617c055cfe2
2018-09-07 15:07:42 -07:00
liwugang
89fd318c81 Check the length of the line_buf before reading it
When some lines begin with '\0' in the XXX_seapp_contexts files,
the length of their lines will be 0 and the index(length -1) which
read the line_buf will be -1. So need to check the length of the
line_buf before reading.

Test: add "\000 this line begin with 0\n" to XXX_seapp_contexts files
Change-Id: I0e6d1d99b2cabf1beec24f8d6e38341ef0f1117b
Signed-off-by: liwugang <liwugang@xiaomi.com>
2018-08-24 11:13:26 +08:00
Hollis Blanchard
70b9658d8c
Fix build break around __atomic_*() with GCC<4.7
The __atomic_* GCC primitives were introduced in GCC 4.7, but Red Hat
Enterprise Linux 6.x (for example) provides GCC 4.4. Tweak the current code to
use the (most conservative) __sync_synchronize() primitive provided by those
older GCC versions.

Fixes https://github.com/SELinuxProject/selinux/issues/97

(Really, no __atomic or __sync operations are needed here at all, since POSIX
4.12 "Memory Synchronization" says pthread_mutex_lock() and
pthread_mutex_unlock() "synchronize memory with respect to other threads"...)
2018-08-22 22:56:08 +02:00
Nicolas Iooss
70c06e38be
libselinux: add a const to suppress a build warning with Python 3.7
On systems using Python 3.7, when compiling libselinux Python wrappers
(with "make install-pywrap"), the following warning is reported by gcc:

    audit2why.c: In function ‘analyze’:
    audit2why.c:364:11: warning: assignment discards ‘const’ qualifier
    from pointer target type [-Wdiscarded-qualifiers]
       permstr = _PyUnicode_AsString( strObj );
               ^

Make permstr "const char *" in order to suppress this warning.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2018-08-19 17:55:13 +02:00
Nicolas Iooss
646bdeb939
libselinux: fix flake8 warnings in SWIG-generated code
flake8, a Python linter, complains:

    libselinux/src/selinux.py💯1: F401 'errno' imported but unused
    libselinux/src/selinux.py💯1: F401 'stat' imported but unused
    libselinux/src/selinux.py💯14: E401 multiple imports on one line
    libselinux/src/selinux.py:130:16: E111 indentation is not a multiple of four
    libselinux/src/selinux.py:130:45: E231 missing whitespace after ','

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2018-08-15 22:12:07 +02:00
Nick Kralevich
4d25411b3a Merge remote-tracking branch 'aosp/upstream-master' into mymerge
Followed the following steps:

  # In repo client
  cd external/selinux
  repo sync .
  repo start mymerge .
  git merge aosp/upstream-master --no-ff # resolve any conflicts
  repo upload .

Test: compiles/boots no problems.
Change-Id: I4cd9f73fbbb818ef7fa07ff8dd183f8a7e892345
2018-08-06 13:55:59 -07:00
Yuri Chornoivan
f032946cf9 Fix minor typos
Signed-off-by: Yuri Chornoivan <yurchor@ukr.net>
2018-06-30 20:28:25 +02:00
Jiyong Park
5340684e43 Export more symbols for init
Following symbols from libselinux are used by init. They need to be
exposed in order for the init to dynamically link to libselinux.

Note that this does not affect symbols visibility to vendor, which is
controlled by other map file, exported_vendor.map.

Bug: 63673171
Test: m -j
Test: adb reboot recovery
Change-Id: Ic149801b60fc739ab99f29711a522d460001a293
2018-06-19 16:51:29 +09:00
Laurent Bigonville
ad83ab51c0 libselinux: fix the whatis line for the selinux_boolean_sub.3 manpage
Signed-off-by: Laurent Bigonville <bigon@bigon.be>
2018-05-30 22:07:49 +02:00
Laurent Bigonville
c6629b0db8 libselinux: Fix line wrapping in selabel_file.5
Fix line wrapping with limited to 80 columns

Fix lintian error:
W: selinux-utils: manpage-has-errors-from-man usr/share/man/man5/selabel_file.5.gz 104: warning [p 2, 10.0i]: cannot adjust line

Signed-off-by: Laurent Bigonville <bigon@bigon.be>
2018-05-30 22:07:49 +02:00
Laurent Bigonville
f42c3d4564 libselinux: Fix spelling errors in manpages
Signed-off-by: Laurent Bigonville <bigon@bigon.be>
2018-05-30 22:07:48 +02:00
Stephen Smalley
a9f8a101fd Update VERSIONs to 2.8 for release.
Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
2018-05-24 14:21:09 -04:00
Jason Zaman
ab0e27003e libselinux: enable linking to musl-fts
Musl libc does not include the fts(3) functions so need to link to the
musl-fts library
https://github.com/pullmoll/musl-fts

Signed-off-by: Jason Zaman <jason@perfinion.com>
2018-05-17 13:07:33 +08:00
Stephen Smalley
20c9b4971e Update VERSION files to 2.8-rc3
Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
2018-05-10 11:08:22 -04:00
Stephen Smalley
c41633b90e libselinux: audit2why: fix build warnings
Fix the following build warnings.

audit2why.c: In function ‘__policy_init’:
audit2why.c:207:22: warning: ‘%s’ directive output may be truncated writing up to 4095 bytes into a region of size 4081 [-Wformat-truncation=]
      "unable to open %s:  %s\n",
                      ^~
      path, strerror(errno));
      ~~~~
audit2why.c:206:4: note: ‘snprintf’ output 20 or more bytes (assuming 4115) into a destination of size 4096
    snprintf(errormsg, sizeof(errormsg),
    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      "unable to open %s:  %s\n",
      ~~~~~~~~~~~~~~~~~~~~~~~~~~~
      path, strerror(errno));
      ~~~~~~~~~~~~~~~~~~~~~~
audit2why.c:253:28: warning: ‘%s’ directive output may be truncated writing up to 4095 bytes into a region of size 4074 [-Wformat-truncation=]
     "invalid binary policy %s\n", path);
                            ^~     ~~~~
audit2why.c:252:3: note: ‘snprintf’ output between 24 and 4119 bytes into a destination of size 4096
   snprintf(errormsg, sizeof(errormsg),
   ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     "invalid binary policy %s\n", path);
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
2018-05-08 08:11:58 -04:00
Stephen Smalley
e76569f863 libselinux: avcstat: fix build warning
Fix the following build warning.

avcstat.c: In function ‘main’:
avcstat.c:113:4: error: ‘strncpy’ specified bound 4096 equals destination size [-Werror=stringop-truncation]
    strncpy(avcstatfile, optarg, sizeof avcstatfile);
    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
2018-05-08 08:11:58 -04:00
Stephen Smalley
8467979d41 libselinux: fix build warning in save_booleans()
Fix the following warning in save_booleans().  We could likely drop
the function altogether, either ignoring or returning EINVAL if
a non-zero permanent argument is passed to security_set_boolean_list(),
since setting persistent booleans is now handled via libsemanage.  This
code and the corresponding security_load_booleans() code is legacy from
RHEL4 days and could be removed although we would need to keep the ABI
for compatibility.

booleans.c: In function ‘save_booleans’:
booleans.c:441:13: error: ‘%d’ directive output may be truncated writing between 1 and 11 bytes into a region of size between 0 and 8191 [-Werror=format-truncation=]
         "%s=%d\n", boolname,
             ^~
booleans.c:440:7: note: ‘snprintf’ output between 4 and 8205 bytes into a destination of size 8192
       snprintf(outbuf, sizeof(outbuf),
       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
         "%s=%d\n", boolname,
         ~~~~~~~~~~~~~~~~~~~~
         boollist[i].value);
         ~~~~~~~~~~~~~~~~~~
booleans.c:454:12: error: ‘%d’ directive output may be truncated writing between 1 and 11 bytes into a region of size between 0 and 8191 [-Werror=format-truncation=]
        "%s=%d\n", boolname, val);
            ^~
booleans.c:453:6: note: ‘snprintf’ output between 4 and 8205 bytes into a destination of size 8192
      snprintf(outbuf, sizeof(outbuf),
      ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        "%s=%d\n", boolname, val);
        ~~~~~~~~~~~~~~~~~~~~~~~~~

Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
2018-05-08 08:11:58 -04:00
Jiyong Park
b6ef6eb45c Mark as recovery_available: true
Libraries that are direct or indirect dependencies of modules installed
to recovery partition (e.g. toybox) are marked as recovery_available:
true. This allows a recovery variant of the lib is created when it is
depended by other recovery or recovery_available modules.

Bug: 67916654
Bug: 64960723
Test: m -j
Change-Id: I63d83278c0f80e1053e92d076e78d41e10270ba4
2018-04-27 21:48:24 +09:00
Stephen Smalley
dc03bae194 Update VERSION files to 2.8-rc2.
Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
2018-04-26 13:20:40 -04:00
Stephen Smalley
87a58b6b4e Revert "libselinux: verify file_contexts when using restorecon"
This reverts commit 814631d3ae.
As reported by Petr Lautrbach, this commit changed the behavior
of selabel_open() when SELABEL_OPT_VALIDATE is 0, and this would
be an API change.

Reported-by: Petr Lautrbach <plautrba@redhat.com>
Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
2018-04-20 10:12:57 -04:00
Treehugger Robot
638e19a885 Merge "libselinux: android: allow dup *_context entries" 2018-04-19 19:22:35 +00:00
Jeff Vander Stoep
5f6217efcf libselinux: android: allow dup *_context entries
Similar to upstream commit 742a350d "libsepol/cil: Improve processing
of context rules", allow multiple-same mappings, but make this the
default for android-specific *_contexts files. Continue to print a
warning. This is useful for Treble where some device-specific
mappings may be moved to core policy. e.g.
https://android-review.googlesource.com/c/platform/system/sepolicy/+/663068.
Old vendor images must continue to work with new system images even
when they contain the same mapping.

Bug: 78134108
Test: Verify multiple same mappings load correctly, and multiple
different specs continue to fail.

Change-Id: I80e81814b7ce213489a7820a12be3fb297150e7d
2018-04-19 07:53:50 -07:00
Stephen Smalley
f04d64012a Update VERSION files to 2.8-rc1
Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
2018-04-19 10:40:16 -04:00
Treehugger Robot
c9806e8562 Merge "Add security_get_initial_context to the exported.map." 2018-04-19 00:09:14 +00:00
Nicolas Iooss
efc77aa209 libselinux: remove unused variable usercon
In getconlist.c, main() does not use usercon. Remove this variable.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2018-04-17 13:55:57 -07:00
Nicolas Iooss
5f76f6b8fb libselinux: fix memory leak in getconlist
In getconlist.c's main(), "level" is duplicated from an optional
argument without being ever freed. clang's static analyzer warns about
this memory leak.

Free the allocated memory properly in order to remove a warning reported
by clang's static analyzer.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2018-04-17 13:55:57 -07:00
Nicolas Iooss
c56bb631c4 libselinux: label_file: fix memory management in store_stem()
If store_stem() fails to expand the memory allocated on data->stem_arr,
some things go wrong:
* the memory referenced by "buf" is leaked,
* data->alloc_stems has been increased without data->stem_arr having
  been expanded. So the next time store_stem() is called, the function
  will behave as if the buffer holds enough space, and will write data
  after the end of data->stem_arr.

The first issue is being spotted by clang's static analyzer, which warns
about leaking variable "stem" in find_stem_from_spec() (this function
calls store_stem()).

This both issues by freeing buf when realloc(data->stem_arr) fails, and
by not increasing data->alloc_stems when this happens.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
2018-04-17 13:55:57 -07:00
yusukes
1e9c093e13 Log setxattr(RESTORECON_LAST) failures
Setting the attribute may actually fail with EPERM when Android
is running inside a container. The log is useful at least for
such an environment.

Bug: 62417973
Test: Run the OS inside a container, then check logcat logs.

Change-Id: I5e4243ee545dfaa486f85d7d691e32d7f1c2a303
2018-04-10 20:07:53 +00:00
Robert Sesek
35a33f5b8e Add security_get_initial_context to the exported.map.
This will be used by ss(8) in platform/external/iproute2.

Test: With topic merged, `m` and `adb shell ss -Z` shows SELinux labels.
Change-Id: I30d5e180fee1c9d99ba8d31586468f83ffd3e177
2018-04-09 16:15:42 -04:00
Yuli Khodorkovskiy
3e47c239ec libselinux: echo line number of bad label in selabel_fini()
Keep track of line numbers for each file context in
selabel_handle. If an error occurs in selabel_fini(), the
line number of an invalid file context is echoed to the user.

Signed-off-by: Yuli Khodorkovskiy <ykhodo@gmail.com>
2018-04-04 11:09:11 -05:00
Yuli Khodorkovskiy
814631d3ae libselinux: verify file_contexts when using restorecon
In permissive mode, calling restorecon with a bad label in file_contexts
does not verify the label's existence in the loaded policy. This
results in any label successfully applying to a file, as long as the
file exists.

This issue has two assumptions:

1) file_contexts must be manually updated with the invalid label.
Running `semanage fcontext` will error when attempting to add
an invalid label to file_contexts.
2) the system must be in permissive. Although applying an invalid label
in enforcing gives an error and fails, successfully labeling a file with a
bad label could cause issues during policy development in permissive.

Instead, as each context is used, verify it is valid before blindly
applying the label. If an error with validation occurs in restorecon,
application of remaining valid labels will be uninterrupted as before.

Signed-off-by: Yuli Khodorkovskiy <ykhodo@gmail.com>
2018-04-04 11:09:11 -05:00
Jeff Vander Stoep
bfe7a7cb53 Merge remote-tracking branch 'aosp/upstream-master' into mymerge
Bug: 72757373
Test: build and run aosp_taimen-userdebug
Change-Id: I1ea08e95205d0aba661b7251c790e153f128f4cf
2018-03-26 16:13:05 -07:00
Nicolas Iooss
07629c0a9f
libselinux,libsemanage: Replace PYSITEDIR with PYTHONLIBDIR
libselinux and libsemanage Makefiles invoke site.getsitepackages() in
order to get the path to the directory /usr/lib/pythonX.Y/site-packages
that matches the Python interpreter chosen with $(PYTHON). This method
is incompatible with Python virtual environments, as described in
https://github.com/pypa/virtualenv/issues/355#issuecomment-10250452 .
This issue has been opened for more than 5 years.

On the contrary python/semanage/ and python/sepolgen/ Makefiles use
distutils.sysconfig.get_python_lib() in order to get the site-packages
path into a variable named PYTHONLIBDIR. This way of computing
PYTHONLIBDIR is compatible with virtual environments and gives the same
result as PYSITEDIR.

As PYTHONLIBDIR works in more cases than PYSITEDIR, make libselinux and
libsemanage Makefiles use it. And as native code is installed (as part
of the SWIG wrapper), use "plat_specific=1" in order to use /usr/lib64
on systems which distinguish /usr/lib64 from /usr/lib.

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
Acked-by: Petr Lautrbach <plautrba@redhat.com>
2018-03-17 09:03:33 +01:00
Bowgo Tsai
f7071895b1 Allow odm_file_contexts to be empty
There might be an empty odm_file_contexts when BOARD_ODM_SEPOLICY_DIRS
is defined. Skip reading empty file_contexts files in function
compute_file_contexts_hash(), instead of returning an error, which makes
device doesn't boot.

Bug: 64240127
Test: boot a device having an empty odm_file_contexts

Change-Id: I359da5fce17eedb65ce288bb2781e61e8ade3cf9
2018-03-16 15:59:42 +08:00
Marcus Folkesson
b24980ec07 libselinux: build: follow standard semantics for DESTDIR and PREFIX
This patch solves the following issues:
- The pkg-config files generates odd paths when using DESTDIR without PREFIX
- DESTDIR is needed during compile time to compute library and header paths which it should not.
- Installing with both DESTDIR and PREFIX set gives us odd paths
- Make usage of DESTDIR and PREFIX more standard

Signed-off-by: Marcus Folkesson <marcus.folkesson@gmail.com>
2018-02-14 15:59:36 +01:00
Richard Haines
8bcee84421 libselinux: Correct manpages regarding removable_context
The selabel_media(5) man page incorrectly stated that the
removable_context(5) would be read if an selabel_lookup(3)
failed. Correct the man pages that fixes [1].

[1] https://bugzilla.redhat.com/show_bug.cgi?id=1395621

Signed-off-by: Richard Haines <richard_c_haines@btinternet.com>
2018-01-13 10:49:13 -08:00
Treehugger Robot
31a6155a15 Merge "libselinux: fix build warning" 2018-01-11 16:59:12 +00:00
liuchao
81e7095388 libselinux: fix build warning
Fix build warning -Wunused-function & -Wunused-variable

Test: Build Test
Change-Id: I7f949709309163e81e9d1133c5103be92cc14de8
2017-12-20 15:57:23 +08:00
Steven Moreland
2b0f03187a Consolidate Treble vs. Non-Treble difference.
Just always read and process vendor policies if they are there.

Bug: 62019611
Test: marlin boots (which is Treble)
Test: bullhead boots (which is non-Treble)
Change-Id: I0483b8c911558c920d55c77a9b4f59d6074ed264
2017-12-20 00:32:13 +00:00