NB SEforAndroid 2

From SELinux Wiki

(Difference between revisions)
Jump to: navigation, search
Revision as of 16:16, 17 June 2013 (edit)
RichardHaines (Talk | contribs)
(intent_mac.xml File)
← Previous diff
Current revision (11:29, 31 July 2014) (edit) (undo)
RichardHaines (Talk | contribs)
(buildifwbundle)
 
(3 intermediate revisions not shown.)
Line 1: Line 1:
= Policy File Configuration Details = = Policy File Configuration Details =
 +This section details the specific SE for Android policy configuration files (i.e. those not used by 'standard' Linux based SELinux). Where those files are used to compute contexts using the SE for Android <tt>libselinux</tt> functions, those functions are also described with examples.
-This section details the specific SE for Android policy configuration files (i.e. those not used by 'standard' Linux based SELinux) as they were in April '13. Where those files are used to compute contexts using the SE for Android libselinux functions, those functions are also described with examples.+== SELinux MAC Configuration Files ==
- +
-As this project is continually being enhanced, it is recommended that the official project wiki is checked for the latest enhancements at [[SEforAndroid | SEforAndroid]]+
- +
- +
-== SELinux MAC Files ==+
=== seapp_contexts File === === seapp_contexts File ===
-This file is loaded and sorted into memory automatically on first use of one of the following SE for Android libselinux functions that are called by the SE for Android enabled services:+This file is loaded and sorted into memory automatically on first use of one of the following SE for Android <tt>libselinux</tt> functions that are called by the SE for Android enabled services:
: <tt>selinux_android_setcontext</tt> - Computes process security contexts. : <tt>selinux_android_setcontext</tt> - Computes process security contexts.
-: <tt>selinux_android_setfilecon2</tt> - Computes file/directory security contexts.+: <tt>selinux_android_setfilecon</tt> - Computes file/directory security contexts.
-<tt>selinux_android_seapp_context_reload</tt> will also reload this file.+: <tt>selinux_android_seapp_context_reload</tt> will reload this file.
-The build process supports additional <tt>seapp_contexts</tt> files to allow devices to specify their specific entries as described in the [[NB_SEforAndroid_1#Building the Policy| Building the Policy]] section.+The build process supports additional <tt>seapp_contexts</tt> files to allow devices to specify their entries as described in the [[NB_SEforAndroid_1#Processing Device Policy|Processing Device Policy]] section.
The following sections will show: The following sections will show:
# The default <tt>external/sepolicy/seapp_contexts</tt> file entries. # The default <tt>external/sepolicy/seapp_contexts</tt> file entries.
# A description of the <tt>seapp_contexts</tt> entries and their usage. # A description of the <tt>seapp_contexts</tt> entries and their usage.
-# A brief description of how a context is computed using either the <tt>selinux_android_setcontext</tt> or <tt>selinux_android_ setfilecon2</tt> function using the <tt>seapp_contexts</tt> file entries.+# A brief description of how a context is computed using either the <tt>selinux_android_setcontext</tt> or <tt>selinux_android_ setfilecon</tt> function using the <tt>seapp_contexts</tt> file entries.
# Examples of computed domain and directory contexts for various apps. # Examples of computed domain and directory contexts for various apps.
 +
==== Default Entries ==== ==== Default Entries ====
-The default <tt>external/sepolicy/seapp_contexts</tt> file contains the following entries:+The default SEAndroid <tt>external/sepolicy/seapp_contexts</tt> file contains the following entries:
<pre> <pre>
-isSystemServer=true domain=system+isSystemServer=true domain=system_server
-user=system domain=system_app type=system_data_file+user=system domain=system_app type=system_app_data_file
user=bluetooth domain=bluetooth type=bluetooth_data_file user=bluetooth domain=bluetooth type=bluetooth_data_file
user=nfc domain=nfc type=nfc_data_file user=nfc domain=nfc type=nfc_data_file
user=radio domain=radio type=radio_data_file user=radio domain=radio type=radio_data_file
-user=_app domain=untrusted_app type=app_data_file levelFrom=app+user=shared_relro domain=shared_relro
-user=_app seinfo=platform domain=platform_app type=platform_app_data_file+user=shell domain=shell type=shell_data_file
-user=_app seinfo=shared domain=shared_app type=platform_app_data_file+
-user=_app seinfo=media domain=media_app type=platform_app_data_file+
-user=_app seinfo=release domain=release_app type=platform_app_data_file+
user=_isolated domain=isolated_app user=_isolated domain=isolated_app
 +user=_app seinfo=platform domain=platform_app type=app_data_file
 +user=_app domain=untrusted_app type=app_data_file
</pre> </pre>
 +
==== Entry Definitions ==== ==== Entry Definitions ====
Line 41: Line 38:
Input selectors from <tt>seapp_contexts</tt> file: Input selectors from <tt>seapp_contexts</tt> file:
-: isSystemServer (boolean)+: <tt>isSystemServer (boolean)</tt>
: <tt>user (string)</tt> : <tt>user (string)</tt>
: <tt>seinfo (string)</tt> : <tt>seinfo (string)</tt>
: <tt>name (string)</tt> - A package name e.g. <tt>com.example.demo</tt> : <tt>name (string)</tt> - A package name e.g. <tt>com.example.demo</tt>
 +: <tt>path (string)</tt> - A path name (added to ensure correct labeling of some files).
: <tt>sebool (string)</tt> - The boolean must be ‘active’ (enabled/true) : <tt>sebool (string)</tt> - The boolean must be ‘active’ (enabled/true)
-<tt>isSystemServer=true</tt> can only be used once. 
-An unspecified <tt>isSystemServer</tt> defaults to false. 
-An unspecified string selector will match any value.+Notes:
- +: <tt>isSystemServer=true</tt> can only be used once.
-A <tt>user</tt> string selector that ends in <tt><nowiki>*</nowiki></tt> will perform a prefix match.+: An unspecified <tt>isSystemServer</tt> defaults to false.
- +: An unspecified string selector will match any value.
-<tt>user=_app</tt> will match any regular app UID.+: A <tt>user</tt> string selector that ends in <tt><nowiki>*</nowiki></tt> will perform a prefix match.
- +: <tt>user=_app</tt> will match any regular app UID.
-<tt>user=_isolated</tt> will match any isolated service UID.+: <tt>user=_isolated</tt> will match any isolated service UID.
- +: All specified input selectors in an entry must match (i.e. logical AND).
-All specified input selectors in an entry must match (i.e. logical AND).+: Matching is case-insensitive.
- +
-Matching is case-insensitive.+
Precedence rules: Precedence rules:
Line 68: Line 62:
: 5) Specified <tt>seinfo= string</tt> before unspecified <tt>seinfo= string</tt>. : 5) Specified <tt>seinfo= string</tt> before unspecified <tt>seinfo= string</tt>.
: 6) Specified <tt>name= string</tt> before unspecified <tt>name= string</tt>. : 6) Specified <tt>name= string</tt> before unspecified <tt>name= string</tt>.
-: 7) Specified <tt>sebool= string</tt> before unspecified <tt>sebool= string</tt>.+: 7) Specified <tt>path= string</tt> before unspecified <tt>path= string</tt>.
 +: 8) Specified <tt>sebool= string</tt> before unspecified <tt>sebool= string</tt>.
 + 
Outputs: Outputs:
: <tt>domain (string)</tt> - The <tt>type</tt> component of a process context. : <tt>domain (string)</tt> - The <tt>type</tt> component of a process context.
Line 74: Line 70:
: <tt>levelFrom</tt> (<tt>string</tt><nowiki>; one of </nowiki><tt>none</tt>, <tt>all</tt>, <tt>app</tt>, or <tt>user</tt>) - A level that will be automatically computed based on the parameter. : <tt>levelFrom</tt> (<tt>string</tt><nowiki>; one of </nowiki><tt>none</tt>, <tt>all</tt>, <tt>app</tt>, or <tt>user</tt>) - A level that will be automatically computed based on the parameter.
: <tt>level (string)</tt> - A predefined level (e.g. <tt>s0:c1022.c1023</tt>) : <tt>level (string)</tt> - A predefined level (e.g. <tt>s0:c1022.c1023</tt>)
-Only entries that specify <tt>domain=</tt> will be used for app process labeling. 
- 
-Only entries that specify <tt>type=</tt> will be used for app directory labeling. 
- 
-<tt>levelFrom=user</tt> is only supported for <tt>_app</tt> or <tt>_isolated</tt> UIDs. 
-<tt>levelFrom=app</tt> or <tt>levelFrom=all</tt> is only supported for <tt>_app</tt> UIDs.+Notes:
 +: Only entries that specify <tt>domain=</tt> will be used for app process labeling.
 +: Only entries that specify <tt>type=</tt> will be used for app directory labeling.
 +: <tt>levelFrom=user</tt> is only supported for <tt>_app</tt> or <tt>_isolated</tt> UIDs.
 +: <tt>levelFrom=app</tt> or <tt>levelFrom=all</tt> is only supported for <tt>_app</tt> UIDs.
 +: <tt>level</tt> may be used to specify a fixed level for any UID.
-<tt>level</tt> may be used to specify a fixed level for any UID. 
==== Computing a Process Context ==== ==== Computing a Process Context ====
Line 88: Line 83:
<pre> <pre>
#include <selinux/android.h> #include <selinux/android.h>
 +
int selinux_android_setcontext(uid_t uid, int isSystemServer, const char *seinfo, const char *pkgname); int selinux_android_setcontext(uid_t uid, int isSystemServer, const char *seinfo, const char *pkgname);
</pre> </pre>
Line 94: Line 90:
: The <tt>uid</tt> is converted to a string that is then used to match the <tt>user=</tt> entries in the <tt>seapp_contexts</tt> file as follows: : The <tt>uid</tt> is converted to a string that is then used to match the <tt>user=</tt> entries in the <tt>seapp_contexts</tt> file as follows:
:: If an Android system service the <tt>uid</tt> is converted to a string via an internal Android table (e.g. "radio", "system"). :: If an Android system service the <tt>uid</tt> is converted to a string via an internal Android table (e.g. "radio", "system").
-:: If an isolated service the <tt>_isolated</tt> string is used.+:: If an isolated service (determined from the apps <tt>AndroidManifest.xml</tt> file) the <tt>_isolated</tt> string is used .
:: For any other app or service the <tt>_app</tt> is used. :: For any other app or service the <tt>_app</tt> is used.
: The <tt>isSystemServer</tt> value must match that set in the running system and be true or false. It will be matched against the <tt>isSystemServer=</tt> entries in the <tt>seapp_contexts</tt> file. : The <tt>isSystemServer</tt> value must match that set in the running system and be true or false. It will be matched against the <tt>isSystemServer=</tt> entries in the <tt>seapp_contexts</tt> file.
: <tt>seinfo</tt> may be <tt>NULL</tt> or that obtained from the <tt>mac_permissions.xml</tt> file. It will be matched against the <tt>seinfo=</tt> entries in the <tt>seapp_contexts</tt> file. : <tt>seinfo</tt> may be <tt>NULL</tt> or that obtained from the <tt>mac_permissions.xml</tt> file. It will be matched against the <tt>seinfo=</tt> entries in the <tt>seapp_contexts</tt> file.
: <tt>pkgname</tt> may be <tt>NULL</tt> or that obtained from the Android package. It will be matched against the <tt>name=</tt> entries in the <tt>seapp_contexts</tt> file. : <tt>pkgname</tt> may be <tt>NULL</tt> or that obtained from the Android package. It will be matched against the <tt>name=</tt> entries in the <tt>seapp_contexts</tt> file.
 +
: The remaining <tt>seapp_contexts</tt> entries will be used as follows: : The remaining <tt>seapp_contexts</tt> entries will be used as follows:
:: The <tt>sebool=</tt> parameter if present will be matched against the SELinux boolean name list. If present, the boolean must be active. :: The <tt>sebool=</tt> parameter if present will be matched against the SELinux boolean name list. If present, the boolean must be active.
Line 104: Line 101:
:: The <tt>domain=</tt> is used to set the process context and must match a context in the policy. Determines the <tt>type</tt> component of the security context. :: The <tt>domain=</tt> is used to set the process context and must match a context in the policy. Determines the <tt>type</tt> component of the security context.
-If a context is computed, it is validated against policy and if correct <tt>'''setcon'''(3)</tt> will then be used to set the process context.+If a context is computed, it is validated against policy and if correct <tt>'''setcon'''(3)</tt> will then set the process context.
'''Examples''' '''Examples'''
The following is an example taken as the system server is loaded: The following is an example taken as the system server is loaded:
<pre> <pre>
-Input selectors:+selinux_android_setcontext() parameters:
- uid 1000+ uid 1000
- isSystemServer true+ isSystemServer true
- seinfo null+ seinfo null
- name null+ pkgname null
- sebool null+
-username computed from uid = system+seapp_contexts input selectors:
 + isSystemServer true
 + seinfo null
 + name null
 + path null
 + sebool null
Matching seapp_contexts entry: Matching seapp_contexts entry:
- isSystemServer=true domain=system+ isSystemServer=true domain=system_server
Outputs: Outputs:
- domain system+ domain system_server
- level s0+ level s0
-Computed context u:r:system:s0+Computed context = u:r:system_server:s0
 + username computed from uid = system
Result using ps -Z command: Result using ps -Z command:
-LABEL USER PID PPID NAME+LABEL USER PID PPID NAME
-u:r:system:s0 system 300 45 system_server+u:r:system_server:s0 system 836 63 system_server
</pre> </pre>
-This is the "radio" application that is part of the platform:+This is the ’radio’ application that is part of the platform:
<pre> <pre>
-Input selectors:+selinux_android_setcontext() parameters:
- uid 1001+ uid 1001
- isSystemServer false+ isSystemServer false
- seinfo platform+ seinfo platform
- name com.android.phone+ pkgname com.android.phone
- sebool null+ 
- +seapp_contexts input selectors:
-username computed from uid = radio+ isSystemServer false
 + seinfo platform
 + name com.android.phone
 + path null
 + sebool null
Matching seapp_contexts entry: Matching seapp_contexts entry:
- user=radio domain=radio type=radio_data_file+ user=radio domain=radio type=radio_data_file
Outputs: Outputs:
- domain radio+ domain radio
- level s0+ level s0
-Computed context u:r:radio:s0+Computed context = u:r:radio:s0
 +username computed from uid = radio
Result using ps -Z command: Result using ps -Z command:
-LABEL USER PID PPID NAME+ 
-u:r:radio:s0 radio 443 45 com.android.phone+LABEL USER PID PPID NAME
 +u:r:radio:s0 radio 1587 63 com.android.phone
</pre> </pre>
-This is the "SE for Android Admin Manager" application that is part of the platform:+This is the ’SEAndroid Admin Manager’ application that is part of the release, however it is treated as an untrusted app (even though it is installed as a privileged app):
<pre> <pre>
-Input selectors:+selinux_android_setcontext() parameters:
- uid 10042+ uid 10013
- isSystemServer false+ isSystemServer false
- seinfo release+ seinfo default
- name com.android.seandroid_admin+ pkgname com.android.seandroid_admin
- sebool null+
-username computed from uid = u0_a42+seapp_contexts input selectors:
 + uid 10013
 + isSystemServer false
 + seinfo default
 + name com.android.seandroid_admin
 + path null
 + sebool null
Matching seapp_contexts entry: Matching seapp_contexts entry:
- user=_app seinfo=release domain=release_app type=platform_app_data_file+ user=_app domain=untrusted_app type=app_data_file
Outputs: Outputs:
- domain release_app+ domain untrusted_app
- level s0+ level s0
-Computed context u:r:release_app:s0+Computed context = u:r:untrusted_app:s0
 +username computed from uid = u0_a13
Result using ps -Z command: Result using ps -Z command:
-LABEL USER PID PPID NAME+LABEL USER PID PPID NAME
-u:r:release_app:s0 u0_a42 827 45 com.android.seandroid_admin+u:r:untrusted_app:s0 u0_a13 827 45 com.android.seandroid_admin
</pre> </pre>
-This is a third party app that also runs an isolated service:+This is a third party app that will run an isolated service that has been installed as a platform app:
<pre> <pre>
-Input selectors:+selinux_android_setcontext() parameters:
- uid 10046+ uid 10058
- isSystemServer false+ isSystemServer false
- seinfo null+ seinfo default
- name com.example.seandroiddemo+ pkgname com.example.runisolatedservice
- sebool null+
-username computed from uid = u0_a46+seapp_contexts input selectors:
 + uid 10058
 + isSystemServer false
 + seinfo default
 + name com.example.runisolatedservice
 + path null
 + sebool null
Matching seapp_contexts entry: Matching seapp_contexts entry:
- user=_app domain=untrusted_app type=app_data_file levelFrom=app+ user=_app domain=untrusted_app type=app_data_file
Outputs: Outputs:
- domain untrusted_app+ domain untrusted_app
- levelFrom app s0:c46,c256+ level s0
-Computed context u:r:untrusted_app:s0:c46,c256+Computed context = u:r:untrusted_app:s0
 +username computed from uid = u0_a58
Result using ps -Z command: Result using ps -Z command:
-LABEL USER PID PPID NAME+ 
-u:r:untrusted_app:s0:c46,c256 u0_a46 855 45 com.example.seandroiddemo+LABEL USER PID PPID NAME
 +u:r:untrusted_app:s0 u0_a58 1138 64 com.example.runisolatedservice
</pre> </pre>
 +
 +The isolated service will then run as follows:
<pre> <pre>
-Input selectors:+selinux_android_setcontext() parameters:
- uid 99000+ uid 99000
- isSystemServer false+ isSystemServer false
- seinfo null+ seinfo platform
- name com.example.seandroiddemo+ pkgname com.se4android.isolatedservice
- sebool null+ 
- +seapp_contexts input selectors:
-username computed from uid = u0_i0+ uid 99000
 + isSystemServer false
 + seinfo platform
 + name com.se4android.isolatedservice
 + path null
 + sebool null
Matching seapp_contexts entry: Matching seapp_contexts entry:
- user=_isolated domain=isolated_app+ user=_isolated domain=isolated_app
 + 
 +Note that uid's 99000-99999 are reserved for isolated services - see:
 + system/core/include/private/android_filesystem_config.h
Outputs: Outputs:
- domain isolated_app+ domain isolated_app
- level s0+ level s0
-Computed context u:r:isolated_app:s0+Computed context = u:r:isolated_app:s0
 +username computed from uid = u0_i0
Result using ps -Z command: Result using ps -Z command:
-LABEL USER PID PPID NAME+LABEL USER PID PPID NAME
-u:r:isolated_app:s0 u0_i0 869 45 com.example.seandroiddemo+u:r:isolated_app:s0 u0_i0 1211 70 com.se4android.isolatedservice
</pre> </pre>
 +
==== Computing a Directory Context ==== ==== Computing a Directory Context ====
-To compute an app package directory context the <tt>selinux_android_setfilecon2</tt> function is called that will use the parameters passed, plus the contents of the <tt>seapp_contexts</tt> file. The function parameters are:+To compute an app package directory context the <tt>selinux_android_setfilecon</tt> function is called that will use the parameters passed, plus the contents of the <tt>seapp_contexts</tt> file. The function parameters are:
<pre> <pre>
#include <selinux/android.h> #include <selinux/android.h>
-int selinux_android_setfilecon2(const char *pkgdir, const char *pkgname, const char *seinfo, uid_t uid);+int selinux_android_setfilecon(const char *pkgdir, const char *pkgname, const char *seinfo, uid_t uid);
</pre> </pre>
Line 243: Line 276:
: <tt>seinfo</tt> may be <tt>NULL</tt> or that obtained from the <tt>mac_permissions.xml</tt> file. It will be matched against the <tt>seinfo=</tt> entries in the <tt>seapp_contexts</tt> file. : <tt>seinfo</tt> may be <tt>NULL</tt> or that obtained from the <tt>mac_permissions.xml</tt> file. It will be matched against the <tt>seinfo=</tt> entries in the <tt>seapp_contexts</tt> file.
: The <tt>uid</tt> is converted to a string that is then used to match the <tt>user=</tt> entries in the <tt>seapp_contexts</tt> file as follows: : The <tt>uid</tt> is converted to a string that is then used to match the <tt>user=</tt> entries in the <tt>seapp_contexts</tt> file as follows:
-:: If an Android system service the <tt>uid</tt> is converted to a string via an internal Android table (e.g. "radio", "system").+:: If an Android system service, the <tt>uid</tt> is converted to a string via an internal Android table (e.g. "radio", "system").
:: If an isolated service the <tt>_isolated</tt> string is used. :: If an isolated service the <tt>_isolated</tt> string is used.
:: For any other app or service the <tt>_app</tt> is used. :: For any other app or service the <tt>_app</tt> is used.
-:The remaining <tt>seapp_contexts</tt> entries will be used as follows:+: The remaining <tt>seapp_contexts</tt> entries will be used as follows:
-:: The <tt>sebool=</tt> parameter if present will be matched against the SELinux boolean name list. If present, the boolean must be active.+:: The <tt>sebool=</tt> parameter if present will be matched against the SELinux boolean name list. If present, the boolean must be active.
:: The <tt>levelFrom=</tt> and <tt>level=</tt> parameters if present will be used to determine the <tt>level</tt> component of the security context. :: The <tt>levelFrom=</tt> and <tt>level=</tt> parameters if present will be used to determine the <tt>level</tt> component of the security context.
:: The <tt>type=</tt> is used to set the file object context and must match a context in the policy. Determines the <tt>type</tt> component of the security context. :: The <tt>type=</tt> is used to set the file object context and must match a context in the policy. Determines the <tt>type</tt> component of the security context.
If a context is computed, it is validated against policy and if correct <tt>'''setfilecon'''(3)</tt> will then be used to label <tt>pkgdir</tt> with the computed context. If a context is computed, it is validated against policy and if correct <tt>'''setfilecon'''(3)</tt> will then be used to label <tt>pkgdir</tt> with the computed context.
-The following example is from a third party app:+The following example is from the third party isolated app:
<pre> <pre>
-Input selectors:+selinux_android_setfilecon() parameters:
- uid 10046+ pkgdir /data/data/com.example.runisolatedservice
- isSystemServer false+ pkgname com.example.runisolatedservice
- seinfo null+ seinfo default
- name com.example.seandroiddemo+ uid 10046
- sebool null+
- pkgdir /data/data/com.example.seandroiddemo+
-username computed from uid = u0_a46+seapp_contexts input selectors:
 + uid 10046
 + isSystemServer false
 + seinfo default
 + name com.example.runisolatedservice
 + path null
 + sebool null
Matching seapp_contexts entry: Matching seapp_contexts entry:
- user=_app domain=untrusted_app type=app_data_file levelFrom=app+ user=_app domain=untrusted_app type=app_data_file
Outputs: Outputs:
- type app_data_file+ type app_data_file
- levelFrom app s0:c46,c256+ level s0
-Computed context u:object_r:app_data_file:s0:c46,c256+Computed context = u:object_r:app_data_file:s0
 +username computed from uid = u0_a46
Result from /data/data directory using ls -Z command: Result from /data/data directory using ls -Z command:
-drwxr-x--x u0_a46 u0_a46 u:object_r:app_data_file:s0:c46,c256 com.example.seandroiddemo+drwxr-x--x u0_a46 u0_a46 u:object_r:app_data_file:s0 com.example.runisolatedservice
</pre> </pre>
-Example <tt>ls -Z /data/data</tt> entries:+ 
 +=== property_contexts File ===
 +This file holds property service keys and their contexts that are matched against property names using <tt>'''selabel_lookup'''(3)</tt>. The returned context will then be used as the target context as described in the example below to determine whether the property is allowed or denied (see <tt>system/core/init/property_service.c</tt> and <tt>init.c</tt>).
 + 
 +The build process supports additional <tt>property_contexts</tt> files to allow devices to specify their entries as described in the [[NB_SEforAndroid_1#Processing Device Policy|Processing Device Policy]] section.
 + 
 +When <tt>'''selabel_open'''(3)</tt> is called specifying this file it will be read into memory and sorted using <tt>'''qsort'''(3)</tt>, subsequent calls using <tt>'''selabel_lookup'''(3)</tt> will then retrieve the appropriate context based on matching the <tt>property_key</tt>.
 + 
 +'''Example:'''
 + 
 +Use <tt>adb</tt> to reload the SELinux policy:
<pre> <pre>
-drwxr-x--x u0_a35 u0_a35 u:object_r:platform_app_data_file:s0 com.android.backupconfirm+adb shell su 0 setprop selinux.reload_policy 1
-drwxr-x--x bluetooth bluetooth u:object_r:bluetooth_data_file:s0 com.android.bluetooth+
-drwxr-x--x u0_a7 u0_a7 u:object_r:platform_app_data_file:s0 com.android.browser+
-drwxr-x--x u0_a37 u0_a37 u:object_r:platform_app_data_file:s0 com.android.deskclock+
-drwxr-x--x u0_a21 u0_a21 u:object_r:platform_app_data_file:s0 com.android.development+
-drwxr-x--x u0_a30 u0_a30 u:object_r:platform_app_data_file:s0 com.android.mms+
-drwxr-x--x u0_a19 u0_a19 u:object_r:platform_app_data_file:s0 com.android.music+
-drwxr-x--x u0_a31 u0_a31 u:object_r:platform_app_data_file:s0 com.android.musicfx+
-drwxr-x--x u0_a5 u0_a5 u:object_r:platform_app_data_file:s0 com.android.musicvis+
-drwxr-x--x u0_a17 u0_a17 u:object_r:platform_app_data_file:s0 com.android.noisefield+
-drwxr-x--x system system u:object_r:system_data_file:s0 com.android.providers.settings+
-drwxr-x--x radio radio u:object_r:radio_data_file:s0 com.android.providers.telephony+
-drwxr-x--x u0_a0 u0_a0 u:object_r:platform_app_data_file:s0 com.android.provision+
-drwxr-x--x u0_a34 u0_a34 u:object_r:platform_app_data_file:s0 com.android.quicksearchbox+
-drwxr-x--x u0_a42 u0_a42 u:object_r:platform_app_data_file:s0 com.android.seandroid_admin+
-drwxr-x--x system system u:object_r:system_data_file:s0 com.android.settings+
-drwxr-x--x u0_a14 u0_a14 u:object_r:platform_app_data_file:s0 com.android.smspush+
-drwxr-x--x u0_a26 u0_a26 u:object_r:platform_app_data_file:s0 com.android.soundrecorder+
-drwxr-x--x u0_a2 u0_a2 u:object_r:platform_app_data_file:s0 com.android.speechrecorder+
-drwxr-x--x u0_a4 u0_a4 u:object_r:platform_app_data_file:s0 com.android.systemui+
-drwxr-x--x u0_a11 u0_a11 u:object_r:platform_app_data_file:s0 com.android.videoeditor+
-drwxr-x--x u0_a12 u0_a12 u:object_r:platform_app_data_file:s0 com.android.voicedialer+
-drwxr-x--x u0_a10 u0_a10 u:object_r:platform_app_data_file:s0 com.android.vpndialogs+
-drwxr-x--x u0_a16 u0_a16 u:object_r:platform_app_data_file:s0 com.android.wallpaper+
-drwxr-x--x u0_a46 u0_a46 u:object_r:app_data_file:s0:c46,c256 com.example.seandroiddemo+
</pre> </pre>
 +Sample <tt>property_contexts</tt> file entries are:
 +<pre>
 +# property_key context to be applied on match
 +net.rmnet u:object_r:net_radio_prop:s0
 +net.gprs u:object_r:net_radio_prop:s0
 +net.ppp u:object_r:net_radio_prop:s0
 +net.qmi u:object_r:net_radio_prop:s0
 +net.lte u:object_r:net_radio_prop:s0
 +net.cdma u:object_r:net_radio_prop:s0
 +net.dns u:object_r:net_radio_prop:s0
 +sys.usb.config u:object_r:system_radio_prop:s0
 +ril. u:object_r:radio_prop:s0
 +gsm. u:object_r:radio_prop:s0
 +persist.radio u:object_r:radio_prop:s0
-=== property_contexts File ===+debug. u:object_r:debug_prop:s0
-This file holds property names and their contexts that will be applied by SELinux when applications are loaded. The property names reflect the 'white list' of Android property entries that are also built into the system (see <tt>system/core/init/property_service.c</tt> and <tt>init.c</tt>) however there are also additional property entries for applications that require specific contexts to be set.+debug.db. u:object_r:debuggerd_prop:s0
 +log. u:object_r:shell_prop:s0
 +service.adb.root u:object_r:shell_prop:s0
 +service.adb.tcp.port u:object_r:shell_prop:s0
-The build process supports additional <tt>seapp_contexts</tt> files to allow devices to specify their specific entries as described in the [[NB_SEforAndroid_1#Building the Policy | Building the Policy]] section.+persist.audio. u:object_r:audio_prop:s0
 +persist.logd. u:object_r:logd_prop:s0
 +persist.sys. u:object_r:system_prop:s0
 +persist.service. u:object_r:system_prop:s0
 +persist.service.bdroid. u:object_r:bluetooth_prop:s0
 +persist.security. u:object_r:system_prop:s0
-When <tt>'''selabel_open'''(3)</tt> is called specifying this file it will be read into memory and sorted using <tt>'''qsort'''(3)</tt>, subsequent calls using <tt>'''selabel_lookup'''(3)</tt> will then retrieve the appropriate context.+# selinux non-persistent properties
 +selinux. u:object_r:security_prop:s0
 + 
 +# default property context (* is wild card match)
 +* u:object_r:default_prop:s0
 +</pre>
-Each line within the property contexts file is as follows:+The property service will call <tt>selabel_lookup</tt> with parameters consisting of the handle passed from <tt>selabel_open</tt>, a buffer to hold the returned context, and the object name "<tt>selinux.reload_policy</tt>" to look-up (the final parameter is not used):
<pre> <pre>
-property_key context+selabel_lookup(handle, &context, "selinux.reload_policy", 1);
</pre> </pre>
-'''Where:'''+The following context will be returned as the look-up process will search for a match based on the length of the <tt>property_key</tt> (and will therefore match against "<tt>selinux.</tt>"):
-: <tt>property_key</tt>+<pre>
-:: The key used to obtain the context that may contain '<tt><nowiki>*</nowiki></tt>' for wildcard matching.+u:object_r:security_prop:s0
-:<tt>context</tt>+</pre>
-:: The security context that will be applied to the object. +
-The default <tt>property_contexts</tt> file entries are:+The property service will then validate whether the service has permission by issuing an <tt>'''selinux_check_access'''(3)</tt> call with the following parameters:
<pre> <pre>
-##########################+source context: u:r:su:s0
-# property service keys+target context: u:object_r:security_prop:s0
-#+class: property_service
- +permission: set
-net.rmnet0 u:object_r:radio_prop:s0+</pre>
-net.gprs u:object_r:radio_prop:s0+
-net.ppp u:object_r:radio_prop:s0+
-net.qmi u:object_r:radio_prop:s0+
-net.lte u:object_r:radio_prop:s0+
-net.cdma u:object_r:radio_prop:s0+
-gsm. u:object_r:radio_prop:s0+
-persist.radio u:object_r:radio_prop:s0+
-net.dns u:object_r:radio_prop:s0+
-sys.usb.config u:object_r:radio_prop:s0+
-ril. u:object_r:rild_prop:s0+
-net. u:object_r:system_prop:s0+
-dev. u:object_r:system_prop:s0+
-runtime. u:object_r:system_prop:s0+
-hw. u:object_r:system_prop:s0+
-sys. u:object_r:system_prop:s0+
-service. u:object_r:system_prop:s0+
-wlan. u:object_r:system_prop:s0+
-dhcp. u:object_r:system_prop:s0+
-debug. u:object_r:shell_prop:s0+
-log. u:object_r:shell_prop:s0+
-service.adb.root u:object_r:shell_prop:s0+
-service.adb.tcp.port u:object_r:shell_prop:s0+
-persist.audio. u:object_r:audio_prop:s0+The policy would then decide whether to allow or deny the property request. Using the [[#sepolicy_check|sepolicy-check]] tool will show that this will be denied by the current policy (a <tt>dontaudit</tt> rule is in the policy, however <tt>su</tt> runs permissive anyway):
-persist.sys. u:object_r:system_prop:s0+<pre>
-persist.service. u:object_r:system_prop:s0+sepolicy-check -s su -t security_prop -c property_service \
-persist.security. u:object_r:system_prop:s0+-p set -P out/target/product/generic/root/sepolicy
 +echo $?
 + 1
 +</pre>
-# mmac persistent properties 
-persist.mmac.u:object_r:security_prop:s0 
-# selinux non-persistent properties+=== service_contexts File ===
-selinux. u:object_r:security_prop:s0+This file holds binder service keys and their contexts that are matched against binder object names using <tt>'''selabel_lookup'''(3)</tt>. The returned context will then be used as the target context as described in the example below to determine whether the binder service is allowed or denied (see <tt>frameworks/native/cmds/servicemanager/servicemanager.c</tt>).
- +
-# default property context+
-* u:object_r:default_prop:s0+
-# data partition encryption properties+The build process supports additional <tt>service_contexts</tt> files to allow devices to specify their entries as described in the [[NB_SEforAndroid_1#Building the Policy|Building the Policy]] section.
-vold. u:object_r:vold_prop:s0+
-crypto. u:object_r:vold_prop:s0+
-# ctl properties+When <tt>'''selabel_open'''(3)</tt> is called specifying this file it will be read into memory and sorted using <tt>'''qsort'''(3)</tt>, subsequent calls using <tt>'''selabel_lookup'''(3)</tt> will then retrieve the appropriate context based on matching the <tt>service_key</tt>.
-ctl.dumpstate u:object_r:ctl_dumpstate_prop:s0+
-ctl.ril-daemon u:object_r:ctl_rildaemon_prop:s0+
-ctl. u:object_r:ctl_default_prop:s0+
-</pre>+
-== Install MMAC File ==+'''Example:'''
-The <tt>mac_permissions.xml</tt> file is used to configure install-time MMAC policy and provides two main functions:+
-# x.509 certificate to <tt>seinfo</tt> string mapping so that Zygote spawns the application in the correct domain. See the [[#Computing a Process Context | Computing a Process Context]] section for how this is achieved using information also contained in the <tt>seapp_contexts</tt> file.+
-# Install-time MMAC permission checking.+
-It is important to note that all third party apps will be subject to the <tt><nowiki><default></nowiki></tt> install MAC policy defined in this file. This is a requirement of AOSP in that all third party apps must be treated alike (i.e. distinctions can only be made between system apps and third party apps and among the system apps, not between two different third party apps). The current <tt><nowiki><default></nowiki></tt> package policy is as follows:+The <tt>healthd</tt> process wants to start a binder service "<tt>batterypropreg</tt>" (see <tt>frameworks/base/services/java/com/android/server/BatteryService.java</tt>).
 +Sample <tt>service_contexts</tt> file entries are:
<pre> <pre>
-<!-- All other keys -->+# service_key context to be applied on match
-<default>+batteryproperties u:object_r:healthd_service:s0
- <seinfo value="default" /></nowiki>+batterystats u:object_r:system_server_service:s0
- <deny-permission name="android.permission.ACCESS_COARSE_LOCATION" />+battery u:object_r:system_server_service:s0
- <deny-permission name="android.permission.ACCESS_FINE_LOCATION" />+
- <deny-permission name="android.permission.AUTHENTICATE_ACCOUNTS" />+# default service context (* is wild card match)
- <deny-permission name="android.permission.CALL_PHONE" />+* u:object_r:default_android_service:s0
- <deny-permission name="android.permission.CAMERA" />+
- <deny-permission name="android.permission.READ_LOGS" />+
- <deny-permission name="android.permission.WRITE_EXTERNAL_STORAGE" />+
-</default>>+
</pre> </pre>
-The build process supports additional <tt>mac_permissions.xml</tt> files to allow devices to specify their specific entries as described in the [[NB_SEforAndroid_1#Building the Policy | Building the Policy]] section.+The service manager will call <tt>selabel_lookup</tt> with parameters consisting of the handle passed from <tt>selabel_open</tt>, a buffer to hold the returned context, and the object name "<tt>batterypropreg</tt>" to look-up (the final parameter is not used):
 +<pre>
 +selabel_lookup(handle, &context, "batterypropreg", 1);
 +</pre>
-==== Signature Entries ====+The following context will be returned as the look-up process will search for a match based on the length of the <tt>service_key</tt> (and will therefore match against "<tt>battery</tt>"):
-The <tt><nowiki><signer signature=</nowiki></tt> entry may have the public base16 signing key present in the string or it may have an entry starting with <tt>@</tt>, then a keyword as shown that allows the key to be extracted from a pem file as discussed in the [[#insertkeys.py | insertkeys.py]] section:+
<pre> <pre>
- <!-- Platform dev key in AOSP -->+u:object_r:system_server_service:s0
- <signer signature="@PLATFORM" >+
- <allow-all />+
- <seinfo value="platform" />+
- </signer>+
</pre> </pre>
-If a base16 key is required, it can be extracted from a package using the <tt>setool</tt> utility as described in the [[#setool | setool]] section. +The service manager will then validate whether the service has permission by issuing an <tt>'''selinux_check_access'''(3)</tt> call with the following parameters:
 +<pre>
 +source context: u:r:healthd:s0
 +target context: u:object_r:system_server_service:s0
 +class: service_manager
 +permission: add
 +</pre>
-==== Policy Rules ====+The policy would then decide whether to allow or deny the service. Using the [[#sepolicy_check|sepolicy-check]] tool will show that this will be allowed by the current policy:
-The following rules have been extracted from the source <tt>mac_permissions.xml</tt> file:+<pre>
 +sepolicy-check -s healthd -t system_server_service \
 +-c service_manager -p add \
 +-P out/target/product/generic/root/sepolicy
 +Match found!
 +</pre>
-* A signature is a hex encoded X.509 certificate and is required for each signer tag. 
-* A <tt><nowiki><signer signature="" ></nowiki></tt> element may have multiple child elements: 
-** <tt>allow-permission</tt> : produces a set of maximal allowed permissions (whitelist). 
-** <tt>deny-permission</tt> : produces a blacklist of permissions to deny. 
-** <tt>allow-all</tt> : a wildcard tag that will allow every permission requested. 
-** <tt>package</tt> : a complex tag which itself defines allow, deny, and wildcard sub elements for a specific package name protected by the signature. 
-* Zero or more global <tt><nowiki><package name=""></nowiki></tt> tags are allowed. These tags allow a policy to be set outside any signature for specific package names. 
-* Unknown tags at any level are skipped. 
-* Zero or more signer tags are allowed. 
-* Zero or more package tags are allowed per signer tag. 
-* A <tt><nowiki><package name=""></nowiki></tt> tag may not contain another <tt><nowiki><package name=""></nowiki></tt> tag. If found, it's skipped. 
-* A <tt><nowiki><default></nowiki></tt> tag is allowed that can contain install policy for all apps not signed with a previously listed cert and not having a per package global policy. 
-* When multiple sub elements appear for a tag the following logic is used to ultimately determine the type of enforcement: 
-** A blacklist is used if at least one <tt>deny-permission</tt> tag is found 
-** A whitelist is used if not a blacklist and at least one <tt>allow-permission</tt> tag is found 
-** A wildcard (accept all permission) policy is used if not a blacklist and not a whitelist and at least one <tt>allow-all</tt> tag is present. 
-** If a <tt><nowiki><package name=""></nowiki></tt> sub element is found then that sub element's policy is used according to the above logic and overrides any signature global policy type. 
-** In order for a policy stanza to be enforced at least one of the above situations must apply. Meaning, empty <tt>signer</tt>, <tt>default</tt> or <tt>package</tt> tags will not be accepted. 
-* Each <tt>signer</tt> / <tt>default</tt> / global <tt>package</tt> tag is allowed to contain one <tt><nowiki><seinfo value=""/></nowiki></tt> tag. This tag represents additional information that each application can use in setting a SELinux security context on the eventual process. Any <tt><nowiki><seinfo value=""/></nowiki></tt> tag found as a child of a <tt><nowiki><package name=""></nowiki></tt> tag which is protected (sub element of <tt>signer</tt> or the <tt>default</tt> tag) is ignored. It's possible that multiple <tt>seinfo</tt> tags are relevant for one application. In the event that this happens, the <tt>seinfo</tt> tag that will be applied is the one for which the corresponding policy stanza is used in the policy decision. 
-* Strict enforcing of any xml stanza is not enforced in most cases. This mainly applies to duplicate tags which are allowed. In the event that a tag already exists, the original tag is replaced. 
-* There are also no checks on the validity of permission names. Although valid android permissions are expected, nothing prevents unknowns. 
-* Enforcement decisions: 
-** All signatures used to sign an application are checked for policy according to signer tags. Only one of the signature policies has to pass however. 
-** In the event that none of the signature policies pass, or none even match, then a global <tt>package</tt> policy is sought. If found, this policy mediates the install. 
-** The <tt>default</tt> tag is consulted last if needed. 
-** A local package policy always overrides any parent policy. 
-** If none of the cases apply then the app is denied. 
-An edited form of the default <tt>mac_permissions.xml</tt> file is as follows:+== Install-time MMAC Configuration File ==
 +The <tt>mac_permissions.xml</tt> file is used to configure Install-time MMAC policy and provides x.509 certificate to <tt>seinfo</tt> string mapping so that Zygote spawns an app in the correct domain. See the [[#Computing a Process Context|Computing a Process Context]] section for how this is achieved using information also contained in the <tt>seapp_contexts</tt> file (AOSP and SEAndroid).
 + 
 +An example AOSP <tt>mac_permissions.xml</tt> file that shows the <tt><nowiki><default></nowiki></tt> entry is:
<pre> <pre>
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
 +
<policy> <policy>
<!-- Platform dev key in AOSP --> <!-- Platform dev key in AOSP -->
 +
<signer signature="@PLATFORM" > <signer signature="@PLATFORM" >
- <allow-all /> 
<seinfo value="platform" /> <seinfo value="platform" />
- </signer> 
- 
- <!-- Media dev key in AOSP --> 
- <signer signature="@MEDIA" > 
- <allow-permission name="android.permission.ACCESS_ALL_DOWNLOADS" /> 
- <allow-permission name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
- <allow-permission name="android.permission.WRITE_MEDIA_STORAGE" /> 
- <allow-permission name="android.permission.WRITE_SETTINGS" /> 
- <seinfo value="media" /> 
- </signer> 
- 
- <!-- shared dev key in AOSP --> 
- <signer signature="@SHARED" > 
- <allow-permission name="android.permission.ACCESS_COARSE_LOCATION" /> 
- <allow-permission name="com.android.voicemail.permission.ADD_VOICEMAIL" /> 
- <seinfo value="shared" /> 
- </signer> 
- 
- <!-- release dev key in AOSP --> 
- <signer signature="@RELEASE" > 
- <seinfo value="release" /> 
- <deny-permission name="android.permission.BRICK" /> 
- <deny-permission name="android.permission.READ_LOGS" /> 
- <package name="com.android.browser" > 
- <allow-permission name="android.permission.SET_WALLPAPER" /> 
- <allow-permission name="android.permission.USE_CREDENTIALS"/> 
- <allow-permission name="android.permission.WAKE_LOCK"/> 
- <allow-permission name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
- <allow-permission name="android.permission.WRITE_SETTINGS" /> 
- <allow-permission name="android.permission.WRITE_SYNC_SETTINGS" /> 
- <seinfo value="release" /> 
- </package> 
</signer> </signer>
Line 489: Line 457:
<default> <default>
<seinfo value="default" /> <seinfo value="default" />
- <deny-permission name="android.permission.ACCESS_COARSE_LOCATION" /> 
- <deny-permission name="android.permission.ACCESS_FINE_LOCATION" /> 
- <deny-permission name="android.permission.AUTHENTICATE_ACCOUNTS" /> 
- <deny-permission name="android.permission.CALL_PHONE" /> 
- <deny-permission name="android.permission.CAMERA" /> 
- <deny-permission name="android.permission.READ_LOGS" /> 
- <deny-permission name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
</default> </default>
 +
</policy> </policy>
</pre> </pre>
 +The <tt><nowiki><signer signature=</nowiki></tt> entry may have the public base16 signing key present in the string or it may have an entry starting with <tt>@</tt>, then a keyword as shown that allows the key to be extracted from a <tt>pem</tt> file as discussed in the [[#insertkeys.py|insertkeys.py]] section. If a base16 key is required, it can be extracted from a package using the [[#post_process_mac_perms|post_process_mac_perms]] and [[#setool|setool]] utilities.
-== Intent MAC Files ==+The build process supports additional <tt>mac_permissions.xml</tt> files to allow devices to specify their entries as described in the [[NB_SEforAndroid_1#Processing Device Policy|Processing Device Policy]] section. An example SEAndroid test device <tt>mac_permissions.xml</tt> file is:
-There are two configuration files to support intent MAC, they are:+
-:: <tt>intent_mac.xml</tt> - This defines the intents that will be allowed between each source and destination. The source and destination may be package names or <tt><nowiki><type></nowiki></tt> entries defined in the <tt>mmac_types.xml</tt> file that will allow intents to be managed on a package, signature and/or permissions basis. There is also an optional <tt><nowiki><allow-all></nowiki></tt> section.+
-:: <tt>mmac_types.xml</tt> - Contains <tt><nowiki><type></nowiki></tt> entries allowing source and destination entries defined in the <tt>intent_mac.xml</tt> file to manage intents on a package, signature and/or permissions basis.+
- +
-=== intent_mac.xml File ===+
-The file supports two entry types:+
-# An intent filter that specifies actions (intents) and the types (defined in <tt>mmac_types.xml</tt>) that can be either the source or destination of the action.+
-# An <tt><nowiki><allow-all></nowiki></tt> entry.+
- +
-==== Intent Filter Entry ====+
-The entries are defined below with:+
-* The <tt><nowiki><action name="" /></nowiki></tt> entry will define the intent.+
-* The <tt>src=</tt> and <tt>dst=</tt> entries may be package names or 'type names' that are further defined in the <tt>mmac_types.xml</tt> file (see the '''Note''' below on implementing these).+
-* The <tt>srcctx=</tt> entry if defined will be matched against the app process source context.+
<pre> <pre>
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
-<policy> <!-- Start intent_mac.xml entries --> 
- <intent> <!-- Starts a new intent filter -->+<policy>
- <filter>+
- <action name="" /> <!-- Only one entry allowed-->+
- <category name="" /> <!-- Multiple entries allowed -->+
- <data scheme="" /> <!-- Multiple entries allowed -->+
- <data mimeType="" /> <!-- Multiple entries allowed -->+
- </filter>+
- <allow <!-- Multiple entries allowed -->+
- name="" <!-- Rule name -->+
- srcctx="" <!-- Source context to be matched -->+
- src="" <!-- Source <type> entry or package name -->+
- dst="" <!-- Destination <type> entry or package name -->+
- </allow>+
- </intent>+
-</policy> <!-- End entries -->+ <!-- NET_APPS key and seinfo for SE4A-NetClient & SE4A-NetServer apps. -->
-</pre>+ <signer signature="@NET_APPS" >
- + <package name="com.se4android.netclient" >
-Example entries are:+ <seinfo value="netclient" />
-<pre>+ </package>
-<?xml version="1.0" encoding="utf-8"?>+ <package name="com.se4android.netserver" >
-<policy>+ <seinfo value="netserver" />
- <intent>+ </package>
- <filter>+ </signer>
- <action name="android.intent.action.CALL_PRIVILEGED"/>+
- <data scheme="tel"/>+
- <data scheme="voicemail"/>+
- </filter>+
- <allow src="contacts_app" dst="telephony_app"/>+
- </intent>+
- <intent> 
- <filter> 
- <action name="android.intent.action.VIEW"/> 
- <data mimeType="vnd.android.cursor.dir/calls" /> 
- </filter> 
- <allow src="telephony_app" dst="contacts_app"/> 
- </intent> 
</policy> </policy>
</pre> </pre>
-==== Allow-all Entry ==== 
-The entries are defined below with: 
-* The <tt>src</tt> and <tt>dst</tt> entries would normally be defined as package names to allow all intents to flow, however they may be 'type names' that are further defined in the <tt>mmac_types.xml</tt> file. The '''Note''' below describes how either of these methods can be implemented.+==== Policy Rules ====
-* The <tt>srcctx</tt> entry if defined will be matched against the app process source context.+The following rules have been extracted from the SEAndroid <tt>mac_permissions.xml</tt> file:
-<pre>+
-<?xml version="1.0" encoding="utf-8"?>+
-<policy> +
- <allow-all> +* A signature is a hex encoded X.509 certificate or a tag defined in <tt>keys.conf</tt> and is required for each <tt>signer</tt> tag.
- <allow <!-- Multiple entries allowed -->+* A <tt>signer</tt> tag may contain a <tt>seinfo</tt> tag and multiple package stanzas.
- name="" <!-- Rule name -->+* A <tt>default</tt> tag is allowed that can contain policy for all apps not signed with a previously listed cert. It may not contain any inner <tt>package</tt> stanzas.
- srcctx="" <!-- Source context to be matched -->+* Each <tt>signer</tt>/<tt>default</tt>/<tt>package</tt> tag is allowed to contain one <tt>seinfo</tt> tag. This tag represents additional info that each app can use in setting a SELinux security context on the eventual process.
- src="" <!-- Source <type> entry or package name -->+* When a package is installed the following logic is used to determine what <tt>seinfo</tt> value, if any, is assigned:
- dst="" <!-- Destination <type> entry or package name -->+** All signatures used to sign the app are checked first.
- </allow>+** If a <tt>signer</tt> stanza has inner <tt>package</tt> stanzas, those stanza will be checked to try and match the package name of the app. If the package name matches then that <tt>seinfo</tt> tag is used. If no inner package matches then the outer <tt>seinfo</tt> tag is assigned.
- </allow-all>+** The <tt>default</tt> tag is consulted last if needed.
-</policy> +** If none of the cases apply then the app is denied install on the device.
-</pre>+
-An <tt><nowiki><allow-all></nowiki></tt> example entry: 
-<pre> 
-<?xml version="1.0" encoding="utf-8"?> 
-<policy> 
- <allow-all>+== EOps MMAC Configuration File ==
- <allow name="phone_to_sms" src="com.android.phone" dst="com.android.smspush"/>+The following text has been taken from the SEAndroid <tt>/external/sepolicy/eops.xml</tt> file (so check if any changes) with a few minor additions (there is also a simple example in the [[#Eops Example|EOps Example]] section section).
- <allow name="shell" srcctx="u:r:shell:s0"/>+
- <allow name="su" srcctx="u:r:su:s0"/>+
- </allow-all>+
-</policy>+EOps (enterprise operations) is a security extension to the App Operations (AppOps) feature already present on Android 4.3+ devices. AppOps lets users fine tune certain functionality requested by apps by allowing the user to toggle these access rights.
-</pre>+
-'''Note:''' The above <tt>allow</tt> example <tt>src</tt> and <tt>dst</tt> entries shown are the actual package names. These may be implemented in the following ways:+EOps seeks to provide an extension whereby a harcoded set of rules explicitly denies certain access rights to groups of installed apps. This feature will allow an enterprise like control over certain operations. EOps is not a frontend for SELinux which somehow ties app permissions to SELinux contexts. Rather, it is an extension of the middleware MAC (MMAC) controls that currently exist on Android 4.3+ devices. EOps uses the <tt>seinfo</tt> labels that are already assigned to apps upon install.
-1) If <tt>persist.mac_applyNameTypes</tt> permission is set to <tt>false</tt> (the default), generate a new type entry for each package name in the <tt>mmac_types.xml</tt> file. For example:+The list of viable op tag names can be found in <tt>AppOpsManager.java</tt>. Just use the string version of each op without the OP_ prefix in your policy tags. These are the current entries (July '14):
-<pre>+
- <type name="com.android.phone"/>+
- <type name="com.android.smspush"/>+
-</pre>+
-2) Set the <tt>persist.mac_applyNameTypes</tt> permission to <tt>true</tt> as this will automatically add package names as type entries.+<tt>
-<pre>+{| border="1"
-adb shell su 0 setprop persist.mac_applyNameTypes 1+| ACCESS_NOTIFICATIONS
-</pre>+| AUDIO_ALARM_VOLUME
 +| AUDIO_BLUETOOTH_VOLUME
-Also existing <tt>type</tt> entries that define the package name could be used, for example the default <tt>mmac_types.xml</tt> file has the following entries:+|-
-<pre>+| AUDIO_MASTER_VOLUME
- <type name="wappush_app">+| AUDIO_MEDIA_VOLUME
- <signature value="@RELEASE"/>+| AUDIO_NOTIFICATION_VOLUME
- <package value="com.android.smspush"/>+
- </type>+
- <type name="telephony_app">+|-
- <signature value="@PLATFORM"/>+| AUDIO_RING_VOLUME
- <package value="com.android.phone"/>+| AUDIO_VOICE_VOLUME
- </type>+| CALL_PHONE
-</pre>+
-The example <tt>allow</tt> entry would then be defined as:+|-
-<pre>+| CAMERA
- <allow name="phone_to_sms" src="telephony_app" dst="wappush_app"/>+| COARSE_LOCATION
-</pre>+| FINE_LOCATION
-The <tt>persist.mac_applyNameTypes</tt> permission is described in [[NB_SEforAndroid_1#Intent_MAC_Configuration | Table 5: Intent MAC system properties and their default values]].+|-
 +| GPS
 +| MONITOR_HIGH_POWER_LOCATION
 +| MONITOR_LOCATION
-=== mmac_types.xml File ===+|-
-The build process supports additional <tt>mmac_types.xml</tt> files to allow devices to specify their specific entries as described in the [[NB_SEforAndroid_1#Building the Policy| Building the Policy]] section that will also expand any signatures.+| NEIGHBORING_CELLS
 +| PLAY_AUDIO
 +| POST_NOTIFICATION
-The entries are defined below with:+|-
-* The <tt><nowiki><type name="" /></nowiki></tt> entry defines the 'type name' entry that will be referenced by the <tt>intent_mac.xml</tt> file <tt>src=""</tt> and <tt>dst=""</tt> entries. The entry will define signatures, package names and or permissions.+| READ_CALENDAR
-* The <tt><nowiki><signature value="" /></nowiki></tt> entries may be the key as extracted by setool (but it will need to be copied from the output produced by [[#setool | setool]]), or use the <tt>"@.."</tt> show in the example below, this will then be generated as a part of the build process by [[#insertkeys.py | insertkeys.py]].+| READ_CALL_LOG
-* The <tt>srcctx=</tt> entry if defined will be matched against the app process source context.+| READ_CLIPBOARD
-<pre>+
-<?xml version="1.0" encoding="utf-8"?>+
-<policy> <!--Start entries -->+
- <type name="" /> <!-- The type entries 'name' -->+|-
- <signature value="" /> <!-- Multiple entries allowed -->+| READ_CONTACTS
- <package value="" /> <!-- Multiple entries allowed -->+| READ_ICC_SMS
- <permission value="" /> <!-- Rule name -->+| READ_SMS
- </type>+
-</policy> <!-- End entries -->+|-
-</pre>+| RECEIVE_EMERGECY_SMS
 +| RECEIVE_MMS
 +| RECEIVE_SMS
-Example entries are:+|-
-<pre>+| RECEIVE_WAP_PUSH
-<?xml version="1.0" encoding="utf-8"?>+| RECORD_AUDIO
-<policy>+| SEND_SMS
- <type name="telephony_app">+|-
- <signature value="@PLATFORM"/>+| SYSTEM_ALERT_WINDOW
- <package value="com.android.phone"/>+| TAKE_AUDIO_FOCUS
- </type>+| TAKE_MEDIA_BUTTONS
- <type name="video_perm">+|-
- <permission value="android.permission.CAMERA"/>+| VIBRATE
- <permission value="android.permission.RECORD_AUDIO"/>+| WAKE_LOCK
- </type>+| WIFI_SCAN
-</policy>+|-
-</pre>+| WRITE_CALENDAR
 +| WRITE_CALL_LOG
 +| WRITE_CLIPBOARD
-== Revoke Permissions File ==+|-
-The <tt>revoke_permissions.xml</tt> file is used to configure revoked permissions. The build process does not currently support additional files. The <tt>revoke_permissions.xml</tt> file entries are as follows:+| WRITE_CONTACTS
 +| WRITE_ICC_SMS
 +| WRITE_SETTINGS
 + 
 +|-
 +| WRITE_SMS
 +|
 +|
 + 
 +|}
 +</tt>
 + 
 +All operations listed in the policy will have a mode of ignored. This means that empty data sets are returned to the caller when an operation is requested. This shadow data will then allow certain apps to presumably still operate. However, AOSP currently is not constructed to return these empty data sets and therefore acts as if ignored operations are completely denied (blocked). Because of this some apps might crash or behave oddly if you apply certain eops policy. In addition, while AOSP seems to have hooked the proper places to check operations against policy some of those hooks fail to follow through with the denial and still allow the operation to occur. Because of this, EOps will also fail to make those distinctions and likewise fail to enforce certain operations. Once the AOSP pieces are in place to return legitimate fake data and enforce all operations then of course eops, by its design, will also do the same.
 + 
 +So, as long as AppOps is beta so too will EOps.
 + 
 +A <tt>debug</tt> tag is also allowed which flips on the global debugging log functionality inside AppOps.
 + 
 +Each stanza is grouped according to the <tt>seinfo</tt> tag that is assigned during install and thus creates a dependency with the <tt>mac_permissions.xml</tt> file. Each <tt>seinfo</tt> tag can then include any number of op tags. By including the op(s) you are simply removing that operation from working for all apps that have been installed with the listed <tt>seinfo</tt> label. These operations are restricted regardless of what any user controlled app ops policy may say. Any op not listed is therefore still subject to user control as normal.
 + 
 +Lastly, there is no permissive mode for EOps. Once a policy is in place all ops listed are enforced.
 + 
 +The following is an example <tt>eops.xml</tt> policy file that will stop the camera being used by any system or default app. The file installation is shown in the [[#buildeopbundle|Build Bundle Tools - ]][[#buildeopbundle|buildeopbundle]] section:
<pre> <pre>
-<?xml version="1.0" encoding="utf-8"?>+<?xml version="1.0"?>
-<revoke-policy> <!-- Start entries -->+<app-ops>
- <package name="" /> <!-- Package containing permissions to revoke -->+ <debug/>
- <revoke-permission="" /> <!-- Multiple entries allowed -->+
- </package>+
- <revoke-policy> <!-- End entries -->+ <seinfo name="default">
 + <op name="CAMERA"/>
 + </seinfo>
 + 
 + <seinfo name="system">
 + <op name="CAMERA"/>
 + </seinfo></nowiki>
 + 
 +</app-ops>
</pre> </pre>
-Example entries are:+ 
 + 
 +== Intent Firewall MMAC Configuration File ==
 +The example <tt>external/sepolicy/ifw.xml</tt> file has some comments regarding the tags, there is also an overview at [http://www.cis.syr.edu/~wedu/android/IntentFirewall/ http://www.cis.syr.edu/~wedu/android/IntentFirewall/].
 + 
 +The following is an example <tt>ifw.xml</tt> policy file that will stop the <tt>DemoIsolatedService</tt> being used by any app other than system apps or apps with the same signature. The file installation is shown in the [[#buildifwbundle|Build Bundle Tools - ]][[#buildifwbundle|buildifwbundle]] section:
<pre> <pre>
-<?xml version="1.0" encoding="utf-8"?>+<?xml version="1.0"?>
-<revoke-policy>+
- <package name="com.example.seandroiddemo">+<rules>
- <revoke-permission name="com.example.seandroiddemo.permission.DEADLY_ACTIVITY"/>+
- </package><+
- <package name="com.example.seandroiddemob">+ <!-- This will stop any app that is not a system app or
- <revoke-permission name="android.permission.CAMERA"/>+ does not have a matching signature from running the
- </package>+ DemoIsolatedService service
 + -->
 + 
 + <service log="true" block="true"></nowiki>
 + <not><sender type="system|signature"/></not><
 + <intent-filter />
 + <component-filter name="com.se4android.isolatedservice/.DemoIsolatedService"/>
 + </service>
-</revoke-policy>+</rules>
</pre> </pre>
 +
 +The events will be in the event log under the '<tt>ifw_intent_matched</tt>' tag, for example:
 +<pre>
 +adb logcat -b events
 +...
 +...
 +I/ifw_intent_matched( 390):[2,com.se4android.isolatedservice/.DemoIsolatedService,10058,1,NULL,NULL,NULL,NULL,0]
 +...
 +</pre>
 +
= Policy Build Tools = = Policy Build Tools =
-This section covers the policy build tools located at <tt>external/sepolicy/tools</tt>. They are checkfc, checkseapp and insertkeys.py. There is also setool that is not used as part of the build process but generates <tt>mac_permissions.xml</tt> entries from packages.+This section covers the policy build tools located at <tt>external/sepolicy/tools</tt>. They are <tt>checkfc</tt>, <tt>checkseapp</tt> and <tt>insertkeys.py</tt>. There is also <tt>setool</tt> that is not used as part of the build process but generates <tt>mac_permissions.xml</tt> entries from packages.
== checkfc == == checkfc ==
-The <tt>checkfc</tt> utility is used during the build process to validate the <tt>file_contexts</tt> and <tt>property_contexts</tt> files against policy. If validation fails <tt>checkfc</tt> will exit with an error.+The <tt>checkfc</tt> utility is used during the build process to validate the <tt>file_contexts</tt>, <tt>property_contexts</tt> and <tt>service_contexts</tt> files against policy. If validation fails <tt>checkfc</tt> will exit with an error.
-<tt>checkfc -h</tt> will give the following output:+Usage:
<pre> <pre>
-usage: <nowiki>checkfc [OPTIONS] sepolicy context_file</nowiki>+usage: checkfc [OPTIONS] sepolicy context_file
Parses a context file and checks for syntax errors. Parses a context file and checks for syntax errors.
The context_file is assumed to be a file_contexts file The context_file is assumed to be a file_contexts file
Line 711: Line 665:
-p : context file represents a property_context file. -p : context file represents a property_context file.
</pre> </pre>
- +Example validating <tt>file_contexts</tt> file (note: no <tt>-p</tt> parameter):
-Example validating <tt>file_contexts</tt> file:+
<pre> <pre>
checkfc out/target/product/generic/root/sepolicy out/target/product/generic/root/file_contexts checkfc out/target/product/generic/root/sepolicy out/target/product/generic/root/file_contexts
Line 721: Line 674:
checkfc -p out/target/product/generic/root/sepolicy out/target/product/generic/root/property_contexts checkfc -p out/target/product/generic/root/sepolicy out/target/product/generic/root/property_contexts
</pre> </pre>
 +
== checkseapp == == checkseapp ==
The <tt>checkseapp</tt> utility is used during the build process to validate the <tt>seapp_contexts</tt> file against policy. If validation fails <tt>checkseapp</tt> will exit with an error. <tt>checkseapp</tt> also consolidates matching entries and outputs the valid file stripped of comments. The <tt>checkseapp</tt> utility is used during the build process to validate the <tt>seapp_contexts</tt> file against policy. If validation fails <tt>checkseapp</tt> will exit with an error. <tt>checkseapp</tt> also consolidates matching entries and outputs the valid file stripped of comments.
-<tt>checkseapp -h</tt> will give the following output:+Usage:
<pre> <pre>
-<nowiki>checkseapp [options] <input file></nowiki>+checkseapp [options] <input file><
-<nowiki>Processes an seapp_contexts file specified by argument <input file> (default stdin) and allows later declarations to +Processes an seapp_contexts file specified by argument <input file> (default stdin) and allows later declarations to override previous ones on a match.
-override previous ones on a match.</nowiki>+ 
Options: Options:
-h - print this help message -h - print this help message
 + -s - enable strict checking of duplicates. This causes the program to exit on a duplicate entry with a non-zero exit status
-v - enable verbose debugging informations -v - enable verbose debugging informations
- -p policy file - specify policy file for strict checking of output selectors+ -p policy file - specify policy file for strict checking of output selectors against the policy
-o output file - specify output file, default is stdout -o output file - specify output file, default is stdout
</pre> </pre>
Line 739: Line 694:
An example command with output to <tt>stdout</tt> is: An example command with output to <tt>stdout</tt> is:
<pre> <pre>
-checkseapp -p out/target/product/generic/root/sepolicy out/target/product/generic/root/seapp_contexts+checkseapp -p out/target/product/se4a_device/root/sepolicy out/target/product/se4a_device/root/seapp_contexts
-isSystemServer=true domain=system+ 
 +isSystemServer=true domain=system_server
user=system domain=system_app type=system_data_file user=system domain=system_app type=system_data_file
user=bluetooth domain=bluetooth type=bluetooth_data_file user=bluetooth domain=bluetooth type=bluetooth_data_file
user=nfc domain=nfc type=nfc_data_file user=nfc domain=nfc type=nfc_data_file
user=radio domain=radio type=radio_data_file user=radio domain=radio type=radio_data_file
-user=_app domain=untrusted_app type=app_data_file levelFrom=app+user=shared_relo domain=shared_relo
-user=_app seinfo=platform domain=platform_app type=platform_app_data_file+user=shell domain=shell type=shell_data_file
-user=_app seinfo=shared domain=shared_app type=platform_app_data_file+
-user=_app seinfo=media domain=media_app type=platform_app_data_file+
-user=_app seinfo=release domain=release_app type=platform_app_data_file+
user=_isolated domain=isolated_app user=_isolated domain=isolated_app
 +user=_app seinfo=platform domain=platform_app type=app_data_file
 +user=_app domain=untrusted_app type=app_data_file
 +user=_app seinfo=netclient domain=netclient_app type=net_apps_log_file levelFrom=app
 +user=_app seinfo=netserver domain=netserver_app type=net_apps_log_file levelFrom=app
</pre> </pre>
 +
== insertkeys.py == == insertkeys.py ==
-The <tt>insertkeys.py</tt> utility is used during the build process to insert signing keys into multiple <tt>mac_permissions.xml</tt> and <tt>mmac_types.xml</tt> files. The keys are obtained from <tt>pem</tt> files and the entries to be replaced start with an <tt>@</tt> followed by a keyword. The <tt>external/sepolicy/keys.conf</tt> file contains corresponding entries that allow mapping of <tt>pem</tt> files to signatures as discussed in the [[#keys.conf | keys.conf]] section.+The <tt>insertkeys.py</tt> utility is used during the build process to insert signing keys into the <tt>mac_permissions.xml</tt> file. The keys are obtained from <tt>pem</tt> files and the entries to be replaced start with an <tt>@</tt> followed by a keyword. The <tt>external/sepolicy/keys.conf</tt> file contains corresponding entries that allow mapping of <tt>pem</tt> files to signatures as discussed in the [[#keys.conf|keys.conf]] section.
-Note that <tt>pem</tt> files are base64 encoded however the Android Package Manager Service uses base16 encodings. Therefore <tt>insertkeys.py</tt> and <tt>setool</tt> will generate base16 encodings for the <tt>mac_permissions.xml</tt> and <tt>mmac_types.xml</tt> files.+<tt>insertkeys.py</tt> generates base16 encodings from the base64 <tt>pem</tt> files as this is required by the Android Package Manager Service. The resulting <tt>mac_permissions.xml</tt> file will also be stripped of comments and whitespace.
-<tt>insertkeys.py</tt> will also strip the files of comments and whitespace to preserve space on the <tt>system.img</tt>. To view the output file in a more human friendly format the <tt>tidy</tt> or <tt>xmllint</tt> command can be used.+Usage:
- +
-<tt>insertkeys.py -h</tt> will give the following output:+
<pre> <pre>
-<nowiki>Usage: insertkeys.py [options] CONFIG_FILE MAC_PERMISSIONS_FILE [MAC_PERMISSIONS_FILE...]</nowiki>+Usage: insertkeys.py [options] CONFIG_FILE MAC_PERMISSIONS_FILE [MAC_PERMISSIONS_FILE...]</nowiki>
 + 
-This tool allows one to configure an automatic inclusion of signing keys into the mac_permission.xml file(s) from the pem files. +This tool allows one to configure an automatic inclusion of signing keys into the mac_permission.xml file(s) from the pem files. If multiple mac_permission.xml files are included then they are unioned to produce a final version.
-If multiple mac_permission.xml files are included then they are unioned to produce a final version.+
Options: Options:
- --version show program's version number and exit+ --version show program's version number and exit
- -h, --help show this help message and exit+ -h, --help show this help message and exit
- -v, --verbose Print internal operations to stdout+ -v, --verbose Print internal operations to stdout
- -o FILE, --output=FILE Specify an output file, default is stdout+ -o FILE, --output=FILE Specify an output file, default is stdout
- -c DIR, --cwd=DIR Specify a root (CWD) directory to run this from, itchdirs' AFTER loading the config file+ -c DIR, --cwd=DIR Specify a root (CWD) directory to run this from, itchdirs' AFTER loading the config file
- -t TARGET_BUILD_VARIANT, --target-build-variant=TARGET_BUILD_VARIANT+ -t TARGET_BUILD_VARIANT, --target-build-variant=TARGET_BUILD_VARIANT
- Specify the TARGET_BUILD_VARIANT, defaults to eng+ Specify the TARGET_BUILD_VARIANT, defaults to eng
 + -d KEY_DIRECTORY, --key-directory Specify a parent directory for keys
</pre> </pre>
-An example command that takes two <tt>mac_permission.xml</tt> files inserts the signatures and concatenates them into a single file is: 
-<pre> 
-insertkeys.py -o demo/unioned_mac_permissions.xml external/sepolicy/keys.conf \ 
-external/sepolicy/mac_permissions.xml demo/mac_permissions.xml 
-</pre> 
-=== keys.conf ===+=== keys.conf File ===
-The <tt>keys.conf</tt> file is used by <tt>insertkeys.py</tt> for mapping the "<tt>@...</tt>" tags in <tt>mac_permissions.xml</tt> and mmac_types.xml signature entries with public keys found in <tt>pem</tt> files. The configuration file can be used in <tt>BOARD_SEPOLICY_UNION</tt> and <tt>BOARD_SEPOLICY_REPLACE</tt> variables and is processed via <tt>m4</tt> macros.+The <tt>keys.conf</tt> file is used by <tt>insertkeys.py</tt> for mapping the "<tt>@...</tt>" tags in <tt>mac_permissions.xml</tt>, <tt>mmac_types.xml</tt> and <tt>content_provider.xml</tt> signature entries with public keys found in <tt>pem</tt> files. The configuration file can be used in <tt>BOARD_SEPOLICY_UNION</tt> and <tt>BOARD_SEPOLICY_REPLACE</tt> variables and is processed via <tt>m4</tt> macros.
<tt>insertkeys.py</tt> allows for mapping any string contained in <tt>TARGET_BUILD_VARIANT</tt> with a specific path to a <tt>pem</tt> file. Typically <tt>TARGET_BUILD_VARIANT</tt> is either <tt>user</tt>, <tt>eng</tt> or <tt>userdebug</tt>. Additionally "<tt>ALL</tt>" may be specified to map a path to any string specified in <tt>TARGET_BUILD_VARIANT</tt>. All tags are matched verbatim and all options are matched lowercase. The options are "<tt>tolowered</tt>" automatically for the user, it is convention to specify tags and options in all uppercase and tags start with <tt>@</tt>. <tt>insertkeys.py</tt> allows for mapping any string contained in <tt>TARGET_BUILD_VARIANT</tt> with a specific path to a <tt>pem</tt> file. Typically <tt>TARGET_BUILD_VARIANT</tt> is either <tt>user</tt>, <tt>eng</tt> or <tt>userdebug</tt>. Additionally "<tt>ALL</tt>" may be specified to map a path to any string specified in <tt>TARGET_BUILD_VARIANT</tt>. All tags are matched verbatim and all options are matched lowercase. The options are "<tt>tolowered</tt>" automatically for the user, it is convention to specify tags and options in all uppercase and tags start with <tt>@</tt>.
Line 790: Line 742:
An example <tt>keys.conf</tt> file is as follows: An example <tt>keys.conf</tt> file is as follows:
<pre> <pre>
-<nowiki>#</nowiki>+#
-<nowiki># Maps an arbitrary tag [TAGNAME] with the string contents found in</nowiki>+# Maps an arbitrary tag [TAGNAME] with the string contents found in
-<nowiki># TARGET_BUILD_VARAINT. Common convention is to start TAGNAME with an @ and</nowiki>+# TARGET_BUILD_VARIANT. Common convention is to start TAGNAME with an @ and
-<nowiki># name it after the base file name of the pem file.</nowiki>+# name it after the base file name of the pem file.
-<nowiki>#</nowiki>+#
-<nowiki># Each tag (section) then allows one to specify any string found in</nowiki>+# Each tag (section) then allows one to specify any string found in
-<nowiki># TARGET_BUILD_VARIANT. Typically this is user, eng, and userdebug. Another</nowiki>+# TARGET_BUILD_VARIANT. Typcially this is user, eng, and userdebug. Another
-<nowiki># option is to use ALL which will match ANY TARGET_BUILD_VARAINT string.</nowiki>+# option is to use ALL which will match ANY TARGET_BUILD_VARIANT string.
-<nowiki>#</nowiki>+#
 +[@PLATFORM]
 +ALL : $DEFAULT_SYSTEM_DEV_CERTIFICATE/platform.x509.pem
-<nowiki>[@PLATFORM]</nowiki>+[@MEDIA]
-ALL : build/target/product/security/platform.x509.pem+ALL : $DEFAULT_SYSTEM_DEV_CERTIFICATE/media.x509.pem
-<nowiki>[@MEDIA]</nowiki>+[@SHARED]
-ALL : build/target/product/security/media.x509.pem+ALL : $DEFAULT_SYSTEM_DEV_CERTIFICATE/shared.x509.pem
-<nowiki>[@SHARED]</nowiki>+# Example of ALL TARGET_BUILD_VARIANTS
-ALL : build/target/product/security/shared.x509.pem+[@RELEASE]
 +ENG : $DEFAULT_SYSTEM_DEV_CERTIFICATE/testkey.x509.pem
 +USER : $DEFAULT_SYSTEM_DEV_CERTIFICATE/testkey.x509.pem
 +USERDEBUG : $DEFAULT_SYSTEM_DEV_CERTIFICATE/testkey.x509.pem
 +</pre>
-<nowiki># Example of ALL TARGET_BUILD_VARIANTS</nowiki>+The following is an example entry that will use a device specific key during the build process:
-<nowiki>[@RELEASE]</nowiki>+<pre>
-ENG : build/target/product/security/testkey.x509.pem+[@NET_APPS]
-USER : build/target/product/security/testkey.x509.pem+ALL : $ANDROID_BUILD_TOP/device/demo_vendor/se4a_device/security/net_apps.x509.pem
-USERDEBUG : build/target/product/security/testkey.x509.pem+
</pre> </pre>
-== setool == 
-The <tt>setool</tt> utility is not used during the build process and is intended only to produce 'starter' entries for the <tt>mac_permissions.xml</tt> file. 
-The entries produced will generally have to be modified because currently:+== Build Bundle Tools ==
-# If multiple packages are given each with the same signature, a separate entry will be generated for each package. If added to the <tt>mac_permissions.xml</tt> file only the first entry will be used by the Install-time MMAC process (therefore the packages need to be consolidated into on entry).+The following tools will produce an Android "bundle" for updating MAC/MMAC policy within a zip file suitable for installation by the SEAdmin app. SEAdmin is currently hard-coded to look for these zip files in the SD Card device (<tt>/sdcard/</tt>).
-# <tt>setool</tt> will generate (<tt>--build</tt>) entries for third party apps, however it should not as they will be ignored by the install-time MMAC.+
-# <tt>setool</tt> will check (<tt>--policy</tt>) third party apps against the full <tt>mac_permissions.xml</tt> policy, however it should not, it should only check them against the <tt><nowiki><default></nowiki></tt> entries only.+
-Having said that, <tt>setool</tt> is still useful as it will generate the signature entries and extract the permissions. +The [[#Using an Intent Example|buildsebundle]] section also shows how a policy can be updated by broadcasting an intent instead of using SEAdmin.
-<tt>setool --help</tt> will give the following output:+ 
 +=== buildsebundle ===
 +The <tt>buildsebundle</tt> tool will produce an Android "bundle" for updating the core SE for Android policy within an <tt>selinux_bundle.zip</tt> file, suitable for installation by the SEAdmin app, although it is possible to update using an intent as described in the [[#Using an Intent Example|Using an Intent Example]] section.
 + 
 +To be able to build the bundle the following mandatory files are required:
 +: selinux_version, sepolicy, file_contexts, seapp_contexts, property_contexts, service_contexts, mac_permissions.xml
 + 
 +Usage:
 +<pre>
 +usage: buildsebundle -k <private key.pk8> [-v <version>] [-r <previous hash>] \
 +[-h] -- <selinux_version> <file_contexts> <property_contexts> \
 +<sepolicy> <seapp_contexts> <service_contexts> <mac_permissions.xml>
 + 
 +This script builds a selinux policy bundle and supporting metadata file capable of being loaded via the ConfigUpdate mechanism. It takes a pkcs8 DER encoded RSA private key that is then used to sign the bundle. For AOSP development you'll typically want to use the key from the source tree at:
 + build/target/product/security/testkey.pk8
 +The built bundle will be written to selinux_bundle.zip which will include the signature metadata file of the bundle.
 + 
 +OPTIONS:
 + -h Show this message.
 + -v Version of the built bundle. Defaults to 1.
 + -r SHA-512 hash of the bundle to replace. Defaults to 'NONE'.
 +</pre>
 + 
 +The following is an example where a new policy has been built with all required files. The wildcard can be used as <tt>buildsebundle</tt> will always use the mandatory list:
 +<pre>
 +buildsebundle -k $ANDROID_BUILD_TOP/build/target/product/security/testkey.pk8 -v 3 -- $ANDROID_BUILD_TOP/device/demo_device/se4a_device/new_sepolicy/*
 + 
 +adb push selinux_bundle.zip /sdcard/
 +</pre>
 + 
 +Once built, the bundle is pushed to the SD card and SEAdmin is used to update the policy (note that SEAdmin only reads the bundle from <tt>/sdcard</tt>).
 + 
 + 
 +==== Using an Intent Example ====
 +This example shows how to update a policy by broadcasting an intent in the same way as SEAdmin.
 + 
 +Extract the <tt>selinux_bundle</tt> files from the <tt>selinux_bundle.zip</tt> file:
 +<pre>
 +unzip selinux_bundle.zip
 +Archive: selinux_bundle.zip
 + inflating: update_bundle
 + inflating: update_bundle_metadata
 +</pre>
 + 
 +The two files contain:
 + 
 +<tt>'''update_bundle'''</tt> - Contains hex encoded policy files to be installed.
 + 
 +<tt>'''update_bundle_metadata'''</tt> - This is used by SEAdmin to form the intent and contains a hash of the bundle to replace or "<tt>NONE</tt>", the signature of the <tt>update_bundle</tt> and the bundle version (in this case "<tt>3</tt>"). Example contents are:
 +<pre>
 +NONE:I6E0cZ8WbF6kJWkDozJCfckw5xuZhXuE0iqrbszsxhi7S4Z3DrR7RiH/aomRQxeskvMv9B/+G7JXfxFAQlV1CWZihnefkHGnei4atKnBLPK/g3gmf0Wb0jjizc4yb4uvu/XQAZvybKcsTvTiegfqTHMFWPGKgoq97RKAjk2kT2fa3liArylTrLl7OfRtKq6mNjQNnfVrte9e/aJptiAmOwDNdQydfRwhewrKPE6rM+YNuHJaJ+h28dNecQtCn9TabTxn8I1G+10d5/wmjjgXq6MdfEMQZ++H4ZIaL4bTdUOQVdFeMsnFLA3hjLGf3BXpHmG84s7iDO158V0kbXikzA==:3
 +</pre>
 + 
 +Push the <tt>update_bundle</tt> to the device:
 +<pre>
 +adb push update_bundle /data/update_bundle
 +</pre>
 + 
 +Build an intent to broadcast via <tt>adb</tt> by including the bundle location, with the hash, signature and version from the <tt>update_bundle_metadata</tt> as follows:
 +<pre>
 +adb shell am broadcast -a android.intent.action.UPDATE_SEPOLICY -e "CONTENT_PATH" "/data/update_bundle" -e "REQUIRED_HASH" "NONE" -e "SIGNATURE" "I6E0cZ8WbF6kJWkDozJCfckw5xuZhXuE0iqrbszsxhi7S4Z3DrR7RiH/aomRQxeskvMv9B/+G7JXfxFAQlV1CWZihnefkHGnei4atKnBLPK/g3gmf0Wb0jjizc4yb4uvu/XQAZvybKcsTvTiegfqTHMFWPGKgoq97RKAjk2kT2fa3liArylTrLl7OfRtKq6mNjQNnfVrte9e/aJptiAmOwDNdQydfRwhewrKPE6rM+YNuHJaJ+h28dNecQtCn9TabTxn8I1G+10d5/wmjjgXq6MdfEMQZ++H4ZIaL4bTdUOQVdFeMsnFLA3hjLGf3BXpHmG84s7iDO158V0kbXikzA==" -e "VERSION" "3"
 +</pre>
 + 
 +When the intent has been broadcast there will be a response, however that does not indicate that the policy was updated, just that the intent was broadcast:
 +<pre>
 +Broadcasting: Intent { act=android.intent.action.UPDATE_SEPOLICY (has extras) }
 +Broadcast completed: result=0
 +</pre>
 + 
 +<tt>logcat</tt> should show whether it was successful:
 +<pre>
 +I/ConfigUpdateInstallReceiver( 908): Found new update, installing...
 +I/ConfigUpdateInstallReceiver( 908): Installation successful
 +I/SELinuxPolicyInstallReceiver( 908): Applying SELinux policy
 +</pre>
 + 
 +If the update failed because of versioning then an error is given (however if signature incorrect fails silently).
 + 
 +The following show various policy information after the third update:
 +<pre>
 +adb shell ls -l /data/security/current
 +lrwxrwxrwx system system 2014-07-19 10:41 current -> /data/security/contexts
 +</pre>
 + 
 +<pre>
 +adb shell ls -l /data/security/contexts
 +-rw-r--r-- system system 10512 2014-07-19 10:41 file_contexts
 +-rw-r--r-- system system 10656 2014-07-19 09:01 file_contexts_backup
 +-rw-r--r-- system system 4203 2014-07-19 10:41 mac_permissions.xml
 +-rw-r--r-- system system 4203 2014-07-19 09:01 mac_permissions.xml_backup
 +-rw-r--r-- system system 2549 2014-07-19 10:41 property_contexts
 +-rw-r--r-- system system 2549 2014-07-19 09:01 property_contexts_backup
 +-rw-r--r-- system system 641 2014-07-19 10:41 seapp_contexts
 +-rw-r--r-- system system 641 2014-07-19 09:01 seapp_contexts_backup
 +-rw-r--r-- system system 78 2014-07-19 10:41 selinux_version
 +-rw-r--r-- system system 78 2014-07-19 09:01 selinux_version_backup
 +-rw-r--r-- system system 115831 2014-07-19 10:41 sepolicy
 +-rw-r--r-- system system 116438 2014-07-19 09:01 sepolicy_backup
 +-rw-r--r-- system system 7748 2014-07-19 10:41 service_contexts
 +-rw-r--r-- system system 7748 2014-07-19 09:01 service_contexts_backup
 +</pre>
 + 
 +<pre>
 +adb shell ls -l /data/security
 +drwx------ system system 2014-07-19 10:41 bundle
 +drwx------ system system 2014-07-19 10:41 contexts
 +lrwxrwxrwx system system 2014-07-19 10:41 current ->/data/security/contexts
 +drwx------ system system 2014-07-19 10:37 eops
 +</pre>
 + 
 +<pre>
 +adb shell ls -l /data/security/bundle
 +drwx------ system system 2014-07-19 10:41 metadata
 +-rw-r--r-- system system 191271 2014-07-19 10:41 sepolicy_bundle
 +</pre>
 + 
 +<pre>
 +adb shell ls -l /data/security/bundle/metadata
 +-rw-r--r-- system system 1 2014-07-19 10:41 version
 +</pre>
 + 
 +<pre>
 +adb shell cat /data/security/bundle/metadata/version
 +3
 +</pre>
 + 
 +The loaded policy can be extracted from the device if required by:
 +<pre>
 +adb pull /sys/fs/selinux/policy sepolicy-v3
 +</pre>
 + 
 + 
 +=== buildeopbundle ===
 +The <tt>buildeopbundle</tt> tool will produce an Android "bundle" for updating the Enterprise Operations policy within an <tt>eops_bundle.zip</tt> file suitable for installation by the SEAdmin app, although it is possible to update using an intent as described in the [[#Using an Intent Example|Using an Intent Example]] section.
 + 
 +To be able to build the bundle an <tt>eops.xml</tt> file is required.
 + 
 +Usage:
 +<pre>
 +usage: buildeopbundle -k <private key.pk8> [-v <version>] [-r <previous hash>] \
 +[-h] -- <eops.xml>
 + 
 +This script builds a eops policy bundle and supporting metadata file capable of being loaded via the ConfigUpdate mechanism. It takes a pkcs8 DER encoded RSA private key that is then used to sign the bundle. For AOSP development you'll typically want to use the key from the source tree at:
 + build/target/product/security/testkey.pk8
 + 
 +If building your own cert you should probably use a key size of at least 1024 or greater. The bundle requires that the eops.xml file be included and with that exact basename. The built bundle will be written to eop_bundle.zip which will include the signature metadata file of the bundle.
 + 
 +OPTIONS:
 + -h Show this message.
 + -v Version of the built bundle. Defaults to 1.
 + -r SHA-512 hash of the bundle to replace. Defaults to 'NONE'.
 +</pre>
 + 
 + 
 +==== Eops Example ====
 +The following is an example where a new <tt>eops.xml</tt> file has been produced, bundled, then pushed to the SD card. SEAdmin is then used to update the policy (note that SEAdmin only reads the bundle from <tt>/sdcard</tt>):
 +<pre>
 +buildeopbundle -k $ANDROID_BUILD_TOP/build/target/product/security/testkey.pk8 -v 1 -- eops.xml
 + 
 +adb push eops_bundle.zip /sdcard/
 +</pre>
 + 
 +<tt>logcat</tt> should show if it was successful:
 +<pre>
 +D/SEAdminConfigUpdateFragment( 904): android.intent.action.UPDATE_EOPS intent being broadcast. Bundle[{CONTENT_PATH=/cache/eops_bundle, SIGNATURE=qZJ8I07MHFTXaII2jhPMooRLzejArUI0qsvkteG9nzEzgzjwyh8RWUaaRil6xrQsPb5g+qWj+nfQCkH7DIEow/WF8S1sTeReS8G/z+hPQi0MHgWGKH0kCIfXn6yqqEri3+Dnolb1vHVuM7t/0mszCvtjqfq5GWbHZc1xYSgMQJXqrhfzSqa2zvO4+7zE0GszfuZXwt9QHci9C1IJ5B50URmmg4TDIuhfISWW9vYkEctwARIyCLhfYiZzIQOwzPj3oSHI1AUWMHxbbpADFzCumZ1WdfpA0txow8rDM+01qkKGtcAsNs8me2FAPz28tckQ9ea6QwAzDCSP3PzQC1Horg==, REQUIRED_HASH=NONE, VERSION=1}]
 +I/ConfigUpdateInstallReceiver( 395): Couldn't find current metadata, assuming first update
 +I/ConfigUpdateInstallReceiver( 395): Failed to read current content, assuming first update!
 +I/ConfigUpdateInstallReceiver( 395): Found new update, installing...
 +I/ConfigUpdateInstallReceiver( 395): Installation successful
 +D/AppOps ( 381): Eops policy: system [ CAMERA]
 +D/AppOps ( 381): Eops policy: default [ CAMERA]
 +</pre>
 + 
 +The new file and its supporting metadata are:
 +<pre>
 +adb shell su 0 ls -lR /data/security/eops
 + 
 +/data/security/eops:
 +-rw-r--r-- system system 189 2014-07-20 14:15 eops.xml
 +drwx------ system system 2014-07-20 14:15 eops_metadata
 + 
 +/data/security/eops/eops_metadata:
 +-rw-r--r-- system system 1 2014-07-20 14:15 version
 +</pre>
 + 
 +The version number after the update is:
 +<pre>
 +adb shell su 0 cat /data/security/eops/eops_metadata/version
 +1
 +</pre>
 + 
 +Because the Eops policy specified an <tt>seinfo</tt> of <tt>system</tt> and the operation <tt>CAMERA</tt>, if the Camera app is now started it will load however, it will not be possible to take pictures as <tt>logcat</tt> will show:
 +<pre>
 +D/AppOps ( 381): startOperation: reject #1 for code 26 (26) uid 10026 package com.android.camera2
 +I/CameraService( 60): Camera 0: Access for "com.android.camera2" has been revoked
 +</pre>
 + 
 +=== buildifwbundle ===
 +The <tt>buildifwbundle</tt> tool will produce an Android "bundle" for updating the Intent Firewall policy within an <tt>ifw_bundle.zip</tt> file suitable for installation by the SEAdmin app, although it is possible to update using an intent as described in the [[#Using an Intent Example|Using an Intent Example]] section.
 + 
 +To be able to build the bundle an <tt>ifw.xml</tt> file is required, although note that the Intent Firewall service will read any file so long as it has the <tt>.xml</tt> extension.
 + 
 +Usage:
 +<pre>
 +usage: buildifwbundle -k <private key.pk8> [-v <version>] [-r <previous hash>] \
 +[-h] -- <ifw.xml>
 + 
 +This script builds an intent firewall policy bundle and supporting metadata file capable of being loaded via the ConfigUpdate mechanism. It takes a pkcs8 DER encoded RSA private key that is then used to sign the bundle. For AOSP development you'll typically want to use the key from the source tree at:
 + 
 +build/target/product/security/testkey.pk8
 + 
 +If building your own cert you should probably use a key size of at least 1024 or greater. The bundle requires that the ifw.xml file be included and with that exact basename. The built bundle will be written to ifw_bundle.zip which will include the signature metadata file of the bundle.
 + 
 +OPTIONS:
 + -h Show this message.
 + -v Version of the built bundle. Defaults to 1.
 + -r SHA-512 hash of the bundle to replace. Defaults to 'NONE'.
 +</pre>
 + 
 + 
 +==== IFW Example ====
 +The following is an example where a new <tt>ifw.xml</tt> file has been produced, bundled, and then pushed to the SD card. SEAdmin is then used to update the policy (note that SEAdmin only reads the bundle from <tt>/sdcard</tt>):
 +<pre>
 +buildsifwbundle -k $ANDROID_BUILD_TOP/build/target/product/security/testkey.pk8 -v 1 -- eops.xml
 + 
 +adb push ifw_bundle.zip /sdcard/
 +</pre>
 + 
 +<tt>logcat</tt> should show whether it was successful:
 +<pre>
 +D/SEAdminConfigUpdateFragment( <nowiki>904): android.intent.action.UPDATE_INTENT_FIREWALL intent being broadcast. Bundle[{CONTENT_PATH=/cache/ifw_bundle, SIGNATURE=tfQONpEZbL1Y6sXj1BY98TO4izK2IyeqO9Hko5tZygE77zry98RGmU5BAAIFs21G9G7WpAcPTR7TGe4LRMpB7SKeZ1Xh+4B+U+30TnHkwXp9HRIgIJcN5Kqiyp/UPAjEJjYmBZk+yM5FLYcMCQS082wfpC9c+gRQcl6AYuSmiynvjgc1d33rtfB7Hd40LF30mBZyyiUJc5YF1ddaITBbL/CCKmFblfBqadZtmCN7xGUIJEHqWPnuEvscatkOLgZa+35ZXfl2WkD/DsGkwocXM9akjD0NJY9WZJpzwAHQPdQFXN6nthrsV8kiC7OUFvK/PKll9oetiyTSEEVH5JlMnA==, REQUIRED_HASH=NONE, VERSION=1}]</nowiki>
 +I/ConfigUpdateInstallReceiver( 395): Couldn't find current metadata, assuming first update
 +I/ConfigUpdateInstallReceiver( 395): Failed to read current content, assuming first update!
 +I/ConfigUpdateInstallReceiver( 395): Found new update, installing...
 +I/ConfigUpdateInstallReceiver( 395): Installation successful
 +I/IntentFirewall( 395): Read new rules (A:0 B:0 S:1)
 +</pre>
 + 
 +The new file and its supporting metadata are:
 +<pre>
 +adb shell su 0 ls -lR /data/system/ifw
 + 
 +/data/system/ifw:
 +-rw-r--r-- system system 454 2014-07-20 13:14 ifw.xml
 +drwx------ system system 2014-07-20 13:14 metadata
 + 
 +/data/system/ifw/metadata:
 +-rw-r--r-- system system 1 2014-07-20 13:14 gservices.version
 +</pre>
 + 
 +The version number after the update is:
 +<pre>
 +adb shell su 0 cat /data/system/ifw/metadata/gservices.version
 +1
 +</pre>
 + 
 +== post_process_mac_perms ==
 +This tool will modify an existing <tt>mac_permissions.xml</tt> with additional app certs not already found in that policy. This becomes useful when a directory containing apps is searched and the certs from those apps are added to the policy not already explicitly listed.
 + 
 +There is no make target for this tool (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>).
 + 
 +Usage:
 +<pre>
 +post_process_mac_perms [-h] -s SEINFO -d DIR -f POLICY
 + 
 + -s SEINFO, --seinfo SEINFO seinfo tag for each generated stanza
 + -d DIR, --dir DIR Directory to search for apks
 + -f POLICY, --file POLICY mac_permissions.xml policy file
 +</pre>
 + 
 +Example:
 +<pre>
 +post_process_mac_perms -s netapps -d ./APK -f mac_permissions.xml
 +</pre>
 + 
 +Before:
 +<pre>
 +<?xml version="1.0" encoding="utf-8"?>
 +<policy>
 + <signer signature="- certificate here -" ><seinfo value="platform"/></signer>
 + <default><seinfo value="default"/></default>
 +</policy>
 +</pre>
 + 
 +After:
 +<pre>
 +<?xml version="1.0" encoding="utf-8"?>
 +<policy>
 + <signer signature="- certificate here -" ><seinfo value="platform"/></signer>
 + <default><seinfo value="default"/></default>
 + <signer signature="- certificate here -"><seinfo value="netapps"/></signer>
 +</policy>
 +</pre>
 + 
 + 
 +== sepolicy_check ==
 +A tool for auditing a <tt>sepolicy</tt> file for any allow rule that grants a given permission.
 + 
 +Usage:
 +<pre>
 +sepolicy-check -s <domain> -t <type> -c <class> -p <permission>
 +-P out/target/product/<board>/root/sepolicy
 +</pre>
 + 
 +The output will be "<tt>Match found!</tt>" or silent if not. <tt>sepolicy_check</tt> will return <tt>0</tt> for found, <tt>1</tt> for not found and <tt>-1</tt> for an error.
 + 
 +Examples:
 +<pre>
 +sepolicy-check -s healthd -t system_server_service -c service_manager -p add -P out/target/product/generic/root/sepolicy
 +Match found!
 +</pre>
 + 
 +<pre>
 +sepolicy-check -s su -t security_prop -c property_service -p set -P out/target/product/generic/root/sepolicy
 +echo $?
 +1
 +</pre>
 + 
 + 
 +== sepolicy-analyze ==
 +This is the text from the <tt>external/sepolicy/tools/README</tt> that describes the tool for performing various kinds of analysis on a sepolicy file. The analysis that are currently supported include:
 + 
 +=== Type Equivalence ===
 +<pre>
 +sepolicy-analyze -e -P out/target/product/<board>/root/sepolicy
 +</pre>
 + 
 +Display all type pairs that are "equivalent", i.e. they are identical with respect to allow rules, including indirect allow rules via attributes and default-enabled conditional rules (i.e. default boolean values yield a true conditional expression).
 + 
 +Equivalent types are candidates for being coalesced into a single type. However, there may be legitimate reasons for them to remain separate, for example: - the types may differ in a respect not included in the current analysis, such as default-disabled conditional rules, audit-related rules (<tt>auditallow</tt> or <tt>dontaudit</tt>), default type transitions, or constraints (e.g. mls), or - the current policy may be overly permissive with respect to one or the other of the types and thus the correct action may be to tighten access to one or the other rather than coalescing them together, or - the domains that would in fact have different accesses to the types may not yet be defined or may be unconfined in the policy you are analyzing.
 + 
 +Example output:
 +<pre>
 +sepolicy-analyze -e -P out/target/product/se4a_device/root/sepolicy
 + 
 +Types adbd_socket and mdns_socket are equivalent.
 +Types rild_debug_socket and init_tmpfs are equivalent.
 +Types rild_debug_socket and qemud_tmpfs are equivalent.
 +Types surfaceflinger_service and mediaserver_service are equivalent.
 +Types surfaceflinger_service and inputflinger_service are equivalent.
 +</pre>
 + 
 +=== Type Difference ===
 +<pre>
 +sepolicy-analyze -d -P out/target/product/<board>/root/sepolicy
 +</pre>
 + 
 +Display type pairs that differ and the first difference found between the two types. This may be used in looking for similar types that are not equivalent but may be candidates for coalescing.
 + 
 +Example output:
 +<pre>
 +sepolicy-analyze -d -P out/target/product/se4a_device/root/sepolicy
 + 
 +Types adbd_socket and functionfs differ, starting with:
 +allow adbd_socket rootfs:filesystem { associate };
 +allow functionfs self:filesystem { associate };
 + 
 +Types adbd_socket and hci_attach_exec differ, starting with:
 +allow system_server adbd_socket:sock_file { ioctl read write getattr lock append open };
 +allow debuggerd hci_attach_exec:file { ioctl read getattr lock open };
 + 
 +Types adbd_socket and system_server differ, starting with:
 +allow adbd_socket rootfs:filesystem { associate };
 +allow system_server rootfs:filesystem { getattr };
 +</pre>
 + 
 + 
 +=== Duplicate Allow Rules ===
 +<pre>
 +sepolicy-analyze -D -P out/target/product/<board>/root/sepolicy
 +</pre>
 + 
 +Displays duplicate allow rules, i.e. pairs of allow rules that grant the same permissions where one allow rule is written directly in terms of individual types and the other is written in terms of attributes associated with those same types. The rule with individual types is a candidate for removal. The rule with individual types may be directly represented in the source policy or may be a result of expansion of a type negation (e.g. <tt>domain -foo -bar</tt> is expanded to individual allow rules by the policy compiler). Domains with <tt>unconfineddomain</tt> will typically have such duplicate rules as a natural side effect and can be ignored.
 + 
 +Example output:
 +<pre>
 +sepolicy-analyze -D -P out/target/product/se4a_device/root/sepolicy
 + 
 +Duplicate allow rule found:
 +allow init hci_attach_exec:file { read getattr execute open };
 +allow unconfineddomain exec_type:file { ioctl read getattr lock execute open };
 + 
 +Duplicate allow rule found:
 +allow ueventd device:dir { write add_name remove_name };
 +allow ueventd dev_type:dir { ioctl read write create getattr setattr unlink link rename add_name remove_name reparent search rmdir open };
 +</pre>
 + 
 + 
 +== setool ==
 +The <tt>setool</tt> utility is not used during the build process and is intended only to produce entries for the <tt>mac_permissions.xml</tt> file and verify a correctly formated file. It is not supplied in AOSP.
 + 
 +Usage:
<pre> <pre>
-Usage: setool [flags] <--build|--policy> <apks>+Usage: setool [flags] <--build keys|package OR --policy policyFile> <apk> [ <apk> ]*
Tool to help build and verify MMAC install policies. Tool to help build and verify MMAC install policies.
-apks List of apks to analyze, space separated. All supplied apks must+--build Generate an MMAC style policy stanza with a given --seinfo string.
-be absolute paths or relative to --apkdir (which defaults to the current directory).+ The resulting stanza can then be used as an entry in the mac_permissions.xml file.
---build Generate an MMAC style policy stanza. The resulting stanza can then be used as an entry in the mac_permissions.xml file.+ package Policy entry that contains the package name inside the signature stanza.
- whitelist +
- Policy entry that contains a white listing of all permissions. The stanza will contain the app's package tag within its+
- signer tag.+
- keys +
- Print a valid signer tag which contains the hex encoded X.509 cert of the app.+
---policy Determine if supplied apks pass the supplied policy.+ keys Print just a signer tag which contains the hex encoded X.509 certs of the app.
 + 
 +--policy Determine if the apks pass the supplied policy by printing the seinfo tag that would be assigned or null otherwise.
 + 
 + apk An apk to analyze. All supplied apks must be absolute paths or relative to --apkdir (which defaults to the current directory).
Flags: Flags:
- --help Prints this message and exits.+--help Prints this message and exits.
- --apkdir Directory to search for supplied apks (default to current directory).+--apkdir Directory to search for supplied apks (default to current directory).
- --verbose Increase the amount of debug statements.+--verbose Increase the amount of debug statements.
- --outfile Dump all output to the given file (defaults to stdout).+--outfile Dump output to the given file (defaults to stdout).
- --seinfo Create an seinfo tag for all generated policy stanzas.+--seinfo Create an seinfo tag for all generated policy stanzas. This is a required flag if using the --build option.
</pre> </pre>
-The following are examples of using <tt>setool</tt>, however, note that they will not produce a valid policy for third party apps. 
-Assuming in Android project directory (<tt>$PREFIX</tt>) and there is a "<tt>demo</tt>" directory present, run <tt>setool</tt> to extract the package info and generate white list entries from a package (any package will suffice for the example):+The following examples show the generation and verification process:
<pre> <pre>
-setool --seinfo demo --build whitelist demo/SEAndroidDemo.apk > demo/ mac_permissions.xml+setool --build package --seinfo service_app --outfile sepolicy/mac_permissions.xml RunIsolatedService.apk
</pre> </pre>
The output will be: The output will be:
<pre> <pre>
-<signer signature="- key will be here -">+<signer signature="- certificate will be here -">
- <package name="com.example.seandroiddemo">+ <package name="com.example.runisolatedservice">
- <allow-permission name="android.permission.READ_EXTERNAL_STORAGE" />+ <seinfo value="service_app" />
- <allow-permission name="android.permission.SEND_SMS" />+
- <allow-permission name="android.permission.WRITE_EXTERNAL_STORAGE" />+
- <allow-permission name="com.example.seandroiddemo.permission.DEADLY_ACTIVITY" />+
- <seinfo value="demo" />+
</package> </package>
</signer> </signer>
</pre> </pre>
-Now assuming a emulator build, add an entry to the <tt>BoardConfig.mk</tt> file <tt>build/target/board/generic/BoardConfig.mk</tt> as follows:+Note that for verification via <tt>setool</tt> requires the segment to be included within a correctly formatted <tt>mac_permissions.xml</tt> file (i.e. have the<tt><nowiki> <policy></nowiki></tt> <tt><nowiki></policy></nowiki></tt> tags present:
<pre> <pre>
-BOARD_SEPOLICY_DIRS := \+setool --policy sepolicy/mac_permissions.xml RunIsolatedService.apk
- demo+</pre>
-BOARD_SEPOLICY_UNION := \+The output will then be:
- mac_permissions.xml+<pre>
 +seinfo tag service_app assigned to ./RunIsolatedService.apk
</pre> </pre>
-Type <tt>make</tt> to rebuild policy changes and run <tt>setool</tt> to check the final concatenated <tt>mac_permissions.xml</tt> policy:+ 
 += selinux-network.sh Configuration =
 +This file may become obsolete, however to enable and configure it for loading <tt>'''iptables'''(8)</tt> with <tt>SECMARK</tt> information as part of the policy build, the following will need to be carried out.
 + 
 +Add an entry in the device make file:
<pre> <pre>
-setool --policy out/target/product/generic/system/etc/security/mac_permissions.xml demo/SEAndroidDemo.apk+PRODUCT_PACKAGES += selinux-network.sh
 +</pre>
-Policy passed for com.example.seandroiddemo (demo/SEAndroidDemo.apk).+Replace the default version in <tt>external/sepolicy</tt> by an entry in the <tt>BoardConfig.mk</tt> file (assumes there is a <tt>BOARD_SEPOLICY_DIRS</tt> entry):
 +<pre>
 +BOARD_SEPOLICY_REPLACE += selinux-network.sh
 +</pre>
 + 
 +Then either load via adb or add to the <tt>init.rc</tt> file:
 +<pre>
 +## Daemon process to be run by init.
 +##
 +...
 +# Load iptables configuration.
 +service netlabels /system/bin/selinux-network.sh
 + class core
 + oneshot
 +</pre>
 + 
 +During the build the file will be installed at <tt>/system/bin/selinux-network.sh</tt> and may be executed at system initialisation time or via <tt>adb</tt>.
 + 
 +Example <tt>selinux-network.sh</tt> entries:
 +<pre>
 +#!/system/bin/sh
 + 
 +############### IPTABLES FOR V4 </nowiki>Using security table #####################
 +IPTABLES="/system/bin/iptables"
 + 
 +# Common rules that copy connection labels to established and related packets:
 +$IPTABLES -t security -A INPUT -m state --state ESTABLISHED,RELATED -j CONNSECMARK --restore
 +$IPTABLES -t security -A OUTPUT -m state --state ESTABLISHED,RELATED -j CONNSECMARK --restore
 + 
 +# Create a chain for the NetLabelDemo app:
 +$IPTABLES -t security -N SELINUX_NET_APPS
 +# Add rules to mark the demo packets:
 +$IPTABLES -t security -A SELINUX_NET_APPS -j SECMARK --selctx u:object_r:net_apps_packet:s0
 +$IPTABLES -t security -A SELINUX_NET_APPS -j CONNSECMARK --save
 +$IPTABLES -t security -A SELINUX_NET_APPS -j ACCEPT
 +$IPTABLES -t security -A OUTPUT -p tcp --dport 9999 -j SELINUX_NET_APPS
 +$IPTABLES -t security -A INPUT -p tcp --sport 9999 -j SELINUX_NET_APPS
 +</pre>
 + 
 +Notes:
 + 
 +# Adding entries to this file will also require additional policy rules to be added for the device.
 +# Kernels supplied as part of AOSP or SEAndroid may not have the kernel build parameters to support all the SECMARK features. The following additional kernel parameters will enable these:
 + 
 + 
 +a) Enable iptables '<tt>security</tt>' table in kernel (although the <tt>mangle</tt> table may be used instead):
 +<pre>
 +CONFIG_IP_NF_SECURITY=y
 +CONFIG_IP6_NF_SECURITY=y
 +</pre>
 + 
 +b) Enable SECMARK/CONNSECMARK in kernel:
 +<pre>
 +CONFIG_NETWORK_SECMARK=y
 +CONFIG_NF_CONNTRACK_SECMARK=y
 +CONFIG_NETFILTER_XT_TARGET_CONNSECMARK=y
 +CONFIG_NETFILTER_XT_TARGET_SECMARK=y
</pre> </pre>
-= uid To username Utility =+= Appendix D - uid To username Utility =
This utility will take an Android <tt>uid</tt> and convert it to a <tt>username</tt>. The code is a modified version from <tt>bionic/libc/bionic/stubbs.cpp</tt> that converts an Android <tt>uid</tt> to <tt>username</tt>. This utility will take an Android <tt>uid</tt> and convert it to a <tt>username</tt>. The code is a modified version from <tt>bionic/libc/bionic/stubbs.cpp</tt> that converts an Android <tt>uid</tt> to <tt>username</tt>.
-To compile this assumes that the environment variable <tt>$PREFIX</tt> is set to the Android project directory. This is to allow the header file to be located:+To compile this utility:
<pre> <pre>
cc -std=gnu99 uid_to_username.c -o uid_to_username -include \ cc -std=gnu99 uid_to_username.c -o uid_to_username -include \
-$PREFIX/system/core/include/private/android_filesystem_config.h+$ANDROID_BUILD_TOP/system/core/include/private/android_filesystem_config.h
</pre> </pre>
<pre> <pre>
-#include <stdio.h>+#include <stdio.h></nowiki>
-#include <stdlib.h>+#include <stdlib.h></nowiki>
-#define CAT_MAPPING_MAX_ID (0x1<<16)+
int main(int argc, char **argv) int main(int argc, char **argv)
Line 911: Line 1,310:
exit(1); exit(1);
} }
 +
uid = atoi(argv[1]); uid = atoi(argv[1]);
uid_t appid = uid % AID_USER; uid_t appid = uid % AID_USER;
uid_t userid = uid / AID_USER; uid_t userid = uid / AID_USER;
- 
- if (appid >= CAT_MAPPING_MAX_ID || userid >= CAT_MAPPING_MAX_ID) { 
- printf("Failed as the maximum uid that can be mapped has been exceeded.\n"); 
- exit(0); 
- } 
- printf("appid: %u userid: %u\nusername: ", appid, userid); 
if (appid >= AID_ISOLATED_START) { if (appid >= AID_ISOLATED_START) {
- printf("u%u_i%u\n", userid, appid - AID_ISOLATED_START);+ printf("username: u%u_i%u\n", userid, appid - AID_ISOLATED_START);
} else if (userid == 0 && appid >= AID_SHARED_GID_START) { } else if (userid == 0 && appid >= AID_SHARED_GID_START) {
- printf("all_a%u\n", appid - AID_SHARED_GID_START);+ printf("username: all_a%u\n", appid - AID_SHARED_GID_START);
} else if (appid < AID_APP) { } else if (appid < AID_APP) {
for (size_t n = 0; n < android_id_count; n++) { for (size_t n = 0; n < android_id_count; n++) {
if (android_ids[n].aid == appid) { if (android_ids[n].aid == appid) {
- printf("u%u_%s\n", userid, android_ids[n].name);+ printf("username: u%u_%s\n", userid, android_ids[n].name);
- printf("Note that only the name \"%s\" is listed in 'ps' etc.\n", android_ids[n].name);+ printf("Note that only \"%s\" will be shown in 'ps' etc.\n", android_ids[n].name);
exit(0); exit(0);
} }
Line 935: Line 1,329:
printf("Failed - invalid uid\n"); printf("Failed - invalid uid\n");
} else { } else {
- printf("u%u_a%u\n", userid, appid - AID_APP);+ printf("username: u%u_a%u\n", userid, appid - AID_APP);
} }
exit(0); exit(0);

Current revision

Contents

[edit] Policy File Configuration Details

This section details the specific SE for Android policy configuration files (i.e. those not used by 'standard' Linux based SELinux). Where those files are used to compute contexts using the SE for Android libselinux functions, those functions are also described with examples.

[edit] SELinux MAC Configuration Files

[edit] seapp_contexts File

This file is loaded and sorted into memory automatically on first use of one of the following SE for Android libselinux functions that are called by the SE for Android enabled services:

selinux_android_setcontext - Computes process security contexts.
selinux_android_setfilecon - Computes file/directory security contexts.
selinux_android_seapp_context_reload will reload this file.

The build process supports additional seapp_contexts files to allow devices to specify their entries as described in the Processing Device Policy section.

The following sections will show:

  1. The default external/sepolicy/seapp_contexts file entries.
  2. A description of the seapp_contexts entries and their usage.
  3. A brief description of how a context is computed using either the selinux_android_setcontext or selinux_android_ setfilecon function using the seapp_contexts file entries.
  4. Examples of computed domain and directory contexts for various apps.


[edit] Default Entries

The default SEAndroid external/sepolicy/seapp_contexts file contains the following entries:

isSystemServer=true domain=system_server
user=system domain=system_app type=system_app_data_file
user=bluetooth domain=bluetooth type=bluetooth_data_file
user=nfc domain=nfc type=nfc_data_file
user=radio domain=radio type=radio_data_file
user=shared_relro domain=shared_relro
user=shell domain=shell type=shell_data_file
user=_isolated domain=isolated_app
user=_app seinfo=platform domain=platform_app type=app_data_file
user=_app domain=untrusted_app type=app_data_file


[edit] Entry Definitions

The following has been extracted from the default file with some additional comments that describe the parameters and how they are used to compute a context:

Input selectors from seapp_contexts file:

isSystemServer (boolean)
user (string)
seinfo (string)
name (string) - A package name e.g. com.example.demo
path (string) - A path name (added to ensure correct labeling of some files).
sebool (string) - The boolean must be ‘active’ (enabled/true)

Notes:

isSystemServer=true can only be used once.
An unspecified isSystemServer defaults to false.
An unspecified string selector will match any value.
A user string selector that ends in * will perform a prefix match.
user=_app will match any regular app UID.
user=_isolated will match any isolated service UID.
All specified input selectors in an entry must match (i.e. logical AND).
Matching is case-insensitive.

Precedence rules:

1) isSystemServer=true before isSystemServer=false.
2) Specified user= string before unspecified user= string.
3) Fixed user= string before user= prefix (i.e. ending in *).
4) Longer user= prefix before shorter user= prefix.
5) Specified seinfo= string before unspecified seinfo= string.
6) Specified name= string before unspecified name= string.
7) Specified path= string before unspecified path= string.
8) Specified sebool= string before unspecified sebool= string.

Outputs:

domain (string) - The type component of a process context.
type (string) - The type component of a file/directory context.
levelFrom (string; one of none, all, app, or user) - A level that will be automatically computed based on the parameter.
level (string) - A predefined level (e.g. s0:c1022.c1023)

Notes:

Only entries that specify domain= will be used for app process labeling.
Only entries that specify type= will be used for app directory labeling.
levelFrom=user is only supported for _app or _isolated UIDs.
levelFrom=app or levelFrom=all is only supported for _app UIDs.
level may be used to specify a fixed level for any UID.


[edit] Computing a Process Context

To compute an app process context the selinux_android_setcontext function is called that will use the parameters passed, plus the contents of the seapp_contexts file. The function parameters are:

#include <selinux/android.h>

int selinux_android_setcontext(uid_t uid, int isSystemServer, const char *seinfo, const char *pkgname);

The context is then computed using the information as follows:

The uid is converted to a string that is then used to match the user= entries in the seapp_contexts file as follows:
If an Android system service the uid is converted to a string via an internal Android table (e.g. "radio", "system").
If an isolated service (determined from the apps AndroidManifest.xml file) the _isolated string is used .
For any other app or service the _app is used.
The isSystemServer value must match that set in the running system and be true or false. It will be matched against the isSystemServer= entries in the seapp_contexts file.
seinfo may be NULL or that obtained from the mac_permissions.xml file. It will be matched against the seinfo= entries in the seapp_contexts file.
pkgname may be NULL or that obtained from the Android package. It will be matched against the name= entries in the seapp_contexts file.
The remaining seapp_contexts entries will be used as follows:
The sebool= parameter if present will be matched against the SELinux boolean name list. If present, the boolean must be active.
The levelFrom= and level= parameters if present will be used to determine the level component of the security context.
The domain= is used to set the process context and must match a context in the policy. Determines the type component of the security context.

If a context is computed, it is validated against policy and if correct setcon(3) will then set the process context.

Examples The following is an example taken as the system server is loaded:

selinux_android_setcontext() parameters:
    uid            1000
    isSystemServer true
    seinfo         null
    pkgname        null

seapp_contexts input selectors:
    isSystemServer true
    seinfo         null
    name           null
    path           null
    sebool         null

Matching seapp_contexts entry:
    isSystemServer=true domain=system_server

Outputs:
    domain system_server
    level  s0

Computed context = u:r:system_server:s0
    username computed from uid = system

Result using ps -Z command:
LABEL                USER   PID  PPID  NAME
u:r:system_server:s0 system 836  63    system_server

This is the ’radio’ application that is part of the platform:

selinux_android_setcontext() parameters:
    uid            1001
    isSystemServer false
    seinfo         platform
    pkgname        com.android.phone

seapp_contexts input selectors:
    isSystemServer false
    seinfo         platform
    name           com.android.phone
    path           null
    sebool         null

Matching seapp_contexts entry:
    user=radio domain=radio type=radio_data_file

Outputs:
    domain radio
    level  s0

Computed context = u:r:radio:s0
username computed from uid = radio

Result using ps -Z command:

LABEL        USER   PID PPID NAME
u:r:radio:s0 radio 1587 63   com.android.phone

This is the ’SEAndroid Admin Manager’ application that is part of the release, however it is treated as an untrusted app (even though it is installed as a privileged app):

selinux_android_setcontext() parameters:
    uid            10013
    isSystemServer false
    seinfo         default
    pkgname        com.android.seandroid_admin

seapp_contexts input selectors:
    uid            10013
    isSystemServer false
    seinfo         default
    name           com.android.seandroid_admin
    path           null
    sebool         null

Matching seapp_contexts entry:
    user=_app domain=untrusted_app type=app_data_file

Outputs:
    domain untrusted_app
    level  s0

Computed context = u:r:untrusted_app:s0
username computed from uid = u0_a13

Result using ps -Z command:
LABEL                USER   PID PPID NAME
u:r:untrusted_app:s0 u0_a13 827 45   com.android.seandroid_admin

This is a third party app that will run an isolated service that has been installed as a platform app:

selinux_android_setcontext() parameters:
    uid            10058
    isSystemServer false
    seinfo         default
    pkgname        com.example.runisolatedservice

seapp_contexts input selectors: 
    uid            10058
    isSystemServer false
    seinfo         default
    name           com.example.runisolatedservice
    path           null
    sebool         null

Matching seapp_contexts entry:
    user=_app domain=untrusted_app type=app_data_file

Outputs:
    domain untrusted_app
    level  s0

Computed context = u:r:untrusted_app:s0
username computed from uid = u0_a58

Result using ps -Z command:

LABEL                USER   PID  PPID NAME
u:r:untrusted_app:s0 u0_a58 1138 64   com.example.runisolatedservice

The isolated service will then run as follows:

selinux_android_setcontext() parameters:
    uid            99000
    isSystemServer false
    seinfo         platform
    pkgname        com.se4android.isolatedservice

seapp_contexts input selectors:
    uid            99000
    isSystemServer false
    seinfo         platform
    name           com.se4android.isolatedservice
    path           null
    sebool         null

Matching seapp_contexts entry:
    user=_isolated domain=isolated_app

Note that uid's 99000-99999 are reserved for isolated services - see:
    system/core/include/private/android_filesystem_config.h

Outputs:
    domain isolated_app
    level  s0

Computed context = u:r:isolated_app:s0
username computed from uid = u0_i0

Result using ps -Z command:
LABEL               USER  PID  PPID NAME
u:r:isolated_app:s0 u0_i0 1211 70   com.se4android.isolatedservice


[edit] Computing a Directory Context

To compute an app package directory context the selinux_android_setfilecon function is called that will use the parameters passed, plus the contents of the seapp_contexts file. The function parameters are:

#include <selinux/android.h>

int selinux_android_setfilecon(const char *pkgdir, const char *pkgname, const char *seinfo, uid_t uid);

The context is then computed using the information as follows:

pkgdir is the file or directory to be labeled with the computed context.
pkgname may be NULL or that obtained from the Android package. It will be matched against the name= entries in the seapp_contexts file.
seinfo may be NULL or that obtained from the mac_permissions.xml file. It will be matched against the seinfo= entries in the seapp_contexts file.
The uid is converted to a string that is then used to match the user= entries in the seapp_contexts file as follows:
If an Android system service, the uid is converted to a string via an internal Android table (e.g. "radio", "system").
If an isolated service the _isolated string is used.
For any other app or service the _app is used.
The remaining seapp_contexts entries will be used as follows:
The sebool= parameter if present will be matched against the SELinux boolean name list. If present, the boolean must be active.
The levelFrom= and level= parameters if present will be used to determine the level component of the security context.
The type= is used to set the file object context and must match a context in the policy. Determines the type component of the security context.

If a context is computed, it is validated against policy and if correct setfilecon(3) will then be used to label pkgdir with the computed context. The following example is from the third party isolated app:

selinux_android_setfilecon() parameters:
    pkgdir    /data/data/com.example.runisolatedservice
    pkgname   com.example.runisolatedservice
    seinfo    default
    uid       10046

seapp_contexts input selectors: 
    uid            10046
    isSystemServer false
    seinfo         default
    name           com.example.runisolatedservice
    path           null
    sebool         null

Matching seapp_contexts entry:
    user=_app domain=untrusted_app type=app_data_file

Outputs:
    type  app_data_file
    level s0

Computed context = u:object_r:app_data_file:s0
username computed from uid = u0_a46

Result from /data/data directory using ls -Z command:
drwxr-x--x u0_a46 u0_a46 u:object_r:app_data_file:s0 com.example.runisolatedservice


[edit] property_contexts File

This file holds property service keys and their contexts that are matched against property names using selabel_lookup(3). The returned context will then be used as the target context as described in the example below to determine whether the property is allowed or denied (see system/core/init/property_service.c and init.c).

The build process supports additional property_contexts files to allow devices to specify their entries as described in the Processing Device Policy section.

When selabel_open(3) is called specifying this file it will be read into memory and sorted using qsort(3), subsequent calls using selabel_lookup(3) will then retrieve the appropriate context based on matching the property_key.

Example:

Use adb to reload the SELinux policy:

adb shell su 0 setprop selinux.reload_policy 1

Sample property_contexts file entries are:

# property_key        context to be applied on match
net.rmnet             u:object_r:net_radio_prop:s0
net.gprs              u:object_r:net_radio_prop:s0
net.ppp               u:object_r:net_radio_prop:s0
net.qmi               u:object_r:net_radio_prop:s0
net.lte               u:object_r:net_radio_prop:s0
net.cdma              u:object_r:net_radio_prop:s0
net.dns               u:object_r:net_radio_prop:s0
sys.usb.config        u:object_r:system_radio_prop:s0
ril.                  u:object_r:radio_prop:s0
gsm.                  u:object_r:radio_prop:s0
persist.radio         u:object_r:radio_prop:s0

debug.                u:object_r:debug_prop:s0
debug.db.             u:object_r:debuggerd_prop:s0
log.                  u:object_r:shell_prop:s0
service.adb.root      u:object_r:shell_prop:s0
service.adb.tcp.port  u:object_r:shell_prop:s0

persist.audio.        u:object_r:audio_prop:s0
persist.logd.         u:object_r:logd_prop:s0
persist.sys.          u:object_r:system_prop:s0
persist.service.      u:object_r:system_prop:s0
persist.service.bdroid. u:object_r:bluetooth_prop:s0
persist.security.     u:object_r:system_prop:s0

# selinux non-persistent properties
selinux.              u:object_r:security_prop:s0

# default property context (* is wild card match)
*                     u:object_r:default_prop:s0

The property service will call selabel_lookup with parameters consisting of the handle passed from selabel_open, a buffer to hold the returned context, and the object name "selinux.reload_policy" to look-up (the final parameter is not used):

selabel_lookup(handle, &context, "selinux.reload_policy", 1);

The following context will be returned as the look-up process will search for a match based on the length of the property_key (and will therefore match against "selinux."):

u:object_r:security_prop:s0

The property service will then validate whether the service has permission by issuing an selinux_check_access(3) call with the following parameters:

source context: u:r:su:s0
target context: u:object_r:security_prop:s0
class:          property_service
permission:     set

The policy would then decide whether to allow or deny the property request. Using the sepolicy-check tool will show that this will be denied by the current policy (a dontaudit rule is in the policy, however su runs permissive anyway):

sepolicy-check -s su -t security_prop -c property_service \
-p set -P out/target/product/generic/root/sepolicy
echo $?
 1


[edit] service_contexts File

This file holds binder service keys and their contexts that are matched against binder object names using selabel_lookup(3). The returned context will then be used as the target context as described in the example below to determine whether the binder service is allowed or denied (see frameworks/native/cmds/servicemanager/servicemanager.c).

The build process supports additional service_contexts files to allow devices to specify their entries as described in the Building the Policy section.

When selabel_open(3) is called specifying this file it will be read into memory and sorted using qsort(3), subsequent calls using selabel_lookup(3) will then retrieve the appropriate context based on matching the service_key.

Example:

The healthd process wants to start a binder service "batterypropreg" (see frameworks/base/services/java/com/android/server/BatteryService.java).

Sample service_contexts file entries are:

# service_key          context to be applied on match
batteryproperties      u:object_r:healthd_service:s0
batterystats           u:object_r:system_server_service:s0
battery                u:object_r:system_server_service:s0
 
# default service context (* is wild card match)
*                      u:object_r:default_android_service:s0

The service manager will call selabel_lookup with parameters consisting of the handle passed from selabel_open, a buffer to hold the returned context, and the object name "batterypropreg" to look-up (the final parameter is not used):

selabel_lookup(handle, &context, "batterypropreg", 1);

The following context will be returned as the look-up process will search for a match based on the length of the service_key (and will therefore match against "battery"):

u:object_r:system_server_service:s0

The service manager will then validate whether the service has permission by issuing an selinux_check_access(3) call with the following parameters:

source context: u:r:healthd:s0
target context: u:object_r:system_server_service:s0
class:          service_manager
permission:     add

The policy would then decide whether to allow or deny the service. Using the sepolicy-check tool will show that this will be allowed by the current policy:

sepolicy-check -s healthd -t system_server_service \
-c service_manager -p add \
-P out/target/product/generic/root/sepolicy
Match found!


[edit] Install-time MMAC Configuration File

The mac_permissions.xml file is used to configure Install-time MMAC policy and provides x.509 certificate to seinfo string mapping so that Zygote spawns an app in the correct domain. See the Computing a Process Context section for how this is achieved using information also contained in the seapp_contexts file (AOSP and SEAndroid).

An example AOSP mac_permissions.xml file that shows the <default> entry is:

<?xml version="1.0" encoding="utf-8"?>

<policy>
    <!-- Platform dev key in AOSP -->

    <signer signature="@PLATFORM" >
        <seinfo value="platform" />
    </signer>

    <!-- All other keys -->
    <default>
        <seinfo value="default" />
    </default>

</policy>

The <signer signature= entry may have the public base16 signing key present in the string or it may have an entry starting with @, then a keyword as shown that allows the key to be extracted from a pem file as discussed in the insertkeys.py section. If a base16 key is required, it can be extracted from a package using the post_process_mac_perms and setool utilities.

The build process supports additional mac_permissions.xml files to allow devices to specify their entries as described in the Processing Device Policy section. An example SEAndroid test device mac_permissions.xml file is:

<?xml version="1.0" encoding="utf-8"?>

<policy>

    <!-- NET_APPS key and seinfo for SE4A-NetClient & SE4A-NetServer apps. -->
    <signer signature="@NET_APPS" >
        <package name="com.se4android.netclient" >
            <seinfo value="netclient" />
        </package>
        <package name="com.se4android.netserver" >
            <seinfo value="netserver" />
        </package>
    </signer>

</policy>


[edit] Policy Rules

The following rules have been extracted from the SEAndroid mac_permissions.xml file:

  • A signature is a hex encoded X.509 certificate or a tag defined in keys.conf and is required for each signer tag.
  • A signer tag may contain a seinfo tag and multiple package stanzas.
  • A default tag is allowed that can contain policy for all apps not signed with a previously listed cert. It may not contain any inner package stanzas.
  • Each signer/default/package tag is allowed to contain one seinfo tag. This tag represents additional info that each app can use in setting a SELinux security context on the eventual process.
  • When a package is installed the following logic is used to determine what seinfo value, if any, is assigned:
    • All signatures used to sign the app are checked first.
    • If a signer stanza has inner package stanzas, those stanza will be checked to try and match the package name of the app. If the package name matches then that seinfo tag is used. If no inner package matches then the outer seinfo tag is assigned.
    • The default tag is consulted last if needed.
    • If none of the cases apply then the app is denied install on the device.


[edit] EOps MMAC Configuration File

The following text has been taken from the SEAndroid /external/sepolicy/eops.xml file (so check if any changes) with a few minor additions (there is also a simple example in the EOps Example section section).

EOps (enterprise operations) is a security extension to the App Operations (AppOps) feature already present on Android 4.3+ devices. AppOps lets users fine tune certain functionality requested by apps by allowing the user to toggle these access rights.

EOps seeks to provide an extension whereby a harcoded set of rules explicitly denies certain access rights to groups of installed apps. This feature will allow an enterprise like control over certain operations. EOps is not a frontend for SELinux which somehow ties app permissions to SELinux contexts. Rather, it is an extension of the middleware MAC (MMAC) controls that currently exist on Android 4.3+ devices. EOps uses the seinfo labels that are already assigned to apps upon install.

The list of viable op tag names can be found in AppOpsManager.java. Just use the string version of each op without the OP_ prefix in your policy tags. These are the current entries (July '14):

ACCESS_NOTIFICATIONS AUDIO_ALARM_VOLUME AUDIO_BLUETOOTH_VOLUME
AUDIO_MASTER_VOLUME AUDIO_MEDIA_VOLUME AUDIO_NOTIFICATION_VOLUME
AUDIO_RING_VOLUME AUDIO_VOICE_VOLUME CALL_PHONE
CAMERA COARSE_LOCATION FINE_LOCATION
GPS MONITOR_HIGH_POWER_LOCATION MONITOR_LOCATION
NEIGHBORING_CELLS PLAY_AUDIO POST_NOTIFICATION
READ_CALENDAR READ_CALL_LOG READ_CLIPBOARD
READ_CONTACTS READ_ICC_SMS READ_SMS
RECEIVE_EMERGECY_SMS RECEIVE_MMS RECEIVE_SMS
RECEIVE_WAP_PUSH RECORD_AUDIO SEND_SMS
SYSTEM_ALERT_WINDOW TAKE_AUDIO_FOCUS TAKE_MEDIA_BUTTONS
VIBRATE WAKE_LOCK WIFI_SCAN
WRITE_CALENDAR WRITE_CALL_LOG WRITE_CLIPBOARD
WRITE_CONTACTS WRITE_ICC_SMS WRITE_SETTINGS
WRITE_SMS

All operations listed in the policy will have a mode of ignored. This means that empty data sets are returned to the caller when an operation is requested. This shadow data will then allow certain apps to presumably still operate. However, AOSP currently is not constructed to return these empty data sets and therefore acts as if ignored operations are completely denied (blocked). Because of this some apps might crash or behave oddly if you apply certain eops policy. In addition, while AOSP seems to have hooked the proper places to check operations against policy some of those hooks fail to follow through with the denial and still allow the operation to occur. Because of this, EOps will also fail to make those distinctions and likewise fail to enforce certain operations. Once the AOSP pieces are in place to return legitimate fake data and enforce all operations then of course eops, by its design, will also do the same.

So, as long as AppOps is beta so too will EOps.

A debug tag is also allowed which flips on the global debugging log functionality inside AppOps.

Each stanza is grouped according to the seinfo tag that is assigned during install and thus creates a dependency with the mac_permissions.xml file. Each seinfo tag can then include any number of op tags. By including the op(s) you are simply removing that operation from working for all apps that have been installed with the listed seinfo label. These operations are restricted regardless of what any user controlled app ops policy may say. Any op not listed is therefore still subject to user control as normal.

Lastly, there is no permissive mode for EOps. Once a policy is in place all ops listed are enforced.

The following is an example eops.xml policy file that will stop the camera being used by any system or default app. The file installation is shown in the Build Bundle Tools - buildeopbundle section:

<?xml version="1.0"?>
<app-ops>

    <debug/>

    <seinfo name="default">
        <op name="CAMERA"/>
    </seinfo>

    <seinfo name="system">
        <op name="CAMERA"/>
    </seinfo></nowiki>

</app-ops>


[edit] Intent Firewall MMAC Configuration File

The example external/sepolicy/ifw.xml file has some comments regarding the tags, there is also an overview at http://www.cis.syr.edu/~wedu/android/IntentFirewall/.

The following is an example ifw.xml policy file that will stop the DemoIsolatedService being used by any app other than system apps or apps with the same signature. The file installation is shown in the Build Bundle Tools - buildifwbundle section:

<?xml version="1.0"?>

<rules>

    <!-- This will stop any app that is not a system app or
         does not have a matching signature from running the
         DemoIsolatedService service
    -->

    <service log="true" block="true"></nowiki>
        <not><sender type="system|signature"/></not><
        <intent-filter />
            <component-filter name="com.se4android.isolatedservice/.DemoIsolatedService"/>
    </service>

</rules>

The events will be in the event log under the 'ifw_intent_matched' tag, for example:

adb logcat -b events
...
...
I/ifw_intent_matched( 390):[2,com.se4android.isolatedservice/.DemoIsolatedService,10058,1,NULL,NULL,NULL,NULL,0]
...


[edit] Policy Build Tools

This section covers the policy build tools located at external/sepolicy/tools. They are checkfc, checkseapp and insertkeys.py. There is also setool that is not used as part of the build process but generates mac_permissions.xml entries from packages.

[edit] checkfc

The checkfc utility is used during the build process to validate the file_contexts, property_contexts and service_contexts files against policy. If validation fails checkfc will exit with an error.

Usage:

usage: checkfc [OPTIONS] sepolicy context_file
Parses a context file and checks for syntax errors.
The context_file is assumed to be a file_contexts file
unless explicitly switched by an option.

    OPTIONS:
        -p : context file represents a property_context file.

Example validating file_contexts file (note: no -p parameter):

checkfc out/target/product/generic/root/sepolicy out/target/product/generic/root/file_contexts

Example validating property_contexts file:

checkfc -p out/target/product/generic/root/sepolicy out/target/product/generic/root/property_contexts


[edit] checkseapp

The checkseapp utility is used during the build process to validate the seapp_contexts file against policy. If validation fails checkseapp will exit with an error. checkseapp also consolidates matching entries and outputs the valid file stripped of comments.

Usage:

checkseapp [options] <input file><
Processes an seapp_contexts file specified by argument <input file> (default stdin) and allows later declarations to override previous ones on a match.

Options:
    -h - print this help message
    -s - enable strict checking of duplicates. This causes the program to exit on a duplicate entry with a non-zero exit status
    -v - enable verbose debugging informations
    -p policy file - specify policy file for strict checking of output selectors against the policy
    -o output file - specify output file, default is stdout

An example command with output to stdout is:

checkseapp -p out/target/product/se4a_device/root/sepolicy out/target/product/se4a_device/root/seapp_contexts

isSystemServer=true domain=system_server
user=system domain=system_app type=system_data_file
user=bluetooth domain=bluetooth type=bluetooth_data_file
user=nfc domain=nfc type=nfc_data_file
user=radio domain=radio type=radio_data_file
user=shared_relo domain=shared_relo
user=shell domain=shell type=shell_data_file
user=_isolated domain=isolated_app
user=_app seinfo=platform domain=platform_app type=app_data_file
user=_app domain=untrusted_app type=app_data_file
user=_app seinfo=netclient domain=netclient_app type=net_apps_log_file levelFrom=app
user=_app seinfo=netserver domain=netserver_app type=net_apps_log_file levelFrom=app


[edit] insertkeys.py

The insertkeys.py utility is used during the build process to insert signing keys into the mac_permissions.xml file. The keys are obtained from pem files and the entries to be replaced start with an @ followed by a keyword. The external/sepolicy/keys.conf file contains corresponding entries that allow mapping of pem files to signatures as discussed in the keys.conf section.

insertkeys.py generates base16 encodings from the base64 pem files as this is required by the Android Package Manager Service. The resulting mac_permissions.xml file will also be stripped of comments and whitespace.

Usage:

Usage: insertkeys.py [options] CONFIG_FILE MAC_PERMISSIONS_FILE [MAC_PERMISSIONS_FILE...]</nowiki>


This tool allows one to configure an automatic inclusion of signing keys into the mac_permission.xml file(s) from the pem files. If multiple mac_permission.xml files are included then they are unioned to produce a final version.

Options:
    --version                           show program's version number and exit
    -h, --help                          show this help message and exit
    -v, --verbose                       Print internal operations to stdout
    -o FILE, --output=FILE              Specify an output file, default is stdout
    -c DIR, --cwd=DIR                   Specify a root (CWD) directory to run this from, itchdirs' AFTER loading the config file
    -t TARGET_BUILD_VARIANT, --target-build-variant=TARGET_BUILD_VARIANT 
                                        Specify the TARGET_BUILD_VARIANT, defaults to eng
    -d KEY_DIRECTORY, --key-directory   Specify a parent directory for keys


[edit] keys.conf File

The keys.conf file is used by insertkeys.py for mapping the "@..." tags in mac_permissions.xml, mmac_types.xml and content_provider.xml signature entries with public keys found in pem files. The configuration file can be used in BOARD_SEPOLICY_UNION and BOARD_SEPOLICY_REPLACE variables and is processed via m4 macros.

insertkeys.py allows for mapping any string contained in TARGET_BUILD_VARIANT with a specific path to a pem file. Typically TARGET_BUILD_VARIANT is either user, eng or userdebug. Additionally "ALL" may be specified to map a path to any string specified in TARGET_BUILD_VARIANT. All tags are matched verbatim and all options are matched lowercase. The options are "tolowered" automatically for the user, it is convention to specify tags and options in all uppercase and tags start with @.

An example keys.conf file is as follows:

#
# Maps an arbitrary tag [TAGNAME] with the string contents found in
# TARGET_BUILD_VARIANT. Common convention is to start TAGNAME with an @ and
# name it after the base file name of the pem file.
#
# Each tag (section) then allows one to specify any string found in
# TARGET_BUILD_VARIANT. Typcially this is user, eng, and userdebug. Another
# option is to use ALL which will match ANY TARGET_BUILD_VARIANT string.
#
[@PLATFORM]
ALL : $DEFAULT_SYSTEM_DEV_CERTIFICATE/platform.x509.pem

[@MEDIA]
ALL : $DEFAULT_SYSTEM_DEV_CERTIFICATE/media.x509.pem

[@SHARED]
ALL : $DEFAULT_SYSTEM_DEV_CERTIFICATE/shared.x509.pem

# Example of ALL TARGET_BUILD_VARIANTS
[@RELEASE]
ENG : $DEFAULT_SYSTEM_DEV_CERTIFICATE/testkey.x509.pem
USER : $DEFAULT_SYSTEM_DEV_CERTIFICATE/testkey.x509.pem
USERDEBUG : $DEFAULT_SYSTEM_DEV_CERTIFICATE/testkey.x509.pem

The following is an example entry that will use a device specific key during the build process:

[@NET_APPS]
ALL : $ANDROID_BUILD_TOP/device/demo_vendor/se4a_device/security/net_apps.x509.pem


[edit] Build Bundle Tools

The following tools will produce an Android "bundle" for updating MAC/MMAC policy within a zip file suitable for installation by the SEAdmin app. SEAdmin is currently hard-coded to look for these zip files in the SD Card device (/sdcard/).

The buildsebundle section also shows how a policy can be updated by broadcasting an intent instead of using SEAdmin.


[edit] buildsebundle

The buildsebundle tool will produce an Android "bundle" for updating the core SE for Android policy within an selinux_bundle.zip file, suitable for installation by the SEAdmin app, although it is possible to update using an intent as described in the Using an Intent Example section.

To be able to build the bundle the following mandatory files are required:

selinux_version, sepolicy, file_contexts, seapp_contexts, property_contexts, service_contexts, mac_permissions.xml

Usage:

usage: buildsebundle -k <private key.pk8> [-v <version>] [-r <previous hash>] \
[-h] -- <selinux_version> <file_contexts> <property_contexts> \
<sepolicy> <seapp_contexts> <service_contexts> <mac_permissions.xml>

This script builds a selinux policy bundle and supporting metadata file capable of being loaded via the ConfigUpdate mechanism. It takes a pkcs8 DER encoded RSA private key that is then used to sign the bundle. For AOSP development you'll typically want to use the key from the source tree at:
    build/target/product/security/testkey.pk8
The built bundle will be written to selinux_bundle.zip which will include the signature metadata file of the bundle.

OPTIONS:
    -h Show this message.
    -v Version of the built bundle. Defaults to 1.
    -r SHA-512 hash of the bundle to replace. Defaults to 'NONE'.

The following is an example where a new policy has been built with all required files. The wildcard can be used as buildsebundle will always use the mandatory list:

buildsebundle -k $ANDROID_BUILD_TOP/build/target/product/security/testkey.pk8 -v 3 -- $ANDROID_BUILD_TOP/device/demo_device/se4a_device/new_sepolicy/*

adb push selinux_bundle.zip /sdcard/

Once built, the bundle is pushed to the SD card and SEAdmin is used to update the policy (note that SEAdmin only reads the bundle from /sdcard).


[edit] Using an Intent Example

This example shows how to update a policy by broadcasting an intent in the same way as SEAdmin.

Extract the selinux_bundle files from the selinux_bundle.zip file:

unzip selinux_bundle.zip
Archive: selinux_bundle.zip
    inflating: update_bundle 
    inflating: update_bundle_metadata

The two files contain:

update_bundle - Contains hex encoded policy files to be installed.

update_bundle_metadata - This is used by SEAdmin to form the intent and contains a hash of the bundle to replace or "NONE", the signature of the update_bundle and the bundle version (in this case "3"). Example contents are:

NONE:I6E0cZ8WbF6kJWkDozJCfckw5xuZhXuE0iqrbszsxhi7S4Z3DrR7RiH/aomRQxeskvMv9B/+G7JXfxFAQlV1CWZihnefkHGnei4atKnBLPK/g3gmf0Wb0jjizc4yb4uvu/XQAZvybKcsTvTiegfqTHMFWPGKgoq97RKAjk2kT2fa3liArylTrLl7OfRtKq6mNjQNnfVrte9e/aJptiAmOwDNdQydfRwhewrKPE6rM+YNuHJaJ+h28dNecQtCn9TabTxn8I1G+10d5/wmjjgXq6MdfEMQZ++H4ZIaL4bTdUOQVdFeMsnFLA3hjLGf3BXpHmG84s7iDO158V0kbXikzA==:3

Push the update_bundle to the device:

adb push update_bundle /data/update_bundle

Build an intent to broadcast via adb by including the bundle location, with the hash, signature and version from the update_bundle_metadata as follows:

adb shell am broadcast -a android.intent.action.UPDATE_SEPOLICY -e "CONTENT_PATH" "/data/update_bundle" -e "REQUIRED_HASH" "NONE" -e "SIGNATURE" "I6E0cZ8WbF6kJWkDozJCfckw5xuZhXuE0iqrbszsxhi7S4Z3DrR7RiH/aomRQxeskvMv9B/+G7JXfxFAQlV1CWZihnefkHGnei4atKnBLPK/g3gmf0Wb0jjizc4yb4uvu/XQAZvybKcsTvTiegfqTHMFWPGKgoq97RKAjk2kT2fa3liArylTrLl7OfRtKq6mNjQNnfVrte9e/aJptiAmOwDNdQydfRwhewrKPE6rM+YNuHJaJ+h28dNecQtCn9TabTxn8I1G+10d5/wmjjgXq6MdfEMQZ++H4ZIaL4bTdUOQVdFeMsnFLA3hjLGf3BXpHmG84s7iDO158V0kbXikzA==" -e "VERSION" "3"

When the intent has been broadcast there will be a response, however that does not indicate that the policy was updated, just that the intent was broadcast:

Broadcasting: Intent { act=android.intent.action.UPDATE_SEPOLICY (has extras) }
Broadcast completed: result=0

logcat should show whether it was successful:

I/ConfigUpdateInstallReceiver( 908): Found new update, installing...
I/ConfigUpdateInstallReceiver( 908): Installation successful
I/SELinuxPolicyInstallReceiver( 908): Applying SELinux policy

If the update failed because of versioning then an error is given (however if signature incorrect fails silently).

The following show various policy information after the third update:

adb shell ls -l /data/security/current
lrwxrwxrwx system system 2014-07-19 10:41 current -> /data/security/contexts
adb shell ls -l /data/security/contexts
-rw-r--r-- system system 10512 2014-07-19 10:41 file_contexts
-rw-r--r-- system system 10656 2014-07-19 09:01 file_contexts_backup
-rw-r--r-- system system 4203 2014-07-19 10:41 mac_permissions.xml
-rw-r--r-- system system 4203 2014-07-19 09:01 mac_permissions.xml_backup
-rw-r--r-- system system 2549 2014-07-19 10:41 property_contexts
-rw-r--r-- system system 2549 2014-07-19 09:01 property_contexts_backup
-rw-r--r-- system system 641 2014-07-19 10:41 seapp_contexts
-rw-r--r-- system system 641 2014-07-19 09:01 seapp_contexts_backup
-rw-r--r-- system system 78 2014-07-19 10:41 selinux_version
-rw-r--r-- system system 78 2014-07-19 09:01 selinux_version_backup
-rw-r--r-- system system 115831 2014-07-19 10:41 sepolicy
-rw-r--r-- system system 116438 2014-07-19 09:01 sepolicy_backup
-rw-r--r-- system system 7748 2014-07-19 10:41 service_contexts
-rw-r--r-- system system 7748 2014-07-19 09:01 service_contexts_backup
adb shell ls -l /data/security
drwx------ system system 2014-07-19 10:41 bundle
drwx------ system system 2014-07-19 10:41 contexts
lrwxrwxrwx system system 2014-07-19 10:41 current ->/data/security/contexts
drwx------ system system 2014-07-19 10:37 eops
adb shell ls -l /data/security/bundle
drwx------ system system 2014-07-19 10:41 metadata
-rw-r--r-- system system 191271 2014-07-19 10:41 sepolicy_bundle
adb shell ls -l /data/security/bundle/metadata
-rw-r--r-- system system 1 2014-07-19 10:41 version
adb shell cat /data/security/bundle/metadata/version
3

The loaded policy can be extracted from the device if required by:

adb pull /sys/fs/selinux/policy sepolicy-v3


[edit] buildeopbundle

The buildeopbundle tool will produce an Android "bundle" for updating the Enterprise Operations policy within an eops_bundle.zip file suitable for installation by the SEAdmin app, although it is possible to update using an intent as described in the Using an Intent Example section.

To be able to build the bundle an eops.xml file is required.

Usage:

usage: buildeopbundle -k <private key.pk8> [-v <version>] [-r <previous hash>] \
[-h] -- <eops.xml>

This script builds a eops policy bundle and supporting metadata file capable of being loaded via the ConfigUpdate mechanism. It takes a pkcs8 DER encoded RSA private key that is then used to sign the bundle. For AOSP development you'll typically want to use the key from the source tree at:
    build/target/product/security/testkey.pk8

If building your own cert you should probably use a key size of at least 1024 or greater. The bundle requires that the eops.xml file be included and with that exact basename. The built bundle will be written to eop_bundle.zip which will include the signature metadata file of the bundle.

OPTIONS:
    -h Show this message.
    -v Version of the built bundle. Defaults to 1.
    -r SHA-512 hash of the bundle to replace. Defaults to 'NONE'.


[edit] Eops Example

The following is an example where a new eops.xml file has been produced, bundled, then pushed to the SD card. SEAdmin is then used to update the policy (note that SEAdmin only reads the bundle from /sdcard):

buildeopbundle -k $ANDROID_BUILD_TOP/build/target/product/security/testkey.pk8 -v 1 -- eops.xml

adb push eops_bundle.zip /sdcard/

logcat should show if it was successful:

D/SEAdminConfigUpdateFragment( 904): android.intent.action.UPDATE_EOPS intent being broadcast. Bundle[{CONTENT_PATH=/cache/eops_bundle, SIGNATURE=qZJ8I07MHFTXaII2jhPMooRLzejArUI0qsvkteG9nzEzgzjwyh8RWUaaRil6xrQsPb5g+qWj+nfQCkH7DIEow/WF8S1sTeReS8G/z+hPQi0MHgWGKH0kCIfXn6yqqEri3+Dnolb1vHVuM7t/0mszCvtjqfq5GWbHZc1xYSgMQJXqrhfzSqa2zvO4+7zE0GszfuZXwt9QHci9C1IJ5B50URmmg4TDIuhfISWW9vYkEctwARIyCLhfYiZzIQOwzPj3oSHI1AUWMHxbbpADFzCumZ1WdfpA0txow8rDM+01qkKGtcAsNs8me2FAPz28tckQ9ea6QwAzDCSP3PzQC1Horg==, REQUIRED_HASH=NONE, VERSION=1}]
I/ConfigUpdateInstallReceiver( 395): Couldn't find current metadata, assuming first update
I/ConfigUpdateInstallReceiver( 395): Failed to read current content, assuming first update!
I/ConfigUpdateInstallReceiver( 395): Found new update, installing...
I/ConfigUpdateInstallReceiver( 395): Installation successful
D/AppOps ( 381): Eops policy: system [ CAMERA]
D/AppOps ( 381): Eops policy: default [ CAMERA]

The new file and its supporting metadata are:

adb shell su 0 ls -lR /data/security/eops

/data/security/eops:
-rw-r--r-- system system 189 2014-07-20 14:15 eops.xml
drwx------ system system 2014-07-20 14:15 eops_metadata

/data/security/eops/eops_metadata:
-rw-r--r-- system system 1 2014-07-20 14:15 version

The version number after the update is:

adb shell su 0 cat /data/security/eops/eops_metadata/version
1

Because the Eops policy specified an seinfo of system and the operation CAMERA, if the Camera app is now started it will load however, it will not be possible to take pictures as logcat will show:

D/AppOps ( 381): startOperation: reject #1 for code 26 (26) uid 10026 package com.android.camera2
I/CameraService( 60): Camera 0: Access for "com.android.camera2" has been revoked

[edit] buildifwbundle

The buildifwbundle tool will produce an Android "bundle" for updating the Intent Firewall policy within an ifw_bundle.zip file suitable for installation by the SEAdmin app, although it is possible to update using an intent as described in the Using an Intent Example section.

To be able to build the bundle an ifw.xml file is required, although note that the Intent Firewall service will read any file so long as it has the .xml extension.

Usage:

usage: buildifwbundle -k <private key.pk8> [-v <version>] [-r <previous hash>] \
[-h] -- <ifw.xml>

This script builds an intent firewall policy bundle and supporting metadata file capable of being loaded via the ConfigUpdate mechanism. It takes a pkcs8 DER encoded RSA private key that is then used to sign the bundle. For AOSP development you'll typically want to use the key from the source tree at:

build/target/product/security/testkey.pk8

If building your own cert you should probably use a key size of at least 1024 or greater. The bundle requires that the ifw.xml file be included and with that exact basename. The built bundle will be written to ifw_bundle.zip which will include the signature metadata file of the bundle.

OPTIONS:
    -h Show this message.
    -v Version of the built bundle. Defaults to 1.
    -r SHA-512 hash of the bundle to replace. Defaults to 'NONE'.


[edit] IFW Example

The following is an example where a new ifw.xml file has been produced, bundled, and then pushed to the SD card. SEAdmin is then used to update the policy (note that SEAdmin only reads the bundle from /sdcard):

buildsifwbundle -k $ANDROID_BUILD_TOP/build/target/product/security/testkey.pk8 -v 1 -- eops.xml

adb push ifw_bundle.zip /sdcard/

logcat should show whether it was successful:

D/SEAdminConfigUpdateFragment( 904): android.intent.action.UPDATE_INTENT_FIREWALL intent being broadcast. Bundle[{CONTENT_PATH=/cache/ifw_bundle, SIGNATURE=tfQONpEZbL1Y6sXj1BY98TO4izK2IyeqO9Hko5tZygE77zry98RGmU5BAAIFs21G9G7WpAcPTR7TGe4LRMpB7SKeZ1Xh+4B+U+30TnHkwXp9HRIgIJcN5Kqiyp/UPAjEJjYmBZk+yM5FLYcMCQS082wfpC9c+gRQcl6AYuSmiynvjgc1d33rtfB7Hd40LF30mBZyyiUJc5YF1ddaITBbL/CCKmFblfBqadZtmCN7xGUIJEHqWPnuEvscatkOLgZa+35ZXfl2WkD/DsGkwocXM9akjD0NJY9WZJpzwAHQPdQFXN6nthrsV8kiC7OUFvK/PKll9oetiyTSEEVH5JlMnA==, REQUIRED_HASH=NONE, VERSION=1}]
I/ConfigUpdateInstallReceiver( 395): Couldn't find current metadata, assuming first update
I/ConfigUpdateInstallReceiver( 395): Failed to read current content, assuming first update!
I/ConfigUpdateInstallReceiver( 395): Found new update, installing...
I/ConfigUpdateInstallReceiver( 395): Installation successful
I/IntentFirewall( 395): Read new rules (A:0 B:0 S:1)

The new file and its supporting metadata are:

adb shell su 0 ls -lR /data/system/ifw

/data/system/ifw:
-rw-r--r-- system system 454 2014-07-20 13:14 ifw.xml
drwx------ system system 2014-07-20 13:14 metadata

/data/system/ifw/metadata:
-rw-r--r-- system system 1 2014-07-20 13:14 gservices.version

The version number after the update is:

adb shell su 0 cat /data/system/ifw/metadata/gservices.version
1

[edit] post_process_mac_perms

This tool will modify an existing mac_permissions.xml with additional app certs not already found in that policy. This becomes useful when a directory containing apps is searched and the certs from those apps are added to the policy not already explicitly listed.

There is no make target for this tool (python script), so either move to HOST_EXECUTABLE or execute directly (e.g. $PREFIX/external/sepolicy/tools/post_process_mac_perms).

Usage:

post_process_mac_perms [-h] -s SEINFO -d DIR -f POLICY

    -s SEINFO, --seinfo SEINFO seinfo tag for each generated stanza
    -d DIR, --dir DIR Directory to search for apks
    -f POLICY, --file POLICY mac_permissions.xml policy file

Example:

post_process_mac_perms -s netapps -d ./APK -f mac_permissions.xml

Before:

<?xml version="1.0" encoding="utf-8"?>
<policy>
    <signer signature="- certificate here -" ><seinfo value="platform"/></signer>
    <default><seinfo value="default"/></default>
</policy>

After:

<?xml version="1.0" encoding="utf-8"?>
<policy>
    <signer signature="- certificate here -" ><seinfo value="platform"/></signer>
    <default><seinfo value="default"/></default>
    <signer signature="- certificate here -"><seinfo value="netapps"/></signer>
</policy>


[edit] sepolicy_check

A tool for auditing a sepolicy file for any allow rule that grants a given permission.

Usage:

sepolicy-check -s <domain> -t <type> -c <class> -p <permission>
-P out/target/product/<board>/root/sepolicy

The output will be "Match found!" or silent if not. sepolicy_check will return 0 for found, 1 for not found and -1 for an error.

Examples:

sepolicy-check -s healthd -t system_server_service -c service_manager -p add -P  out/target/product/generic/root/sepolicy
Match found!
sepolicy-check -s su -t security_prop -c property_service -p set -P out/target/product/generic/root/sepolicy
echo $?
1


[edit] sepolicy-analyze

This is the text from the external/sepolicy/tools/README that describes the tool for performing various kinds of analysis on a sepolicy file. The analysis that are currently supported include:

[edit] Type Equivalence

sepolicy-analyze -e -P out/target/product/<board>/root/sepolicy

Display all type pairs that are "equivalent", i.e. they are identical with respect to allow rules, including indirect allow rules via attributes and default-enabled conditional rules (i.e. default boolean values yield a true conditional expression).

Equivalent types are candidates for being coalesced into a single type. However, there may be legitimate reasons for them to remain separate, for example: - the types may differ in a respect not included in the current analysis, such as default-disabled conditional rules, audit-related rules (auditallow or dontaudit), default type transitions, or constraints (e.g. mls), or - the current policy may be overly permissive with respect to one or the other of the types and thus the correct action may be to tighten access to one or the other rather than coalescing them together, or - the domains that would in fact have different accesses to the types may not yet be defined or may be unconfined in the policy you are analyzing.

Example output:

sepolicy-analyze -e -P out/target/product/se4a_device/root/sepolicy

Types adbd_socket and mdns_socket are equivalent.
Types rild_debug_socket and init_tmpfs are equivalent.
Types rild_debug_socket and qemud_tmpfs are equivalent.
Types surfaceflinger_service and mediaserver_service are equivalent.
Types surfaceflinger_service and inputflinger_service are equivalent.

[edit] Type Difference

sepolicy-analyze -d -P out/target/product/<board>/root/sepolicy

Display type pairs that differ and the first difference found between the two types. This may be used in looking for similar types that are not equivalent but may be candidates for coalescing.

Example output:

sepolicy-analyze -d -P out/target/product/se4a_device/root/sepolicy

Types adbd_socket and functionfs differ, starting with:
allow adbd_socket rootfs:filesystem { associate };
allow functionfs self:filesystem { associate };

Types adbd_socket and hci_attach_exec differ, starting with:
allow system_server adbd_socket:sock_file { ioctl read write getattr lock append open };
allow debuggerd hci_attach_exec:file { ioctl read getattr lock open };

Types adbd_socket and system_server differ, starting with:
allow adbd_socket rootfs:filesystem { associate };
allow system_server rootfs:filesystem { getattr };


[edit] Duplicate Allow Rules

sepolicy-analyze -D -P out/target/product/<board>/root/sepolicy

Displays duplicate allow rules, i.e. pairs of allow rules that grant the same permissions where one allow rule is written directly in terms of individual types and the other is written in terms of attributes associated with those same types. The rule with individual types is a candidate for removal. The rule with individual types may be directly represented in the source policy or may be a result of expansion of a type negation (e.g. domain -foo -bar is expanded to individual allow rules by the policy compiler). Domains with unconfineddomain will typically have such duplicate rules as a natural side effect and can be ignored.

Example output:

sepolicy-analyze -D -P out/target/product/se4a_device/root/sepolicy

Duplicate allow rule found:
allow init hci_attach_exec:file { read getattr execute open };
allow unconfineddomain exec_type:file { ioctl read getattr lock execute open };

Duplicate allow rule found:
allow ueventd device:dir { write add_name remove_name };
allow ueventd dev_type:dir { ioctl read write create getattr setattr unlink link rename add_name remove_name reparent search rmdir open };


[edit] setool

The setool utility is not used during the build process and is intended only to produce entries for the mac_permissions.xml file and verify a correctly formated file. It is not supplied in AOSP.

Usage:

Usage: setool [flags] <--build keys|package OR --policy policyFile> <apk> [ <apk> ]*

Tool to help build and verify MMAC install policies.

--build       Generate an MMAC style policy stanza with a given --seinfo string.
              The resulting stanza can then be used as an entry in the mac_permissions.xml file.

    package   Policy entry that contains the package name inside the signature stanza.

    keys      Print just a signer tag which contains the hex encoded X.509 certs of the app.

--policy      Determine if the apks pass the supplied policy by printing the seinfo tag that would be assigned or null otherwise.

    apk       An apk to analyze. All supplied apks must be absolute paths or relative to --apkdir (which defaults to the current directory).

Flags:
--help Prints this message and exits.
--apkdir Directory to search for supplied apks (default to current directory).
--verbose Increase the amount of debug statements.
--outfile Dump output to the given file (defaults to stdout).
--seinfo Create an seinfo tag for all generated policy stanzas. This is a required flag if using the --build option.


The following examples show the generation and verification process:

setool --build package --seinfo service_app --outfile sepolicy/mac_permissions.xml RunIsolatedService.apk

The output will be:

<signer signature="- certificate will be here -">
    <package name="com.example.runisolatedservice">
        <seinfo value="service_app" />
    </package>
</signer>

Note that for verification via setool requires the segment to be included within a correctly formatted mac_permissions.xml file (i.e. have the <policy> </policy> tags present:

setool --policy sepolicy/mac_permissions.xml RunIsolatedService.apk

The output will then be:

seinfo tag service_app assigned to ./RunIsolatedService.apk


[edit] selinux-network.sh Configuration

This file may become obsolete, however to enable and configure it for loading iptables(8) with SECMARK information as part of the policy build, the following will need to be carried out.

Add an entry in the device make file:

PRODUCT_PACKAGES += selinux-network.sh

Replace the default version in external/sepolicy by an entry in the BoardConfig.mk file (assumes there is a BOARD_SEPOLICY_DIRS entry):

BOARD_SEPOLICY_REPLACE += selinux-network.sh

Then either load via adb or add to the init.rc file:

## Daemon process to be run by init.
##
...
# Load iptables configuration.
service netlabels /system/bin/selinux-network.sh
     class core
      oneshot

During the build the file will be installed at /system/bin/selinux-network.sh and may be executed at system initialisation time or via adb.

Example selinux-network.sh entries:

#!/system/bin/sh

############### IPTABLES FOR V4 </nowiki>Using security table #####################
IPTABLES="/system/bin/iptables"

# Common rules that copy connection labels to established and related packets:
$IPTABLES -t security -A INPUT  -m state --state ESTABLISHED,RELATED -j CONNSECMARK --restore
$IPTABLES -t security -A OUTPUT -m state --state ESTABLISHED,RELATED -j CONNSECMARK --restore

# Create a chain for the NetLabelDemo app:
$IPTABLES -t security -N SELINUX_NET_APPS
# Add rules to mark the demo packets:
$IPTABLES -t security -A SELINUX_NET_APPS -j SECMARK --selctx u:object_r:net_apps_packet:s0
$IPTABLES -t security -A SELINUX_NET_APPS -j CONNSECMARK --save
$IPTABLES -t security -A SELINUX_NET_APPS -j ACCEPT
$IPTABLES -t security -A OUTPUT -p tcp --dport 9999 -j SELINUX_NET_APPS
$IPTABLES -t security -A INPUT  -p tcp --sport 9999 -j SELINUX_NET_APPS

Notes:

  1. Adding entries to this file will also require additional policy rules to be added for the device.
  2. Kernels supplied as part of AOSP or SEAndroid may not have the kernel build parameters to support all the SECMARK features. The following additional kernel parameters will enable these:


a) Enable iptables 'security' table in kernel (although the mangle table may be used instead):

CONFIG_IP_NF_SECURITY=y
CONFIG_IP6_NF_SECURITY=y

b) Enable SECMARK/CONNSECMARK in kernel:

CONFIG_NETWORK_SECMARK=y
CONFIG_NF_CONNTRACK_SECMARK=y
CONFIG_NETFILTER_XT_TARGET_CONNSECMARK=y
CONFIG_NETFILTER_XT_TARGET_SECMARK=y

[edit] Appendix D - uid To username Utility

This utility will take an Android uid and convert it to a username. The code is a modified version from bionic/libc/bionic/stubbs.cpp that converts an Android uid to username.

To compile this utility:

cc -std=gnu99 uid_to_username.c -o uid_to_username -include \
$ANDROID_BUILD_TOP/system/core/include/private/android_filesystem_config.h
#include <stdio.h></nowiki>
#include <stdlib.h></nowiki>

int main(int argc, char **argv)
{
    uid_t uid;

    if (argc != 2) {
        printf("Converts an Android uid to username\n");
        printf("usage: %s uid\n\n", argv[0]);
        exit(1);
    }

    uid = atoi(argv[1]);
    uid_t appid = uid % AID_USER;
    uid_t userid = uid / AID_USER;

    if (appid >= AID_ISOLATED_START) {
        printf("username: u%u_i%u\n", userid, appid - AID_ISOLATED_START);
    } else if (userid == 0 && appid >= AID_SHARED_GID_START) {
        printf("username: all_a%u\n", appid - AID_SHARED_GID_START);
    } else if (appid < AID_APP) {
        for (size_t n = 0; n < android_id_count; n++) {
            if (android_ids[n].aid == appid) {
                printf("username: u%u_%s\n", userid, android_ids[n].name);
                printf("Note that only \"%s\" will be shown in 'ps' etc.\n", android_ids[n].name);
                exit(0);
            }
        }
        printf("Failed - invalid uid\n");
    } else {
        printf("username: u%u_a%u\n", userid, appid - AID_APP);
    }
    exit(0);
}



    Personal tools