NB SEforAndroid 1

From SELinux Wiki

Jump to: navigation, search


[edit] Security Enhancements for Android

[edit] Introduction

This section gives an overview of the enhancements made to Android to produce Security Enhancements for Android&trade (SE for Android).

The main objective of this document is to provide a reference for the tools, commands, policy building tools and file formats of SE for Android based on the 4.4 release. The builds discussed are from AOSP master and SEAndriod master repositories (as July '14).

The AOSP git repositories can be found at https://android.googlesource.com and the SEAndroid enhancements at https://bitbucket.org/seandroid.

For up to date information on the status of SE for Android the following should be consulted: http://seandroid.bitbucket.org/.

[edit] Terminology

This section describes how the terms SE for Android, AOSP and SEAndroid are used in this document.

SE for Android Used to describe the overall framework for implementing SELinux mandatory access control (MAC) and Middleware mandatory access control (MMAC) on Android.
AOSP The Android code base distributed by Google (see http://source.android.com/source/downloading.html). Release 4.4 contains SELinux support that is described at http://source.android.com/devices/tech/security/se-linux.html.

AOSP contains the core SELinux MAC functionality with the Install-time MMAC framework and policy as described in the Building the Policy section (also see http://seandroid.bitbucket.org/MergeStatus.html#2 for the latest status).

AOSP also contains services to allow the updating of Intent Firewall policies, however currently no files are installed (although SEAndroid supplies a sample and update tools).

SEAndroid The SEAndroid project enhancements are decreasing as more features move into AOSP. The additional SEAndroid features are:
  1. Enhanced MAC policy.
  2. Installation of Enterprise Operations (EOps) configuration files.
  3. Sample EOps and Intent Firewall configuration files (the actual services are supplied by AOSP, replacing the SEAndroid Intent MMAC, Content Provider MMAC and Revoke Permissions services that are now obsolete).
  4. Tools to manage bundles for policy, EOps and Intent Firewall updates.

See the SE for Android project page for up-to-date details at http://seandroid.bitbucket.org/

[edit] Useful Links

The following link describes how to validate SELinux in Android:


The http://seandroid.bitbucket.org/ pages describe the current merge status with AOSP, how to obtain the code, install SE for Android and the features that have been implemented. It also has useful reference papers with "Security Enhanced (SE) Android: Bringing Flexible MAC to Android" available at http://www.internetsociety.org/sites/default/files/02_4.pdf being a recommended read.

The white paper "An Overview of Samsung KNOX" also gives an overview of how SE for Android is being integrated with other security services (such as secure boot and integrity measurement) to help provide a more secure mobile platform.

[edit] Document Sections

The sections that follow cover:

  • Overview of Android package additions and updates to support MAC
  • Additional kernel LSM / SELinux support
  • SE for Android Classes & Permissions
  • SELinux commands and methods to support SE for Android
  • SELinux extensions for init
  • Policy construction and build
    • Build file locations
    • Policy files
    • Build tools
  • Logging and auditing
  • SE for Android libselinux additional functions
  • Object labeling configuration file details

[edit] SE for Android Project Updates

This gives a high level view of the new and updated projects to support SE for Android services and covers AOSP with any additional SEAndroid functions noted. These are not a complete set of updates, but give some idea of the scope.

Provides the SELinux userspace function library that is installed on the device. It is based on the Linux version but has additional functions to support Android, for example:
Sets the correct domain context when launching applications using setcon(3). Information contained in the seapp_contexts file is used to compute the correct context.
It is called by frameworks/base/core/jni/com_android_internal_os_Zygote.cpp when forking a new process and the system/core/run-as/run-as.c utility.
Sets the correct context on application directory / files using setfilecon(3). Information contained in the seapp_contexts file is used to compute the correct context.
The function is used by the package installer within frameworks/native/cmds/installd/commands.c via the package install() and make_user_data() functions.
Basically these functions are used to label files and directories based on entries from the file_contexts and/or seapp_contexts files. They call a common handler (selinux_android_restorecon_common()) that will then relabel the requested directories and files. It will also handle recursive labeling of directories and files should a new app, file_contexts or seapp_contexts be installed (see the Checking File Labels section for further information).
The selinux_android_restorecon function is used by:
frameworks/native/cmds/installd/installd.c when installing a new app.
frameworks/base/core/jni/android_os_SELinux.cpp for the Java native_restorecon method.
frameworks/native/cmds/dumpstate/utils.c when dumping Dalvik and stack traces to ensure correct label.
The selinux_android_restorecon_pkgdir function is used by:
frameworks/native/cmds/installd/commands.c for the package restorecon_data() and make_user_data() functions.
Loads the seapp_contexts file for frameworks/native/cmds/installd/installd.c when the package installer is loaded.
Mounts the SELinux filesystem if SELinux is enabled and then calls selinux_android_reload_policy to load the policy into the kernel. Used by system/core/init/init.c to initialise SELinux.
Reloads the policy into the kernel. Used by system/core/init/init.c selinux_reload_policy() to reload policy after setting the selinux.reload_policy property.
Used by system/core/init/init.c to decide which policy directory to load the property_contexts file from.
There is also a new labeling service for selabel_lookup(3) to query the Android property_contexts and service_contexts files.
Various Android services will also call (not a complete list):
selinux_status_updated(3), is_selinux_enabled(3), to check whether anything changed within the SELinux environment (e.g. updated configuration files).
selinux_check_access(3) to check if the source context has access premission for the class on the target context.
selinux_label_open(3), selabel_lookup(3), selinux_android_file_context_handle, selinux_android_prop_context_handle, setfilecon(3), setfscreatecon(3) to manage file labeling.
selinux_lookup_best_match called by system/core/init/devices.c when ueventd creates a device node as it may also create one or more symlinks (for block and PCI devices). Therefore a "best match" look-up for a device node is based on its real path, plus any links that may have been created (see patches https://android.googlesource.com/platform/system/core/+/b0ab94b7d5a888f0b6920b156e5c6a075fa0741a, https://android.googlesource.com/platform/system/core/+/b4c5200f51c3568f604a4557119ab545a6ddac94 and https://android.googlesource.com/platform/external/libselinux/+/be7f5e8814c4954aca51d3f95455c5d9d527658c).
Provides the policy userspace library. There are no specific updates to support SE for Android, also this library is not available on the device.
Provides the policy build tool. Added support for MacOS X (darwin). Not available on the device as policy rebuilds are done in the development environment.
This is a policy specifically for the core components of SE for Android that looks much like the reference policy, but is contained in one directory that has the policy modules (*.te files), class / permission files etc.. The policy is built by the Android.mk file and the resulting policy is installed on the target device (as sepolicy) along with its supporting configuration files.
Device specific policy may be defined under the device directory as discussed in the Processing Device Policy section.
The policy can be updated along with its configuration files as discussed in the Updating Policy section.
The policy files are discussed in the SELinux MAC Policy Files section and support tools in the [NB_SEforAndroid_2#Policy_Build_Tools|Policy Build Tools] section.
The Android specific object classes are described in the SE for Android Classes and Permissions section.
The directory also contains sample MMAC configuration files.
mkyaffs2image support for labeling and extended attributes (xattr)
This is an Android application to manage the SE for Android environment (such as loading a new policy). Only available on SEAndroid build.
SELinux settings for the settings manager application.
Bionic is the Android libc that is a derived from the BSD standard C library code. It contains enhancements to support security providers such as SELinux.
Changes to manage file labeling on recovery.
Changes to build SE for Android and manage file labeling on images and OTA (over the air) target files.
JNI - Add SELinux support functions such as isSELinuxEnabled and setFSCreateCon.
SELinux Java class and method definitions.
Checking Zygote connection contexts.
Managing file permissions for the package manager and wallpaper services.
SELinux additions to support install / run time MMAC and for SEAndroid the MMAC services.
SELinux support services for toolbox (e.g. load_policy, runcon).
SELinux support for system initialisation (e.g. init, init.rc).
SELinux support for auditing avc's (auditd).
SELinux support for the ext4 file system. Note that the make_ext4fs utility is used to build these file systems and relies on the file_contexts file having all the relevant entries, if not, it will be unable to set the security.selinux xattr on the inode and fail.
There are a number of kernels that have been enhanced to support Linux Security Module (LSM) and SELinux services that are listed at:
Note that the Android kernels are based on various versions (currently 3.4 for Goldfish used by the emulator), therefore the latest SELinux enhancements may not always be present. The Kernel LSM / SELinux Support section describes the Andriod kernel changes.
Build information for each device, details regarding SEAndroid supported devices can be found at:
Device specific policy can be added as discussed in the Building the Policy and Processing Device Policy sections.

[edit] Kernel LSM / SELinux Support

The paper "Security Enhanced (SE) Android: Bringing Flexible MAC to Android" available at http://www.internetsociety.org/sites/default/files/02_4.pdf gives a good review of what did and didn't change in the kernel to support Android. This section briefly describes the only major change that was to support the Binder IPC service that consists of the following:

  1. LSM hooks in the binder code (drivers/staging/android/binder.c) and (include/linux/security.h)
  2. Default support for capabilities (security/capability.c) in case no other module is loaded.
  3. Hooks in the LSM security module (security/security.c).
  4. SELinux support for the binder object class and permissions (security/selinux/include/classmap.h) that are shown in the SE for Android Classes and Permissions section. Support for these permission checks are added to security/selinux/hooks.c.

[edit] SE for Android Classes and Permissions

Additional classes have been added to SE for Android and are listed in the following tables with descriptions of their permissions:

binder class - This is a kernel object to manage the Binder IPC service.
Permission Description (4 unique permissions)
call Perform a binder IPC to a given target process (can A call B?).
impersonate Perform a binder IPC on behalf of another process (can A impersonate B on an IPC?).

Not currently used in policy but kernel (selinux/hooks.c) checks permission in selinux_binder_transaction call.

set_context_mgr Register self as the Binder Context Manager aka servicemanager (global name service). Can A set the context manager to B, where normally A == B.

See policy module servicemanager.te.

transfer Transfer a binder reference to another process (can A transfer a binder reference to B?).

zygote class - This is a userspace object to manage the Android application loader. See Java SELinux.checkSELinuxAccess() in frameworks/base/core/java/com/android/internal/os/ZygoteConnection.java
Permission Description (4 unique permissions)
specifyids Peer may specify uid’s or gid’s.
specifyrlimits Peer may specify rlimits.
specifyinvokewith Peer may specify --invoke-with to launch Zygote with a wrapper command.
specifyseinfo Specify a seinfo string for use in determining the app security label.

property_service class - This is a userspace object to manage the Android Property Service. See check_mac_perms() in system/core/init/property_service.c
Permission Description (1 unique permission)
set Set a property.

service_manager class - This is a userspace object to manage Android services. See check_mac_perms() in frameworks/native/cmds/servicemanager/service_manager.c
Permission Description (3 unique permission)
add Add a service.
find Find a service.
list List services.

keystore_key class - This is a userspace object to manage the Android keystore (see system/security/keystore/keystore.cpp).
Permission Description (16 unique permissions)
test Test if keystore okay.
get Get key.
insert Insert/update key.
delete Delete key.
exist Check if key exists.
saw Search for matching string.
reset Reset keystore.
password Generate new keystore password.
lock Lock keystore.
unlock Unlock keystore.
zero Check if keystore empty.
sign Sign data.
verify Verify data.
grant Add or remove access.
duplicate Duplicate the key.
clear_uid Clear keys for this uid.

debuggerd class - This is a userspace object to allow file dumps (see system/core/debuggerd/debuggerd.cpp).
Permission Description (2 unique permissions)
dump_tombstone Write tombstone file.
dump_backtrace Write backtrace file.

drmservice class - This is a userspace object to allow finer access control of the Digital Rights Management services (see frameworks/av/drm/drmserver/DrmManagerService.cpp).
Permission Description (8 unique permissions)
consumeRights Consume rights for content.
setPlaybackStatus Set the playback state.
openDecryptSession Open the DRM session for the requested DRM plugin.
closeDecryptSession Close DRM session.
initializeDecrypSession Initialise the decrypt resources.
decrypt Decrypt data stream.
finalizeDecryptUnit Release DRM resources.
pread Read the data stream.

[edit] SELinux Commands

A subset of the Linux SELinux commands have been implemented in SE for Android and are listed in Table 1. They are available as Toolbox commands (see system/core/toolbox) and can be run via adb shell, for example:

adb shell su 0 setenforce permissive

Table 1: SELinux enabled adb shell commands (in Android toolbox)

Command Comment
chcon Change security context of file:
chcon context path
getenforce Returns the current enforcing mode.
getsebool Returns SELinux boolean value(s):
getsebool [-a | boolean_name]
id If SELinux is enabled then the security context is automatically displayed.
load_policy Load new policy into kernel:
load_policy policy-file
ls Supports -Z option to display security context.
ps Supports -Z option to display security context.
restorecon Restore file default security context as defined in the file_contexts or seapp_contexts files. The options are: D - data files, F - Force reset, n - do not change, R/r - Recursive change, v - Show changes.
restorecon [-DFnrRv] pathname
runcon Run command in specified security context:
runcon context program args...
setenforce Modify the SELinux enforcing mode:
setenforce [enforcing|permissive|1|0]
setsebool Set SELinux boolean to a value (note that the cmd does not set the boolean across reboots):
setsebool boolean_name [1|true|on|0|false|off]

[edit] SELinux Public Methods

The public methods implemented are equivalent to libselinux functions and are show in Table 2. They have been taken from frameworks/base/core/java/android/os/SELinux.java.

The SELinux class and its methods are not available in the Android SDK, however if developing SELinux enabled apps within AOSP then reflection would be used (see the proguard.flags and Android.mk files in packages/apps/SEAdmin).

Table 2: SELinux class public methods

boolean isSELinuxEnabled()
   Determine whether SELinux is enabled or disabled. 
   Return true if SELinux is enabled.
boolean isSELinuxEnforced()
   Determine whether SELinux is permissive or enforcing.
   Returns true if SELinux is enforcing.
boolean setSELinuxEnforce(boolean value)
   Set whether SELinux is in permissive or enforcing modes.
   value of true sets SELinux to enforcing mode.
   Returns true if the desired mode was set.
boolean setFSCreateContext(String context)
   Sets the security context for newly created file objects.
   context is the security context to set.
   Returns true if the operation succeeded.
boolean setFileContext(String path, String context)
   Change the security context of an existing file object.
   path represents the path of file object to relabel.
   context is the new security context to set.
   Returns true if the operation succeeded.
String getFileContext(String path)
   Get the security context of a file object.
   path the pathname of the file object.
   Returns the requested security context or null.
String getPeerContext(FileDescriptor fd)
   Get the security context of a peer socket.
   FileDescriptor is the file descriptor class of the peer socket.
   Returns the peer socket security context or null.
String getContext()
   Gets the security context of the current process.
   Returns the current process security context or null.
String getPidContext(int pid)
   Gets the security context of a given process id.
   pid an int representing the process id to check.
   Returns the security context of the given pid or null.
String[] getBooleanNames()
   Gets a list of the SELinux boolean names.
   Return an array of strings containing the SELinux boolean names.
boolean getBooleanValue(String name)
   Gets the value for the given SELinux boolean name.
   name is the name of the SELinux boolean.
   Returns true or false indicating whether the SELinux boolean is set or not.
boolean setBooleanValue(String name, boolean value)
   Sets the value for the given SELinux boolean name. Note that this will be set the boolean permanently across reboots.
   name is the name of the SELinux boolean.
   value is the new value of the SELinux boolean.
   Returns true if the operation succeeded.
boolean checkSELinuxAccess(String scon, String tcon, String tclass, String perm)
   Check permissions between two security contexts.
   scon is the source or subject security context.
   tcon is the target or object security context.
   tclass is the object security class name.
   perm is the permission name.
   Returns true if permission was granted.
boolean native_restorecon(String pathname)
   Restores a file to its default SELinux security context. If the system is not compiled with SELinux, then true is automatically returned. If SELinux is compiled in, but disabled, then true is returned.
   pathname is the pathname of the file to be relabeled.
   Returns true if the relabeling succeeded.
boolean restorecon(String pathname)
   Restores a file to its default SELinux security context. If the system is not compiled with SELinux, then true is automatically returned. If SELinux is compiled in, but disabled, then true is returned.
   pathname is the pathname of the file to be relabeled.
   Returns true if the relabeling succeeded.
   exception NullPointerException if the pathname is a null object.
boolean restorecon(File file)
   Restores a file to its default SELinux security context. If the system is not compiled with SELinux, then true is automatically returned. If SELinux is compiled in, but disabled, then true is returned.
   file is the file object representing the path to be relabeled. 
   Returns true if the relabeling succeeded.
   exception NullPointerException if the file is a null object.

[edit] Android Init Language SELinux Extensions

The Android init process language has been expanded to support SELinux as shown in Table 3. The complete Android init language description is available in the system/core/init/readme.txt file.

Table 3: SELinux init extensions

seclabel <securitycontext>

service option: Change to security context before exec'ing this service. Primarily for use by services run from the rootfs, e.g. ueventd, adbd. Services on the system partition can instead use policy defined transitions based on their file security context. If not specified and no transition is defined in policy, defaults to the init context.

restorecon <path>

action command: Restore the file named by <path> to the security context specified in the file_contexts configuration. Not required for directories created by the init.rc as these are automatically labeled correctly by init.

restorecon_recursive <path> [ <path> ]*

action command: Recursively restore the directory tree named by <path> to the security context specified in the file_contexts configuration. Do NOT use this with paths leading to shell-writable or app-writable directories, e.g. /data/local/tmp, /data/data or any prefix thereof.

See the Checking File Labels section for further details.

setcon <securitycontext>

action command: Set the current process security context to the specified string. This is typically only used from early-init to set the init context before any other process is started (see init.rc example above).

setenforce 0|1

action command: Set the SELinux system-wide enforcing status. 0 is permissive (i.e. log but do not deny), 1 is enforcing.

setsebool <name> <value>

action command: Set SELinux boolean <name> to <value>.

<value> may be 1|true|on or 0|false|off

Examples of their usage are shown in the following init.rc file segments:


on early-init

    # Set the security context for the init process.
    # This should occur before anything else (e.g. ueventd) is started.
    setcon u:r:init:s0

    # Set the security context of /adb_keys if present.
    restorecon /adb_keys

    start ueventd

on post-fs-data
    # Reload policy from /data/security if present.
    setprop selinux.reload_policy 1

    # Set SELinux security contexts on upgrade or policy update.</nowiki>
    restorecon_recursive /data
service ueventd /sbin/ueventd
    class core
    seclabel u:r:ueventd:s0

[edit] Device Policy File Locations

Table 4 shows the SE for Android policy files with their default location when the device is built, and their alternate locations when devices are updated by other methods (such as OTA or via adb). The alternate locations are always checked first as if present they override the default location as discussed in the comments section of Table 4.

The init process will initially load the SELinux set of policy files from root (/). Once the /data partition setup has been completed (see init.rc) a policy reload is performed. This will check whether there is a valid policy at /data/security/current and load that if valid.

If safe mode, then only the root policy files will be loaded. A factory reset will wipe /data and will therefore revert to the original root policy files.

Table 4: Policy file locations

Default Location
Alternate Location







/data/security/current Any or all these files may be in the alternate directory as each conponent that requires them will look in the alternate first and then the default, however:
  1. During a policy reload, if there is an selinux_version file in the alternate location, then the default location will be over-ridden. If the policy has been updated via the buildsebundle / SEAdmin app process then this would be the case.
  2. The alternate directory may be a symbolic link to another directory. For example the buildsebundle / SEAdmin app process adds a link to /data/security/context that holds the policy files
  3. If the policy has been updated via the buildsebundle / SEAdmin app process, then the following will also be present:
/data/security/bundle will contain the sepolicy_bundle (the packed files) and a metadata directory containing a version file holding the last version number.
There will be *_backup policy files of the previous version that could be restored if required.

See the Build Bundle Tools - buildsebundle section for a worked example.

/system/etc/security/eops.xml /data/security/eops If the policy has been updated via the buildeopbundle / SEAdmin app process, then the following will also be present in the alternative location:
  • /data/security/eops/eops_metadata/version file holding the last version number.

See the Build Bundle Tools - buildeopbundle section for a worked example.

/data/system/ifw/ifw.xml /data/secure/system/ifw

(default for encrypted systems)

This file is not installed by default and note that the Intent Firewall service will read any file from /data/system/ifw/ so long as it has an .xml extension.

If required would be built and delivered by the buildifwbundle / SEAdmin app process, with the following also present in the default location:

  • /data/system/ifw/metadata/gservices.version file holding the last version number.

See the Build Bundle Tools - buildifwbundle section for a worked example.

/system/etc/sepolicy.recovery none Only used for recovery.

[edit] Building the Policy

This section covers building of SELinux MAC and Install-time MMAC policies. The file formats of SE for Android specific configuration files are detailed in the Policy File Configuration Details section with examples.

[edit] SELinux MAC Policy Files

The policy files are contained in the external/sepolicy directory, however there may also be additional policy configuration files to enable specific device features under the device/<vendor>/<device>/sepolicy directory (see the Processing Device Policy section). Once generated the policy and its supporting configuration files are installed on the device as part of the build process.

[edit] Policy Build Files

The following files are used to build the kernel binary policy file that is named sepolicy and installed by default in the root directory.

access_vectors, security_classes
These have been modified to support the new SE for Android classes and permissions (although they still contain the unused Linux userspace items).
initial_sids, initial_sids_contexts
Contains the system initialisation (before policy is loaded) and failsafe (for objects that would not otherwise have a valid label).
fs_use, genfs_contexts, port_contexts
For flexibility of policy building, these files have been separated to allow additional policy files to be defined for specific devices as discussed below.
users, roles
These define the only user (u) and role (r) used by the policy, although there is no reason why others cannot be added.
Contains the constraints to be applied to the defined classes and permissions.
global_macros, mls_macro, te_marcos
These contain the m4 macros that expand the policy files to build a policy in the kernel policy language as described in Policy Language section. The policy can then be compiled by checkpolicy(8).
Contains the attribute names (forming the attribute statements) that will be used to group type identifiers defined by the policy.
Contains the policy capabilities enabled for the kernel policy (see policycap statement).
The *.te files are the core policy module definition files. These are the same format as the standard reference policy and are expanded by the m4 macros. There is (generally) one .te file for each domain/service defined containing the policy rules.

[edit] Policy Configuration Files

These files will be installed on the device and used to compute SE for Android security contexts (see the Checking File Labels section for further information).

Contains default file contexts for setting the filesystem as Linux based SELinux (note that it does not contain entries for labeling apps or their data stores, the seapp_contexts file is used for that purpose). The format of this file is defined in file_contexts(5)</tt>. The file is installed by default in the root directory. SE for Android services (such as restorecon) will first check for this file at (this is where updated files would be placed):
If not present they will then check the root directory:
Contains default contexts for Android property services as discussed in the property_contexts File section. The file is installed by default in the root directory. The SE for Android initialisation / reload process will first check for this file at (this is where updated files would be placed):
If not present they will then check the root directory:
Contains default contexts for Android services as discussed in the service_contexts File section. The file is installed by default in the root directory. The SE for Android initialisation / reload process will first check for this file at (this is where updated files would be placed):
If not present they will then check the root directory:
Contains information to allow domain or file contexts to be computed based on parameters as discussed in the seapp_contexts File section. The file is installed by default in the root directory. The SE for Android initialisation / reload process will first check for this file at (this is where updated files would be placed):
If not present they will then check the root directory:
This will not be processed by the SE for Android build, it must be specifically added to the device make file if required. See the selinux-network.sh Configuration section for details on configuring this file.

The following files will be built as part of the build process and installed on the device:

The kernel binary policy. The SE for Android initialisation / reload process will first check for this file at (this is where updated files would be placed):
If not present they will then check the root directory:
For reference, the policy text file is available at:
The compiled kernel policy (sepolicy) is also in this directory along with policy.conf.dontaudit and sepolicy.dontaudit files that have the dontaudit rules removed.
A recovery policy is installed at system/etc/sepolicy.recovery. It is build with the macro target_recovery = true that will add additional rules defined in the recovery.te module (see Android.mk and te_macros). For reference the recovery policy text file is available at:
The selinux_version file is generated containing the BUILD_FINGERPRINT that the policy was built against. Its existence is used at boot time, policy upgrades or reloads to determine whether the policy configuration files should be read from /data/security/current or root (/). The mac_permissions.xml would also be read from either /data/security/current or /system/etc/security).

[edit] Install-time MMAC Policy File

The Install-time MMAC is part of AOSP and SEAndroid policy build that is always enabled. The file that configures policy is mac_permissions.xml and its format is discussed in the Install-time MMAC Configuration File section. The file is installed by default at:


The SE for Android initialisation / reload process will first check for this file at:


This file can be replaced through BOARD_SEPOLICY_REPLACE or appended to by the BOARD_SEPOLICY_UNION variable as described in the Processing Device Policy section.

This file can be updated along with all other MAC policy files as described in the Updating Policy section.

The main code for the service is frameworks/base/services/java/com/android/server/pm/SELinuxMMAC.java, however it does hook into other Android services. Note that AOSP and SEAndroid builds now support the same code base which was implemented by https://android-review.googlesource.com/#/c/80871. The change commit message is:

Prior support forced all third party apps to be resolved against the default stanza of the mac_permissions.xml file when assigning seinfo labels. This meant that all third party apps, in effect, were untrusted regardless of cert and therefore received the same SELinux domain. This also had the unfortunate side effect of forcing certain third party apps into the wrong domains because of shared userid requests among apps.
This patch removes that restriction and instead allows all apps, regardless of location, to be matched against the full mac_permissions.xml policy file. This then allows all apps signed with known good certs to receive the same SELinux domains of other apps with whom they share trust.

[edit] Device Specific Policy

Some of this section has been extracted from the external/sepolicy/README file that should be checked in case there have been updates. It describes how files in external/sepolicy can be manipulated during the build process to reflect requirements of different device vendors whose policy files would normally be located in the device/<vendor>/<device>/sepolicy directory.

[edit] Managing Device Policy File

Additional per device policy files may be added or removed during the policy build and are configured through the use of the following four variables that would be added to the device BoardConfig.mk file:


They are used as follows:


BOARD_SEPOLICY_DIRS contains a list of directories to search for files listed by the BOARD_SEPOLICY_UNION and BOARD_SEPOLICY_REPLACE variables. Order matters in this list. e.g. If the following is defined:
and there are two instances of widget.te files on the BOARD_SEPOLICY_DIRS search path, the first one found (at the first search directory containing the file) gets processed first. Reviewing the devices policy.conf[1] will help sort out ordering issues and is located at:


BOARD_SEPOLICY_UNION is a list of files that will be "unioned", i.e. concatenated at the END of their respective files in external/sepolicy
Note to add a unique/new file this variable would be used.


BOARD_SEPOLICY_REPLACE is a list of files that will be used instead of the corresponding file in external/sepolicy.


BOARD_SEPOLICY_IGNORE is a list of paths (directory + filename) of files that are not to be included in the resulting policy. This list is passed to filter-out to remove any paths to be ignored. This is useful if there are numerous configuration directories that contain a file, and that file is NOT to be included in the resulting policy, either by BOARD_SEPOLICY_UNION or BOARD_SEPOLICY_REPLACE.
For example, suppose the following:
with directories X and Y containing a copy of file A. The resulting policy is created by using Y/A only, thus X/A was ignored.

Error Handling:

  • It is an error to specify a BOARD_POLICY_REPLACE file that does not exist in external/sepolicy.
  • It is an error to specify a BOARD_POLICY_REPLACE file that appears multiple times on the policy search path defined by BOARD_SEPOLICY_DIRS.
For example, if shell.te is specified in BOARD_SEPOLICY_REPLACE and BOARD_SEPOLICY_DIRS is set to:
vendor/widget/common/sepolicy device/widget/x/sepolicy
and shell.te appears in both locations, it is an error. Unless it is in BOARD_SEPOLICY_IGNORE to be filtered out. See BOARD_SEPOLICY_IGNORE for more details.
  • It is an error to specify the same file name in both BOARD_POLICY_REPLACE and BOARD_POLICY_UNION.
  • It is an error to specify a BOARD_SEPOLICY_DIRS that has no entries when specifying BOARD_SEPOLICY_REPLACE.

Examples: Two example BoardConfig.mk entries showing the use of BOARD_SEPOLICY_UNION that will take files referenced in BOARD_SEPOLICY_DIRS and add their contents to the end of the respective files in external/sepolicy, it will also include those not in external/sepolicy, and BOARD_SEPOLICY_REPLACE that will replace those files in external/sepolicy.

Example 1:


genfs_contexts \
file_contexts \

Example 2:


netclient_server.te \
secmark.te \
seapp_contexts \
keys.conf \


[edit] Build Tools

The kernel policy is compiled using checkpolicy(8) via the external/sepolicy/Android.mk file. There are also a number of SE for Android specific tools used to assist in policy configuration that are described in the Policy Build Tools section, with a summary as follows:

checkfc - Used to parse the file_contexts file against the binary policy sepolicy. This is to ensure all file contexts are valid for the policy. There is a -p option that is used to validate the contexts defined in the property_contexts or service_contexts file.
checkseapp - Used to validate the seapp_contexts file entries against the binary policy sepolicy.
insertkeys.py - Used to replace keywords in the signature sections of the mac_permissions.xml file with information obtained from pem files. This uses information contained in the external/sepolicy/keys.conf file that is detailed in the insertkeys.py tools section.

Note that the tools listed below are not built as part of the standard build process, therefore use make <tool_name> except where indicated.

post_process_mac_perms - Assists in generating new entries in an existing mac_permissions.xml file (also see setool). There is no make target for this python script, so either move to HOST_EXECUTABLE or execute directly (e.g. $PREFIX/external/sepolicy/tools/post_process_mac_perms).
sepolicy-analyze - Used to analyze the kernel policy file (sepolicy) for equivalent or different type pairs, or duplicate allow rules.
sepolicy-check - Used to check the kernel policy file (sepolicy) for allow rules based on source / target types, class and a single permission.
build<???>bundle - Used to build bundles for sepolicy et al., eop.xml or ifw.xml files to handle policy updates. Not available on AOSP.
setool - Assists in generating new entries for the mac_permissions.xml file. It will extract certificates from one or more packages then generate the package sections. Its output may need to be modified before inclusion in the master file as detailed in the setool tools section. Not available on AOSP.

[edit] Miscellaneous Information

[edit] SELinux Policy Versions

The default SELinux policy version is 26 that requires a kernel >= 3.0 and is set in external/sepolicy/Android.mk as follows:


If an older kernel must be supported POLICYVERS can be set as an environment variable as follows:

export POLICYVERS=24

Information regarding policy versions can be found at http://selinuxproject.org/page/NB_PolicyType#Policy_Versions that also gives information on the kernel versions required.

[edit] SELinux Policy Booleans

AOSP does not allow the use of booleans and the Android Compatibility Test Suite will specifically check and fail if they are present. They may still be defined in SEAndroid policy though.

[edit] Setting Permissive / Enforcing Mode

Version 4.4 is always started in enforcing mode, although some domains may be running in 'per-domain' permissive mode due to the permissivestatement being present in the policy. Also in 4.4 there is a permissive_or_unconfined macro (see te_macros policy file) that can be controlled via the FORCE_PERMISSIVE_TO_UNCONFINED flag defined in the policy Android.mk file (see comments in Android.mk for the detail).

These are ways to set permissive or enforcing mode:

  • To set across reboots, add the setenforce command to init.rc or init.<board>.rc files.
  • Using adb to run the setenforce command (not set across reboots):
# 1 = enforcing 0 = permissive
adb shell su 0 setenforce 1

If running the emulator the following may also be used:

emulator -selinux permissive
emulator -qemu -append androidboot.selinux=permissive

[edit] Checking File Labels

Checks on file labels take place at boot time, policy upgrades / reloads, app installation / upgrade, and via adb using restorecon/chcon. Depending on whether data, app or system areas are being labeled by the various restorecon services, there are two files involved: file_contexts for all areas other than /data/data and /data/user where the seapp_contexts file is used. There use and format are decribed in the Policy Configuration Files and seapp_contexts File sections.

To determine whether either of these two files have changed:

  • The file_contexts file has an SHA hash taken when loaded. This will be used when a recursive restorecon request is made and will be written to the pathname inode xattr entry of "security.resorecon_last" as files are labeled (except /sys files). When restorecon is run again (policy reload/update etc.), the xattr hash will be compared to the loaded file_contexts file hash, thus allowing automatic relabeling should the file change.
  • The seapp_contexts file has an SHA hash taken when loaded and stored as /data/system/seapp_hash by SELinuxMMAC.java. This is used to determine whether a recursive restorecon should be carried out on the /data/data and data/user directories by the package manager.

[edit] Updating Policy Files

This is covered at http://seandroid.bitbucket.org/PolicyUpdates.html in some detail and there are worked examples in the following sections:

There are also details in the Device Policy File Locations section.

The Android services that manage the updates are contained in the following java source files within the frameworks/base/services/java/com/android/server/updates directory:

  • SELinuxPolicyInstallReceiver.java
  • IntentFirewallInstallReceiver.java
  • EopsInstallReceiver.java

[edit] Local Policy Update

An example of loading a different policy via adb is described at http://seandroid.bitbucket.org/AddressingHiddenDenials.html#13, however this is an alternate method:

  • Modify the required policy source files including the relevant device policy modules. Rebuild the kernel policy file by:
make sepolicy
  • Copy the policy file to the device (it copies the new policy to the alternate directory so that it is picked up by the reload property):
adb push out/target/product/<device>/root/sepolicy /data/security/current
  • Then load the new policy by:
adb shell su setprop selinux.reload_policy 1

[edit] Logging and Auditing

SE for Android 4.4 now supports auditing of SELinux events via the AOSP logger service that can be viewed using logcat, for example:

adb logcat > logcat.log

Example SELinux audit events (avc denials) are:

W/iptables( 92): type=1400 audit(0.0:18): avc: denied { relabelto } for scontext=u:r:init:s0 tcontext=u:object_r:net_apps_packet:s0 tclass=packet
W/iptables( 92): type=1300 audit(0.0:18): arch=40000028 syscall=294 per=800000 success=no exit=-13 a0=4 a1=0 a2=40 a3=b845a468 items=0 ppid=54 auid=4294967295 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=(none) ses=4294967295 exe="/system/bin/iptables" subj=u:r:init:s0 key=(null)
W/com.se4android.netclient( 3168): type=1400 audit(0.0:200): avc: denied { send } for comm=4173796E635461736B202331 saddr= src=43397 daddr= dest=9999 netif=lo scontext=u:r:netclient_app:s0:c15,c256 tcontext=u:object_r:unlabeled:s0 tclass=packet
W/com.se4android.netclient( 3168): type=1300 audit(0.0:200): arch=40000028 syscall=283 per=800000 success=no exit=-111 a0=14 a1=abf4e6c4 a2=1c a3=b6f98e98 items=0 ppid=66 auid=4294967295 uid=10015 gid=10015 euid=10015 suid=10015 fsuid=10015 egid=10015 sgid=10015 fsgid=10015 tty=(none) ses=4294967295 comm=4173796E635461736B202331 exe="/system/bin/app_process32" subj=u:r:netclient_app:s0:c15,c256 key=(null)
E/SE4A-NetClient( 3141): java.net.ConnectException: failed to connect to / (port 9999): connect failed: ECONNREFUSED (Connection refused)

The audit2allow(1) command can be used to create policy rules as follows:

audit2allow -p out/target/product/<device>/root/sepolicy < logcat.log > policy.te

The result from the above avc denials would be:

#============= init ==============
allow init net_apps_packet:packet relabelto;

#============= netclient_app ==============
allow netclient_app unlabeled:packet send;

As the requirement of the app is to only accept packets labeled net_apps_packet via iptables(8) SECMARK, the relabelto allow rule was added to the device policy (see the selinux-network.sh Configuration section for using SECMARK).

Note that before the auditing daemon is loaded messages will be logged in the kernel buffers that can be read using dmesg(1):

adb shell su 0 dmesg

[edit] Policy File Configuration Details

These are detailed in the following section:

  1. The policy.conf file contains the policy language statements as described at http://selinuxproject.org/page/PolicyLanguage. These define the policy that will be enforced and devices labeled.
Personal tools