Difference between revisions of "NB SEforAndroid 1"

From SELinux Wiki
Jump to: navigation, search
(Introduction)
 
(15 intermediate revisions by 2 users not shown)
Line 1: Line 1:
= SE for Android =
+
= Security Enhancements for Android =
 +
 
 
== Introduction ==
 
== Introduction ==
This section gives an overview of the enhancements made to Android to produce Security Enhancements for Android™ (SE for Android) as it stood in April '13. As this project is continually being enhanced, it is recommended that the official project wiki is checked for the latest enhancements at [[SEforAndroid | SEforAndroid]].
+
This section gives an overview of the enhancements made to Android to add SELinux services to Security Enhancements for Android™ (SE for Android).  
  
The following email is also useful regarding the merging of SE for Andriod: http://article.gmane.org/gmane.comp.security.seandroid/675/match=mainstreaming
+
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 main objective of this document is to provide a reference for the tools, commands, policy building tools and file formats of SE for Android as currently there are no man pages and useful information is buried in code or git log summaries (although there are some README's).
+
The AOSP git repositories can be found at [https://android.googlesource.com/ https://android.googlesource.com].  
  
The [[SEforAndroid | SEforAndriod]] page will also describe how to obtain the code, install SE for Android and the features that have been implemented. It also has useful reference papers with [http://selinuxproject.org/~seandroid/papers/NDSS2013-SEAndroid-Paper.pdf Security Enhanced (SE) Android: Bringing Flexible MAC to Android] being a recommended read.
+
For up to date information on the status of SE for Android the following should be consulted: [http://selinuxproject.org/page/SEforAndroid http://selinuxproject.org/page/SEforAndroid].
  
The white paper [http://www.samsung.com/global/business/business-images/resource/white-paper/2013/05/Samsung_KNOX_whitepaper_April2013_v1.1-0.pdf "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.
+
=== Terminology ===
 +
This section describes how the terms SE for Android, AOSP and SEAndroid are used in this document.
  
The http://en.wikipedia.org/wiki/Android_%28operating_system%29 site gives a good introduction to Android and http://source.android.com gives details on installation of the source.
+
{| border="1"
 +
| '''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.
  
The sections that follow cover:
+
|-
* Overview of current MAC and Middleware MAC support.
+
| '''AOSP'''
* Overview of Android package additions and updates to support MAC
+
| The Android code base distributed by Google (see [http://source.android.com/source/downloading.html 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 http://source.android.com/devices/tech/security/se-linux.html].
* Additional kernel LSM / SELinux support
+
* SE for Android Classes and Permissions
+
* SELinux commands and methods to support SE for Android
+
* SELinux extensions for init
+
* Policy construction and build
+
** Build file locations (helps determine errors)
+
** Policy booleans
+
** Policy configuration files
+
** Policy support tools
+
** Install / run time MMAC configuration
+
** Intent MMAC configuration
+
** Revoke permissions middleware configuration
+
* Logging and auditing
+
* SE for Android libselinux additional functions
+
* Policy configuration file detail
+
  
 +
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 | Install/Run-time MMAC Policy]] section.
  
== Supported MAC Services ==
+
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).
The information here is subject to change, however the SELinux MAC and install-time MMAC seem to be stable, the others will probably change<ref name="ftn1">With regard to AOSP, their stance is that all third party apps must be treated alike. This means that these apps cannot be run in different domains to provide isolation or have individual MMAC policies applied. AOSP does allow system apps to have different policies applied to them though. The SE for Android repository at https://bitbucket.org/seandroid holds the source code that may be modified to support different MAC policies for third party apps, however this would be outside AOSP.</ref> and content provider support will be added soon.
+
  
The four MAC services listed are with respect to SE for Android builds using the following local manifests checked out from the git repository on 10<sup>th</sup> April '13 (see https://bitbucket.org/seandroid/manifests):
+
|-
:<tt>git checkout master</tt> - Builds SELinux MAC + Install-time MMAC
+
| '''SEAndroid'''
:<tt>git checkout intent_mac</tt> - Builds SELinux MAC + Install-time MMAC + Intent MAC
+
| 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:
:<tt>git checkout revoke-perms</tt> - Builds SELinux MAC + Install-time MMAC + Revoke permissions.
+
# Install time MMAC (an enhancement of the AOSP Run-time MMAC service)
 +
# Installation of Enterprise Operations (EOps) configuration files.
 +
# 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).
 +
# Tools to manage bundles for policy, EOps and Intent Firewall updates.
  
An overview of the four MAC services is as follows:
+
See the SE for Android project page for up-to-date details at [http://selinuxproject.org/page/SEforAndroid http://selinuxproject.org/page/SEforAndroid]
# The 'standard' SELinux MAC policy based on type enforcement (TE) / multi-level system<ref name="ftn2">More precisely the multi-category system (MCS) as currently only a single level is used.</ref> (MLS) services (i.e. deny all access unless specifically allowed).
+
# Install-time MMAC policy that checks whether app permissions are allowed or not. If not allowed, the app cannot be installed or if the app is already installed before the updated policy, then the app cannot be run after the update. The configuration supports allow, deny and allow all permissions and checks these in the following way:
+
## If installing or updating a third party app, its permissions will be checked against the <tt><nowiki><default></nowiki></tt> entry of the install-time MMAC policy. If the default is to deny any of its permissions, then the installation will fail.
+
## Pre-installed apps and their updates will have their permissions checked against the against the complete install-time MMAC policy. Should a deny permission be found in policy for the app on a package and/or signature basis, then the installation will fail. The installation will also fail if the app has not specifically been allowed the permission in its package and/or signature entry and there is a deny permission entry in the <tt><nowiki><default></nowiki></tt> entry.
+
# The install-time MMAC policy also supports an <tt>seinfo</tt> tag on a package and/or signature basis that is used to compute an SELinux security context for labeling apps. These apps must be pre-installed (system) apps, third party apps cannot be be relabeled.
+
# Intent MMAC policy that checks whether the policy configured app intents (on a package and/or signature basis) are allowed or not at run time. If not allowed, that intent will not be sent. It is currently limited to the features described at [[SEforAndroid#Middleware_MAC | SEforAndroid Middleware_MAC]]. This is an optional policy and does not require any specific SELinux policy support, however it does allow source context validation to take place. The configuration supports allow and allow all intents (i.e. deny all unless specifically allowed).
+
# Revoke permissions policy that checks whether the policy configured permissions on a package basis will be revoked at run time. If not allowed, that permission will be revoked (i.e. allow all unless specifically revoked). This is an optional policy and does not require any specific SELinux policy support.
+
  
 +
|}
  
== Overview of Android changes to support MAC ==
+
=== Useful Links ===
SE for Android enhances the Android system by adding SELinux support to the kernel and userspace with the main objectives being to (taken from documents at [[SEforAndroid | SEforAndroid]]):
+
The following link describes how to validate SELinux in Android:
# Confine privileged daemons to protect them from misuse and limit the damage that can be done via them.
+
# Sandbox and isolate apps from each other and from the system
+
# Prevent privilege escalation by apps.
+
# Allow application privileges to be controlled at installation and run-time using Middleware-MAC.
+
# Provide a centralized, analyzable policy.
+
  
These objectives are achieved by:
+
[http://source.android.com/devices/tech/security/se-linux.html http://source.android.com/devices/tech/security/se-linux.html]
* Per-file security labeling support for yaffs2
+
* Filesystem images (yaffs2 and ext4) labeled at build time
+
* Labeling support in the recovery console and updater program
+
* Kernel permission checks controlling Binder IPC
+
* Labeling of service sockets and socket files created by init
+
* Labeling of device nodes created by ueventd
+
* Flexible, configurable labeling of apps and app data directories
+
* Minimal port of SELinux userspace
+
* SELinux support for the Android toolbox
+
* JNI bindings for SELinux APIs
+
* Userspace permission checks controlling use of the Zygote socket commands
+
* Userspace permission checks controlling setting of Android properties
+
* Small TE policy written from scratch for Android
+
* Confined domains for system services and apps
+
* Use of MLS categories to isolate apps
+
  
The Android git repositories can be found at https://android.googlesource.com and the SE for Android enhancements at https://bitbucket.org/seandroid.  
+
The [http://selinuxproject.org/page/SEforAndroid 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 http://www.internetsociety.org/sites/default/files/02_4.pdf] being a recommended read.
  
'''But do read the information at [[SEforAndroid | SEforAndroid]] first.'''
+
The white paper "[http://www.samsung.com/global/business/business-images/resource/white-paper/2013/05/Samsung_KNOX_whitepaper_April2013_v1.1-0.pdf 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 <tt>init</tt>
 +
* Policy construction and build:
 +
** Build file locations
 +
** Policy files
 +
** Build tools
 +
* Logging and auditing
 +
* Android <tt>libselinux</tt> additional functions
 +
* Configuration file formats
  
 
== SE for Android Project Updates ==
 
== SE for Android Project Updates ==
This gives a high level view of the new and updated projects to support the SE for Android build:
+
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.
  
: external/libselinux
+
: <tt>'''external/libselinux'''</tt>
:: Provides the SELinux userspace function library that is installed on the device. It is based on a version of the Linux library but has additional functions to support Android. The additional functions are:
+
:: 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 <tt>external/libselinux/README.android</tt>. Some additional detail is as follows:
::: '''<tt>selinux_android_setcontext</tt>'''
+
::: <tt>'''selinux_android_setcontext'''</tt>
::::Sets the correct domain context for applications using <tt>'''setcon'''(3)</tt>. Information contained in the <tt>seapp_contexts</tt> file is used to compute the correct context. This function also calls <tt>selinux_android_seapp_context_reload</tt> on initialisation to load the <tt>seapp_contexts</tt> file and sort the entries in order of precedence as discussed in the <tt>seapp_contexts</tt> File section.
+
:::: Sets the correct domain context when launching applications using <tt>'''setcon'''(3)</tt>. Information contained in the <tt>seapp_contexts</tt> file is used to compute the correct context.
::::It is called by <tt>dalvik/vm/native/dalvik-system-Zygote.cpp</tt> and <tt>system/core/run-as/run-as.c</tt>
+
:::: It is called by <tt>frameworks/base/core/jni/com_android_internal_os_Zygote.cpp</tt> when forking a new process and the <tt>system/core/run-as/run-as.c</tt> utility for app debugging.
::: <tt>'''selinux_android_setfilecon2'''</tt>
+
::: <tt>'''selinux_android_setfilecon'''</tt>
::::This is used to set the correct context on application directory / files using <tt>'''setfilecon'''(3)</tt>. Information contained in the <tt>seapp_contexts</tt> file is used to compute the correct context. This function also calls <tt>selinux_android_seapp_context_reload</tt> on initialisation to load the <tt>seapp_contexts</tt> file and sort the entries in order of precedence as discussed in the <tt>seapp_contexts</tt> file section.
+
:::: Sets the correct context on application directory / files using <tt>'''setfilecon'''(3)</tt>. Information contained in the <tt>seapp_contexts</tt> file is used to compute the correct context.
::::Used by <tt>frameworks/base/cmds/installd/commands.c</tt> for package <tt>install</tt>, <tt>make_user_data</tt> and <tt>protect</tt> functions.
+
:::: The function is used by the package installer within <tt>frameworks/native/cmds/installd/commands.c</tt> via the package <tt>install()</tt> and <tt>make_user_data()</tt> functions.
 
::: <tt>'''selinux_android_restorecon'''</tt>
 
::: <tt>'''selinux_android_restorecon'''</tt>
::::Set file contexts to match entries defined in the <tt>file_contexts</tt> file using <tt>'''lsetfilecon'''(3)</tt>. Used by various commands to reset contexts during initialisation, installation etc.
+
::: <tt>'''selinux_android_restorecon_pkgdir'''</tt>
 +
:::: Basically these functions are used to label files and directories based on entries from the <tt>file_contexts</tt> and/or <tt>seapp_contexts</tt> files. They call a common handler (<tt>selinux_android_restorecon_common()</tt>) that will then relabel the requested directories and files. It will also handle recursive labeling of directories and files should a new app, <tt>file_contexts</tt> or <tt>seapp_contexts</tt> be installed (see the [[#Checking File Labels | Checking File Labels]] section for further information).
 +
:::: The <tt>'''selinux_android_restorecon'''</tt> function is used by:
 +
::::: <tt>frameworks/native/cmds/installd/installd.c</tt> when installing a new app.
 +
::::: <tt>frameworks/base/core/jni/android_os_SELinux.cpp</tt> for the Java <tt>native_restorecon</tt> method.
 +
::::: <tt>frameworks/native/cmds/dumpstate/utils.c</tt> when dumping Dalvik and stack traces to ensure correct label.
 +
:::: The <tt>'''selinux_android_restorecon_pkgdir'''</tt> function is used by:
 +
::::: <tt>frameworks/native/cmds/installd/commands.c</tt> for the package <tt>restorecon_data()</tt> and <tt>make_user_data()</tt> functions.
 +
::: <tt>'''selinux_android_seapp_context_reload'''</tt>
 +
:::: Loads the <tt>seapp_contexts</tt> file for <tt>frameworks/native/cmds/installd/installd.c</tt> when the package installer is loaded.
 
::: <tt>'''selinux_android_load_policy'''</tt>
 
::: <tt>'''selinux_android_load_policy'''</tt>
::::Mounts the SELinux filesystem if SELinux is enabled and then calls <tt>'''selinux_android_reload_policy'''</tt> to load the policy into the kernel. Used by <tt>system/core/init/init.c -</tt> <tt>main()</tt> to mount <tt>selinuxfs</tt> and load the policy.
+
:::: Mounts the SELinux filesystem if SELinux is enabled and then calls <tt>'''selinux_android_reload_policy'''</tt> to load the policy into the kernel. Used by <tt>system/core/init/init.c</tt> to initialise SELinux.
 
::: <tt>'''selinux_android_reload_policy'''</tt>
 
::: <tt>'''selinux_android_reload_policy'''</tt>
::::Loads the policy into the kernel. Used by <tt>system/core/init/init.c</tt> to reload the policy.
+
:::: Reloads the policy into the kernel. Used by <tt>system/core/init/init.c</tt> <tt>selinux_reload_policy()</tt> to reload policy after setting the <tt>selinux.reload_policy</tt> property.
::There is also a new labeling service for <tt>'''selabel_lookup'''(3)</tt> to query the <tt>property_contexts</tt> file (see <tt>external/libselinux/src/label_android_property.c</tt>). This file is loaded at init time (see <tt>system/core/init/init.c</tt>) and used by <tt>system/core/init/property_service.c</tt>. that checks property MAC permissions at system initialisation time.
+
::: <tt>'''selinux_android_use_data_policy'''</tt>
 +
:::: Used by <tt>system/core/init/init.c</tt> to decide which policy directory to load the <tt>property_contexts</tt> file from.
 +
::: There is also a new labeling service for <tt>'''selabel_lookup'''(3)</tt> to query the Android <tt>property_contexts</tt> and <tt>service_contexts</tt> files.
 +
::: Various Android services will also call (not a complete list):
 +
:::: <tt>'''selinux_status_updated'''(3)</tt>, <tt>'''is_selinux_enabled'''(3)</tt>, to check whether anything changed within the SELinux environment (e.g. updated configuration files).
 +
:::: <tt>'''selinux_check_access'''(3)</tt> to check if the source context has access permission for the class on the target context.
 +
:::: <tt>'''selinux_label_open'''(3)</tt>, <tt>'''selabel_lookup'''(3)</tt>, <tt>'''selinux_android_file_context_handle'''</tt>, <tt>'''selinux_android_prop_context_handle'''</tt>, <tt>'''setfilecon'''(3)</tt>, <tt>'''setfscreatecon'''(3)</tt> to manage file labeling.
 +
:::: <tt>'''selinux_lookup_best_match'''</tt> called by<tt> system/core/init/devices.c</tt> when <tt>ueventd</tt> 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/][https://android.googlesource.com/platform/system/core/+/b0ab94b7d5a888f0b6920b156e5c6a075fa0741a +/b0ab94b7d5a888f0b6920b156e5c6a075fa0741a], [https://android.googlesource.com/platform/system/core/+/b4c5200f51c3568f604a4557119ab545a6ddac94 https://android.googlesource.com/platform/system/core/][https://android.googlesource.com/platform/system/core/+/b4c5200f51c3568f604a4557119ab545a6ddac94 +/b4c5200f51c3568f604a4557119ab545a6ddac94] and''' '''[https://android.googlesource.com/platform/external/libselinux/+/be7f5e8814c4954aca51d3f95455c5d9d527658c https://android.googlesource.com/platform/external/libselinux/+/be7f5e8814c4954aca51d3f95455c5d9d527658c]).
  
: external/libsepol
+
: <tt>'''external/libsepol'''</tt>
:: 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 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 <tt>Android.mk</tt> file.
: external/checkpolicy
+
:: Provides the policy build tool. There are no specific updates to support SE for Android, also this is not available on the device (therefore policy rebuilds must be done in the development environment).
+
  
: external/sepolicy
+
: <tt>'''external/checkpolicy'''</tt>
:: This is a new policy specifically for SE for Android. It looks much like the reference policy but is contained in one directory that has the policy modules (<tt><nowiki>*.te</nowiki></tt> files), class / permission files etc.. The policy is built by the <tt>Android.mk</tt> file and the resulting policy is installed on the target device (as <tt>sepolicy</tt>) along with its supporting configuration files (<tt>file_contexts</tt>, <tt>seapp_contexts</tt> and <tt>property_contexts</tt>). There are facilities that enable policy to be modified depending on the device as discussed in the [[#Building the Policy | Building the Policy]] section.
+
:: Provides the policy build tool. Added support for MacOS X. Not available on the device as policy rebuilds are done in the development environment.
:: The policy files are discussed in the [[NB_SEforAndroid_2#SELinux MAC Policy Files | SELinux MAC Policy Files]] section and support tools in [[#Policy Build Tools | Policy Build Tools]].
+
:: There are three new object classes defined for the policy that are described in the [[#SE for Android Classes and Permissions | SE for Android Classes and Permissions]] section.
+
:: The directory also contains the install / run time MMAC and if configured the intent MMAC configuration files (also see: [[SEforAndroid#Middleware_MAC | SEforAndroid - Middleware_MAC]]).
+
  
: external/mac-policy
+
: <tt>'''external/sepolicy'''</tt>
:: Contains the revoke permissions middleware policy file (<tt>revoke_permissions.xml</tt>) that allows Android permissions to be revoked at run time. The <tt>revoke-perms</tt> branch will enable this functionality.
+
:: 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 (<tt><nowiki>*.te</nowiki></tt> files), class / permission files etc.. The policy is built by the <tt>Android.mk</tt> file and the resulting policy is installed on the target device (as <tt>sepolicy</tt>) along with its supporting configuration files.
 +
:: Device specific policy may be defined under the device directory as discussed in the [[#Processing Device Policy | Processing Device Policy]] section.
 +
:: The policy can be updated along with its configuration files as discussed in the [[#Updating Policy | Updating Policy]] section.
 +
:: The policy files are discussed in the [[#SELinux Policy Files | SELinux Policy Files]] section and support tools in [[NB_SEforAndroid_2#Policy_Build_Tools | Policy Build Tools]].
 +
:: The Android specific object classes are described in the [[#Android Classes and Permissions | Android Classes and Permissions]] section.
 +
:: The directory also contains the MMAC configuration files.
  
: external/yaffs2
+
: <tt>'''packages/apps/SEAdmin'''</tt>
:: <tt>mkyaffs2image</tt> support for labeling and extended attributes (<tt>xattr</tt>)  
+
:: This is an example Android application to manage the SE for Android environment (such as loading a new policy). Only available on SEAndroid build.
  
: packages/apps/SEAandroidAdmin
+
: <tt>'''packages/apps/Settings'''</tt>
:: This is an Android application to manage the SE for Android environment. It allows control of the enforcement modes, booleans etc. There is also an optional <tt>SEAndroidManager</tt> app that is not installed by default.
+
 
+
: packages/apps/Settings
+
 
:: SELinux settings for the settings manager application.
 
:: SELinux settings for the settings manager application.
  
: bionic
+
: <tt>'''bionic'''</tt>
 
:: Bionic is the Android <tt>libc</tt> that is a derived from the BSD standard C library code. It contains enhancements to support security providers such as SELinux.
 
:: Bionic is the Android <tt>libc</tt> that is a derived from the BSD standard C library code. It contains enhancements to support security providers such as SELinux.
  
: bootable/recovery
+
: <tt>'''bootable/recovery'''</tt>
:: Changes to manage file labeling on recovery.
+
:: Changes to manage file labeling on recovery plus a recovery <tt>init.rc</tt> file in the etc directory.
 
+
: build
+
:: Changes to build SE for Android (see the "<tt><nowiki># SELinux packages</nowiki></tt>" comment in the <tt>build/target/product/core.mk</tt> file) and manage file labeling on images and OTA (over the air) target files.
+
  
: dalvik
+
: <tt>'''build'''</tt>
:: Set the context using <tt>selinux_android_setcontext</tt> on the dalvik process being forked.
+
:: Changes to build SE for Android and manage file labeling on images and OTA (over the air) target files.
  
: libcore
+
: <tt>'''frameworks/base'''</tt>
:: Add additional parameters <tt>seInfo</tt> and <tt>niceName</tt> to <tt>Zygote.java</tt>
+
 
+
: frameworks/base
+
 
:: JNI - Add SELinux support functions such as <tt>isSELinuxEnabled</tt> and <tt>setFSCreateCon</tt>.
 
:: JNI - Add SELinux support functions such as <tt>isSELinuxEnabled</tt> and <tt>setFSCreateCon</tt>.
 
 
:: SELinux Java class and method definitions.
 
:: SELinux Java class and method definitions.
 
:: Checking Zygote connection contexts.
 
:: Checking Zygote connection contexts.
 
:: Managing file permissions for the package manager and wallpaper services.
 
:: Managing file permissions for the package manager and wallpaper services.
:: SELinux additions to support install / run time MMAC, intent MMAC and revoke permissions middleware.
+
:: SELinux additions to support run time MMAC and for SEAndroid the additional MMAC services.
  
: system/core
+
: <tt>'''system/core'''</tt>
 
:: SELinux support services for toolbox (e.g. <tt>load_policy</tt>, <tt>runcon</tt>).
 
:: SELinux support services for toolbox (e.g. <tt>load_policy</tt>, <tt>runcon</tt>).
 
:: SELinux support for system initialisation (e.g. <tt>init</tt>, <tt>init.rc</tt>).  
 
:: SELinux support for system initialisation (e.g. <tt>init</tt>, <tt>init.rc</tt>).  
 
:: SELinux support for auditing avc's (<tt>auditd</tt>).
 
:: SELinux support for auditing avc's (<tt>auditd</tt>).
  
: system/extras
+
: <tt>'''system/extras'''</tt>
:: SELinux support for the <tt>ext4</tt> file system.
+
:: SELinux support for the <tt>ext4</tt> file system. Note that the <tt>make_ext4fs</tt> utility is used to build these file systems and relies on the <tt>file_contexts</tt> file having all the relevant entries, if not, it will be unable to set the <tt>security.selinux</tt> xattr on the inode and fail.
  
: kernel
+
: <tt>'''kernel'''</tt>
:: There are a number of kernels that have been enhanced to support LSM and SELinux services and are listed at [[SEforAndroid#Building_for_a_Device | SEforAndroid - Building for a Device]].
+
:: 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 | Kernel LSM / SELinux Support]] section describes the Andriod kernel changes.
:: Note that the Android kernels are based on various versions (currently 3.4 for the goldfish used by the emulator), therefore the latest SELinux enhancements may not always be present. The [[#Kernel LSM / SELinux Support | Kernel LSM / SELinux Support]] section describes the kernel changes.
+
 
+
: device
+
:: Details regarding supported devices can be found at [[SEforAndroid#Building_for_a_Device | SEforAndroid - Building for a Device]]
+
:: Device configurations can be modified to allow the policy to be tailored, see the [[#Building_the_Policy | Building the Policy]] section.
+
  
 +
: <tt>'''device'''</tt>
 +
:: Build information for each device, details regarding SEAndroid supported devices can be found at:
 +
::: [http://seandroid.bitbucket.org/BuildingKernels.html#9 http://seandroid.bitbucket.org/BuildingKernels.html#9]
 +
:: Device specific policy can be added as discussed in the [[#Building the Policy | Building the Policy]] and [[#Processing Device Policy | Processing Device Policy]] sections.
  
 
== Kernel LSM / SELinux Support ==
 
== Kernel LSM / SELinux Support ==
The paper [http://selinuxproject.org/~seandroid/papers/NDSS2013-SEAndroid-Paper.pdf Security Enhanced (SE) Android: Bringing Flexible MAC to Android] gives a good review of what did and didn't changed in the kernel to support Android. This section briefly describes the only major change that was to support the Binder IPC service, these changes consist of:
+
The paper "Security Enhanced (SE) Android: Bringing Flexible MAC to Android" available at [http://www.internetsociety.org/sites/default/files/02_4.pdf 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:
# Linux Security Module (LSM) hooks in the binder code (<tt>drivers/staging/android/binder.c</tt>) and (<tt>include/linux/security.h</tt>)
+
 
 +
# LSM hooks in the binder code (<tt>drivers/staging/android/binder.c</tt>) and (<tt>include/linux/security.h</tt>)
 
# Default support for capabilities (<tt>security/capability.c</tt>) in case no other module is loaded.
 
# Default support for capabilities (<tt>security/capability.c</tt>) in case no other module is loaded.
 
# Hooks in the LSM security module (<tt>security/security.c</tt>).
 
# Hooks in the LSM security module (<tt>security/security.c</tt>).
# SELinux support for the binder object class and permissions (<tt>security/selinux/include/classmap.h</tt>) that are shown in the [[#SE for Android Classes and Permissions| SE for Android Classes and Permissions]] section. Support for these permission checks are added to <tt>security/selinux/hooks.c</tt>.
+
# SELinux support for the binder object class and permissions (<tt>security/selinux/include/classmap.h</tt>) that are shown in the [[#Android Classes and Permissions | Android Classes and Permissions]] section. Support for these permission checks are added to <tt>security/selinux/hooks.c</tt>.
  
 
+
== Android Classes and Permissions ==
== SE for 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 <tt>external/sepolicy/security_classes</tt> and <tt>external/sepolicy/access_vectors</tt> contain the complete list with descriptions available at: [http://selinuxproject.org/page/NB_ObjectClassesPermissions http://selinuxproject.org/page/NB_ObjectClassesPermissions]. However, note that while the <tt>security_classes</tt> file contains many entries, not all are required for Android.
Three additional classes (<tt>binder</tt>, <tt>zygote</tt> and <tt>property_service</tt>) have been added to SE for Android and are listed in the following tables with descriptions of their permissions:
+
  
 
{| border="1"
 
{| border="1"
 
| colspan="2" | <tt>'''binder'''</tt> class - This is a kernel object to manage the Binder IPC service.
 
| colspan="2" | <tt>'''binder'''</tt> class - This is a kernel object to manage the Binder IPC service.
 +
 
|-
 
|-
 
| '''Permission'''
 
| '''Permission'''
| '''Description'''
+
| '''Description''' (4 unique permissions)
 +
 
 
|-
 
|-
| call
+
| <tt>call</tt>
 
| Perform a binder IPC to a given target process (can A call B?).
 
| Perform a binder IPC to a given target process (can A call B?).
 +
 
|-
 
|-
| impersonate
+
| <tt>impersonate</tt>
 
| Perform a binder IPC on behalf of another process (can A impersonate B on an IPC?).
 
| Perform a binder IPC on behalf of another process (can A impersonate B on an IPC?).
 +
 
Not currently used in policy but kernel (<tt>selinux/hooks.c</tt>) checks permission in <tt>selinux_binder_transaction</tt> call.
 
Not currently used in policy but kernel (<tt>selinux/hooks.c</tt>) checks permission in <tt>selinux_binder_transaction</tt> call.
 +
 
|-
 
|-
| set_context_mgr
+
| <tt>set_context_mgr</tt>
 
| Register self as the Binder Context Manager aka <tt>servicemanager</tt> (global name service). Can A set the context manager to B, where normally A == B.
 
| Register self as the Binder Context Manager aka <tt>servicemanager</tt> (global name service). Can A set the context manager to B, where normally A == B.
 +
 
See policy module <tt>servicemanager.te</tt>.  
 
See policy module <tt>servicemanager.te</tt>.  
 +
 
|-
 
|-
| transfer
+
| <tt>transfer</tt>
 
| Transfer a binder reference to another process (can A transfer a binder reference to B?).
 
| Transfer a binder reference to another process (can A transfer a binder reference to B?).
 +
 
|}
 
|}
  
  
 
{| border="1"
 
{| border="1"
| colspan="2" | <tt>'''zygote'''</tt> class This is a userspace object to manage the Android application loader. See Java <tt>SELinux.checkSELinuxAccess</tt>. In <tt>ZygoteConnection.java</tt>
+
| colspan="2" | <tt>'''property_service'''</tt> class - This is a userspace object to manage the Android Property Service. <tt>See check_mac_perms()</tt> in <tt>system/core/init/property_service.c</tt>
 +
 
 
|-
 
|-
 
| '''Permission'''
 
| '''Permission'''
| '''Description'''
+
| '''Description''' (1 unique permission)
 +
 
 
|-
 
|-
| specifyids
+
| <tt>set</tt>
| Peer may specify uid’s or gid’s.
+
| Set a property.
 +
 
 +
|}
 +
 
 +
 
 +
{| border="1"
 +
| colspan="2" | <tt>'''service_manager'''</tt> class - This is a userspace object to manage Android services. See <tt>check_mac_perms()</tt> in <tt>frameworks/native/cmds/servicemanager/service_manager.c</tt>
 +
 
 
|-
 
|-
| specifyrlimits
+
| '''Permission'''
| Peer may specify rlimits.
+
| '''Description''' (3 unique permission)
 +
 
 
|-
 
|-
| specifycapabilities
+
| <tt>add</tt>
| Peer may specify capabilities.
+
| Add a service.
 +
 
 
|-
 
|-
| specifyinvokewith
+
| <tt>find</tt>
| Peer may specify <tt>--invoke-with</tt> to launch Zygote with a wrapper command.
+
| Find a service.
 +
 
 
|-
 
|-
| specifyseinfo
+
| <tt>list</tt>
| Specify a <tt>seinfo</tt> string for use in determining the app security label.
+
| List services.
 +
 
 
|}
 
|}
  
  
 
{| border="1"
 
{| border="1"
| colspan="2" | <tt>'''property_service'''</tt> class This is a userspace object to manage the Android Property Service.
+
| colspan="2" | <tt>'''keystore_key'''</tt> class - This is a userspace object to manage the Android keystore (see <tt>system/security/keystore/keystore.cpp</tt>).
 +
 
 
|-
 
|-
 
| '''Permission'''
 
| '''Permission'''
| '''Description''' (1 unique permission)
+
| '''Description''' (16 unique permissions)
 +
 
 
|-
 
|-
| set
+
| <tt>test</tt>
| Set a property.
+
| Test if keystore okay.
 +
 
 +
|-
 +
| <tt>get</tt>
 +
| Get key.
 +
 
 +
|-
 +
| <tt>insert</tt>
 +
| Insert/update key.
 +
 
 +
|-
 +
| <tt>delete</tt>
 +
| Delete key.
 +
 
 +
|-
 +
| <tt>exist</tt>
 +
| Check if key exists.
 +
 
 +
|-
 +
| <tt>saw</tt>
 +
| Search for matching string.
 +
 
 +
|-
 +
| <tt>reset</tt>
 +
| Reset keystore.
 +
 
 +
|-
 +
| <tt>password</tt>
 +
| Generate new keystore password.
 +
 
 +
|-
 +
| <tt>lock</tt>
 +
| Lock keystore.
 +
 
 +
|-
 +
| <tt>unlock</tt>
 +
| Unlock keystore.
 +
 
 +
|-
 +
| <tt>zero</tt>
 +
| Check if keystore empty.
 +
 
 +
|-
 +
| <tt>sign</tt>
 +
| Sign data.
 +
 
 +
|-
 +
| <tt>verify</tt>
 +
| Verify data.
 +
 
 +
|-
 +
| <tt>grant</tt>
 +
| Add or remove access.
 +
 
 +
|-
 +
| <tt>duplicate</tt>
 +
| Duplicate the key.
 +
 
 +
|-
 +
| <tt>clear_uid</tt>
 +
| Clear keys for this uid.
 
|}
 
|}
  
  
== SELinux Commands ==
+
{| border="1"
A subset of the Linux SELinux commands have been implemented for SE for Android and are listed in Table 1. They are available as Toolbox commands (see <tt>system/core/toolbox</tt>) and can be run via adb shell, for example:
+
| colspan="2" | <tt>'''debuggerd'''</tt> class - This is a userspace object to allow file dumps (see <tt>system/core/debuggerd/debuggerd.cpp</tt>).
<pre>
+
 
adb shell su o setenforce permissive
+
|-
</pre>
+
| '''Permission'''
 +
| '''Description''' (2 unique permissions)
 +
 
 +
|-
 +
| <tt>dump_tombstone</tt>
 +
| Write tombstone file.
 +
 
 +
|-
 +
| <tt>dump_backtrace</tt>
 +
| Write backtrace file.
 +
 
 +
|}
  
  
'''Table 1: SELinux enabled adb shell commands (in Android toolbox)'''
 
 
{| border="1"
 
{| border="1"
| '''Command'''
+
| colspan="2" | <tt>'''drmservice'''</tt> class - This is a userspace object to allow finer access control of the Digital Rights Management services (see <tt>frameworks/av/drm/drmserver/DrmManagerService.cpp</tt>).
| '''Comment'''
+
  
 
|-
 
|-
| <tt>chcon</tt>
+
| '''Permission'''
| Change security context of file. As the first part of <tt>chcon(1)</tt> (only supports the <tt>context path</tt> parameters.
+
| '''Description''' (8 unique permissions)
  
<tt>chcon context pathname</tt>
+
|-
 +
| <tt>consumeRights</tt>
 +
| Consume rights for content.
  
 
|-
 
|-
| <tt>getenforce</tt>
+
| <tt>setPlaybackStatus</tt>
| Get current enforcing mode:
+
| Set the playback state.
  
<tt>getenforce</tt>
+
|-
 +
| <tt>openDecryptSession</tt>
 +
| Open the DRM session for the requested DRM plugin.
  
 
|-
 
|-
| <tt>getsebool</tt>
+
| <tt>closeDecryptSession</tt>
| Get SELinux boolean value(s):
+
| Close DRM session.
  
<tt><nowiki>getsebool [-a | boolean]</nowiki></tt>
+
|-
 +
| <tt>initializeDecrypSession</tt>
 +
| Initialise the decrypt resources.
  
 
|-
 
|-
| <tt>id</tt>
+
| <tt>decrypt</tt>
| Does not take any options. If SELinux is enabled then the security context is automatically displayed.
+
| Decrypt data stream.
 +
 
 +
|-
 +
| <tt>finalizeDecryptUnit</tt>
 +
| Release DRM resources.
 +
 
 +
|-
 +
| <tt>pread</tt>
 +
| 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 <tt>system/core/toolbox</tt>) and can be run via <tt>adb shell</tt>, for example:
 +
<pre>
 +
adb shell su 0 setenforce permissive
 +
</pre>
 +
 
 +
 
 +
'''Table 1: SELinux enabled commands'''
 +
{| border="1"
 +
| '''Command'''
 +
| '''Comment'''
 +
 
 +
|-
 +
|  <tt>getenforce</tt>
 +
| Returns the current enforcing mode.
 +
 
 +
|-
 +
|  <tt>setenforce</tt>
 +
| Modify the SELinux enforcing mode:
 +
 
 +
<tt><nowiki>setenforce [enforcing|permissive|1|0]</nowiki></tt>
  
 
|-
 
|-
Line 272: Line 389:
 
|-
 
|-
 
|  <tt>ls</tt>
 
|  <tt>ls</tt>
| Supports -Z option to display security context.
+
| Supports <tt>-Z</tt> option to display security context.
 +
 
 +
|-
 +
|  <tt>ps</tt>
 +
| Supports <tt>-Z</tt> option to display security context.
  
 
|-
 
|-
 
|  <tt>restorecon</tt>
 
|  <tt>restorecon</tt>
| Restore file default security context as defined in the <tt>file_contexts</tt> file. As <tt>restorecon(8)</tt> but supports less options:
+
| Restore file default security context as defined in the <tt>file_contexts</tt> or <tt>seapp_contexts</tt> files. The options are: <tt>D</tt> - data files, <tt>F</tt> - Force reset, <tt>n</tt> - do not change, <tt>R</tt>/<tt>r</tt> - Recursive change, <tt>v</tt> - Show changes.
 +
 
 +
<tt><nowiki>restorecon [-DFnrRv] pathname</nowiki></tt>
 +
 
 +
|-
 +
|  <tt>chcon</tt>
 +
| Change security context of file. The options are: <tt>h</tt> - Change symlinks, <tt>R</tt> - Recurse into subdirectories, <tt>v</tt> - Verbose output.
  
  <tt><nowiki>restorecon [-nrRv] pathname</nowiki></tt>
+
  <tt><nowiki>chcon [-hRv] context file...</nowiki></tt>
  
 
|-
 
|-
Line 287: Line 414:
  
 
|-
 
|-
|  <tt>setenforce</tt>
+
|  <tt>id</tt>
| Modify the SELinux enforcing mode:
+
| If SELinux is enabled then the security context is automatically displayed.
  
  <tt><nowiki>setenforce [enforcing|permissive|1|0]</nowiki></tt>
+
|-
 +
|  <tt>getsebool</tt>
 +
| Deprecated as policy booleans no longer supported.
 +
 
 +
Returns SELinux boolean value(s):
 +
 
 +
  <tt><nowiki>getsebool [-a | boolean_name]</nowiki></tt>
  
 
|-
 
|-
 
|  <tt>setsebool</tt>
 
|  <tt>setsebool</tt>
| Set SELinux boolean to a value (note that the cmd does not set the boolean across reboots):
+
| Deprecated as policy booleans no longer supported.
 +
 
 +
Set SELinux boolean to a value, does not set the boolean across reboots:
  
  <tt><nowiki>setsebool name [1|true|on|0|false|off]</nowiki></tt>
+
  <tt><nowiki>setsebool boolean_name [1|true|on|0|false|off]</nowiki></tt>
  
 
|}
 
|}
Line 302: Line 437:
  
 
== SELinux Public Methods ==
 
== SELinux Public Methods ==
The public methods implemented are equivalent to <tt>libselinux</tt> functions are show in Table 2. They have been taken from <tt>framework/base/core/java/android/os/SELinux.java</tt>.
+
The public methods implemented are equivalent to <tt>libselinux</tt> functions and shown in Table 2. They have been taken from <tt>frameworks/base/core/java/android/os/SELinux.java</tt>.
 +
 
 +
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 <tt>proguard.flags</tt> and <tt>Android.mk</tt> files in <tt>packages/apps/SEAdmin</tt>).  
  
  
Line 309: Line 446:
 
| <tt>'''boolean isSELinuxEnabled()'''</tt>
 
| <tt>'''boolean isSELinuxEnabled()'''</tt>
  
     Determine whether SELinux is disabled or enabled.  
+
     Determine whether SELinux is enabled or disabled.  
 
+
 
     Return <tt>true</tt> if SELinux is enabled.
 
     Return <tt>true</tt> if SELinux is enabled.
  
Line 317: Line 453:
  
 
     Determine whether SELinux is permissive or enforcing.
 
     Determine whether SELinux is permissive or enforcing.
 
 
     Returns <tt>true</tt> if SELinux is enforcing.
 
     Returns <tt>true</tt> if SELinux is enforcing.
  
Line 324: Line 459:
  
 
     Set whether SELinux is in permissive or enforcing modes.
 
     Set whether SELinux is in permissive or enforcing modes.
 
 
     <tt>value</tt> of <tt>true</tt> sets SELinux to enforcing mode.
 
     <tt>value</tt> of <tt>true</tt> sets SELinux to enforcing mode.
 
 
     Returns <tt>true</tt> if the desired mode was set.
 
     Returns <tt>true</tt> if the desired mode was set.
  
Line 333: Line 466:
  
 
     Sets the security context for newly created file objects.
 
     Sets the security context for newly created file objects.
 
 
     <tt>context</tt> is the security context to set.
 
     <tt>context</tt> is the security context to set.
 
 
     Returns <tt>true</tt> if the operation succeeded.
 
     Returns <tt>true</tt> if the operation succeeded.
  
Line 342: Line 473:
  
 
     Change the security context of an existing file object.
 
     Change the security context of an existing file object.
 
 
     <tt>path</tt> represents the path of file object to relabel.
 
     <tt>path</tt> represents the path of file object to relabel.
 
 
     <tt>context</tt> is the new security context to set .
 
     <tt>context</tt> is the new security context to set .
 
 
     Returns <tt>true</tt> if the operation succeeded.
 
     Returns <tt>true</tt> if the operation succeeded.
  
Line 353: Line 481:
  
 
     Get the security context of a file object.
 
     Get the security context of a file object.
 
 
     <tt>path</tt> the pathname of the file object.
 
     <tt>path</tt> the pathname of the file object.
 
 
     Returns the requested security context or null.
 
     Returns the requested security context or null.
  
Line 362: Line 488:
  
 
     Get the security context of a peer socket.
 
     Get the security context of a peer socket.
 
 
     <tt>FileDescriptor</tt> is the file descriptor class of the peer socket.
 
     <tt>FileDescriptor</tt> is the file descriptor class of the peer socket.
 
 
     Returns the peer socket security context or null.
 
     Returns the peer socket security context or null.
  
Line 371: Line 495:
  
 
     Gets the security context of the current process.
 
     Gets the security context of the current process.
 
 
     Returns the current process security context or null.
 
     Returns the current process security context or null.
  
Line 378: Line 501:
  
 
     Gets the security context of a given process id.
 
     Gets the security context of a given process id.
 
 
     <tt>pid</tt> an <tt>int</tt> representing the process id to check.
 
     <tt>pid</tt> an <tt>int</tt> representing the process id to check.
 
 
     Returns the security context of the given pid or null.
 
     Returns the security context of the given pid or null.
  
 
|-
 
|-
| <tt>'''<nowiki>String[] getBooleanNames()</nowiki>'''</tt>
+
| Deprecated as policy booleans no longer supported.
  
    Gets a list of the SELinux boolean names.
+
<tt>'''<nowiki>String[] getBooleanNames()</nowiki>'''</tt>
  
 +
    Gets a list of the SELinux boolean names.
 
     Return an array of strings containing the SELinux boolean names.
 
     Return an array of strings containing the SELinux boolean names.
  
 
|-
 
|-
| <tt>'''boolean getBooleanValue(String name)'''</tt>
+
| Deprecated as policy booleans no longer supported.
 +
 
 +
<tt>'''boolean getBooleanValue(String name)'''</tt>
  
 
     Gets the value for the given SELinux boolean name.
 
     Gets the value for the given SELinux boolean name.
 
 
     <tt>name</tt> is the name of the SELinux boolean.
 
     <tt>name</tt> is the name of the SELinux boolean.
 
 
     Returns true or false indicating whether the SELinux boolean is set or not.
 
     Returns true or false indicating whether the SELinux boolean is set or not.
  
 
|-
 
|-
| <tt>'''boolean setBooleanValue(String name, boolean value)'''</tt>
+
| Deprecated as policy booleans no longer supported.
  
    Sets the value for the given SELinux boolean name. Note that this will be set the boolean
+
<tt>'''boolean setBooleanValue(String name, boolean value)'''</tt>
    permanently across reboots.
+
  
 +
    Sets the value for the given SELinux boolean name. Note that this will be set the boolean permanently across reboots.
 
     <tt>name</tt> is the name of the SELinux boolean.
 
     <tt>name</tt> is the name of the SELinux boolean.
 
 
     <tt>value</tt> is the new value of the SELinux boolean.
 
     <tt>value</tt> is the new value of the SELinux boolean.
 
 
     Returns true if the operation succeeded.
 
     Returns true if the operation succeeded.
  
 
|-
 
|-
| <tt>'''boolean checkSELinuxAccess(String scon, String tcon,'''</tt> <tt>'''String tclass, String perm)'''</tt>
+
| <tt>'''boolean checkSELinuxAccess(String scon, String tcon, String tclass, String perm)'''</tt>
  
 
     Check permissions between two security contexts.
 
     Check permissions between two security contexts.
 
 
     <tt>scon</tt> is the source or subject security context.
 
     <tt>scon</tt> is the source or subject security context.
 
 
     <tt>tcon</tt> is the target or object security context.
 
     <tt>tcon</tt> is the target or object security context.
 
 
     <tt>tclass</tt> is the object security class name.
 
     <tt>tclass</tt> is the object security class name.
 
 
     <tt>perm</tt> is the permission name.
 
     <tt>perm</tt> is the permission name.
 
 
     Returns true if permission was granted.
 
     Returns true if permission was granted.
  
Line 429: Line 544:
 
| <tt>'''boolean restorecon(String pathname)'''</tt>
 
| <tt>'''boolean restorecon(String pathname)'''</tt>
  
     Restores a file to its default SELinux security context. If the system is not compiled with SELinux,
+
     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.
    then true is automatically returned. If SELinux is compiled in, but disabled, then true is returned.
+
 
+
 
     <tt>pathname</tt> is the pathname of the file to be relabeled.
 
     <tt>pathname</tt> is the pathname of the file to be relabeled.
 
 
     Returns true if the relabeling succeeded.
 
     Returns true if the relabeling succeeded.
 
 
     <tt>exception NullPointerException</tt> if the pathname is a null object.
 
     <tt>exception NullPointerException</tt> if the pathname is a null object.
  
Line 441: Line 552:
 
| <tt>'''boolean restorecon(File file)'''</tt>
 
| <tt>'''boolean restorecon(File file)'''</tt>
  
     Restores a file to its default SELinux security context. If the system is not compiled with SELinux,
+
     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.
    then true is automatically returned. If SELinux is compiled in, but disabled, then true is returned.
+
 
+
 
     <tt>file</tt> is the file object representing the path to be relabeled.  
 
     <tt>file</tt> is the file object representing the path to be relabeled.  
 
 
     Returns true if the relabeling succeeded.
 
     Returns true if the relabeling succeeded.
 
 
     <tt>exception NullPointerException</tt> if the file is a null object.
 
     <tt>exception NullPointerException</tt> if the file is a null object.
 +
 +
|-
 +
| <tt>'''boolean restoreconRecursive(File file)'''</tt>
 +
 +
    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.
 +
    <tt>pathname</tt> is the pathname of the file to be relabeled.
 +
    Returns a boolean indicating whether the relabeling succeeded.
  
 
|}
 
|}
 
  
  
 
== Android Init Language SELinux Extensions ==
 
== 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 <tt>system/core/init/readme.txt</tt> file.
+
The Android init process language has been expanded to support SELinux as shown in Table 3. The complete Android <tt>init</tt> language description is available in the <tt>system/core/init/readme.txt</tt> file.
  
 
'''Table 3: SELinux init extensions'''
 
'''Table 3: SELinux init extensions'''
Line 461: Line 574:
 
|  <tt>'''<nowiki>seclabel <securitycontext></nowiki>'''</tt>
 
|  <tt>'''<nowiki>seclabel <securitycontext></nowiki>'''</tt>
  
Change to security context before exec'ing this service. Primarily for use by services run from the rootfs, e.g. <tt>ueventd</tt>, <tt>adbd</tt>. 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.
+
: <tt>service option</tt>: Change to security context before exec'ing this service. Primarily for use by services run from the rootfs, e.g. <tt>ueventd</tt>, <tt>adbd</tt>. 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.
  
 
|-
 
|-
 
|  <tt>'''<nowiki>restorecon <path></nowiki>'''</tt>
 
|  <tt>'''<nowiki>restorecon <path></nowiki>'''</tt>
  
Restore the file named by <tt><nowiki><path></nowiki></tt> to the security context specified in the <tt>file_contexts</tt> configuration. Not required for directories created by the <tt>init.rc</tt> as these are automatically labeled correctly by init.
+
: <tt>action command</tt>: Restore the file named by <tt><nowiki><path></nowiki></tt> to the security context specified in the <tt>file_contexts</tt> configuration. Not required for directories created by the <tt>init.rc</tt> as these are automatically labeled correctly by init.
 +
 
 +
|-
 +
|  <tt>'''<nowiki>restorecon_recursive <path> [ <path> ]*</nowiki>'''</tt>
 +
 
 +
: <tt>action command</tt>: Recursively restore the directory tree named by <tt><nowiki><path></nowiki></tt> to the security context specified in the <tt>file_contexts</tt> 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|Checking File Labels]] section for further details.
  
 
|-
 
|-
 
|  <tt>'''<nowiki>setcon <securitycontext></nowiki>'''</tt>
 
|  <tt>'''<nowiki>setcon <securitycontext></nowiki>'''</tt>
  
Set the current process security context to the specified string. This is typically only used from <tt>early-init</tt> to set the init context before any other process is started (see <tt>init.rc</tt> example above).
+
: <tt>action command</tt>: Set the current process security context to the specified string. This is typically only used from <tt>early-init</tt> to set the init context before any other process is started (see <tt>init.rc</tt> example above).
  
 
|-
 
|-
|  <tt>'''setenforce <nowiki>0|1</nowiki>'''</tt>
+
|  <tt>'''<nowiki>setenforce 0|1</nowiki>'''</tt>
  
Set the SELinux system-wide enforcing status. 0 is permissive (i.e. log but do not deny), 1 is enforcing.
+
: <tt>action command</tt>: Set the SELinux system-wide enforcing status. 0 is permissive (i.e. log but do not deny), 1 is enforcing.
  
 
|-
 
|-
 
|  <tt>'''<nowiki>setsebool <name> <value></nowiki>'''</tt>
 
|  <tt>'''<nowiki>setsebool <name> <value></nowiki>'''</tt>
  
Set SELinux boolean <tt><nowiki><name></nowiki></tt> to <tt><nowiki><value></nowiki></tt>.  
+
: Deprecated as booleans no longer supported.
 
+
: <tt>action command</tt>: Set SELinux boolean <tt><nowiki><name></nowiki></tt> to <tt><nowiki><value></nowiki></tt>.  
<tt><nowiki><value></nowiki></tt> may be <tt>1|true|on</tt> or <tt>0|false|off</tt>
+
: <tt><nowiki><value></nowiki></tt> may be <tt>1|true|on</tt> or <tt>0|false|off</tt>
  
 
|}
 
|}
  
  
Examples of their usage are shown in the following init file segments:
+
Examples of their usage are shown in the following <tt>init.rc</tt> file segments:
 
<pre>
 
<pre>
# system/core/rootdir/init.rc
+
system/core/rootdir/init.rc
 
+
 
...
 
...
 +
 
on early-init
 
on early-init
<nowiki>    # Set init and its forked children's oom_adj.</nowiki>
+
    ...
write /proc/1/oom_adj -16
+
 
 +
    # 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
 +
    ...
  
<nowiki>    # Set the security context for the init process.</nowiki>
+
on post-fs-data
<nowiki>    # This should occur before anything else (e.g. ueventd) is started.</nowiki>
+
setcon u:r:init:s0
+
start ueventd
+
...
+
on boot
+
 
...
 
...
 +
    # 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
 
service ueventd /sbin/ueventd
 
     class core
 
     class core
Line 509: Line 638:
 
     seclabel u:r:ueventd:s0
 
     seclabel u:r:ueventd:s0
 
</pre>
 
</pre>
<pre>
 
# system/core/rootdir/init.goldfish.rc
 
  
...
 
on boot
 
    setsebool in_qemu 1
 
    restorecon /sys/qemu_trace/process_name
 
    restorecon /sys/qemu_trace/state
 
    restorecon /sys/qemu_trace/symbol
 
...
 
</pre>
 
  
 +
== 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 <tt>adb</tt>). The alternate locations are always checked first as if present they override the default location as discussed in the comments section of Table 4.
  
== Policy Construction and Build ==
+
The <tt>init</tt> process will initially load the SELinux set of policy files from root (<tt>/</tt>). Once the <tt>/data</tt> partition setup has been completed (see <tt>init.rc</tt>) a policy reload is performed. This will check whether there is a valid policy at <tt>/data/security/current</tt> and load that if valid.  
An overview of the sections that cover the configuration and building of SELinux MAC and MMAC policies are as follows:
+
: [[#SELinux MAC Policy Files | SELinux MAC Policy Files]] - Describes the SELinux MAC policy files that define the policy and how they relate, and also the [[#Policy Versions | SELinux MAC Policy Files]] required. The [[#Policy Booleans | Policy Booleans]] are also detailed with their default state.
+
  
: [[#Install-time MMAC Configuration | Install-time MMAC Configuration]] - This is installed as part of default policy and contains information that is used to determine permissions allowed and/or denied.
+
If safe mode, then only the root policy files will be loaded. A factory reset will wipe <tt>/data</tt> and will therefore revert to the original root policy files.
  
: [[#Intent MAC Configuration | Intent MAC Configuration]] - Describes how the intent MMAC is configured and built when using the <tt>intent_mac</tt> branch build.
+
'''Table 4: Policy file locations'''
 +
{| border="1"
 +
| <center>'''Default Location'''</center>
 +
| <center>'''Alternate Location'''</center>
 +
| <center>'''Comments'''</center>
  
: [[#Revoke Permissions Configuration | Revoke Permissions Configuration]] - Describes how the revoke permissions middleware is configured and built when using the <tt>revoke-perms</tt> branch build.
+
|-
 +
| <tt>/sepolicy</tt>
 +
<tt>/file_contexts</tt>
 +
<tt>/seapp_contexts</tt>
 +
<tt>/property_contexts</tt>
 +
<tt>/service_contexts</tt>
 +
<tt>/selinux_version</tt>
 +
<tt>/mac_permissions.xml</tt>
  
: [[#Policy Build Tools | Policy Build Tools]] - Describes the tools available that assist in building the policy and their configuration files.
+
|  <tt>/data/security/current</tt>
 +
| 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:
 +
# During a policy reload, if there is an <tt>selinux_version</tt> file in the alternate location, then the default location will be over-ridden. If the policy has been updated via the <tt>buildsebundle</tt> / SEAdmin app process then this would be the case.
 +
# The alternate directory may be a symbolic link to another directory. For example the <tt>buildsebundle</tt> / SEAdmin app process adds a link to <tt>/data/security/context</tt> that holds the policy files
 +
# If the policy has been updated via the <tt>buildsebundle</tt> / SEAdmin app process, then the following will also be present:
  
: [[#Building the Policy | Building the Policy]] - Describes how the SELinux MAC and MMAC policies are configured and built during the make process including support for device dependent policy.
+
::: <tt>/data/security/bundle</tt> will contain the <tt>sepolicy_bundle</tt> (the packed files) and a <tt>metadata</tt> directory containing a <tt>version</tt> file holding the last version number.
 +
::: There will be <tt><nowiki>*_backup</nowiki></tt> policy files of the previous version that could be restored if required.
  
 +
See the [[NB_SEforAndroid_2#buildsebundle|Build Bundle Tools - ]][[NB_SEforAndroid_2#buildsebundle|buildsebundle]] section for a worked example.
  
=== SELinux MAC Policy Files ===
+
|-
The MAC policy configuration files are contained in the <tt>external/sepolicy</tt> directory, however there may also be policy configuration files to enable specific device features under <tt><nowiki>device/<vendor></nowiki></tt> directories (see the [[#Building_the_Policy | Building the Policy]] section). Once generated, the policy and its supporting configuration files are installed on the device as part of the build process.
+
<tt>/system/etc/security/eops.xml</tt>
 +
<tt>/data/security/eops</tt>
 +
| If the policy has been updated via the <tt>buildeopbundle</tt> / SEAdmin app process, then the following will also be present in the alternative location:
  
The following files are used to build the kernel binary policy file that will be named <tt>sepolicy</tt> and installed by default in the root directory. An updated policy may be installed at <tt>/data/security/sepolicy</tt>. The initialisation or policy reload process will always check for a policy at <tt>/data/security/sepolicy</tt> first and then if not present at <tt>/sepolicy</tt>. The policy files consist of the following:
+
* <tt>/data/security/eops/eops_metadata/version</tt> file holding the last version number.
  
: <tt>access_vectors</tt>, <tt>security_classes</tt>
+
See the [[NB_SEforAndroid_2#buildeopbundle|Build Bundle Tools - ]][[NB_SEforAndroid_2#buildeopbundle|buildeopbundle]] section for a worked example.
:: These have been modified to support the new SE for Android classes and permissions.
+
  
: <tt>initial_sids</tt>, <tt>initial_sids_contexts</tt>, <tt>fs_use</tt>, <tt>genfs_contexts</tt>, <tt>port_contexts</tt>
+
|-
:: For flexibility of policy building, these files have been separated to allow additional policy files to be defined for specific devices as discussed below.
+
<tt>/data/system/ifw/ifw.xml</tt>
 +
<tt>/data/secure/system/ifw</tt>
  
: <tt>users</tt>, <tt>roles</tt>
+
(default for encrypted systems)
:: These define the only user (<tt>u</tt>) and role (<tt>r</tt>) used by the policy, although there is no reason why others cannot be added.
+
| This file is not installed by default and note that the Intent Firewall service will read any file from <tt>/data/system/ifw/</tt> so long as it has an <tt>.xml</tt> extension.
  
: <tt>mls</tt>
+
If required would be built and delivered by the <tt>buildifwbundle</tt> / SEAdmin app process, with the following also present in the default location:
:: Contains the constraints applied to the defined classes and permissions.
+
  
: <tt>global_macros</tt>, <tt>mls_macro</tt>, <tt>te_marcos</tt>
+
* <tt>/data/system/ifw/metadata/gservices.version</tt> file holding the last version number.
:: These contain the m4 macros that expand the policy files to build a policy in the kernel policy language as described in the [[PolicyLanguage  | Policy Language]] section. The policy can then be compiled by <tt>'''checkpolicy'''(8)</tt>. For reference, the policy text file is built and placed in:
+
::: <nowiki>out/target/product/<device>/obj/ETC/sepolicy_intermediates/policy.conf</nowiki>
+
  
:: The compiled kernel policy can also be found in this directory and is named <tt>sepolicy</tt>. There are also <tt>policy.conf.dontaudit</tt> and <tt>sepolicy.dontaudit</tt> files that have the <tt>dontaudit</tt> rules removed. Stripping out these rules stops the auditing of denial messages as they are known events and do not cause any issues. This also helps to manage the audit log by excluding known denial events.
+
See the [[NB_SEforAndroid_2#buildifwbundle|Build Bundle Tools - ]][[NB_SEforAndroid_2#buildifwbundle|buildifwbundle]] section for a worked example.
  
: <tt>attributes</tt>
+
|-
:: Contains the attribute names (forming the [[TypeStatements#attribute_Statement | attribute statements]]) that will be used to group [[TypeStatements#type_Statement | type identifiers ]] defined by the policy.
+
<tt>/system/etc/sepolicy.recovery</tt>
 +
| none
 +
| Only used for recovery.
  
: <tt>policy_capabilities</tt>
+
|}
:: Contains the policy capabilities enabled for the kernel policy (see [[PolicyStatements#policycap_Statement | policycap statement]]).
+
  
: <tt><nowiki>*.te</nowiki></tt>
 
:: The <tt><nowiki>*.te</nowiki></tt> files are the 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 <tt>.te</tt> file for each domain/service defined for the device and will contain all the required [[AVCRules | allow]], [[TypeRules#Type_Enforcement_Rules | type_transition]] etc. rules. It will also call any <tt>te_macros</tt> to access other domains resources (e.g. <tt>init_daemon_domain</tt>, <tt>binder_call</tt>).
 
  
The following files are used to compute and/or configure SE for Android security contexts and reflect information configured within the kernel policy. These files are:
+
== 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 [[NB_SEforAndroid_2#Policy Configuration File Formats | Policy Configuration File Formats]] with examples.
  
: <tt>file_contexts</tt>
+
=== SELinux Policy Files ===
:: Contains default file contexts for setting the filesystem as standard SELinux. The format of this file is defined in [[PolicyStoreConfigurationFiles#file_contexts_File |<tt>'''file_contexts'''(5)</tt>]]. The file is installed by default in the root directory. SE for Android services (such as <tt>[[#SELinux Commands | restorecon]](8)</tt>) will first check for this file at (this is where updated files should be placed):
+
The core policy files are contained in <tt>external/sepolicy</tt>, with device specific policy in <tt><nowiki>device/<vendor>/<device>/sepolicy</nowiki><ref name="ftn1">Except for the emulator device policy that is in <tt>build/target/board/generic/sepolicy</tt>.</ref> (see the [[#Processing Device Policy | 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.
::: <tt>/data/security/file_contexts</tt>  
+
:: If not present they will then check the root directory:
+
::: <tt>/file_contexts</tt>
+
  
: <tt>property_contexts</tt>
+
==== Core Policy Files ====
:: Contains default contexts to be applied to Android property services as discussed in the [[NB_SEforAndroid_2#property_contexts File | 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 should be placed):
+
The following files (along with any device specific policy) are used to build the kernel binary policy file named <tt>sepolicy</tt> and installed by default in the root directory.
::: <tt>/data/security/property_contexts</tt>
+
::If not present they will then check the root directory:
+
:::<tt>/property_contexts</tt>
+
  
: <tt>seapp_contexts</tt>
+
: <tt>'''access_vectors'''</tt>
:: Contains information to allow domain or file contexts to be computed based on parameters as discussed in the [[NB_SEforAndroid_2#seapp_contexts File | 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 should be placed):
+
: <tt>'''security_classes'''</tt>
::: <tt>/data/security/seapp_contexts</tt>
+
:: These have been modified to support the new Android classes and permissions (although they still contain the unused Linux userspace items).
:: If not present they will then check the root directory:
+
::: <tt>/seapp_contexts</tt>
+
  
: <tt>selinux-network.sh</tt>
+
: <tt>'''initial_sids'''</tt>
:: If using <tt>'''iptables'''(8)</tt> then SECMARK information may be configured in this file as part of the build. It is installed in <tt>system/bin</tt> and executed at system initialisation time.
+
: <tt>'''initial_sids_contexts'''</tt>
 +
:: Contains the system initialisation (before policy is loaded) and failsafe (for objects that would not otherwise have a valid label).
  
 +
: <tt>'''fs_use'''
 +
: '''genfs_contexts'''
 +
: '''port_contexts'''</tt>
 +
:: For flexibility of policy building, these files have been separated to allow additional policy files to be defined for specific devices as discussed below.
  
==== SELinux Policy Versions ====
+
: <tt>'''users'''
The default SELinux policy version is 26 that requires a kernel >= 3.0 and is set in <tt>external/sepolicy/Android.mk</tt> as follows:
+
: '''roles'''</tt>
<pre>
+
:: These define the only user (<tt>u</tt>) and role (<tt>r</tt>) used by the policy.
POLICYVERS ?= 26
+
</pre>
+
  
If an older kernel must be supported <tt>POLICYVERS</tt> can be set in your environment as follows:
+
: <tt>'''mls'''</tt>
<pre>
+
:: Contains the constraints to be applied to the defined classes and permissions.
export POLICYVERS=24
+
</pre>
+
  
Information regarding policy versions can be found at [[NB_PolicyType#Policy_Versions | Policy Versions]].
+
: <tt>'''global_macros'''
 +
: '''mls_macro'''
 +
: '''te_marcos'''</tt>
 +
:: 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 http://selinuxproject.org/page/PolicyLanguage]. The policy will then be compiled by <tt>'''checkpolicy'''(8)</tt>.
  
Note that the current libsepol used by SE for Android will support a maximum of version 27. If greater required, then upgrade libsepol to a later version and check that the kernel will also support the higher version.
+
: <tt>'''attributes'''</tt>
 +
:: Contains the attribute names (forming the [http://selinuxproject.org/page/TypeStatements#attribute_Statement attribute] statements) that will be used to group [http://selinuxproject.org/page/TypeStatements#type_Statement type] identifiers defined by the policy.
  
 +
: <tt>'''policy_capabilities'''</tt>
 +
:: Contains the policy capabilities enabled for the kernel policy (see [http://selinuxproject.org/page/Policy_Configuration_Statements policycap] statement).
  
==== SELinux Policy Booleans ====
+
: <tt>'''<nowiki>*.te</nowiki>'''</tt>
Table 4 describes the SELinux policy booleans and their default state. Their state can be changed permanently across reboots using the SEAdmin / SEManager apps (as they call the <tt>setBooleanValue()</tt> method), or temporarily using the <tt>adb shell setsebool</tt> command. They can also be made permanent by adding them to the init.rc or init.<board>.rc files (this is the only way to make them permanent on vanilla AOSP builds or if SEAdmin / SEManager are not installed).
+
:: The <tt><nowiki>*.te</nowiki></tt> 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 <tt>.te</tt> file for each domain/service defined containing the policy rules.
  
'''Table 4: SE for Android SELinux Policy Booleans'''
+
==== Policy Configuration Files ====
{| border="1"
+
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 | Checking File Labels]] section for further information).
| <center>'''Boolean Name'''</center>
+
| <center>'''Default state'''</center>
+
| <center>'''Comments'''</center>
+
  
|-
+
: <tt>'''file_contexts'''</tt>
<tt>android_cts</tt>
+
:: Contains default file contexts for setting the SELinux extended file attributes (<tt>'''attr'''(1)</tt>). The format of this file is defined in the [[NB_SEforAndroid_2#file_contexts | file_contexts]] section. The file is installed by default in the root directory.<tt> </tt>Android services (such as [[#SELinux Commands | restorecon]]) will first check for this file at:
| <center>FALSE</center>
+
::: <tt>/data/security/current/file_contexts</tt>
| Allow the Android CTS to run if TRUE. Do not enable in production policy.
+
:: If not present then check root directory:
 +
::: <tt>/file_contexts</tt>
  
|-
+
: <tt>'''seapp_contexts'''</tt>
| <tt>app_external_sdcard_rw</tt>
+
:: Contains information to allow domain or data file contexts to be computed based on parameters as discussed in the [[NB_SEforAndroid_2#seapp_contexts | 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:
| <center>TRUE</center>
+
::: <tt>/data/security/current/seapp_contexts</tt>
| Allow <tt>untrusted_app</tt> domain external SD card <tt>rw</tt> access if TRUE.
+
:: If not present then check root directory:
 +
::: <tt>/seapp_contexts</tt>
 +
 +
: <tt>'''property_contexts'''</tt>
 +
:: Contains default contexts for Android property services as discussed in the [[NB_SEforAndroid_2#property_contexts | 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:
 +
::: <tt>/data/security/property_contexts</tt>
 +
:: If not present then check root directory:
 +
::: <tt>/property_contexts</tt>
  
|-
+
: <tt>'''service_contexts'''</tt>
<tt>app_internal_sdcard_rw</tt>
+
:: Contains default contexts for Android services as discussed in the [[NB_SEforAndroid_2#service_contexts | 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:
| <center>TRUE</center>
+
::: <tt>/data/security/service_contexts</tt>
| Allow <tt>untrusted_app</tt> domain internal SD card <tt>rw</tt> access if TRUE.
+
:: If not present then check root directory:
 +
::: <tt>/service_contexts</tt>
  
|-
+
The following files will be built as part of the build process and installed on the device:
|  <tt>debugfs</tt>
+
| <center>FALSE</center>
+
| Allow <tt>domain</tt> <tt>rw</tt> access on <tt>debugfs</tt> if TRUE.
+
  
|-
+
: <tt>'''sepolicy'''</tt>
<tt>in_qemu</tt>
+
:: The kernel binary policy. The Android initialisation / reload process will first check for this file at:
| <center>FALSE</center>
+
::: <tt>/data/security/current/sepolicy</tt>
| Allow <tt>domain</tt> <tt>rw</tt> access on <tt>/sys/qemu_trace</tt> files in the emulator if TRUE.
+
:: If not present then check root directory:
 +
::: <tt>/sepolicy</tt>
 +
:: For reference, the policy text file containing the [http://selinuxproject.org/page/PolicyLanguage#Kernel_Policy_Language_Definition_Links kernel policy language statements] is available at:
 +
::: <tt><nowiki>out/target/product/<device>/obj/ETC/sepolicy_intermediates/policy.conf</nowiki></tt>
 +
:: The compiled kernel policy (<tt>sepolicy</tt>) is also in this directory along with <tt>policy.conf.dontaudit</tt> and <tt>sepolicy.dontaudit</tt> files that have the <tt>dontaudit</tt> rules removed.
  
Note that when running the emulator this is automatically set TRUE on boot (see <tt>init.goldfish.rc</tt>)
+
: <tt>'''sepolicy.recovery'''</tt>
 +
:: A recovery policy is installed at <tt>system/etc/sepolicy.recovery</tt>. It is build with the macro<tt> target_recovery = true</tt> that will add additional rules defined in the <tt>recovery.te</tt> module (see <tt>Android.mk</tt> and <tt>te_macros</tt>). For reference the recovery policy text file is available at:
 +
:: <tt><nowiki>out/target/product/<device>/obj/ETC/sepolicy.recovery_intermediates/policy_recovery.conf</nowiki></tt>
 +
 +
: <tt>'''selinux_version'''</tt>
 +
:: The <tt>selinux_version</tt> file is generated containing the <tt>BUILD_FINGERPRINT</tt> 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 <tt>/data/security/current</tt> or root (<tt>/</tt>). The <tt>mac_permissions.xml</tt> would also be read from either <tt>/data/security/current</tt> or <tt>/system/etc/security</tt>).
  
|-
+
=== Install/Run-time MMAC Policy ===
|  <tt>support_runas</tt>
+
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.
| <center>TRUE</center>
+
| Support the Android adb shell <tt>run-as</tt> command if TRUE.
+
  
|-
+
The file that configures this policy is <tt>mac_permissions.xml</tt> that assigns an <tt>seinfo</tt> tag to apps based on their signature and optionally their package name. The <tt>seinfo</tt> tag can then be used as a key in the <tt>seapp_contexts</tt> file to assign a specific label to all apps with that <tt>seinfo</tt> tag. The configuration file is read by <tt>system_server</tt> during start-up. Its format is discussed in the [[NB_SEforAndroid_2#mac_permissions.xml | mac_permissions.xml]] section.
<tt>system_app_manage</tt>
+
| <center>FALSE</center>
+
| When set to TRUE will allow the <tt>system_app</tt> domain the ability to manage SE for Android (as well as the <tt>system</tt> domain).
+
  
When set to FALSE only the <tt>system</tt> domain can manage SE for Android.
+
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 <tt>mac_permissions.xml</tt> file when no <tt><nowiki><default></nowiki></tt> entry is present.
  
The management is based on the status of the <tt>manage_selinux</tt> and <tt>manage_mac</tt> booleans logically anded with <tt>system_app_manage</tt> i.e. if <tt>system_app_manage</tt> is TRUE, but <tt>mmac_manage</tt> is FALSE, the <tt>system_app</tt> domain will not be able to manage MMAC.
+
The file is installed by default at:
 +
:: <tt>/system/etc/security/mac_permissions.xml</tt>
  
|-
+
The Android initialisation / reload process will first check for this file at:
<tt>manage_selinux</tt>
+
:: <tt>/data/security/current/mac_permissions.xml</tt>
| <center>TRUE</center>
+
| Allow management of SELinux policy if TRUE. Also see the <tt>system_app_manage</tt> boolean.
+
  
|-
+
This file can be:
<tt>manage_mac</tt>
+
# Appended to by the <tt>BOARD_SEPOLICY_UNION</tt> variable as described in the [[#Processing Device Policy | Processing Device Policy]] section.
| <center>TRUE</center>
+
# Updated along with all other MAC policy files as described in the [[#Updating Policy | Updating Policy]] section.
| Allow management of MMAC policy if TRUE. Also see the <tt>system_app_manage</tt> boolean.
+
  
|}
+
The main code for the service is <tt>frameworks/base/services/java/com/android/server/pm/SELinuxMMAC.java</tt>, however it does hook into other Android services such as <tt>PackageManagerService.java</tt>.
  
 +
=== Device Specific Policy ===
 +
Some of this section has been extracted from the <tt>external/sepolicy/README</tt> that should be checked in case there have been updates. It describes how files in <tt>external/sepolicy</tt> can be manipulated during the build process to reflect requirements of different device vendors whose policy files would normally be located in the <tt><nowiki>device/<vendor>/<device>/sepolicy</nowiki></tt> directory.
  
 +
Important Note: Android policy has a number of [http://selinuxproject.org/page/AVCRules neverallow] rules defined in the core policy to ensure that [http://selinuxproject.org/page/AVCRules 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:
 +
:: [http://marc.info/?l=seandroid-list&m=141116103611797&w=2 http://marc.info/?l=seandroid-list&m=141116103611797&w=2]
  
==== Setting Permissive / Enforcing Mode ====
+
==== Managing Device Policy Files ====
There are three ways to set permissive or enforcing mode in SE for Android:
+
Additional per device policy files are manipulated by the policy build process using the following two variables that may be added to the device <tt>BoardConfig.mk</tt> file:
# Using the SEAdmin or SEManager apps.
+
# Adding the <tt>setenforce</tt> command to the init.rc or init.<board>.rc files.
+
# Using <tt>adb</tt> to run the <tt>setenforce</tt> command.
+
  
 +
: <tt>'''BOARD_SEPOLICY_DIRS'''</tt>
 +
:: Contains a list of directories to search for files listed by the <tt>BOARD_SEPOLICY_UNION</tt> variable. Order matters in this list. e.g. If the following is defined:
 +
::: <tt>BOARD_SEPOLICY_UNION := widget.te</tt>
 +
:: and there are two instances of <tt>widget.te</tt> files on the <tt>BOARD_SEPOLICY_DIRS</tt> search path, the first one found (at the first search directory containing the file) gets processed first. Reviewing the devices <tt>policy.conf<ref name="ftn2">The <tt>policy.conf</tt> file contains the policy language statements as described at [http://selinuxproject.org/page/PolicyLanguage http://selinuxproject.org/page/PolicyLanguage]. These define the policy that will be enforced.</ref> will help sort out ordering issues and is located at:
 +
::: <tt><nowiki>out/target/product/<device>/obj/ETC/sepolicy_intermediates/policy.conf</nowiki></tt>
  
==== Modifying and Reloading Policy ====
+
: <tt>'''BOARD_SEPOLICY_UNION'''</tt>
This is covered at [[SEforAndroid#Policy | SEforAndroid - Policy]] in detail. This section gives a brief overview:
+
:: Contains a list of files that will be "unioned", i.e. concatenated at the END of their respective files in <tt>external/sepolicy</tt>
 +
:: To add a unique/new file this variable would be used.
 +
:: It is an error to specify a <tt>BOARD_POLICY_UNION</tt> file that does not exist in <tt>external/sepolicy</tt>.
  
# Modify the required policy source files, then regenerate the kernel policy file by:
+
'''Examples:'''
<pre>
+
make sepolicy
+
</pre>
+
  
# Copy the policy file to the device:
+
The example <tt>BoardConfig.mk</tt> entries showing the use of <tt>BOARD_SEPOLICY_UNION</tt> that will take files referenced in <tt>BOARD_SEPOLICY_DIRS</tt> and add their contents to the end of the respective files in <tt>external/sepolicy</tt>, it will also include those not in <tt>external/sepolicy</tt>.
<pre>
+
adb push out/target/product/<device>/root/sepolicy /data/security
+
</pre>
+
  
# Then load the new policy by:
+
Example:
 
<pre>
 
<pre>
adb shell su 0 setprop selinux.reload_policy 1
+
BOARD_SEPOLICY_DIRS := device/samsung/tuna/sepolicy
 +
 +
BOARD_SEPOLICY_UNION := \
 +
    genfs_contexts \
 +
    file_contexts \
 +
    sepolicy.te
 
</pre>
 
</pre>
  
=== Install-time MMAC Configuration ===
+
=== Build Tools ===
The install-time MMAC is part of the standard policy build but is classed as a middleware MAC. The file that configures policy is called <tt>mac_permissions.xml</tt> and its format is discussed in the [[NB_SEforAndroid_2#Install_MMAC_File | mac_permissions.xml file]] section. The file is installed by default at:
+
The kernel policy is compiled using <tt>'''checkpolicy'''(8)</tt> via the <tt>external/sepolicy/Android.mk</tt> file. There are also a number of Android specific tools used to assist in policy configuration that are described in [[NB_SEforAndroid_2#Policy Build Tools|Policy Build Tools]], with a summary as follows:
: <tt>/system/etc/security/mac_permissions.xml</tt>
+
: <tt>'''checkfc'''</tt> - Used to parse the <tt>file_contexts</tt> file against the binary policy <tt>sepolicy</tt>. This is to ensure all file contexts are valid for the policy. There is a <tt>-p</tt> option that is used to validate the contexts defined in the <tt>property_contexts</tt> or <tt>service_contexts</tt> file.
The SE for Android initialisation / reload process will first check for this file at (this is where updated files should be placed):
+
: <tt>'''checkseapp'''</tt> - Used to validate the <tt>seapp_contexts</tt> file entries against the binary policy <tt>sepolicy</tt>.  
: <tt>/data/security/mac_permissions.xml</tt>
+
: <tt>'''insertkeys.py'''</tt> - Used to replace keywords in the <tt>signature</tt> sections of the <tt>mac_permissions.xml</tt> file with information obtained from <tt>pem</tt> files. This uses information contained in the <tt>external/sepolicy/keys.conf</tt> file that is detailed in the [[NB_SEforAndroid_2#insertkeys.py |insertkeys.py]] tools section.
This file can be replaced through <tt>BOARD_SEPOLICY_REPLACE </tt>containing the value <tt>mac_permissions.xml</tt>, or appended to by using the <tt>BOARD_SEPOLICY_UNION</tt> variable as described in the [[#README Extract | Building the Policy]] section.
+
:: Note that the tools listed below are not built as part of the standard build process, therefore use <tt><nowiki>make <tool_name></nowiki></tt> except where indicated.
The main code for the service is <tt>frameworks/base/services/java/com/android/server/pm/SELinuxMMAC.java</tt>, however it does hook into other Android services.  
+
: <tt>'''post_process_mac_perms'''</tt> - Assists in generating new entries in an existing <tt>mac_permissions.xml</tt> file (also see <tt>setool</tt>). There is no make target for this python script, so either move to <tt>HOST_EXECUTABLE</tt> or execute directly (e.g. <tt>$PREFIX/external/sepolicy/tools/post_process_mac_perms</tt>).
There is a system property to control whether the service is in permissive or enforcing mode and can be set by the SEAdmin app or using adb (note that this property also used for intent MAC):
+
: <tt>'''sepolicy-analyze'''</tt> - Used to analyze the kernel policy file (<tt>sepolicy</tt>) for equivalent or different type pairs, or duplicate allow rules.
<pre>
+
: <tt>'''sepolicy-check'''</tt> - Used to check the kernel policy file (<tt>sepolicy</tt>) for allow rules based on source / target types, class and a single permission.
<nowiki># 1 = enforcing 0 = permissive</nowiki>
+
: <tt>'''<nowiki>build<???>bundle</nowiki>'''</tt> - Used to build bundles for <tt>sepolicy</tt> et al., <tt>eop.xml</tt> or <tt>ifw.xml</tt> files to handle policy updates. Not available on AOSP.
  adb shell su 0 setprop persist.mmac.enforce 1
+
: <tt>'''setool'''</tt> - Assists in generating new entries for the <tt>mac_permissions.xml</tt> 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 [[NB_SEforAndroid_2#setool | setool]] tools section. Not available on AOSP.
</pre>
+
  
 +
=== Miscellaneous Information ===
 +
==== SELinux Policy Versions ====
 +
The default SELinux policy version is 26 that requires a kernel >= 3.0 and is set in <tt>external/sepolicy/Android.mk</tt> as follows:
 +
: <tt>POLICYVERS ?= 26</tt>
  
=== Intent MAC Configuration ===
+
If an older kernel must be supported <tt>POLICYVERS</tt> can be set as an environment variable as follows:
Intent MAC is not part of the standard policy and can be found in the <tt>intent_mac</tt> branch as described in [[SEforAndroid#Intent_MAC | IntentMAC]]. However if it is enabled, the build process will automatically install and update the required components (such as SEAdmin to set enforcing / permissive mode).
+
: <tt>export POLICYVERS=24</tt>
The files that configure policy are <tt>intent_mac.xml</tt> and <tt>mmac_types.xml</tt> and by default they are installed at:
+
: <tt>/system/etc/security/intent_mac.xml</tt>
+
: <tt>/system/etc/security/mmac_types.xml</tt>
+
  
The SE for Android initialisation / reload process will first check for these files at (this is where updated files should be placed):
+
Information regarding policy versions can be found at [http://selinuxproject.org/page/NB_PolicyType#Policy_Versions http://selinuxproject.org/page/NB_PolicyType#Policy_Versions] that also gives information on the kernel versions required.
: <tt>/data/security/intent_mac.xml</tt>
+
: <tt>/data/security/mmac_types.xml</tt>
+
  
The file formats and their usage are discussed in the [[NB_SEforAndroid_2#Intent MAC Files |Intent MAC Files]] section. The files can also be replaced through <tt>BOARD_SEPOLICY_REPLACE </tt>containing the required file name, however only the <tt>mmac_types.xml</tt> file can be appended to by using the <tt>BOARD_SEPOLICY_UNION</tt> variable as described in the [[#README Extract | Building the Policy]] section.
+
==== SELinux Policy Booleans ====
The main code for the service is <tt>frameworks/base/core/java/andriod/content/pm/IntentMAC.java and MMACtypes.java</tt>, however it does hook into other Android services.
+
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.
There are a number of system properties that control the service and are defined in Table 5 with their default values. The enforcing mode is set using the SEAdmin app (Enforce MMAC policy tick box), however it may be also be set using <tt>setprop</tt>, for example:
+
<pre>
+
<nowiki># 1 = Enforcing 0 = Permissive</nowiki>
+
adb shell su 0 setprop persist.mmac_enforce 1
+
</pre>
+
  
 +
==== 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 [[PolicyStatements#permissive_Statement | permissive]] being present in the policy. These are ways to set permissive or enforcing mode:
  
'''Table 5: Intent MAC system properties and their default values'''
+
: Using adb to run the setenforce command:
{| border="1"
+
<pre>
<tt>persist.mmac.enforce = false</tt>
+
# enforcing = 1 permissive = 0
  
True turns on Intent MAC enforcing mode (as well as install-time MMAC). The SEAdmin app will also toggle this property.
+
adb shell su 0 setenforce 1
 +
</pre>
  
|-
+
: If running the emulator:
<tt>persist.mac_intent_allowSelf = true</tt>
+
<pre>
 +
emulator -selinux permissive
 +
</pre>
  
True allows intents going to an app's own component. This reduces amount of work required to create useful policy. If an app gets owned, this allows malicious code to send an Intent to an component running in the same process.
+
==== Checking File Labels ====
 +
Checks on file labels take place at boot time, policy upgrades / reloads, app installation / upgrade, and via <tt>adb</tt> using <tt>restorecon</tt>. Depending on whether data, app or system areas are being labeled by the various <tt>restorecon</tt> services, there are two files involved:
 +
# <tt>file_contexts</tt> for all areas other than <tt>/data/data</tt> and <tt>/data/user</tt>.
 +
# <tt>seapp_contexts</tt> file for <tt>/data/data</tt> and <tt>/data/user</tt> directories.
  
|-
+
Their use and format are described in the [[NB_SEforAndroid_2#file_contexts | file_contexts]] and [[NB_SEforAndroid_2#seapp_contexts | seapp_contexts]] sections.
| <tt>persist.mac_intent_allowSystem = true</tt>
+
  
True allows all intents coming from the <tt>system_server</tt>. This reduces the amount of work required to create useful policy.
+
To determine whether either of these two files have changed:
 +
# The <tt>file_contexts</tt> file has an SHA hash taken when loaded. This will be used when a recursive <tt>restorecon</tt> request is made and will be written to the pathname inode <tt>xattr</tt> entry of "<tt>security.resorecon_last</tt>" as files are labeled (except <tt>/sys</tt> files). When <tt>restorecon</tt> is run again (policy reload/update etc.), the <tt>xattr</tt> hash will be compared to the loaded <tt>file_contexts</tt> file hash, thus allowing automatic relabeling should the file change.
 +
# The s<tt>eapp_contexts</tt> file has an SHA hash taken when loaded and stored as <tt>/data/system/seapp_hash</tt> by <tt>SELinuxMMAC.java</tt>. This is used to determine whether a recursive <tt>restorecon</tt> should be carried out on the <tt>/data/data</tt> and <tt>data/user</tt> directories by the package manager.
  
|-
+
== Updating Policy Files ==
|  <tt>persist.mac_intent_allowSig = true</tt>
+
This is covered at [http://seandroid.bitbucket.org/PolicyUpdates.html http://seandroid.bitbucket.org/PolicyUpdates.html] in some detail and there are worked examples in the following sections:
  
True allows apps signed with the same signature to bypass checks. This boolean is intended to allow custom intents to work between apps that were written by the same author.
+
* [[NB_SEforAndroid_2#buildsebundle|Build Bundle Tools - ]][[NB_SEforAndroid_2#buildsebundle|buildsebundle]] - This includes using an intent to update policy.
 +
* [[NB_SEforAndroid_2#buildeopbundle|Build Bundle Tools - ]][[NB_SEforAndroid_2#buildeopbundle|buildeopbundle]]
 +
* [[NB_SEforAndroid_2#buildifwbundle|Build Bundle Tools - ]][[NB_SEforAndroid_2#buildifwbundle|buildifwbundle]]
  
|-
+
There are also details in the [[#Device Policy File Locations | Device Policy File Locations]] section.
|  <tt>persist.mac_intent_allowUid = true</tt>
+
  
True allows apps running with the same UID to bypass checks. This boolean is a little stronger than same signature, since apps can have different UIDs but authored by the same developer.
+
The Android services that manage the updates are contained in the following java source files within the <tt>frameworks/base/services/java/com/android/server/updates</tt> directory:
 +
* <tt>SELinuxPolicyInstallReceiver.java</tt>
 +
* <tt>IntentFirewallInstallReceiver.java</tt>
 +
* <tt>EopsInstallReceiver.java</tt>
  
|-
+
==== Local Policy Update ====
<tt>persist.mac_intent_printJSON = false</tt>
+
An example of loading a different policy via <tt>adb</tt> is described at [http://seandroid.bitbucket.org/AddressingHiddenDenials.html#13 http://seandroid.bitbucket.org/AddressingHiddenDenials.html#13], however this is an alternate method:
  
True prints a JSON formatted debugging string.
+
* Modify the required policy source files including the relevant device policy modules. Rebuild the kernel policy file by:
 +
<pre>
 +
make sepolicy
 +
</pre>
  
|-
+
* 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):
|  <tt>persist.mac_applyNameTypes = false</tt>
+
 
+
True - A type that is the same as a package name will be added to the list of types.
+
 
+
|-
+
|  <tt>persist.mac_applyPermTypes = false</tt>
+
 
+
True - For each permission, a type that is the same as that permission will be added to the list of types.
+
 
+
|}
+
 
+
 
+
=== Revoke Permissions Configuration ===
+
The revoke permission MAC is not part of the standard policy and can be found in the <tt>revoke-perms</tt> branch as described at [[SEforAndroid#Permission_revocation | SEforAndroid - Permission_revocation]]. The file that configures the policy is the <tt>revoke_permissions.xml</tt> and by default is installed at:
+
: <tt>/system/etc/security/revoke_permissions.xml</tt>
+
 
+
The SE for Android initialisation / reload process will first check for this file at (this is where updated files should be placed):
+
: <tt>/data/system/revoke_permissions.xml</tt>
+
 
+
The file format is shown in the [[NB_SEforAndroid_2#Revoke Permissions File|Revoke Permissions file]] section.
+
 
+
The main code for the service is self contained in:
+
: <tt>frameworks/base/services/java/com/android/server/pm/PackageManagerService.java</tt>
+
 
+
=== Building the Policy ===
+
Some of this section has been extracted from the <tt>external/sepolicy/README</tt> file that should be checked in case there have been updates. It describes how files in <tt>external/sepolicy</tt> can be manipulated during the build process to reflect requirements of different device vendors whose policy files would normally be located in the <tt><nowiki>device/<vendor>/<device>/sepolicy</nowiki></tt> directory.
+
 
+
==== Build Tools ====
+
The kernel policy is compiled using <tt>'''checkpolicy'''(8)</tt> via the <tt>external/sepolicy/Android.mk</tt> file. There are also a number of SE for Android specific tools used to assist in policy configuration that are described in [[NB_SEforAndroid_2#Policy Build Tools | Policy Build Tools]], with a summary as follows:
+
 
+
: <tt>[[NB_SEforAndroid_2#checkfc | checkfc]]</tt> - Used to parse the <tt>file_contexts</tt> file against the binary policy <tt>sepolicy</tt>. This is to ensure all file contexts are valid for the policy. There is a <tt>-p</tt> option that is used to validate the contexts defined in the <tt>property_contexts</tt> file.
+
 
+
: <tt>[[NB_SEforAndroid_2#checkseapp | checkseapp]]</tt> - Used to parse the <tt>seapp_contexts</tt> file against the binary policy <tt>sepolicy</tt>. This is to ensure policy related information is valid (e.g. checks booleans, types, levels etc.).
+
 
+
: <tt>[[NB_SEforAndroid_2#insertkeys.py | insertkeys.py]]</tt> - Used to replace keywords in the signature sections of the <tt>mac_permissions.xml</tt> and <tt>mmac_types.xml</tt> files with keys obtained from <tt>pem</tt> files. This uses information contained in the <tt>external/sepolicy/keys.conf</tt> file that is detailed in the [[NB_SEforAndroid_2#keys.conf | keys.conf]] section. This utility will also strip files of comments.
+
 
+
: <tt>[[NB_SEforAndroid_2#setool | setool]]</tt> - This is not used by the actual build process but assists in generating new entries for the <tt>mac_permissions.xml</tt> file. It will extract permissions from one or more packages with their signatures then generate the package sections. Its output may need to be modified before inclusion in the master file as detailed in the [[NB_SEforAndroid_2#setool| setool]] section.
+
 
+
==== README Extract ====
+
Additional per device policy files can be added or removed during the policy build. They can be configured through the use of the following four variables:
+
: <tt>BOARD_SEPOLICY_DIRS
+
: BOARD_SEPOLICY_UNION
+
: BOARD_SEPOLICY_REPLACE
+
: BOARD_SEPOLICY_IGNORE</tt>
+
 
+
The variables should be set in the <tt>BoardConfig.mk</tt> file in the device or vendor directories.
+
 
+
<tt>'''BOARD_SEPOLICY_DIRS'''</tt>
+
: <tt>BOARD_SEPOLICY_DIRS</tt> contains a list of directories to search for <tt>BOARD_SEPOLICY_UNION</tt> and <tt>BOARD_SEPOLICY_REPLACE</tt> files. Order matters in this list. e.g. If you have:
+
:: <tt>BOARD_SEPOLICY_UNION := widget.te</tt>
+
: and two instances of <tt>widget.te</tt> files are on <tt>BOARD_SEPOLICY_DIRS</tt> search path, the first one found (at the first search directory containing the file) gets processed first. Reviewing the devices <tt>policy.conf</tt><ref name="ftn3">The <tt>policy.conf</tt> file contains the policy language statements as described at [[PolicyLanguage | Policy Language]]. These define the policy that will be enforced and devices labeled.</ref> will help sort out ordering issues and is located at:
+
:: <tt><nowiki>out/target/product/<device>/obj/ETC/sepolicy_intermediates/policy.conf</nowiki></tt>
+
 
+
<tt>'''BOARD_SEPOLICY_UNION'''</tt>
+
: <tt>BOARD_SEPOLICY_UNION</tt> is a list of files that will be "unioned", i.e. concatenated, at the END of their respective files in <tt>external/sepolicy</tt>
+
: Note to add a unique/new file you would use this variable.
+
 
+
<tt>'''BOARD_SEPOLICY_REPLACE'''</tt>
+
: <tt>BOARD_SEPOLICY_REPLACE</tt> is a list of files that will be used instead of the corresponding file in <tt>external/sepolicy</tt>
+
 
+
<tt>'''BOARD_SEPOLICY_IGNORE'''</tt>
+
: <tt>BOARD_SEPOLICY_IGNORE</tt> is a list of paths (directory + filename) of files that are not to be included in the resulting policy. This list is passed to <tt>filter-out</tt> to remove any paths you may want to ignore. This is useful if you have numerous configuration directories that contain a file and you want to NOT include a particular file in your resulting policy file, either by <tt>BOARD_SEPOLICY_UNION</tt> or <tt>BOARD_SEPOLICY_REPLACE</tt>.
+
: For example, suppose the following:
+
 
<pre>
 
<pre>
BOARD_SEPOLICY_DIRS := X Y
+
adb push out/target/product/<device>/root/sepolicy /data/security/current
BOARD_SEPOLICY_REPLACE := A
+
BOARD_SEPOLICY_IGNORE := X/A
+
 
</pre>
 
</pre>
: with directories <tt>X</tt> and <tt>Y</tt> containing a copy of file <tt>A</tt>. The resulting policy is created by using <tt>Y/A</tt> only, thus <tt>X/A</tt> was ignored.
 
 
'''Error Handling:'''
 
* It is an error to specify a <tt>BOARD_POLICY_REPLACE</tt> file that does not exist in <tt>external/sepolicy</tt>.
 
* It is an error to specify a <tt>BOARD_POLICY_REPLACE</tt> file that appears multiple times on the policy search path defined by <tt>BOARD_SEPOLICY_DIRS</tt>.
 
: For example, if you specify <tt>shell.te</tt> in <tt>BOARD_SEPOLICY_REPLACE</tt> and <tt>BOARD_SEPOLICY_DIRS</tt> is set to:
 
:: <tt>vendor/widget/common/sepolicy device/widget/x/sepolicy</tt>
 
: and <tt>shell.te</tt> appears in both locations, it is an error. Unless it is in <tt>BOARD_SEPOLICY_IGNORE</tt> to be filtered out. See <tt>BOARD_SEPOLICY_IGNORE</tt> for more details.
 
* It is an error to specify the same file name in both <tt>BOARD_POLICY_REPLACE</tt> and <tt>BOARD_POLICY_UNION</tt>.
 
* It is an error to specify a <tt>BOARD_SEPOLICY_DIRS</tt> that has no entries when specifying <tt>BOARD_SEPOLICY_REPLACE</tt>.
 
  
'''Example:'''
+
* Then load the new policy by:
: An example <tt>BoardConfig.mk</tt> entry taken from <tt>device/samsung/tuna/BoardConfig.mk</tt> will take the files referenced in <tt>BOARD_SEPOLICY_DIRS</tt> and add their contents to the end of the respective files in <tt>external/sepolicy</tt>
+
 
<pre>
 
<pre>
BOARD_SEPOLICY_DIRS := \
+
adb shell su 0 setprop selinux.reload_policy 1
    device/samsung/tuna/sepolicy
+
BOARD_SEPOLICY_UNION := \
+
    genfs_contexts \
+
    file_contexts
+
 
</pre>
 
</pre>
  
 
== Logging and Auditing ==
 
== Logging and Auditing ==
=== Kernel Logs ===
+
Android now supports auditing of SELinux events via the AOSP logger service that can be viewed using <tt>logcat</tt>, for example:
The SE for Android version from 4.2.2 includes an optional audit daemon, if this is not available then the messages will be logged in the kernel buffers that can be read using <tt>'''dmesg'''(1)</tt>:
+
 
<pre>
 
<pre>
adb shell su 0 dmesg
+
adb logcat > logcat.log
 
</pre>
 
</pre>
  
Note that if auditing is available, then before the auditing daemon is loaded messages will be logged in the kernel buffers.
+
Example SELinux audit events (avc denials) are:
 
+
<pre>
 +
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=10.0.2.15 src=43397 daddr=10.0.2.15 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)
 +
</pre>
  
=== SE for Android App and Service Logging ===
+
The <tt>'''audit2allow'''(1)</tt> command can be used to create policy rules as follows:
SE for Android services will log errors using the standard Android logging service <tt>logcat</tt>. The entries will generally be categorised by the service such as <tt>SELinuxMMAC</tt>, <tt>IntentMMAC</tt>, <tt>MMACtypes</tt>, however as the SELinux services hook into Android services, there will be entries that related to these, for example an intent denial will show as:
+
 
<pre>
 
<pre>
E/PackageManager( 281): INTENT_DENIAL: {"intent":{"action":"android.intent.action.CALL_PRIVILEGED", "data":"tel:085-2369"},
+
audit2allow -p out/target/product/<device>/root/sepolicy < logcat.log > policy.te
"callingPid":600, "callingPkgs":["com.android.providers.contacts","com.android.providers.applications","com.android.contacts",
+
"com.android.providers.userdictionary"], "callingTypes":["phone_state_perm","nfc_handler"], "destPkgs":["com.android.phone"],
+
"destTypes":["wappush_manager","phone_state_perm","telephony_app"]}
+
 
</pre>
 
</pre>
  
Generally though, there are enough clues to find most errors, and be aware that events logged may change with each update.
+
Note that before the auditing daemon is loaded, messages will be logged in the kernel buffers that can be read using <tt>'''dmesg'''(1)</tt>:
 
+
 
+
=== auditd Daemon ===
+
The majority of this text has been extracted from <tt>system/core/auditd/README</tt> that describes its configuration, however note that:
+
* Kernel auditing is included by default when building the SE for Android supplied kernels (e.g. for goldfish kernel see the <tt>kernel/goldfish/arch/arm/configs/goldfish_arm7_defconfig</tt> file) and <tt>auditd</tt> daemon is also included by default (see <tt>build/target/product/core.mk</tt> - under the SELinux packages).
+
* The audit daemon output is formatted so that <tt>'''ausearch'''(8)</tt> can be used to search for SELinux events.
+
* AOSP has not yet merged auditd, therefore instructions to enable it are described below.
+
 
+
 
+
The audit daemon is a simplified version of its desktop counterpart designed to gather the audit logs from the audit kernel subsystem. The audit subsystem of the kernel includes Linux Security Modules (LSM) messages as well.
+
To enable the audit subsystem, you must add this to your kernel config:
+
: <tt>CONFIG_AUDIT=y
+
: CONFIG_AUDITSYSCALL=y</tt>
+
 
+
To enable a LSM, you must consult that LSM's documentation, the example below is for SELinux:
+
: <tt>CONFIG_SECURITY_SELINUX=y</tt>
+
 
+
This does not include possible dependencies that may need to be satisfied for that particular LSM.
+
 
+
The daemon maintains two log files <tt>audit.log</tt> and <tt>audit.old</tt> at <tt>/data/misc/audit/</tt>. On boot, if <tt>audit.log</tt> exists, and the size is greater than 0, <tt>audit.log</tt> is renamed to <tt>audit.old</tt>. The log file is also renamed, or rotated, when a threshold is hit. This threshold is hard-coded to 100KB but can be adjusted through the <tt>AUDITD_MAX_LOG_FILE_SIZEKB</tt> Makefile file variable that can be overridden in the <tt>device.mk</tt>. Note that the value is in kilobytes e.g. <tt>AUDITD_MAX_LOG_FILE_SIZEKB := 50</tt> will set the threshold to 50KB.
+
 
+
The daemon is not yet included by default in AOSP builds, and must explicitly be added to <tt>PRODUCT_PACKAGES</tt>. This could be set in the <tt>device.mk</tt> with an example configuration as follows:
+
 
<pre>
 
<pre>
<nowiki># 1MB Log file threshold</nowiki>
+
adb shell su 0 dmesg
AUDITD_MAX_LOG_FILE_SIZEKB := 1000
+
PRODUCT_PACKAGES += auditd
+
 
</pre>
 
</pre>
  
The daemon also has no external interfaces, but one could use <tt>inotify</tt> to start and build a system from this. The log files are owned by UID audit and readable by system. A system UID application could conceivably be used to consume these logs.
 
  
 
+
= Policy Configuration File Formats =
= Policy File Configuration Details =
+
 
These are detailed in the following section:
 
These are detailed in the following section:
* [[NB_SEforAndroid_2 | Policy File Configuration Details]]
+
* [[NB_SEforAndroid_2 | Policy Configuration File Formats]]
  
 +
 +
 +
{| style="width: 100%;" border="0"
 +
|-
 +
| [[NB_Imp_SELinux-aware_Apps | '''Previous''']]
 +
| <center>[[NewUsers | '''Home''']]</center>
 +
| <center>[[NB_SEforAndroid_2 | '''Next''']]</center>
 +
|}
  
  

Latest revision as of 14:48, 7 May 2018

Security Enhancements for Android

Introduction

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.

Terminology

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:

http://source.android.com/devices/tech/security/se-linux.html

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.

external/libselinux
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:
selinux_android_setcontext
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.
selinux_android_setfilecon
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.
selinux_android_restorecon
selinux_android_restorecon_pkgdir
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.
selinux_android_seapp_context_reload
Loads the seapp_contexts file for frameworks/native/cmds/installd/installd.c when the package installer is loaded.
selinux_android_load_policy
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.
selinux_android_reload_policy
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.
selinux_android_use_data_policy
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).
external/libsepol
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.
external/checkpolicy
Provides the policy build tool. Added support for MacOS X. Not available on the device as policy rebuilds are done in the development environment.
external/sepolicy
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.
packages/apps/SEAdmin
This is an example Android application to manage the SE for Android environment (such as loading a new policy). Only available on SEAndroid build.
packages/apps/Settings
SELinux settings for the settings manager application.
bionic
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.
bootable/recovery
Changes to manage file labeling on recovery plus a recovery init.rc file in the etc directory.
build
Changes to build SE for Android and manage file labeling on images and OTA (over the air) target files.
frameworks/base
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.
system/core
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).
system/extras
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.
kernel
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.
device
Build information for each device, details regarding SEAndroid supported devices can be found at:
http://seandroid.bitbucket.org/BuildingKernels.html#9
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:

system/core/rootdir/init.rc
...

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
    critical
    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
Comments
/sepolicy

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

access_vectors
security_classes
These have been modified to support the new 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.
mls
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 http://selinuxproject.org/page/PolicyLanguage. The policy will then be compiled by checkpolicy(8).
attributes
Contains the attribute names (forming the attribute statements) that will be used to group type identifiers defined by the policy.
policy_capabilities
Contains the policy capabilities enabled for the kernel policy (see policycap statement).
*.te
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).

file_contexts
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:
/data/security/current/file_contexts
If not present then check root directory:
/file_contexts
seapp_contexts
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:
/data/security/current/seapp_contexts
If not present then check root directory:
/seapp_contexts
property_contexts
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:
/data/security/property_contexts
If not present then check root directory:
/property_contexts
service_contexts
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:
/data/security/service_contexts
If not present then check root directory:
/service_contexts

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

sepolicy
The kernel binary policy. The Android initialisation / reload process will first check for this file at:
/data/security/current/sepolicy
If not present then check root directory:
/sepolicy
For reference, the policy text file containing the kernel policy language statements is available at:
out/target/product/<device>/obj/ETC/sepolicy_intermediates/policy.conf
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.
sepolicy.recovery
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:
out/target/product/<device>/obj/ETC/sepolicy.recovery_intermediates/policy_recovery.conf
selinux_version
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:

/system/etc/security/mac_permissions.xml

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

/data/security/current/mac_permissions.xml

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:

http://marc.info/?l=seandroid-list&m=141116103611797&w=2

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:

BOARD_SEPOLICY_DIRS
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:
BOARD_SEPOLICY_UNION := widget.te
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:
<tt>out/target/product/<device>/obj/ETC/sepolicy_intermediates/policy.conf
BOARD_SEPOLICY_UNION
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.

Examples:

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.

Example:

BOARD_SEPOLICY_DIRS := device/samsung/tuna/sepolicy
 
BOARD_SEPOLICY_UNION := \
    genfs_contexts \
    file_contexts \
    sepolicy.te

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:

POLICYVERS ?= 26

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=10.0.2.15 src=43397 daddr=10.0.2.15 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:


Previous
Home
Next



  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.