NB SEforAndroid 1

From SELinux Wiki
Jump to: navigation, search

Security Enhancements for Android


This section gives an overview of the enhancements made to Android to add SELinux services to Security Enhancements for Android™ (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 5.1 release. The builds discussed are from AOSP master and SEAndriod master repositories (as March '15).

The AOSP git repositories can be found at https://android.googlesource.com.

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


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

SE for Android This is the overall programme by Google to improve security on Android. For this document, it is used to describe the implementation of SELinux (MAC) and Middleware MAC (MMAC) on Android.
AOSP The Android code base distributed by Google (see http://source.android.com/source/downloading.html). Release 5.1 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 a run-time MMAC framework to support specific labeling of apps as described in the Install/Run-time MMAC Policy section.

AOSP also contains services to allow 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 (for example the MAC policy is now the same as AOSP). The additional SEAndroid features are:
  1. Install time MMAC (an enhancement of the AOSP Run-time MMAC service)
  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://selinuxproject.org/page/SEforAndroid

Useful Links

The following link describes how to validate SELinux in Android:


The http://selinuxproject.org/page/SEforAndroid pages describe the current merge status with AOSP, how to obtain the code, install SEAndroid 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.

Document Sections

The sections that follow cover:

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

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 2.1.0 Linux version but has additional functions to support Android as summarised in the external/libselinux/README.android. Some additional detail is as follows:
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 for app debugging.
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 permission 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 commits 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 for building policy on the host and is not available on the device. There are no specific updates to support Android except an Android.mk file.
Provides the policy build tool. Added support for MacOS X. Not available on the device as policy rebuilds are done in the development environment.
This is a policy specifically for the core components of 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 Policy Files section and support tools in Policy Build Tools.
The Android specific object classes are described in the Android Classes and Permissions section.
The directory also contains the MMAC configuration files.
This is an example 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 plus a recovery init.rc file in the etc directory.
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 run time MMAC and for SEAndroid the additional 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.
All Android kernels support the Linux Security Module (LSM) and SELinux services, however they 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.

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 Android Classes and Permissions section. Support for these permission checks are added to security/selinux/hooks.c.

Android Classes and Permissions

Additional classes have been added to Android and are listed in the following tables with descriptions of their permissions. The policy files external/sepolicy/security_classes and external/sepolicy/access_vectors contain the complete list with descriptions available at: http://selinuxproject.org/page/NB_ObjectClassesPermissions. However, note that while the security_classes file contains many entries, not all are required for Android.

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?).

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.

SELinux Commands

A subset of the Linux SELinux commands have been implemented in Android and are listed in Table 1. Some 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 commands

Command Comment
getenforce Returns the current enforcing mode.
setenforce Modify the SELinux enforcing mode:
setenforce [enforcing|permissive|1|0]
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
chcon Change security context of file. The options are: h - Change symlinks, R - Recurse into subdirectories, v - Verbose output.
chcon [-hRv] context file...
runcon Run command in specified security context:
runcon context program args...
id If SELinux is enabled then the security context is automatically displayed.
getsebool Deprecated as policy booleans no longer supported.

Returns SELinux boolean value(s):

getsebool [-a | boolean_name]
setsebool Deprecated as policy booleans no longer supported.

Set SELinux boolean to a value, does not set the boolean across reboots:

setsebool boolean_name [1|true|on|0|false|off]

SELinux Public Methods

The public methods implemented are equivalent to libselinux functions and shown 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.
Deprecated as policy booleans no longer supported.

String[] getBooleanNames()

   Gets a list of the SELinux boolean names.
   Return an array of strings containing the SELinux boolean names.
Deprecated as policy booleans no longer supported.

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.
Deprecated as policy booleans no longer supported.

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 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.
boolean restoreconRecursive(File file)
   Recursively restores all files under the given path to their 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 a boolean indicating whether the relabeling succeeded.

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>
Deprecated as booleans no longer supported.
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

Device Policy File Locations

Table 4 shows the 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

/file_contexts /seapp_contexts /property_contexts /service_contexts /selinux_version /mac_permissions.xml

/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.

Building the Policy

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

SELinux Policy Files

The core policy files are contained in external/sepolicy, with device specific policy in device/<vendor>/<device>/sepolicy[1] (see the Processing Device Policy section). Once generated, the policy and its supporting configuration files will be installed on the device as part of the build process.

Core Policy Files

The following files (along with any device specific policy) are used to build the kernel binary policy file named <tt>sepolicy and installed by default in the root directory.

These have been modified to support the new Android classes and permissions (although they still contain the unused Linux userspace items).
Contains the system initialisation (before policy is loaded) and failsafe (for objects that would not otherwise have a valid label).
For flexibility of policy building, these files have been separated to allow additional policy files to be defined for specific devices as discussed below.
These define the only user (u) and role (r) used by the policy.
Contains the constraints to be applied to the defined classes and permissions.
These contain the m4 macros that expand the policy files to build a policy in the kernel policy language as described in http://selinuxproject.org/page/PolicyLanguage. The policy will 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.

Policy Configuration Files

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

Contains default file contexts for setting the SELinux extended file attributes (attr(1)). The format of this file is defined in the file_contexts section. The file is installed by default in the root directory. Android services (such as restorecon) will first check for this file at:
If not present then check root directory:
Contains information to allow domain or data file contexts to be computed based on parameters as discussed in the seapp_contexts section. The file is installed by default in the root directory. The Android initialisation / reload process will first check for this file at:
If not present then check root directory:
Contains default contexts for Android property services as discussed in the property_contexts section. The file is installed by default in the root directory. The Android initialisation / reload process will first check for this file at:
If not present then check root directory:
Contains default contexts for Android services as discussed in the service_contexts section. The file is installed by default in the root directory. The Android initialisation / reload process will first check for this file at:
If not present then check root directory:

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

The kernel binary policy. The Android initialisation / reload process will first check for this file at:
If not present then check root directory:
For reference, the policy text file containing the kernel policy language statements 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).

Install/Run-time MMAC Policy

The Install/Run-time MMAC is part of AOSP (Run-time only currently) and SEAndroid (Install and Run time) policy build that is always enabled.

The file that configures this policy is mac_permissions.xml that assigns an seinfo tag to apps based on their signature and optionally their package name. The seinfo tag can then be used as a key in the seapp_contexts file to assign a specific label to all apps with that seinfo tag. The configuration file is read by system_server during start-up. Its format is discussed in the mac_permissions.xml section.

Note that AOSP and SEAndroid builds only differ in that SEAndroid will not install or load an app if there is no matching entry in the mac_permissions.xml file when no <default> entry is present.

The file is installed by default at:


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


This file can be:

  1. Appended to by the BOARD_SEPOLICY_UNION variable as described in the Processing Device Policy section.
  2. 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 such as PackageManagerService.java.

Device Specific Policy

Some of this section has been extracted from the external/sepolicy/README 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.

Important Note: Android policy has a number of neverallow rules defined in the core policy to ensure that allow rules are never added to domains that would weaken security. However developers may need to customise their device policies, and as a consequence they may fail one or more of these rules. If so, then this thread may be useful:


Managing Device Policy Files

Additional per device policy files are manipulated by the policy build process using the following two variables that may be added to the device BoardConfig.mk file:

Contains a list of directories to search for files listed by the BOARD_SEPOLICY_UNION variable. 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[2] will help sort out ordering issues and is located at:
Contains a list of files that will be "unioned", i.e. concatenated at the END of their respective files in external/sepolicy
To add a unique/new file this variable would be used.
It is an error to specify a BOARD_POLICY_UNION file that does not exist in external/sepolicy.


The 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.


BOARD_SEPOLICY_DIRS := device/samsung/tuna/sepolicy
    genfs_contexts \
    file_contexts \

Build Tools

The kernel policy is compiled using checkpolicy(8) via the external/sepolicy/Android.mk file. There are also a number of Android specific tools used to assist in policy configuration that are described in Policy Build Tools, 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.

Miscellaneous Information

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.

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 in a policy.

Setting Permissive / Enforcing Mode

Since version 4.4 Android is always started in enforcing mode, although some domains may be running in 'per-domain' permissive mode due to the permissive being present in the policy. These are ways to set permissive or enforcing mode:

Using adb to run the setenforce command:
# enforcing = 1 permissive = 0

adb shell su 0 setenforce 1
If running the emulator:
emulator -selinux permissive

Checking File Labels

Checks on file labels take place at boot time, policy upgrades / reloads, app installation / upgrade, and via adb using restorecon. Depending on whether data, app or system areas are being labeled by the various restorecon services, there are two files involved:

  1. file_contexts for all areas other than /data/data and /data/user.
  2. seapp_contexts file for /data/data and /data/user directories.

Their use and format are described in the file_contexts and seapp_contexts sections.

To determine whether either of these two files have changed:

  1. 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.
  2. 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.

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

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 0 setprop selinux.reload_policy 1

Logging and Auditing

Android 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)

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

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

Policy Configuration File Formats

These are detailed in the following section:


  1. Except for the emulator device policy that is in build/target/board/generic/sepolicy.
  2. 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.