Difference between revisions of "NB SEforAndroid 1"

From SELinux Wiki
Jump to: navigation, search
(SELinux Public Methods)
Line 302: Line 302:
  
 
== SELinux Public Methods ==
 
== SELinux Public Methods ==
The public methods implemented are equivalent to <tt>libselinux</tt> functions are show in Table 2. They have been taken from <tt>framework/base/core/java/android/os/SELinux.java</tt>.
+
The public methods implemented are equivalent to <tt>libselinux</tt> functions are show in Table 2. They have been taken from <tt>frameworks/base/core/java/android/os/SELinux.java</tt>.
  
  
Line 451: Line 451:
  
 
|}
 
|}
 
 
  
 
== Android Init Language SELinux Extensions ==
 
== Android Init Language SELinux Extensions ==

Revision as of 13:44, 17 June 2013

SE for Android

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.

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 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 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 Security Enhanced (SE) Android: Bringing Flexible MAC to Android 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.

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.

The sections that follow cover:

  • Overview of current MAC and Middleware MAC support.
  • Overview of Android package additions and updates to support MAC
  • 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


Supported MAC Services

The information here is subject to change, however the SELinux MAC and install-time MMAC seem to be stable, the others will probably change[1] 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 10th April '13 (see https://bitbucket.org/seandroid/manifests):

git checkout master - Builds SELinux MAC + Install-time MMAC
git checkout intent_mac - Builds SELinux MAC + Install-time MMAC + Intent MAC
git checkout revoke-perms - Builds SELinux MAC + Install-time MMAC + Revoke permissions.

An overview of the four MAC services is as follows:

  1. The 'standard' SELinux MAC policy based on type enforcement (TE) / multi-level system[2] (MLS) services (i.e. deny all access unless specifically allowed).
  2. 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:
    1. If installing or updating a third party app, its permissions will be checked against the <default> entry of the install-time MMAC policy. If the default is to deny any of its permissions, then the installation will fail.
    2. 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 <default> entry.
  3. The install-time MMAC policy also supports an seinfo 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.
  4. 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. 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).
  5. Revoke permissions policy that checks whether the policy configured permissions on a package basis will be revoked at run time. If not allowed, that permission will be revoked (i.e. allow all unless specifically revoked). This is an optional policy and does not require any specific SELinux policy support.


Overview of Android changes to support MAC

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

  1. Confine privileged daemons to protect them from misuse and limit the damage that can be done via them.
  2. Sandbox and isolate apps from each other and from the system
  3. Prevent privilege escalation by apps.
  4. Allow application privileges to be controlled at installation and run-time using Middleware-MAC.
  5. 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 first.


SE for Android Project Updates

This gives a high level view of the new and updated projects to support the SE for Android build:

external/libselinux
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:
selinux_android_setcontext
Sets the correct domain context for applications using setcon(3). Information contained in the seapp_contexts file is used to compute the correct context. This function also calls selinux_android_seapp_context_reload on initialisation to load the seapp_contexts file and sort the entries in order of precedence as discussed in the seapp_contexts File section.
It is called by dalvik/vm/native/dalvik-system-Zygote.cpp and system/core/run-as/run-as.c
selinux_android_setfilecon2
This is used to set the correct context on application directory / files using setfilecon(3). Information contained in the seapp_contexts file is used to compute the correct context. This function also calls selinux_android_seapp_context_reload on initialisation to load the seapp_contexts file and sort the entries in order of precedence as discussed in the seapp_contexts file section.
Used by frameworks/base/cmds/installd/commands.c for package install, make_user_data and protect functions.
selinux_android_restorecon
Set file contexts to match entries defined in the file_contexts file using lsetfilecon(3). Used by various commands to reset contexts during initialisation, installation etc.
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 - main() to mount selinuxfs and load the policy.
selinux_android_reload_policy
Loads the policy into the kernel. Used by system/core/init/init.c to reload the policy.
There is also a new labeling service for selabel_lookup(3) to query the property_contexts file (see external/libselinux/src/label_android_property.c). This file is loaded at init time (see system/core/init/init.c) and used by system/core/init/property_service.c. that checks property MAC permissions at system initialisation time.
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. 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
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 (*.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 (file_contexts, seapp_contexts and property_contexts). There are facilities that enable policy to be modified depending on the device as discussed in the Building the Policy section.
The policy files are discussed in the SELinux MAC Policy Files section and support tools in Policy Build Tools.
There are three new object classes defined for the policy that are described in the 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).
external/mac-policy
Contains the revoke permissions middleware policy file (revoke_permissions.xml) that allows Android permissions to be revoked at run time. The revoke-perms branch will enable this functionality.
external/yaffs2
mkyaffs2image support for labeling and extended attributes (xattr)
packages/apps/SEAandroidAdmin
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 SEAndroidManager app that is not installed by default.
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 (see the "# SELinux packages" comment in the build/target/product/core.mk file) and manage file labeling on images and OTA (over the air) target files.
dalvik
Set the context using selinux_android_setcontext on the dalvik process being forked.
libcore
Add additional parameters seInfo and niceName to Zygote.java
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, intent MMAC and revoke permissions middleware.
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.
kernel
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.
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 section describes the kernel changes.
device
Details regarding supported devices can be found at SEforAndroid - Building for a Device
Device configurations can be modified to allow the policy to be tailored, see the Building the Policy section.


Kernel LSM / SELinux Support

The paper 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:

  1. Linux Security Module (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.


SE for Android Classes and Permissions

Three additional classes (binder, zygote and property_service) 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
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 ZygoteConnection.java
Permission Description
specifyids Peer may specify uid’s or gid’s.
specifyrlimits Peer may specify rlimits.
specifycapabilities Peer may specify capabilities.
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.
Permission Description (1 unique permission)
set Set a property.


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 system/core/toolbox) and can be run via adb shell, for example:

adb shell su o setenforce permissive


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

Command Comment
chcon Change security context of file. As the first part of chcon(1) (only supports the context path parameters.
chcon context pathname
getenforce Get current enforcing mode:
getenforce
getsebool Get SELinux boolean value(s):
getsebool [-a | boolean]
id Does not take any options. 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.
restorecon Restore file default security context as defined in the file_contexts file. As restorecon(8) but supports less options:
restorecon [-nrRv] 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 name [1|true|on|0|false|off]


SELinux Public Methods

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


Table 2: SELinux class public methods

boolean isSELinuxEnabled()
   Determine whether SELinux is disabled or enabled. 
   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 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.

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>

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>

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.

setcon <securitycontext>

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

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

setsebool <name> <value>

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 file segments:

# system/core/rootdir/init.rc

...
on early-init
    # Set init and its forked children's oom_adj.
write /proc/1/oom_adj -16

    # Set the security context for the init process.
    # This should occur before anything else (e.g. ueventd) is started.
setcon u:r:init:s0
start ueventd
...
on boot
...
service ueventd /sbin/ueventd
    class core
    critical
    seclabel u:r:ueventd:s0
# system/core/rootdir/init.goldfish.rc

...
on boot
    setsebool in_qemu 1
    restorecon /sys/qemu_trace/process_name
    restorecon /sys/qemu_trace/state
    restorecon /sys/qemu_trace/symbol
...


Policy Construction and Build

An overview of the sections that cover the configuration and building of SELinux MAC and MMAC policies are as follows:

SELinux MAC Policy Files - Describes the SELinux MAC policy files that define the policy and how they relate, and also the SELinux MAC Policy Files required. The Policy Booleans are also detailed with their default state.
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.
Intent MAC Configuration - Describes how the intent MMAC is configured and built when using the intent_mac branch build.
Revoke Permissions Configuration - Describes how the revoke permissions middleware is configured and built when using the revoke-perms branch build.
Policy Build Tools - Describes the tools available that assist in building the policy and their configuration files.
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.


SELinux MAC Policy Files

The MAC policy configuration files are contained in the external/sepolicy directory, however there may also be policy configuration files to enable specific device features under device/<vendor> directories (see the 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 following files are used to build the kernel binary policy file that will be named sepolicy and installed by default in the root directory. An updated policy may be installed at /data/security/sepolicy. The initialisation or policy reload process will always check for a policy at /data/security/sepolicy first and then if not present at /sepolicy. The policy files consist of the following:

access_vectors, security_classes
These have been modified to support the new SE for Android classes and permissions.
initial_sids, initial_sids_contexts, 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 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 the Policy Language section. The policy can then be compiled by checkpolicy(8). For reference, the policy text file is built and placed in:
out/target/product/<device>/obj/ETC/sepolicy_intermediates/policy.conf
The compiled kernel policy can also be found in this directory and is named sepolicy. There are also policy.conf.dontaudit and sepolicy.dontaudit files that have the dontaudit 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.
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 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 for the device and will contain all the required allow, type_transition etc. rules. It will also call any te_macros to access other domains resources (e.g. init_daemon_domain, binder_call).

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:

file_contexts
Contains default file contexts for setting the filesystem as standard SELinux. The format of this file is defined in file_contexts(5). The file is installed by default in the root directory. SE for Android services (such as restorecon(8)) will first check for this file at (this is where updated files should be placed):
/data/security/file_contexts
If not present they will then check the root directory:
/file_contexts
property_contexts
Contains default contexts to be applied to 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 should be placed):
/data/security/property_contexts
If not present they will then check the root directory:
/property_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 should be placed):
/data/security/seapp_contexts
If not present they will then check the root directory:
/seapp_contexts
selinux-network.sh
If using iptables(8) then SECMARK information may be configured in this file as part of the build. It is installed in system/bin and executed at system initialisation time.


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 in your environment as follows:

export POLICYVERS=24

Information regarding policy versions can be found at Policy Versions.

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.


SELinux Policy Booleans

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 setBooleanValue() method), or temporarily using the adb shell setsebool 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).

Table 4: SE for Android SELinux Policy Booleans

Boolean Name
Default state
Comments
android_cts
FALSE
Allow the Android CTS to run if TRUE. Do not enable in production policy.
app_external_sdcard_rw
TRUE
Allow untrusted_app domain external SD card rw access if TRUE.
app_internal_sdcard_rw
TRUE
Allow untrusted_app domain internal SD card rw access if TRUE.
debugfs
FALSE
Allow domain rw access on debugfs if TRUE.
in_qemu
FALSE
Allow domain rw access on /sys/qemu_trace files in the emulator if TRUE.

Note that when running the emulator this is automatically set TRUE on boot (see init.goldfish.rc)

support_runas
TRUE
Support the Android adb shell run-as command if TRUE.
system_app_manage
FALSE
When set to TRUE will allow the system_app domain the ability to manage SE for Android (as well as the system domain).

When set to FALSE only the system domain can manage SE for Android.

The management is based on the status of the manage_selinux and manage_mac booleans logically anded with system_app_manage i.e. if system_app_manage is TRUE, but mmac_manage is FALSE, the system_app domain will not be able to manage MMAC.

manage_selinux
TRUE
Allow management of SELinux policy if TRUE. Also see the system_app_manage boolean.
manage_mac
TRUE
Allow management of MMAC policy if TRUE. Also see the system_app_manage boolean.


Setting Permissive / Enforcing Mode

There are three ways to set permissive or enforcing mode in SE for Android:

  1. Using the SEAdmin or SEManager apps.
  2. Adding the setenforce command to the init.rc or init.<board>.rc files.
  3. Using adb to run the setenforce command.


Modifying and Reloading Policy

This is covered at SEforAndroid - Policy in detail. This section gives a brief overview:

  1. Modify the required policy source files, then regenerate the kernel policy file by:
make sepolicy
  1. Copy the policy file to the device:
adb push out/target/product/<device>/root/sepolicy /data/security
  1. Then load the new policy by:
adb shell su 0 setprop selinux.reload_policy 1

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 mac_permissions.xml and its format is discussed in the mac_permissions.xml 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 (this is where updated files should be placed):

/data/security/mac_permissions.xml

This file can be replaced through BOARD_SEPOLICY_REPLACE containing the value mac_permissions.xml, or appended to by using the BOARD_SEPOLICY_UNION variable as described in the Building the 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. 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):

 # 1 = enforcing 0 = permissive
  adb shell su 0 setprop persist.mmac.enforce 1


Intent MAC Configuration

Intent MAC is not part of the standard policy and can be found in the intent_mac branch as described in 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). The files that configure policy are intent_mac.xml and mmac_types.xml and by default they are installed at:

/system/etc/security/intent_mac.xml
/system/etc/security/mmac_types.xml

The SE for Android initialisation / reload process will first check for these files at (this is where updated files should be placed):

/data/security/intent_mac.xml
/data/security/mmac_types.xml

The file formats and their usage are discussed in the Intent MAC Files section. The files can also be replaced through BOARD_SEPOLICY_REPLACE containing the required file name, however only the mmac_types.xml file can be appended to by using the BOARD_SEPOLICY_UNION variable as described in the Building the Policy section. The main code for the service is frameworks/base/core/java/andriod/content/pm/IntentMAC.java and MMACtypes.java, 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 setprop, for example:

 # 1 = Enforcing 0 = Permissive
 adb shell su 0 setprop persist.mmac_enforce 1


Table 5: Intent MAC system properties and their default values

persist.mmac.enforce = false

True turns on Intent MAC enforcing mode (as well as install-time MMAC). The SEAdmin app will also toggle this property.

persist.mac_intent_allowSelf = true

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.

persist.mac_intent_allowSystem = true

True allows all intents coming from the system_server. This reduces the amount of work required to create useful policy.

persist.mac_intent_allowSig = true

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.

persist.mac_intent_allowUid = true

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.

persist.mac_intent_printJSON = false

True prints a JSON formatted debugging string.

persist.mac_applyNameTypes = false

True - A type that is the same as a package name will be added to the list of types.

persist.mac_applyPermTypes = false

True - For each permission, a type that is the same as that permission will be added to the list of types.


Revoke Permissions Configuration

The revoke permission MAC is not part of the standard policy and can be found in the revoke-perms branch as described at SEforAndroid - Permission_revocation. The file that configures the policy is the revoke_permissions.xml and by default is installed at:

/system/etc/security/revoke_permissions.xml

The SE for Android initialisation / reload process will first check for this file at (this is where updated files should be placed):

/data/system/revoke_permissions.xml

The file format is shown in the Revoke Permissions file section.

The main code for the service is self contained in:

frameworks/base/services/java/com/android/server/pm/PackageManagerService.java

Building the 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.

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 Policy Build Tools, with a summary as follows:

checkfc - Used to parse the file_contexts file against the binary policy sepolicy. This is to ensure all file contexts are valid for the policy. There is a -p option that is used to validate the contexts defined in the property_contexts file.
checkseapp - Used to parse the seapp_contexts file against the binary policy sepolicy. This is to ensure policy related information is valid (e.g. checks booleans, types, levels etc.).
insertkeys.py - Used to replace keywords in the signature sections of the mac_permissions.xml and mmac_types.xml files with keys obtained from pem files. This uses information contained in the external/sepolicy/keys.conf file that is detailed in the keys.conf section. This utility will also strip files of comments.
setool - This is not used by the actual build process but assists in generating new entries for the mac_permissions.xml 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 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:

BOARD_SEPOLICY_DIRS
BOARD_SEPOLICY_UNION
BOARD_SEPOLICY_REPLACE
BOARD_SEPOLICY_IGNORE

The variables should be set in the BoardConfig.mk file in the device or vendor directories.

BOARD_SEPOLICY_DIRS

BOARD_SEPOLICY_DIRS contains a list of directories to search for BOARD_SEPOLICY_UNION and BOARD_SEPOLICY_REPLACE files. Order matters in this list. e.g. If you have:
BOARD_SEPOLICY_UNION := widget.te
and two instances of widget.te files are on 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[3] 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 you would use this variable.

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 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 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 you specify shell.te 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.

Example:

An example BoardConfig.mk entry taken from device/samsung/tuna/BoardConfig.mk will take the files referenced in BOARD_SEPOLICY_DIRS and add their contents to the end of the respective files in external/sepolicy
BOARD_SEPOLICY_DIRS := \
    device/samsung/tuna/sepolicy
BOARD_SEPOLICY_UNION := \
    genfs_contexts \
    file_contexts

Logging and Auditing

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 dmesg(1):

adb shell su 0 dmesg

Note that if auditing is available, then before the auditing daemon is loaded messages will be logged in the kernel buffers.


SE for Android App and Service Logging

SE for Android services will log errors using the standard Android logging service logcat. The entries will generally be categorised by the service such as SELinuxMMAC, IntentMMAC, MMACtypes, 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:

E/PackageManager( 281): INTENT_DENIAL: {"intent":{"action":"android.intent.action.CALL_PRIVILEGED", "data":"tel:085-2369"}, 
"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"]}

Generally though, there are enough clues to find most errors, and be aware that events logged may change with each update.


auditd Daemon

The majority of this text has been extracted from system/core/auditd/README 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 kernel/goldfish/arch/arm/configs/goldfish_arm7_defconfig file) and auditd daemon is also included by default (see build/target/product/core.mk - under the SELinux packages).
  • The audit daemon output is formatted so that ausearch(8) can be used to search for SELinux events.
  • AOSP has not yet merged auditd, therefore instructions to enable it are described below.


The audit daemon is a simplified version of its desktop counterpart designed to gather the audit logs from the audit kernel subsystem. The audit subsystem of the kernel includes Linux Security Modules (LSM) messages as well. To enable the audit subsystem, you must add this to your kernel config:

CONFIG_AUDIT=y
CONFIG_AUDITSYSCALL=y

To enable a LSM, you must consult that LSM's documentation, the example below is for SELinux:

CONFIG_SECURITY_SELINUX=y

This does not include possible dependencies that may need to be satisfied for that particular LSM.

The daemon maintains two log files audit.log and audit.old at /data/misc/audit/. On boot, if audit.log exists, and the size is greater than 0, audit.log is renamed to audit.old. 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 AUDITD_MAX_LOG_FILE_SIZEKB Makefile file variable that can be overridden in the device.mk. Note that the value is in kilobytes e.g. AUDITD_MAX_LOG_FILE_SIZEKB := 50 will set the threshold to 50KB.

The daemon is not yet included by default in AOSP builds, and must explicitly be added to PRODUCT_PACKAGES. This could be set in the device.mk with an example configuration as follows:

# 1MB Log file threshold
AUDITD_MAX_LOG_FILE_SIZEKB := 1000
PRODUCT_PACKAGES += auditd

The daemon also has no external interfaces, but one could use inotify 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

These are detailed in the following section:



  1. 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.
  2. More precisely the multi-category system (MCS) as currently only a single level is used.
  3. The policy.conf file contains the policy language statements as described at Policy Language. These define the policy that will be enforced and devices labeled.