NB SEforAndroid 1

From SELinux Wiki

(Difference between revisions)
Jump to: navigation, search
Revision as of 13:55, 17 June 2013 (edit)
RichardHaines (Talk | contribs)
(Intent MAC Configuration)
← Previous diff
Current revision (13:34, 31 July 2014) (edit) (undo)
RichardHaines (Talk | contribs)

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

Current revision

Contents

[edit] Security Enhancements for Android

[edit] Introduction

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

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

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

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


[edit] Terminology

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

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

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

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

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

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


[edit] Useful Links

The following link describes how to validate SELinux in Android:

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 SE for Android and the features that have been implemented. It also has useful reference papers with "Security Enhanced (SE) Android: Bringing Flexible MAC to Android" available at http://www.internetsociety.org/sites/default/files/02_4.pdf being a recommended read.

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


[edit] Document Sections

The sections that follow cover:

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


[edit] SE for Android Project Updates

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

external/libselinux
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:
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.
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 premission for the class on the target context.
selinux_label_open(3), selabel_lookup(3), selinux_android_file_context_handle, selinux_android_prop_context_handle, setfilecon(3), setfscreatecon(3) to manage file labeling.
selinux_lookup_best_match called by system/core/init/devices.c when ueventd creates a device node as it may also create one or more symlinks (for block and PCI devices). Therefore a "best match" look-up for a device node is based on its real path, plus any links that may have been created (see patches https://android.googlesource.com/platform/system/core/+/b0ab94b7d5a888f0b6920b156e5c6a075fa0741a, https://android.googlesource.com/platform/system/core/+/b4c5200f51c3568f604a4557119ab545a6ddac94 and https://android.googlesource.com/platform/external/libselinux/+/be7f5e8814c4954aca51d3f95455c5d9d527658c).
external/libsepol
Provides the policy userspace library. There are no specific updates to support SE for Android, also this library is not available on the device.
external/checkpolicy
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.
external/sepolicy
This is a policy specifically for the core components of SE for Android that looks much like the reference policy, but is contained in one directory that has the policy modules (*.te files), class / permission files etc.. The policy is built by the Android.mk file and the resulting policy is installed on the target device (as sepolicy) along with its supporting configuration files.
Device specific policy may be defined under the device directory as discussed in the Processing Device Policy section.
The policy can be updated along with its configuration files as discussed in the Updating Policy section.
The policy files are discussed in the SELinux MAC Policy Files section and support tools in the [NB_SEforAndroid_2#Policy_Build_Tools|Policy Build Tools] section.
The Android specific object classes are described in the SE for Android Classes and Permissions section.
The directory also contains sample MMAC configuration files.
external/yaffs2
mkyaffs2image support for labeling and extended attributes (xattr)
packages/apps/SEAdmin
This is an 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.
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 install / run time MMAC and for SEAndroid the 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
There are a number of kernels that have been enhanced to support Linux Security Module (LSM) and SELinux services that are listed at:
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 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.

[edit] Kernel LSM / SELinux Support

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

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

[edit] SE for Android Classes and Permissions

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

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

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

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

See policy module servicemanager.te.

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


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


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


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


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


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


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


[edit] SELinux Commands

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

adb shell su 0 setenforce permissive

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

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


[edit] SELinux Public Methods

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

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

Table 2: SELinux class public methods

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


[edit] Android Init Language SELinux Extensions

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

Table 3: SELinux init extensions

seclabel <securitycontext>

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

restorecon <path>

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

restorecon_recursive <path> [ <path> ]*

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

See the Checking File Labels section for further details.

setcon <securitycontext>

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

setenforce 0|1

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

setsebool <name> <value>

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

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


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

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

[edit] Device Policy File Locations

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

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

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

Table 4: Policy file locations

Default Location
Alternate Location
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.


[edit] Building the Policy

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

[edit] SELinux MAC Policy Files

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

[edit] Policy Build Files

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

access_vectors, security_classes
These have been modified to support the new SE for Android classes and permissions (although they still contain the unused Linux userspace items).
initial_sids, initial_sids_contexts
Contains the system initialisation (before policy is loaded) and failsafe (for objects that would not otherwise have a valid label).
fs_use, genfs_contexts, port_contexts
For flexibility of policy building, these files have been separated to allow additional policy files to be defined for specific devices as discussed below.
users, roles
These define the only user (u) and role (r) used by the policy, although there is no reason why others cannot be added.
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 Policy Language section. The policy can 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.


[edit] Policy Configuration Files

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

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

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

sepolicy
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):
/data/security/current/sepolicy
If not present they will then check the root directory:
/sepolicy
For reference, the policy text file 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).


[edit] Install-time MMAC Policy File

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

/system/etc/security/mac_permissions.xml

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

/data/security/current/mac_permissions.xml

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

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

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

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


[edit] Device Specific Policy

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


[edit] Managing Device Policy File

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

BOARD_SEPOLICY_DIRS
BOARD_SEPOLICY_UNION
BOARD_SEPOLICY_REPLACE
BOARD_SEPOLICY_IGNORE

They are used as follows:

BOARD_SEPOLICY_DIRS

BOARD_SEPOLICY_DIRS contains a list of directories to search for files listed by the BOARD_SEPOLICY_UNION and BOARD_SEPOLICY_REPLACE variables. Order matters in this list. e.g. If the following is defined:
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[1] will help sort out ordering issues and is located at:
out/target/product/<device>/obj/ETC/sepolicy_intermediates/policy.conf


BOARD_SEPOLICY_UNION

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

BOARD_SEPOLICY_REPLACE

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

BOARD_SEPOLICY_IGNORE

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

Error Handling:

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

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

Example 1:

BOARD_SEPOLICY_DIRS := \
device/samsung/tuna/sepolicy

BOARD_SEPOLICY_UNION := \
genfs_contexts \
file_contexts \
sepolicy.te

Example 2:

BOARD_SEPOLICY_DIRS := \
device/demo_vendor/se4a_device/sepolicy

BOARD_SEPOLICY_UNION := \
netclient_server.te \
secmark.te \
seapp_contexts \
keys.conf \
mac_permissions.xml

BOARD_SEPOLICY_REPLACE := \
selinux-network.sh 


[edit] Build Tools

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

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

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

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


[edit] Miscellaneous Information

[edit] SELinux Policy Versions

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

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.

[edit] SELinux Policy Booleans

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

[edit] Setting Permissive / Enforcing Mode

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

These are ways to set permissive or enforcing mode:

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

If running the emulator the following may also be used:

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


[edit] Checking File Labels

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

To determine whether either of these two files have changed:

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


[edit] Updating Policy Files

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

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

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

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

[edit] Local Policy Update

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

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


[edit] Logging and Auditing

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

adb logcat > logcat.log

Example SELinux audit events (avc denials) are:

W/iptables( 92): type=1400 audit(0.0:18): avc: denied { relabelto } for scontext=u:r:init:s0 tcontext=u:object_r:net_apps_packet:s0 tclass=packet
W/iptables( 92): type=1300 audit(0.0:18): arch=40000028 syscall=294 per=800000 success=no exit=-13 a0=4 a1=0 a2=40 a3=b845a468 items=0 ppid=54 auid=4294967295 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=(none) ses=4294967295 exe="/system/bin/iptables" subj=u:r:init:s0 key=(null)
...
...
...
W/com.se4android.netclient( 3168): type=1400 audit(0.0:200): avc: denied { send } for comm=4173796E635461736B202331 saddr=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)
...
E/SE4A-NetClient( 3141): java.net.ConnectException: failed to connect to /10.0.2.15 (port 9999): connect failed: ECONNREFUSED (Connection refused)

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

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

The result from the above avc denials would be:

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

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

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

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

adb shell su 0 dmesg

[edit] Policy File Configuration Details

These are detailed in the following section:



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