Difference between revisions of "NB SEforAndroid 1"

From SELinux Wiki
Jump to: navigation, search
(Policy File Configuration Details)
Line 1: Line 1:
 
= Security Enhancements 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&trade (SE for Android).  
+
This section gives an overview of the enhancements made to Android to add SELinux services to Security Enhancements for Android™ (SE for Android).  
  
The main objective of this document is to provide a reference for the tools, commands, policy building tools and file formats of SE for Android based on the 4.4 release. The builds discussed are from AOSP master and SEAndriod master repositories (as July '14).
+
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/ https://android.googlesource.com] and the SEAndroid enhancements at [https://bitbucket.org/seandroid https://bitbucket.org/seandroid].  
 
The AOSP git repositories can be found at [https://android.googlesource.com/ https://android.googlesource.com] and the SEAndroid enhancements at [https://bitbucket.org/seandroid https://bitbucket.org/seandroid].  
  
 
For up to date information on the status of SE for Android the following should be consulted: [http://seandroid.bitbucket.org/ http://seandroid.bitbucket.org/].
 
For up to date information on the status of SE for Android the following should be consulted: [http://seandroid.bitbucket.org/ http://seandroid.bitbucket.org/].
 
  
 
=== Terminology ===
 
=== Terminology ===
Line 15: Line 15:
 
{| border="1"
 
{| border="1"
 
| '''SE for Android'''
 
| '''SE for Android'''
| Used to describe the overall framework for implementing SELinux mandatory access control (MAC) and Middleware mandatory access control (MMAC) on 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'''
 
| '''AOSP'''
| The Android code base distributed by Google (see [http://source.android.com/source/downloading.html http://source.android.com/source/downloading.html]). Release 4.4 contains SELinux support that is described at [http://source.android.com/devices/tech/security/se-linux.html http://source.android.com/devices/tech/security/se-linux.html].
+
| 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].
  
AOSP contains the core SELinux MAC functionality with the Install-time MMAC framework and policy as described in the [[#Building_the_Policy|Building the Policy]] section (also see [http://seandroid.bitbucket.org/MergeStatus.html#2 http://seandroid.bitbucket.org/MergeStatus.html#2] for the latest status).
+
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.
  
AOSP also contains services to allow the updating of Intent Firewall policies, however currently no files are installed (although SEAndroid supplies a sample and update tools).
+
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'''
 
| '''SEAndroid'''
| The SEAndroid project enhancements are decreasing as more features move into AOSP. The additional SEAndroid features are:
+
| 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:
 
+
# Install time MMAC (an enhancement of the AOSP Run-time MMAC service)
# Enhanced MAC policy.
+
 
# Installation of Enterprise Operations (EOps) configuration files.
 
# 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).  
 
# 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).  
Line 44: Line 43:
 
[http://source.android.com/devices/tech/security/se-linux.html http://source.android.com/devices/tech/security/se-linux.html]
 
[http://source.android.com/devices/tech/security/se-linux.html http://source.android.com/devices/tech/security/se-linux.html]
  
The [http://seandroid.bitbucket.org/ http://seandroid.bitbucket.org/] pages describe the current merge status with AOSP, how to obtain the code, install SE for Android and the features that have been implemented. It also has useful reference papers with "Security Enhanced (SE) Android: Bringing Flexible MAC to Android" available at [http://www.internetsociety.org/sites/default/files/02_4.pdf http://www.internetsociety.org/sites/default/files/02_4.pdf] being a recommended read.
+
The [http://seandroid.bitbucket.org/ http://seandroid.bitbucket.org/] 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.
  
 
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.
 
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 ===
 
=== Document Sections ===
Line 54: Line 52:
 
* Overview of Android package additions and updates to support MAC
 
* Overview of Android package additions and updates to support MAC
 
* Additional kernel LSM / SELinux support
 
* Additional kernel LSM / SELinux support
* SE for Android Classes & Permissions
+
* Android Classes & Permissions
* SELinux commands and methods to support SE for Android
+
* SELinux commands and methods
 
* SELinux extensions for <tt>init</tt>
 
* SELinux extensions for <tt>init</tt>
* Policy construction and build
+
* Policy construction and build:
 
** Build file locations
 
** Build file locations
 
** Policy files
 
** Policy files
 
** Build tools
 
** Build tools
 
* Logging and auditing
 
* Logging and auditing
* SE for Android <tt>libselinux</tt> additional functions
+
* Android <tt>libselinux</tt> additional functions
* Object labeling configuration file details
+
* Configuration file formats
 
+
  
 
== SE for Android Project Updates ==
 
== SE for Android Project Updates ==
Line 70: Line 67:
  
 
: <tt>'''external/libselinux'''</tt>
 
: <tt>'''external/libselinux'''</tt>
:: Provides the SELinux userspace function library that is installed on the device. It is based on the Linux version but has additional functions to support Android, for example:
+
:: 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:
::: '''selinux_android_setcontext'''
+
::: <tt>'''selinux_android_setcontext'''</tt>
 
:::: 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.
 
:::: 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>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.
+
:::: 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.
::: '''selinux_android_setfilecon'''
+
::: <tt>'''selinux_android_setfilecon'''</tt>
 
:::: 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.
 
:::: 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.
 
:::: 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.
 
:::: 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.
::: '''selinux_android_restorecon'''
+
::: <tt>'''selinux_android_restorecon'''</tt>
::: '''selinux_android_restorecon_pkgdir'''
+
::: <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).
+
:::: 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 '''selinux_android_restorecon''' function is used by:
+
:::: 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/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/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.
 
::::: <tt>frameworks/native/cmds/dumpstate/utils.c</tt> when dumping Dalvik and stack traces to ensure correct label.
:::: The '''selinux_android_restorecon_pkgdir''' function is used by:
+
:::: 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>frameworks/native/cmds/installd/commands.c</tt> for the package <tt>restorecon_data()</tt> and <tt>make_user_data()</tt> functions.
::: '''selinux_android_seapp_context_reload'''
+
::: <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.
 
:::: Loads the <tt>seapp_contexts</tt> file for <tt>frameworks/native/cmds/installd/installd.c</tt> when the package installer is loaded.
::: '''selinux_android_load_policy'''
+
::: <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> to initialise SELinux.
 
:::: 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.
::: '''selinux_android_reload_policy'''
+
::: <tt>'''selinux_android_reload_policy'''</tt>
 
:::: 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.
 
:::: 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.
::: '''selinux_android_use_data_policy'''
+
::: <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.
 
:::: 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.
 
::: 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):
 
::: 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_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 premission for the class on the target context.
+
:::: <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_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 patches [https://android.googlesource.com/platform/system/core/+/b0ab94b7d5a888f0b6920b156e5c6a075fa0741a https://android.googlesource.com/platform/system/core/+/b0ab94b7d5a888f0b6920b156e5c6a075fa0741a], [https://android.googlesource.com/platform/system/core/+/b4c5200f51c3568f604a4557119ab545a6ddac94 https://android.googlesource.com/platform/system/core/+/b4c5200f51c3568f604a4557119ab545a6ddac94] and [https://android.googlesource.com/platform/external/libselinux/+/be7f5e8814c4954aca51d3f95455c5d9d527658c https://android.googlesource.com/platform/external/libselinux/+/be7f5e8814c4954aca51d3f95455c5d9d527658c]).
+
:::: <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]).
  
 
: <tt>'''external/libsepol'''</tt>
 
: <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.
  
 
: <tt>'''external/checkpolicy'''</tt>
 
: <tt>'''external/checkpolicy'''</tt>
:: Provides the policy build tool. Added support for MacOS X (darwin). Not available on the device as policy rebuilds are done in the development environment.
+
:: Provides the policy build tool. Added support for MacOS X. Not available on the device as policy rebuilds are done in the development environment.
  
 
: <tt>'''external/sepolicy'''</tt>
 
: <tt>'''external/sepolicy'''</tt>
:: This is a policy specifically for the core components of SE for Android that looks much like the reference policy, but is contained in one directory that has the policy modules (<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.  
+
:: 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.  
+
:: 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 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_MAC_Policy_Files|SELinux MAC Policy Files]] section and support tools in the [NB_SEforAndroid_2#Policy_Build_Tools|Policy Build Tools] 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 [[#SE_for_Android_Classes_and_Permissions|SE for Android Classes and Permissions]] section.
+
:: The Android specific object classes are described in the [[#Android Classes and Permissions | Android Classes and Permissions]] section.
:: The directory also contains sample MMAC configuration files.
+
:: The directory also contains the MMAC configuration files.
 
+
: <tt>'''external/yaffs2'''</tt>
+
:: <tt>mkyaffs2image</tt> support for labeling and extended attributes (<tt>xattr</tt>)
+
  
 
: <tt>'''packages/apps/SEAdmin'''</tt>
 
: <tt>'''packages/apps/SEAdmin'''</tt>
:: This is an Android application to manage the SE for Android environment (such as loading a new policy). Only available on SEAndroid build.
+
:: This is an example Android application to manage the SE for Android environment (such as loading a new policy). Only available on SEAndroid build.
  
 
: <tt>'''packages/apps/Settings'''</tt>
 
: <tt>'''packages/apps/Settings'''</tt>
Line 128: Line 122:
  
 
: <tt>'''bootable/recovery'''</tt>
 
: <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.
  
 
: <tt>'''build'''</tt>
 
: <tt>'''build'''</tt>
Line 138: Line 132:
 
:: 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 and for SEAndroid the MMAC services.
+
:: SELinux additions to support run time MMAC and for SEAndroid the additional MMAC services.
  
 
: <tt>'''system/core'''</tt>
 
: <tt>'''system/core'''</tt>
Line 149: Line 143:
  
 
: <tt>'''kernel'''</tt>
 
: <tt>'''kernel'''</tt>
:: There are a number of kernels that have been enhanced to support Linux Security Module (LSM) and SELinux services that are listed at:
+
:: 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.
::: [http://seandroid.bitbucket.org/BuildingKernels.html#9 http://seandroid.bitbucket.org/BuildingKernels.html#9]
+
:: Note that the Android kernels are based on various versions (currently 3.4 for Goldfish used by the emulator), therefore the latest SELinux enhancements may not always be present. The [[#Kernel_LSM_/_SELinux_Support|Kernel LSM / SELinux Support]] section describes the Andriod kernel changes.
+
  
 
: <tt>'''device'''</tt>
 
: <tt>'''device'''</tt>
 
:: Build information for each device, details regarding SEAndroid supported devices can be found at:  
 
:: 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]
 
::: [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.
+
:: 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 ==
Line 164: Line 156:
 
# 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_andPermissions|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>.
  
== SE for Android Classes and Permissions ==
+
== Android Classes and Permissions ==
Additional classes have been added to SE for Android and are listed in the following tables with descriptions of their permissions:
+
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.
  
 
{| border="1"
 
{| border="1"
Line 195: Line 187:
 
| <tt>transfer</tt>
 
| <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"
 
| 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>frameworks/base/core/java/com/android/internal/os/ZygoteConnection.java</tt>
 
 
|-
 
| '''Permission'''
 
| '''Description''' (4 unique permissions)
 
 
|-
 
| <tt>specifyids</tt>
 
| Peer may specify uid’s or gid’s.
 
 
|-
 
| <tt>specifyrlimits</tt>
 
| Peer may specify rlimits.
 
 
|-
 
| <tt>specifyinvokewith</tt>
 
| Peer may specify <tt>--invoke-with</tt> to launch Zygote with a wrapper command.
 
 
|-
 
| <tt>specifyseinfo</tt>
 
| Specify a <tt>seinfo</tt> string for use in determining the app security label.
 
  
 
|}
 
|}
Line 395: Line 361:
  
 
== SELinux Commands ==
 
== SELinux Commands ==
A subset of the Linux SELinux commands have been implemented in SE for Android and are listed in Table 1. They are available as Toolbox commands (see <tt>system/core/toolbox</tt>) and can be run via <tt>adb shell</tt>, for example:
+
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>
 
<pre>
 
adb shell su 0 setenforce permissive
 
adb shell su 0 setenforce permissive
 
</pre>
 
</pre>
  
'''Table 1: SELinux enabled adb shell commands (in Android toolbox)'''
+
 
 +
'''Table 1: SELinux enabled commands'''
 
{| border="1"
 
{| border="1"
 
| '''Command'''
 
| '''Command'''
 
| '''Comment'''
 
| '''Comment'''
 
|-
 
|  <tt>chcon</tt>
 
| Change security context of file:
 
 
<tt>chcon context path</tt>
 
  
 
|-
 
|-
 
|  <tt>getenforce</tt>
 
|  <tt>getenforce</tt>
 
| Returns the current enforcing mode.
 
| Returns the current enforcing mode.
 
<tt>getenforce</tt>
 
  
 
|-
 
|-
|  <tt>getsebool</tt>
+
|  <tt>setenforce</tt>
| Returns SELinux boolean value(s):
+
| Modify the SELinux enforcing mode:
  
  <tt><nowiki>getsebool [-a | boolean_name]</nowiki></tt>
+
  <tt><nowiki>setenforce [enforcing|permissive|1|0]</nowiki></tt>
 
+
|-
+
|  <tt>id</tt>
+
| If SELinux is enabled then the security context is automatically displayed.
+
  
 
|-
 
|-
Line 443: Line 398:
 
|-
 
|-
 
|  <tt>restorecon</tt>
 
|  <tt>restorecon</tt>
| 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, v - Show changes.
+
| 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><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>chcon [-hRv] context file...</nowiki></tt>
  
 
|-
 
|-
Line 454: Line 415:
  
 
|-
 
|-
|  <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 boolean_name [1|true|on|0|false|off]</nowiki></tt>
 
  <tt><nowiki>setsebool boolean_name [1|true|on|0|false|off]</nowiki></tt>
  
 
|}
 
|}
 
  
  
 
== SELinux Public Methods ==
 
== SELinux Public Methods ==
The public methods implemented are equivalent to <tt>libselinux</tt> functions and are show in Table 2. They have been taken from <tt>frameworks/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>).  
  
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>).
 
  
 
'''Table 2: SELinux class public methods'''
 
'''Table 2: SELinux class public methods'''
Line 479: Line 448:
  
 
     Determine whether SELinux is enabled or disabled.  
 
     Determine whether SELinux is enabled or disabled.  
 
 
     Return <tt>true</tt> if SELinux is enabled.
 
     Return <tt>true</tt> if SELinux is enabled.
  
 
|-
 
|-
| <tt>'''boolean isSELinuxEnforced()'''</tt>
+
| <tt>'''boolean isSELinuxEnforced()'''</tt>
  
 
     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.
  
 
|-
 
|-
| <tt>'''boolean setSELinuxEnforce(boolean value)'''</tt>
+
| <tt>'''boolean setSELinuxEnforce(boolean value)'''</tt>
  
 
     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.
  
 
|-
 
|-
| <tt>'''boolean setFSCreateContext(String context)'''</tt>
+
| <tt>'''boolean setFSCreateContext(String context)'''</tt>
  
 
     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.
  
 
|-
 
|-
| <tt>'''boolean setFileContext(String path, String context)'''</tt>
+
| <tt>'''boolean setFileContext(String path, String context)'''</tt>
  
 
     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.
  
 
|-
 
|-
| <tt>'''String getFileContext(String path)'''</tt>
+
| <tt>'''String getFileContext(String path)'''</tt>
  
 
     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.
  
 
|-
 
|-
| <tt>'''String getPeerContext(FileDescriptor fd)'''</tt>
+
| <tt>'''String getPeerContext(FileDescriptor fd)'''</tt>
  
 
     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.
  
 
|-
 
|-
| <tt>'''String getContext()'''</tt>
+
| <tt>'''String getContext()'''</tt>
  
 
     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.
  
 
|-
 
|-
| <tt>'''String getPidContext(int pid)'''</tt>
+
| <tt>'''String getPidContext(int pid)'''</tt>
  
 
     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.
 +
 
 +
<tt>'''<nowiki>String[] getBooleanNames()</nowiki>'''</tt>
  
 
     Gets a list of the SELinux boolean names.
 
     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.
 +
 
 +
<tt>'''boolean setBooleanValue(String name, boolean value)'''</tt>
  
 
     Sets the value for the given SELinux boolean name. Note that this will be set the boolean 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, 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.
  
 
|-
 
|-
| <tt>'''boolean native_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, then true is automatically returned. If SELinux is compiled in, but disabled, then true is returned.
 
     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.
 
 
     <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>'''boolean restorecon(String pathname)'''</tt>
+
| <tt>'''boolean restorecon(File file)'''</tt>
  
 
     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.
 
     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.
 
+
     <tt>file</tt> is the file object representing the path 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 file is a null object.
     <tt>exception NullPointerException</tt> if the pathname is a null object.
+
  
 
|-
 
|-
| <tt>'''boolean restorecon(File file)'''</tt>
+
| <tt>'''boolean restoreconRecursive(File file)'''</tt>
  
     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.
+
     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.
     <tt>file</tt> is the file object representing the path to be relabeled.  
+
     Returns a boolean indicating whether the relabeling succeeded.
 
+
     Returns true if the relabeling succeeded.
+
 
+
    <tt>exception NullPointerException</tt> if the file is a null object.
+
  
 
|}
 
|}
 
  
  
Line 636: Line 575:
 
|  <tt>'''<nowiki>seclabel <securitycontext></nowiki>'''</tt>
 
|  <tt>'''<nowiki>seclabel <securitycontext></nowiki>'''</tt>
  
<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>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>
  
<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>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>'''<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.
+
: <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.
See the [[#Checking File Labels|Checking File Labels]] section for further details.
+
  
 
|-
 
|-
 
|  <tt>'''<nowiki>setcon <securitycontext></nowiki>'''</tt>
 
|  <tt>'''<nowiki>setcon <securitycontext></nowiki>'''</tt>
  
<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>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>'''<nowiki>setenforce 0|1</nowiki>'''</tt>
 
|  <tt>'''<nowiki>setenforce 0|1</nowiki>'''</tt>
  
<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>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>
  
<tt>action command</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>
  
 
|}
 
|}
Line 701: Line 639:
 
     seclabel u:r:ueventd:s0
 
     seclabel u:r:ueventd:s0
 
</pre>
 
</pre>
 +
  
 
== Device Policy File Locations ==
 
== Device Policy File Locations ==
Table 4 shows the SE for Android policy files with their default location when the device is built, and their alternate locations when devices are updated by other methods (such as OTA or via <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.
+
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.
  
The <tt>init</tt> process will initially load the SELinux set of policy files from root (/). 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.  
+
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.  
  
 
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.
 
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.
  
 
'''Table 4: Policy file locations'''
 
'''Table 4: Policy file locations'''
 
 
{| border="1"
 
{| border="1"
 
| <center>'''Default Location'''</center>
 
| <center>'''Default Location'''</center>
Line 719: Line 657:
 
| <tt>/sepolicy</tt>
 
| <tt>/sepolicy</tt>
 
<tt>/file_contexts</tt>
 
<tt>/file_contexts</tt>
 
 
<tt>/seapp_contexts</tt>
 
<tt>/seapp_contexts</tt>
 
 
<tt>/property_contexts</tt>
 
<tt>/property_contexts</tt>
 
 
<tt>/service_contexts</tt>
 
<tt>/service_contexts</tt>
 
 
<tt>/selinux_version</tt>
 
<tt>/selinux_version</tt>
 
 
<tt>/mac_permissions.xml</tt>
 
<tt>/mac_permissions.xml</tt>
  
Line 772: Line 705:
  
 
== Building the Policy ==
 
== Building the Policy ==
This section covers building of SELinux MAC and Install-time MMAC policies. The file formats of SE for Android specific configuration files are detailed in the [[NB_SEforAndroid_2#Policy_File_Configuration_Details|Policy File Configuration Details]] section with examples.
+
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.
  
=== SELinux MAC Policy Files ===
+
=== SELinux Policy Files ===
The policy files are contained in the <tt>external/sepolicy</tt> directory, however there may also be additional policy configuration files to enable specific device features under the <tt><nowiki>device/<vendor>/<device>/sepolicy</nowiki></tt> directory (see the [[#Processing Device Policy|Processing Device Policy]] section). Once generated the policy and its supporting configuration files are installed on the device as part of the build process.
+
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.
  
==== Policy Build Files ====
+
==== Core Policy Files ====
The following files are used to build the kernel binary policy file that is named <tt>sepolicy</tt> and installed by default in the root directory.
+
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>access_vectors</tt>, <tt>security_classes</tt>
+
: <tt>'''access_vectors'''</tt>
:: These have been modified to support the new SE for Android classes and permissions (although they still contain the unused Linux userspace items).
+
: <tt>'''security_classes'''</tt>
 +
:: These have been modified to support the new Android classes and permissions (although they still contain the unused Linux userspace items).
  
: <tt>initial_sids</tt>, <tt>initial_sids_contexts</tt>
+
: <tt>'''initial_sids'''</tt>
 +
: <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).
 
:: Contains the system initialisation (before policy is loaded) and failsafe (for objects that would not otherwise have a valid label).
  
: <tt>fs_use</tt>, <tt>genfs_contexts</tt>, <tt>port_contexts</tt>
+
: <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.  
 
:: 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>users</tt>, <tt>roles</tt>
+
: <tt>'''users'''
:: 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.
+
: '''roles'''</tt>
 +
:: These define the only user (<tt>u</tt>) and role (<tt>r</tt>) used by the policy.
  
: <tt>mls</tt>
+
: <tt>'''mls'''</tt>
 
:: Contains the constraints to be applied to the defined classes and permissions.
 
:: Contains the constraints to be applied to the defined classes and permissions.
  
: <tt>global_macros</tt>, <tt>mls_macro</tt>, <tt>te_marcos</tt>
+
: <tt>'''global_macros'''
:: 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 Policy Language] section. The policy can then be compiled by <tt>'''checkpolicy'''(8)</tt>.
+
: '''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>.
  
: <tt>attributes</tt>
+
: <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.
+
:: 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>
+
: <tt>'''policy_capabilities'''</tt>
:: Contains the policy capabilities enabled for the kernel policy (see [http://selinuxproject.org/page/PolicyStatements#policycap_Statement policycap statement]).
+
:: Contains the policy capabilities enabled for the kernel policy (see [http://selinuxproject.org/page/Policy_Configuration_Statements policycap] statement).
  
: <tt><nowiki>*.te</nowiki></tt>
+
: <tt>'''<nowiki>*.te</nowiki>'''</tt>
 
:: 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.
 
:: 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.
 
  
 
==== Policy Configuration Files ====
 
==== Policy Configuration Files ====
These files will be installed on the device and used to compute SE for Android security contexts (see the [[#Checking_File_Labels|Checking File Labels]] section for further information).
+
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).
  
: <tt>file_contexts</tt>
+
: <tt>'''file_contexts'''</tt>
:: Contains default file contexts for setting the filesystem as Linux based SELinux (note that it does not contain entries for labeling apps or their data stores, the <tt>seapp_contexts</tt> file is used for that purpose). The format of this file is defined in [http://selinuxproject.org/page/PolicyStoreConfigurationFiles#file_contexts_File file_contexts](5)</tt>. The file is installed by default in the root directory.<tt> </tt>SE for Android services (such as [[#SELinux_Commands|restorecon]]) will first check for this file at (this is where updated files would be placed):
+
:: 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:
 
::: <tt>/data/security/current/file_contexts</tt>  
 
::: <tt>/data/security/current/file_contexts</tt>  
:: If not present they will then check the root directory:
+
:: If not present then check root directory:
 
::: <tt>/file_contexts</tt>
 
::: <tt>/file_contexts</tt>
  
: <tt>property_contexts</tt>
+
: <tt>'''seapp_contexts'''</tt>
:: Contains default contexts for 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 would be placed):
+
:: 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:
 +
::: <tt>/data/security/current/seapp_contexts</tt>
 +
:: 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>
 
::: <tt>/data/security/property_contexts</tt>
:: If not present they will then check the root directory:
+
:: If not present then check root directory:
 
::: <tt>/property_contexts</tt>
 
::: <tt>/property_contexts</tt>
  
: <tt>service_contexts</tt>
+
: <tt>'''service_contexts'''</tt>
:: Contains default contexts for Android services as discussed in the [[NB_SEforAndroid_2#service_contexts File|service_contexts File]] section. The file is installed by default in the root directory. The SE for Android initialisation / reload process will first check for this file at (this is where updated files would be placed):
+
:: 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:
 
::: <tt>/data/security/service_contexts</tt>
 
::: <tt>/data/security/service_contexts</tt>
:: If not present they will then check the root directory:
+
:: If not present then check root directory:
 
::: <tt>/service_contexts</tt>
 
::: <tt>/service_contexts</tt>
 
: <tt>seapp_contexts</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 would be placed):
 
::: <tt>/data/security/current/seapp_contexts</tt>
 
:: If not present they will then check the root directory:
 
:::  <tt>/seapp_contexts</tt>
 
 
: <tt>selinux-network.sh</tt>
 
:: This will not be processed by the SE for Android build, it must be specifically added to the device make file if required. See the [[NB_SEforAndroid_2#selinux-network.sh Configuration|selinux-network.sh Configuration]] section for details on configuring this file.
 
  
 
The following files will be built as part of the build process and installed on the device:
 
The following files will be built as part of the build process and installed on the device:
  
: <tt>sepolicy</tt>
+
: <tt>'''sepolicy'''</tt>
:: The kernel binary policy. The SE for Android initialisation / reload process will first check for this file at (this is where updated files would be placed):
+
:: The kernel binary policy. The Android initialisation / reload process will first check for this file at:
 
::: <tt>/data/security/current/sepolicy</tt>
 
::: <tt>/data/security/current/sepolicy</tt>
:: If not present they will then check the root directory:
+
:: If not present then check root directory:
 
::: <tt>/sepolicy</tt>
 
::: <tt>/sepolicy</tt>
:: For reference, the policy text file is available at:
+
:: 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>
 
::: <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.
 
:: 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.
  
: <tt>sepolicy.recovery</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:
 
:: 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><nowiki>out/target/product/<device>/obj/ETC/sepolicy.recovery_intermediates/policy_recovery.conf</nowiki></tt>
 
+
: <tt>selinux_version</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>).
 
:: 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 ===
 +
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.
  
=== Install-time MMAC Policy File ===
+
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.
The Install-time MMAC is part of AOSP and SEAndroid policy build that is always enabled. The file that configures policy is <tt>mac_permissions.xml</tt> and its format is discussed in the [[NB_SEforAndroid_2#Install-time MMAC Configuration File|Install-time MMAC Configuration File]] section. The file is installed by default at:
+
: <tt>/system/etc/security/mac_permissions.xml</tt>
+
  
The SE for Android initialisation / reload process will first check for this file at:
+
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.
: <tt>/data/security/current/mac_permissions.xml</tt>
+
  
This file can be replaced through <tt>BOARD_SEPOLICY_REPLACE </tt>or appended to by the <tt>BOARD_SEPOLICY_UNION</tt> variable as described in the [[#Processing Device Policy|Processing Device Policy]] section.
+
The file is installed by default at:
 +
:: <tt>/system/etc/security/mac_permissions.xml</tt>
  
This file can be updated along with all other MAC policy files as described in the [[#Updating Policy|Updating Policy]] section.
+
The Android initialisation / reload process will first check for this file at:
 +
:: <tt>/data/security/current/mac_permissions.xml</tt>
  
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. Note that AOSP and SEAndroid builds now support the same code base which was implemented by [https://android-review.googlesource.com/#/c/80871 https://android-review.googlesource.com/#/c/80871]. The change commit message is:
+
This file can be:
: Prior support forced all third party apps to be resolved against the default stanza of the <tt>mac_permissions.xml</tt> file when assigning <tt>seinfo</tt> labels. This meant that all third party apps, in effect, were untrusted regardless of cert and therefore received the same SELinux domain. This also had the unfortunate side effect of forcing certain third party apps into the wrong domains because of shared userid requests among apps.
+
# Appended to by the <tt>BOARD_SEPOLICY_UNION</tt> variable as described in the [[#Processing Device Policy | Processing Device Policy]] section.
: This patch removes that restriction and instead allows all apps, regardless of location, to be matched against the full <tt>mac_permissions.xml</tt> policy file. This then allows all apps signed with known good certs to receive the same SELinux domains of other apps with whom they share trust.
+
# Updated along with all other MAC policy files as described in the [[#Updating Policy | Updating Policy]] section.
  
 +
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 ===
 
=== Device Specific 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.
+
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]
  
==== Managing Device Policy File ====
+
==== Managing Device Policy Files ====
Additional per device policy files may be added or removed during the policy build and are configured through the use of the following four variables that would be added to the device <tt>BoardConfig.mk</tt> file:
+
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:
  
: <tt>BOARD_SEPOLICY_DIRS
+
: <tt>'''BOARD_SEPOLICY_DIRS'''</tt>
: BOARD_SEPOLICY_UNION  
+
:: 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:
: BOARD_SEPOLICY_REPLACE
+
::: <tt>BOARD_SEPOLICY_UNION := widget.te</tt>
: BOARD_SEPOLICY_IGNORE</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>
  
They are used as follows:
+
: <tt>'''BOARD_SEPOLICY_UNION'''</tt>
 
+
:: Contains a list of files that will be "unioned", i.e. concatenated at the END of their respective files in <tt>external/sepolicy</tt>
<tt>'''BOARD_SEPOLICY_DIRS'''</tt>
+
:: To add a unique/new file this variable would be used.
: <tt>BOARD_SEPOLICY_DIRS</tt> contains a list of directories to search for files listed by the <tt>BOARD_SEPOLICY_UNION</tt> and <tt>BOARD_SEPOLICY_REPLACE</tt> variables. Order matters in this list. e.g. If the following is defined:
+
:: It is an error to specify a <tt>BOARD_POLICY_UNION</tt> file that does not exist in <tt>external/sepolicy</tt>.
:: <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</tt><ref name="ftn1">The policy.conf 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 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 this variable would be used.
+
 
+
<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 to be ignored. This is useful if there are numerous configuration directories that contain a file, and that file is NOT to be included in the resulting policy, either by <tt>BOARD_SEPOLICY_UNION</tt> or <tt>BOARD_SEPOLICY_REPLACE</tt>.
+
: For example, suppose the following:
+
<pre>
+
BOARD_SEPOLICY_DIRS += X Y
+
BOARD_SEPOLICY_REPLACE += A
+
BOARD_SEPOLICY_IGNORE += X/A
+
</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 <tt>shell.te</tt> is specified 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>.
+
  
 
'''Examples:'''
 
'''Examples:'''
Two 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>, and <tt>BOARD_SEPOLICY_REPLACE</tt> that will replace those files in <tt>external/sepolicy</tt>.
 
  
Example 1:
+
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>
+
BOARD_SEPOLICY_DIRS := \
+
device/samsung/tuna/sepolicy
+
 
+
BOARD_SEPOLICY_UNION := \
+
genfs_contexts \
+
file_contexts \
+
sepolicy.te
+
</pre>
+
  
Example 2:
+
Example:
 
<pre>
 
<pre>
BOARD_SEPOLICY_DIRS := \
+
BOARD_SEPOLICY_DIRS := device/samsung/tuna/sepolicy
device/demo_vendor/se4a_device/sepolicy
+
 
+
 
BOARD_SEPOLICY_UNION := \
 
BOARD_SEPOLICY_UNION := \
netclient_server.te \
+
    genfs_contexts \
secmark.te \
+
    file_contexts \
seapp_contexts \
+
    sepolicy.te
keys.conf \
+
mac_permissions.xml
+
 
+
BOARD_SEPOLICY_REPLACE := \
+
selinux-network.sh
+
 
</pre>
 
</pre>
 
  
 
=== Build Tools ===
 
=== 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 the [[NB_SEforAndroid_2#Policy Build Tools|Policy Build Tools]] section, with a summary as follows:
+
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>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.
+
: <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.
: <tt>checkseapp</tt> - Used to validate the <tt>seapp_contexts</tt> file entries against the binary policy <tt>sepolicy</tt>.  
+
: <tt>'''checkseapp'''</tt> - Used to validate the <tt>seapp_contexts</tt> file entries against the binary policy <tt>sepolicy</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.
+
: <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.
 
+
:: 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.
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.
+
: <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>).
: <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>).
+
: <tt>'''sepolicy-analyze'''</tt> - Used to analyze the kernel policy file (<tt>sepolicy</tt>) for equivalent or different type pairs, or duplicate allow rules.
: <tt>sepolicy-analyze</tt> - Used to analyze the kernel policy file (<tt>sepolicy</tt>) for equivalent or different type pairs, or duplicate allow rules.
+
: <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.  
: <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.  
+
: <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.
: <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.
+
: <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.
: <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#4.4.setool|setool]] tools section. Not available on AOSP.
+
 
+
 
+
  
 
=== Miscellaneous Information ===
 
=== Miscellaneous Information ===
 
==== SELinux Policy Versions ====
 
==== 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:
 
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:
<pre>
+
: <tt>POLICYVERS ?= 26</tt>
POLICYVERS ?= 26
+
</pre>
+
  
 
If an older kernel must be supported <tt>POLICYVERS</tt> can be set as an environment variable as follows:
 
If an older kernel must be supported <tt>POLICYVERS</tt> can be set as an environment variable as follows:
<pre>
+
: <tt>export POLICYVERS=24</tt>
export POLICYVERS=24
+
</pre>
+
  
 
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.
 
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.
  
 
==== SELinux Policy Booleans ====
 
==== SELinux Policy Booleans ====
AOSP does not allow the use of booleans and the Android Compatibility Test Suite will specifically check and fail if they are present. They may still be defined in SEAndroid policy though.
+
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 ====
 
==== Setting Permissive / Enforcing Mode ====
Version 4.4 is always started in enforcing mode, although some domains may be running in 'per-domain' permissive mode due to the [http://selinuxproject.org/page/PolicyStatements#permissive_Statement permissive][http://selinuxproject.org/page/PolicyStatements#permissive_Statement  statement] being present in the policy. Also in 4.4 there is a <tt>permissive_or_unconfined</tt> macro (see <tt>te_macros</tt> policy file) that can be controlled via the <tt>FORCE_PERMISSIVE_TO_UNCONFINED</tt> flag defined in the policy <tt>Android.mk</tt> file (see comments in <tt>Android.mk</tt> for the detail).
+
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:
  
These are ways to set permissive or enforcing mode:
+
: Using adb to run the setenforce command:
 +
<pre>
 +
# enforcing = 1 permissive = 0
  
* To set across reboots, add the <tt>setenforce</tt> command to <tt>init.rc</tt> or <tt><nowiki>init.<board>.rc</nowiki></tt> files.
 
* Using <tt>adb</tt> to run the <tt>setenforce</tt> command (not set across reboots):
 
<pre>
 
# 1 = enforcing 0 = permissive
 
 
adb shell su 0 setenforce 1
 
adb shell su 0 setenforce 1
 
</pre>
 
</pre>
  
If running the emulator the following may also be used:
+
: If running the emulator:
 
<pre>
 
<pre>
 
emulator -selinux permissive
 
emulator -selinux permissive
 
</pre>
 
</pre>
<pre>
 
emulator -qemu -append androidboot.selinux=permissive
 
</pre>
 
 
  
 
==== Checking File Labels ====
 
==== 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>/<tt>chcon</tt>. Depending on whether data, app or system areas are being labeled by the various restorecon services, there are two files involved: <tt>file_contexts</tt> for all areas other than <tt>/data/data</tt> and <tt>/data/user</tt> where the <tt>seapp_contexts</tt> file is used. There use and format are decribed in the [[NB_SEforAndroid_2#2.9.1.2.Policy Configuration Files|Policy Configuration Files]] and [[NB_SEforAndroid_2#seapp_contexts File|seapp_contexts File]] sections.
+
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.
  
To determine whether either of these two files have changed:
+
Their use and format are described in the [[NB_SEforAndroid_2#file_contexts | file_contexts]] and [[NB_SEforAndroid_2#seapp_contexts | seapp_contexts]] sections.
* The <tt>file_contexts</tt> 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 <tt>xattr</tt> entry of "<tt>security.resorecon_last</tt>" as files are labeled (except <tt>/sys</tt> files). When restorecon 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 restorecon should be carried out on the <tt>/data/data</tt> and <tt>data/user</tt> directories by the package manager.
+
  
 +
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 ==
 
== Updating Policy Files ==
Line 1,020: Line 903:
 
* [[NB_SEforAndroid_2#buildifwbundle|Build Bundle Tools - ]][[NB_SEforAndroid_2#buildifwbundle|buildifwbundle]]
 
* [[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.
+
There are also details in the [[#Device Policy File Locations | Device Policy File Locations]] section.
  
 
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:
 
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>SELinuxPolicyInstallReceiver.java</tt>  
 
* <tt>IntentFirewallInstallReceiver.java</tt>  
 
* <tt>IntentFirewallInstallReceiver.java</tt>  
Line 1,043: Line 925:
 
* Then load the new policy by:
 
* Then load the new policy by:
 
<pre>
 
<pre>
adb shell su setprop selinux.reload_policy 1
+
adb shell su 0 setprop selinux.reload_policy 1
 
</pre>
 
</pre>
 
  
 
== Logging and Auditing ==
 
== Logging and Auditing ==
SE for Android 4.4 now supports auditing of SELinux events via the AOSP logger service that can be viewed using <tt>logcat</tt>, for example:
+
Android now supports auditing of SELinux events via the AOSP logger service that can be viewed using <tt>logcat</tt>, for example:
 
<pre>
 
<pre>
 
adb logcat > logcat.log
 
adb logcat > logcat.log
Line 1,057: Line 938:
 
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=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/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=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)
 
W/com.se4android.netclient( 3168): type=1300 audit(0.0:200): arch=40000028 syscall=283 per=800000 success=no exit=-111 a0=14 a1=abf4e6c4 a2=1c a3=b6f98e98 items=0 ppid=66 auid=4294967295 uid=10015 gid=10015 euid=10015 suid=10015 fsuid=10015 egid=10015 sgid=10015 fsgid=10015 tty=(none) ses=4294967295 comm=4173796E635461736B202331 exe="/system/bin/app_process32" subj=u:r:netclient_app:s0:c15,c256 key=(null)
...
 
E/SE4A-NetClient( 3141): java.net.ConnectException: failed to connect to /10.0.2.15 (port 9999): connect failed: ECONNREFUSED (Connection refused)
 
 
</pre>
 
</pre>
  
Line 1,071: Line 949:
 
</pre>
 
</pre>
  
The result from the above avc denials would be:
+
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>:
 
<pre>
 
<pre>
#============= init ==============
+
adb shell su 0 dmesg
allow init net_apps_packet:packet relabelto;
+
 
+
#============= netclient_app ==============
+
allow netclient_app unlabeled:packet send;
+
 
</pre>
 
</pre>
  
As the requirement of the app is to only accept packets labeled <tt>net_apps_packet</tt> via <tt>'''iptables'''(8)</tt> SECMARK, the <tt>relabelto</tt> allow rule was added to the device policy (see the [[NB_SEforAndroid_2#selinux-network.sh Configuration|selinux-network.sh Configuration]] section for using SECMARK).
 
 
Note that before the auditing daemon is loaded messages will be logged in the kernel buffers that can be read using <tt>'''dmesg'''(1)</tt>:
 
<pre>
 
adb shell su 0 dmesg
 
</pre>
 
  
= Policy File Configuration Details =
+
= Policy Configuration File Formats =
 
These are detailed in the following section:
 
These are detailed in the following section:
* [[NB_SEforAndroid_2 | SE4Android Policy File Configuration Details]]
+
* [[NB_SEforAndroid_2 | Policy Configuration File Formats]]
  
  

Revision as of 14:34, 15 March 2015

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 and the SEAndroid enhancements at https://bitbucket.org/seandroid.

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

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://seandroid.bitbucket.org/


Useful Links

The following link describes how to validate SELinux in Android:

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

The http://seandroid.bitbucket.org/ 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.