Difference between revisions of "NB SEforAndroid 2"

From SELinux Wiki
Jump to: navigation, search
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). Where those files are used to compute contexts using the SE for Android <tt>libselinux</tt> functions, those functions are also described with examples.
 
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 Configuration Files ==
 
== SELinux MAC Configuration 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.
+
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>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.
 
  
 
==== 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
  
Each line within the property contexts file is as follows:
+
# default property context (* is wild card match)
 +
*                    u:object_r:default_prop:s0
 +
</pre>
 +
 
 +
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>).
 +
 
 +
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.
 +
 
 +
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>.  
 +
 
 +
'''Example:'''
 +
 
 +
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>
 +
# 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 property context
+
# default service context (* is wild card match)
*                      u:object_r:default_prop:s0
+
*                      u:object_r:default_android_service:s0
 +
</pre>
  
# data partition encryption properties
+
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):
vold.                  u:object_r:vold_prop:s0
+
<pre>
crypto.                u:object_r:vold_prop:s0
+
selabel_lookup(handle, &context, "batterypropreg", 1);
 +
</pre>
  
# ctl properties
+
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>"):
ctl.dumpstate          u:object_r:ctl_dumpstate_prop:s0
+
<pre>
ctl.ril-daemon          u:object_r:ctl_rildaemon_prop:s0
+
u:object_r:system_server_service:s0
ctl. u:object_r:ctl_default_prop:s0
+
 
</pre>
 
</pre>
  
 +
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>
  
== Install MMAC Configuration File ==
+
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 <tt>mac_permissions.xml</tt> file is used to configure Install MMAC policy and provides two main functions:
+
<pre>
# 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 (AOSP and SEAndroid).
+
sepolicy-check -s healthd -t system_server_service \
# Install MMAC permission checking (SEAndroid only).
+
-c service_manager -p add \
 +
-P out/target/product/generic/root/sepolicy
 +
Match found!
 +
</pre>
  
It is important to note that all third party apps will be subject to the <tt><nowiki><default></nowiki></tt> install MMAC 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).
 
  
An example AOSP <tt>mac_permissions.xml</tt> file that also shows the <tt><nowiki><default></nowiki></tt> entry is:
+
== 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" >
 
         <seinfo value="platform" />
 
         <seinfo value="platform" />
    </signer>
 
 
    <!-- Media dev key in AOSP -->
 
    <signer signature="@MEDIA" >
 
        <seinfo value="media" />
 
    </signer>
 
 
    <!-- shared dev key in AOSP -->
 
    <signer signature="@SHARED" >
 
        <seinfo value="shared" />
 
    </signer>
 
 
    <!-- release dev key in AOSP -->
 
    <signer signature="@RELEASE" >
 
        <seinfo value="release" />
 
 
     </signer>
 
     </signer>
  
Line 414: Line 458:
 
         <seinfo value="default" />
 
         <seinfo value="default" />
 
     </default>
 
     </default>
 +
 
</policy>
 
</policy>
 
</pre>
 
</pre>
  
An example SEAndroid <tt><nowiki><default></nowiki></tt> package policy is:
+
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.
 +
 
 +
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:
 
<pre>
 
<pre>
<!-- All other keys -->
+
<?xml version="1.0" encoding="utf-8"?>
<default>
+
    <seinfo value="default" /></nowiki>
+
    <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>>
+
</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.
+
<policy>
  
==== Signature Entries ====
+
     <!-- NET_APPS key and seinfo for SE4A-NetClient & SE4A-NetServer apps. -->
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 (e.g <tt>@PLATFORM</tt>) that will signify that the key is to be extracted from a pem file as discussed in the <tt>[[#insertkeys.py | insertkeys.py]]</tt> section:
+
     <signer signature="@NET_APPS" >
<pre>
+
         <package name="com.se4android.netclient" >
     <!-- Platform dev key in AOSP -->
+
            <seinfo value="netclient" />
     <signer signature="@PLATFORM" >
+
         </package>
         <allow-all />
+
        <package name="com.se4android.netserver" >
         <seinfo value="platform" />
+
            <seinfo value="netserver" />
 +
        </package>
 
     </signer>
 
     </signer>
 +
 +
</policy>
 
</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 <tt>[[#setool | setool]]</tt> section.
 
  
 
==== Policy Rules ====
 
==== Policy Rules ====
 
The following rules have been extracted from the SEAndroid <tt>mac_permissions.xml</tt> file:
 
The following rules have been extracted from the SEAndroid <tt>mac_permissions.xml</tt> file:
  
* A signature is a hex encoded X.509 certificate and is required for each signer tag.
+
* 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.
* A <tt><nowiki><signer signature="" ></nowiki></tt> element may have multiple child elements:
+
* A <tt>signer</tt> tag may contain a <tt>seinfo</tt> tag and multiple package stanzas.
** <tt>allow-permission</tt> : produces a set of maximal allowed permissions (whitelist).
+
* 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.
** <tt>deny-permission</tt> : produces a blacklist of permissions to deny.
+
* 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.
** <tt>allow-all</tt> : a wildcard tag that will allow every permission requested.
+
* When a package is installed the following logic is used to determine what <tt>seinfo</tt> value, if any, is assigned:
** <tt>package</tt> : a complex tag which itself defines allow, deny, and wildcard sub elements for a specific package name protected by the signature.
+
** All signatures used to sign the app are checked first.
* 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.
+
** 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.
* 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.
 
** 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 install on the device.
** If none of the cases apply then the app is denied.
+
  
An edited form of an SEAndroid <tt>mac_permissions.xml</tt> file is as follows:
 
<pre>
 
<?xml version="1.0" encoding="utf-8"?>
 
<policy>
 
    <!-- Platform dev key in AOSP -->
 
    <signer signature="@PLATFORM" >
 
        <allow-all />
 
        <seinfo value="platform" />
 
    </signer>
 
  
    <!-- Media dev key in AOSP -->
+
== EOps MMAC Configuration File ==
    <signer signature="@MEDIA" >
+
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-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 -->
+
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.
    <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 -->
+
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.
    <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>
+
  
    <!-- All other keys -->
+
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):
    <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>
+
</policy>
+
</pre>
+
  
 +
<tt>
 +
{| border="1"
 +
|  ACCESS_NOTIFICATIONS
 +
|  AUDIO_ALARM_VOLUME
 +
|  AUDIO_BLUETOOTH_VOLUME
  
== Intent MMAC Configuration Files ==
+
|-
There are two configuration files to support Intent MMAC, they are:
+
|  AUDIO_MASTER_VOLUME
:: <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 name</nowiki></tt> entries defined in the <tt>mmac_types.xml</tt> file (see [[Using Type or Package Names | Using Type or Package Names]] below on implementing these). There is also an optional <tt><nowiki><allow-all></nowiki></tt> section.
+
| AUDIO_MEDIA_VOLUME
:: <tt>mmac_types.xml</tt> - Contains <tt><nowiki><type name</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.
+
|  AUDIO_NOTIFICATION_VOLUME
  
=== intent_mac.xml File ===
+
|-
The file supports two optional types of entry:
+
|  AUDIO_RING_VOLUME
# <tt><nowiki><intent></nowiki></tt> filters that specify actions (intents) allowed between their source and destination, additional optional entries may also be added that refine the intent. The source and destination entries may be defined in the <tt>[[#mmac_types.xml File|mmac_types.xml]]</tt> file.
+
| AUDIO_VOICE_VOLUME
# <tt><nowiki><allow-all></nowiki></tt> that will allow all intents from the source to destination entries.
+
|  CALL_PHONE
  
 +
|-
 +
|  CAMERA
 +
|  COARSE_LOCATION
 +
|  FINE_LOCATION
  
All <tt>intent_mac.xml</tt> file entries are between <tt><nowiki><policy></nowiki></tt> tags:
+
|-
<pre>
+
|  GPS
<?xml version="1.0" encoding="utf-8"?>
+
|  MONITOR_HIGH_POWER_LOCATION
<policy>
+
|  MONITOR_LOCATION
    ......
+
</policy>
+
</pre>
+
  
The build process supports additional device specific <tt>intent_mac.xml</tt> files as described in the [[NB_SEforAndrooid_1#Building the Policy|Building the Policy]] section.
+
|-
 +
|  NEIGHBORING_CELLS
 +
|  PLAY_AUDIO
 +
|  POST_NOTIFICATION
  
==== Intent Filter Entry ====
+
|-
Each intent entry is as follows:
+
|  READ_CALENDAR
 +
|  READ_CALL_LOG
 +
|  READ_CLIPBOARD
  
* <tt><nowiki><intent></nowiki></tt> start tag.
+
|-
** <tt><nowiki><filter></nowiki></tt> start tag. The entries that follow would generally be obtained from the appropriate package manifest that describe the intent and its parameters.
+
|  READ_CONTACTS
*** An <tt><nowiki><action name="" /></nowiki></tt> entry defining the intent action name.
+
|  READ_ICC_SMS
*** Zero or more <tt><nowiki><category name="" /></nowiki></tt> entries defining the intent category name.
+
| READ_SMS
*** Zero or more <tt><nowiki><data scheme="" /></nowiki></tt> entries defining the intent scheme data specification.
+
*** Zero or more <tt><nowiki><data mimeType="" /></nowiki></tt> entries defining the intent mime type data specification.
+
** <tt><nowiki></filter></nowiki></tt> end tag.
+
** One or more <tt><nowiki><allow</nowiki></tt> entries that consist of the following:
+
*** An optional rule <tt>name=</tt> entry that will be displayed in debug logs.
+
*** Optional <tt>src=</tt> and <tt>dst=</tt> references for the allowed intents. These entries are generally <tt><nowiki><type name=""</nowiki></tt> entries defined in the <tt>mmac_types.xml</tt> file, however they may also be package names, see the [[Using Type or Package Names | Using Type or Package Names]] section for further details. Note: It is recommended that both <tt>src=</tt> and <tt>dst=</tt> entries are specified. Not specifying either of them or the <tt>dst=</tt> will allow the intent to 'anywhere'. The only exception should be when source context matching is used.
+
*** An optional <tt>srcctx=</tt> entry that will be matched against the source app process context.
+
** <tt>/></tt> The <tt>allow</tt> end tag.
+
* <tt><nowiki></intent></nowiki></tt> end tag.
+
  
Example entries are:
+
|-
 +
|  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
 +
|
 +
|
 +
 
 +
|}
 +
</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"?>
<policy>
+
<app-ops>
    <intent>
+
        <filter>
+
            <action name="android.intent.action.CALL_PRIVILEGED"/>
+
            <data scheme="tel"/>
+
            <data scheme="voicemail"/>
+
        </filter>
+
        <allow src="contacts_app" dst="telephony_app"/>
+
    </intent>
+
  
     <intent>
+
     <debug/>
        <filter>
+
 
            <action name="android.intent.action.VIEW"/>
+
    <seinfo name="default">
            <data mimeType="vnd.android.cursor.dir/calls" />
+
        <op name="CAMERA"/>
        </filter>
+
    </seinfo>
        <allow src="telephony_app" dst="contacts_app"/>
+
 
     </intent>
+
    <seinfo name="system">
</policy>
+
        <op name="CAMERA"/>
 +
     </seinfo></nowiki>
 +
 
 +
</app-ops>
 
</pre>
 
</pre>
  
==== allow-all Entry ====
 
An <tt><nowiki><allow-all></nowiki></tt> entry consists of:
 
  
* <tt><nowiki><allow-all></nowiki></tt> start tag.
 
** Zero of more <tt><nowiki><allow</nowiki></tt> entries that consist of the following:
 
*** An optional rule <tt>name=</tt> entry that will be displayed in debug logs.
 
*** Optional <tt>src</tt> and <tt>dst</tt> references of the allowed intents. These entries are generally package names to allow all intents to flow between them, however they may be <tt><nowiki><type name=""</nowiki></tt> entries defined in the <tt>mmac_types.xml</tt> file, see the [[Using Type or Package Names | Using Type or Package Names]] section for further details.
 
*** An optional <tt>srcctx</tt> entry that will be matched against the source app process context.
 
** <tt>/></tt> The <tt>allow</tt> end tag.
 
* <tt><nowiki></allow-all></nowiki></tt> end tag.
 
  
An example <tt><nowiki><allow-all></nowiki></tt> entry:
+
== 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>
<allow-all>
+
<?xml version="1.0"?>
    <allow name="phone_to_sms" src="com.android.phone" dst="com.android.smspush"/>
+
    <allow name="shell" srcctx="u:r:shell:s0"/>
+
    <allow name="su" srcctx="u:r:su:s0"/>
+
</allow-all>
+
</pre>
+
  
===Using Type or Package Names===
+
<rules>
The above <tt><nowiki><allow name=</nowiki></tt> example <tt>src=</tt> and <tt>dst=</tt> entries shown are the actual package names. These entries may be implemented in the following ways:
+
 
 +
    <!-- 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>
 +
</pre>
  
1) Generate a new type entry for each package name in the <tt>mmac_types.xml</tt> file, for example:
+
The events will be in the event log under the '<tt>ifw_intent_matched</tt>' tag, for example:
 
<pre>
 
<pre>
    <type name="com.android.phone"/>
+
adb logcat -b events
    <type name="com.android.smspush"/>
+
...
 +
...
 +
I/ifw_intent_matched( 390):[2,com.se4android.isolatedservice/.DemoIsolatedService,10058,1,NULL,NULL,NULL,NULL,0]
 +
...
 
</pre>
 
</pre>
  
: This would satisfy the <tt><nowiki><allow name="phone_to_sms"</nowiki></tt> example entry given above.
 
  
2) Use existing type entries that already define the package name, for example the default <tt>mmac_types.xml</tt> file has the following entries:
+
= Policy Build Tools =
 +
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 ==
 +
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.
 +
 
 +
Usage:
 
<pre>
 
<pre>
    <type name="wappush_app">
+
usage: checkfc [OPTIONS] sepolicy context_file
        <signature value="@RELEASE"/>
+
Parses a context file and checks for syntax errors.
        <package value="com.android.smspush"/>
+
The context_file is assumed to be a file_contexts file
    </type>
+
unless explicitly switched by an option.
+
    <type name="telephony_app">
+
        <signature value="@PLATFORM"/>
+
        <package value="com.android.phone"/>
+
    </type>
+
</pre>
+
  
: The example <tt><nowiki><allow</nowiki></tt> entry would then be defined as:  
+
    OPTIONS:
 +
        -p : context file represents a property_context file.
 +
</pre>
 +
Example validating <tt>file_contexts</tt> file (note: no <tt>-p</tt> parameter):
 
<pre>
 
<pre>
    <allow name="phone_to_sms" src="telephony_app" dst="wappush_app"/>
+
checkfc out/target/product/generic/root/sepolicy out/target/product/generic/root/file_contexts
 
</pre>
 
</pre>
  
3) Set the <tt>persist.mac_applyNameTypes</tt> permission to <tt>true</tt>, as this enables package names to be automatically be added as <tt><nowiki><type name=</nowiki></tt> entries as the policy is loaded.
+
Example validating <tt>property_contexts</tt> file:
 
<pre>
 
<pre>
adb shell su 0 setprop persist.mac_applyNameTypes 1
+
checkfc -p out/target/product/generic/root/sepolicy out/target/product/generic/root/property_contexts
 
</pre>
 
</pre>
  
  
=== mmac_types.xml File ===
+
== checkseapp ==
The <tt>mmac_types.xml</tt> file contains the <tt><nowiki><type></nowiki></tt> entries that provide the source / destination references for the package and/or permissions rules used by the <tt>intent_mac.xml</tt> file. All entries are between <tt><nowiki><policy></nowiki></tt> tags:
+
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.
 +
 
 +
Usage:
 
<pre>
 
<pre>
<?xml version="1.0" encoding="utf-8"?>
+
checkseapp [options] <input file><
<policy>
+
Processes an seapp_contexts file specified by argument <input file> (default stdin) and allows later declarations to override previous ones on a match.
      ......
+
 
</policy>
+
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
 
</pre>
 
</pre>
  
The build process supports additional device specific <tt>mmac_types.xml</tt> files as described in the [[NB_SEforAndroid_1#Building the Policy|Building the Policy]] section.
+
An example command with output to <tt>stdout</tt> is:
 +
<pre>
 +
checkseapp -p out/target/product/se4a_device/root/sepolicy out/target/product/se4a_device/root/seapp_contexts
  
Each <tt>mmac_types.xml</tt> file entry is as follows:
+
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
 +
</pre>
  
* <tt><nowiki><type name="" ></nowiki></tt> entry that defines the name that will be referenced by the <tt>intent_mac.xml</tt> file <tt>src=""</tt> and <tt>dst=""</tt> entries.
 
** Zero or more <tt>package value=""</tt> entries containing package names.
 
** Zero or more <tt><nowiki><signature value="" /></nowiki></tt> entries. These may be the key as extracted by <tt>setool</tt> (but it will need to be copied here from the <tt>[[#setool|setool]]</tt> output), or the <tt>"@.."</tt> format as shown in the example below, the signature will then be automatically generated as part of the build process by <tt>[[#insertkeys.py|insertkeys.py]}</tt> as described in [[NB_SEforAndroid_1#Building the Policy| Building the Policy]] section. It is recommended that a signature is always present.
 
** Zero or more <tt>permission value="" /></tt> entries containing the allowed package permissions.
 
* <tt><nowiki></type></nowiki></tt> end tag.
 
  
Example entries are:
+
== insertkeys.py ==
 +
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.
 +
 
 +
<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.
 +
 
 +
Usage:
 
<pre>
 
<pre>
<?xml version="1.0" encoding="utf-8"?>
+
Usage: insertkeys.py [options] CONFIG_FILE MAC_PERMISSIONS_FILE [MAC_PERMISSIONS_FILE...]</nowiki>
<policy>
+
    <type name="telephony_app">
+
        <signature value="@PLATFORM"/>
+
        <package value="com.android.phone"/>
+
    </type>
+
  
    <type name="video_perm">
+
 
        <permission value="android.permission.CAMERA"/>
+
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.
        <permission value="android.permission.RECORD_AUDIO"/>
+
 
     </type>
+
Options:
</policy>
+
     --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
 
</pre>
 
</pre>
  
  
== Content Provider MMAC Configuration File ==
+
=== keys.conf File ===
The <tt>content_provider.xml</tt> file supports the following types of entry:
+
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.
  
# Package <tt><nowiki><type></nowiki></tt> entries that describe source package parameters.
+
<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>.
# Content <tt><nowiki><type></nowiki></tt> entries that describe target content provider parameters.
+
# <tt><nowiki><attribute></nowiki></tt> entries that assign a common name to multiple <tt><nowiki><type></nowiki></tt> entries.
+
# <tt><nowiki><allow-content></nowiki></tt> entries that define the source, target and permissions to allow access to content.
+
  
All entries are between <tt><nowiki><policy></nowiki></tt> tags:
+
An example <tt>keys.conf</tt> file is as follows:
 
<pre>
 
<pre>
<?xml version="1.0" encoding="utf-8"?>
+
#
<policy>
+
# Maps an arbitrary tag [TAGNAME] with the string contents found in
    ......
+
# TARGET_BUILD_VARIANT. Common convention is to start TAGNAME with an @ and
</policy>
+
# 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
 
</pre>
 
</pre>
  
The build process supports additional device specific <tt>content_provider.xml</tt> files as described in the [[NB_SEforAndroid_1#Building the Policy| Building the Policy]] section.
+
The following is an example entry that will use a device specific key during the build process:
 +
<pre>
 +
[@NET_APPS]
 +
ALL : $ANDROID_BUILD_TOP/device/demo_vendor/se4a_device/security/net_apps.x509.pem
 +
</pre>
  
=== Package <type> Entries ===
 
Each <tt>content_provider.xml</tt> file package type entry is as follows:
 
  
* <tt><nowiki><type name="" component="package" ></nowiki></tt> entry. The <tt>name</tt> entry defines the name that will be referenced by the attribute <tt><nowiki><type></nowiki></tt> and/or <tt><nowiki><allow></nowiki></tt> source entry. The <tt>component</tt> entry specifies this as a package entry (other entries may be supported later).
+
== Build Bundle Tools ==
** Zero or more <tt><nowiki><package value="" /></nowiki></tt> entries defining the package name.
+
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>).
** Zero or more <tt><nowiki><signature value="" /></nowiki></tt> entries. These may be the key as extracted by <tt>setool</tt> (but it will need to be copied here from the <tt>[[#setool|setool]]</tt> output), or the <tt>"@.."</tt> format as shown in the example below, the signature will then be automatically generated as part of the build process by <tt>[[#insertkeys.py|insertkeys.py]]</tt> as described in [[NB_SEforAndroid_1#Building the Policy| Building the Policy]] section.
+
** Zero or more <tt><nowiki><permission value="" /></nowiki></tt> entries defining the permissions.
+
* <tt><nowiki></type></nowiki></tt> end tag.
+
  
When computing access to content the following precedence rules apply to package type entries:
+
The [[#Using an Intent Example|buildsebundle]] section also shows how a policy can be updated by broadcasting an intent instead of using SEAdmin.
  
# Signature defined over signature not defined.
 
# Package name defined over package name not defined.
 
# Permission set defined over permission set not defined.
 
  
There is no distinction between a stanza that has more signatures than another. They are considered of equal precedence.
+
=== 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.
  
Example entries are:
+
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>
 
<pre>
<?xml version="1.0" encoding="utf-8"?>
+
usage: buildsebundle -k <private key.pk8> [-v <version>] [-r <previous hash>] \
<policy>
+
[-h] -- <selinux_version> <file_contexts> <property_contexts> \
    <type name="platform" component="package">
+
<sepolicy> <seapp_contexts> <service_contexts> <mac_permissions.xml>
        <signature value="@PLATFORM"/>
+
    </type>
+
  
    <type name="shared" component="package">
+
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:
        <signature value="@SHARED"/>
+
     build/target/product/security/testkey.pk8
     </type>
+
The built bundle will be written to selinux_bundle.zip which will include the signature metadata file of the bundle.
  
     <type name="release" component="package">
+
OPTIONS:
        <signature value="@RELEASE"/>
+
     -h Show this message.
     </type>
+
    -v Version of the built bundle. Defaults to 1.
 +
     -r SHA-512 hash of the bundle to replace. Defaults to 'NONE'.
 +
</pre>
  
    <type name="media" component="package">
+
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:
        signature value="@MEDIA"/>
+
<pre>
    </type>
+
buildsebundle -k $ANDROID_BUILD_TOP/build/target/product/security/testkey.pk8 -v 3 -- $ANDROID_BUILD_TOP/device/demo_device/se4a_device/new_sepolicy/*
  
    <type name="defualt_package" component="package">
+
adb push selinux_bundle.zip /sdcard/
    </type>
+
 
+
    <type name="demo_resolver_package" component="package">
+
        <package value="com.example.resolvecontent" />
+
        <permission value="com.se4android.contentprovider.READ" />
+
        <permission value="com.se4android.contentprovider.WRITE" />
+
    </type>
+
</policy>
+
 
</pre>
 
</pre>
  
=== Provider <type> Entries ===
+
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>).
Each <tt>content_provider.xml</tt> file provider type entry is as follows:
+
  
* <tt><nowiki><type name="" ></nowiki></tt> entry. The <tt>name</tt> entry defines the name that will be referenced by the attribute <tt><nowiki><type></nowiki></tt> and/or <tt><nowiki><allow></nowiki></tt> destination entries.
 
** Zero or more <tt><nowiki><provider value="" /></nowiki></tt> entries defining the provider authority.
 
** Zero or more <tt><nowiki><package value="" /></nowiki></tt> entries defining the package name.
 
** Zero or more <tt><nowiki><signature value="" /></nowiki></tt> entries. These may be the key as extracted by <tt>setool</tt> (but it will need to be copied here from the <tt>[[#setool|setool]]</tt> output), or the <tt>"@.."</tt> format as shown in the example below, the signature will then be automatically generated as part of the build process by <tt>[[#insertkeys.py|insertkeys.py]]</tt> as described in [[NB_SEforAndroid_1#Building the Policy| Building the Policy]] section. It is recommended that a signature is always present.
 
** Zero or more <tt><nowiki><export-read value="" /></nowiki></tt> entries defining the read protection level (<tt>protectionLevel=</tt> in manifest). These are defined as <tt>normal</tt>, <tt>dangerous</tt>, <tt>signature</tt> or <tt>signatureOrSystem</tt>).
 
** Zero or more <tt><nowiki><export-write value="" /></nowiki></tt> entries defining the write protection level (as <tt>export-read</tt> above).
 
* <tt><nowiki></type></nowiki></tt> end tag.
 
  
When computing access to content the following precedence rules apply to content type entries:
+
==== Using an Intent Example ====
 +
This example shows how to update a policy by broadcasting an intent in the same way as SEAdmin.
  
# Signature defined over signature not defined.
+
Extract the <tt>selinux_bundle</tt> files from the <tt>selinux_bundle.zip</tt> file:
# Provider defined over provider not defined.
+
<pre>
# Package name defined over package name not defined.
+
unzip selinux_bundle.zip
 +
Archive: selinux_bundle.zip
 +
    inflating: update_bundle
 +
    inflating: update_bundle_metadata
 +
</pre>
  
There is no distinction between a stanza that has more signatures than another. They are considered of equal precedence.
+
The two files contain:
  
Example entries are:
+
<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>
 
<pre>
<?xml version="1.0" encoding="utf-8"?>
+
NONE:I6E0cZ8WbF6kJWkDozJCfckw5xuZhXuE0iqrbszsxhi7S4Z3DrR7RiH/aomRQxeskvMv9B/+G7JXfxFAQlV1CWZihnefkHGnei4atKnBLPK/g3gmf0Wb0jjizc4yb4uvu/XQAZvybKcsTvTiegfqTHMFWPGKgoq97RKAjk2kT2fa3liArylTrLl7OfRtKq6mNjQNnfVrte9e/aJptiAmOwDNdQydfRwhewrKPE6rM+YNuHJaJ+h28dNecQtCn9TabTxn8I1G+10d5/wmjjgXq6MdfEMQZ++H4ZIaL4bTdUOQVdFeMsnFLA3hjLGf3BXpHmG84s7iDO158V0kbXikzA==:3
<policy>
+
</pre>
    <type name="browser_exported_provider">
+
        <signature value="@RELEASE"/>
+
        <provider value="com.android.browser"/>
+
        <provider value="browser"/>
+
    </type>
+
  
    <type name="browser_protected_provider">
+
Push the <tt>update_bundle</tt> to the device:
        <signature value="@RELEASE"/>
+
<pre>
        <provider value="com.android.browser.home"/>
+
adb push update_bundle /data/update_bundle
        <provider value="com.android.browser.snapshots"/>
+
</pre>
    </type>
+
  
    <type name="platform_default_provider">
+
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:
        <signature value="@PLATFORM"/>
+
<pre>
    </type>
+
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>
  
    <type name="shared_default_provider">
+
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:
        <signature value="@SHARED"/>
+
<pre>
    </type>
+
Broadcasting: Intent { act=android.intent.action.UPDATE_SEPOLICY (has extras) }
 +
Broadcast completed: result=0
 +
</pre>
  
    <type name="media_default_provider">
+
<tt>logcat</tt> should show whether it was successful:
        <signature value="@MEDIA"/>
+
<pre>
    </type>
+
I/ConfigUpdateInstallReceiver( 908): Found new update, installing...
 +
I/ConfigUpdateInstallReceiver( 908): Installation successful
 +
I/SELinuxPolicyInstallReceiver( 908): Applying SELinux policy
 +
</pre>
  
    <type name="release_default_provider">
+
If the update failed because of versioning then an error is given (however if signature incorrect fails silently).
        <signature value="@RELEASE"/>
+
    </type>
+
  
    <type name="default_provider">
+
The following show various policy information after the third update:
    </type>
+
<pre>
 +
adb shell ls -l /data/security/current
 +
lrwxrwxrwx system system 2014-07-19 10:41 current -> /data/security/contexts
 +
</pre>
  
    <type name="demo_provider">
+
<pre>
        <package value="com.se4android.contentprovider" />
+
adb shell ls -l /data/security/contexts
        <signature value="@RELEASE"/>
+
-rw-r--r-- system system 10512 2014-07-19 10:41 file_contexts
        <provider value="com.se4android.contentprovider.contentproviderdemo"/>
+
-rw-r--r-- system system 10656 2014-07-19 09:01 file_contexts_backup
        <export-read value="normal" />
+
-rw-r--r-- system system 4203 2014-07-19 10:41 mac_permissions.xml
        <export-write value="dangerous" />
+
-rw-r--r-- system system 4203 2014-07-19 09:01 mac_permissions.xml_backup
    </type>
+
-rw-r--r-- system system 2549 2014-07-19 10:41 property_contexts
<policy>
+
-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>
  
=== Attribute Entries ===
+
<pre>
The <tt>content_provider.xml</tt> file attribute entries consist of:
+
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>
  
* <tt><nowiki><attributes></nowiki></tt> start tag.
+
<pre>
** Zero or more <tt><nowiki><attribute name="" ></nowiki></tt> entries. The <tt>name=</tt> entry defines the group name used to reference all the <tt><nowiki><type></nowiki></tt> entries. The <tt>name=</tt> may then be used in <tt><nowiki><allow></nowiki></tt> <tt>source=</tt> (for groups of package types) or <tt>destination=</tt> (for groups of content types) entries.
+
adb shell ls -l /data/security/bundle
*** Zero or more <tt><nowiki><type name="" /></nowiki></tt> entries. The <tt>name=</tt> entry refers to a package or content type entry.
+
drwx------ system system 2014-07-19 10:41 metadata
** <tt><nowiki></attribute></nowiki></tt> end tag.
+
-rw-r--r-- system system 191271 2014-07-19 10:41 sepolicy_bundle
* <tt><nowiki></attributes></nowiki></tt> end tag.
+
</pre>
  
Example <tt><nowiki><attributes></nowiki></tt> entry:
 
 
<pre>
 
<pre>
<?xml version="1.0" encoding="utf-8"?>
+
adb shell ls -l /data/security/bundle/metadata
<policy>
+
-rw-r--r-- system system 1 2014-07-19 10:41 version
    <attributes>
+
</pre>
        <attribute name="all">
+
            <type name="platform"/>
+
            <type name="release"/>
+
            <type name="shared"/>
+
            <type name="gapps"/>
+
            <type name="media"/>
+
            <type name="vpn"/>
+
            <type name="default"/>
+
            </attribute>
+
  
        <attribute name="trusted_apps">
+
<pre>
            <type name="platform"/>
+
adb shell cat /data/security/bundle/metadata/version
            <type name="release"/>
+
3
            <type name="shared"/>
+
</pre>
            <type name="gapps"/>
+
            <type name="media"/>
+
        </attribute>
+
  
        <attribute name="all_media_provider">
+
The loaded policy can be extracted from the device if required by:
            <type name="media_provider"/>
+
<pre>
            <type name="drm_provider"/>
+
adb pull /sys/fs/selinux/policy sepolicy-v3
        </attribute>
+
    </attributes>
+
</policy>
+
 
</pre>
 
</pre>
  
=== allow-content Entry ===
 
The <tt>content_provider.xml</tt> file allow content entries consist of:
 
  
* <tt><nowiki><allow-content></nowiki></tt> start tag.
+
=== buildeopbundle ===
** Zero of more <tt><nowiki><allow</nowiki></tt> entries that consist of the following:
+
The <tt>buildeopbundle</tt> tool will produce an Android "bundle" for updating the Enterprise Operations 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.
*** A <tt>source=""</tt> reference to a package type entry.
+
*** A <tt>destination=""</tt> reference to a content type entry.
+
*** A <tt>permission=""</tt> entry stating that the <tt>source=</tt> reference may use (<tt>use</tt>), read (<tt>r</tt>), write (<tt>w</tt>) or read/write (<tt>rw</tt>) the <tt>destination=</tt> content provider. Each permission is separated by a semi-colon (<tt><nowiki>;</nowiki></tt>). The <tt>use</tt> permission is required to obtain a handle to the content provider, but does not provide read or write capability. Read, Write, or Read-Write imply the <tt>use</tt> permission.
+
** <tt>/></tt> The <tt>allow</tt> end tag.
+
* <tt><nowiki></allow-content></nowiki></tt> end tag.
+
  
Example <tt><nowiki><allow-content></nowiki></tt> entry:
+
To be able to build the bundle an <tt>eops.xml</tt> file is required.
 +
 
 +
Usage:
 
<pre>
 
<pre>
<?xml version="1.0" encoding="utf-8"?>
+
usage: buildeopbundle -k <private key.pk8> [-v <version>] [-r <previous hash>] \
<policy>
+
[-h] -- <eops.xml>
    <allow-content>
+
 
        <allow source="all" destination="settings_provider" permission="use;r"/>
+
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:
        <allow source="trusted_apps" destination="all_contacts_provider" permission="use;r"/>
+
    build/target/product/security/testkey.pk8
        <allow source="platform" destination="media_provider" permission="use;rw"/>
+
 
        <allow source="release" destination="mms_sms_provider" permission="use;rw"/>
+
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.
        <allow source="release" destination="browser_exported_provider" permission="use;rw"/>
+
 
        <allow source="release" destination="all_calendar_provider" permission="use;r"/>
+
OPTIONS:
        <allow source="release" destination="all_email_provider" permission="use;r"/>
+
     -h Show this message.
        <allow source="platform" destination="all_telephony_provider" permission="use;r"/>
+
    -v Version of the built bundle. Defaults to 1.
        <allow source="release" destination="search_provider" permission="use;r"/>
+
    -r SHA-512 hash of the bundle to replace. Defaults to 'NONE'.
        <allow source="release" destination="media_provider" permission="use;rw"/>
+
        <allow source="shared" destination="dictionary_provider" permission="use;r"/>
+
        <allow source="shared" destination="email_attach_provider" permission="use;r"/>
+
        <allow source="demo_resolver_package" destination="demo_provider" permission="use;rw"/>
+
        <allow source="demo_resolver_package" destination="settings_provider" permission="use;r"/>
+
     </allow-content>
+
</policy>
+
 
</pre>
 
</pre>
  
== Revoke Permissions MMAC Configuration File ==
 
The <tt>revoke_permissions.xml</tt> file is used to configure revoked permissions. The build process does not currently support additional files.
 
  
All entries are between <tt><nowiki><revoke-policy></nowiki></tt> tags:
+
==== 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>
 
<pre>
<?xml version="1.0" encoding="utf-8"?>
+
buildeopbundle -k $ANDROID_BUILD_TOP/build/target/product/security/testkey.pk8 -v 1 -- eops.xml
<revoke-policy>
+
 
    ......
+
adb push eops_bundle.zip /sdcard/
</revoke-policy>
+
 
</pre>
 
</pre>
  
The <tt>revoke_permissions.xml</tt> file entries are as follows:
+
<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>
  
* <tt><nowiki><package name="" ></nowiki></tt> entry. The <tt>name=</tt> refers to the package name.
+
The new file and its supporting metadata are:
** One or more <tt><nowiki><revoke-permission name="" /></nowiki></tt> entries. The <tt>name=</tt> refers to the permission to be denied.
+
<pre>
* <tt><nowiki></package></nowiki></tt> end tag.
+
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>
  
An example entry is:
+
The version number after the update is:
 
<pre>
 
<pre>
<?xml version="1.0" encoding="utf-8"?>
+
adb shell su 0 cat /data/security/eops/eops_metadata/version
<revoke-policy>
+
1
    <package name="com.example.runisolatedservice ">
+
        <revoke-permission name="com.se4android.isolatedservice.permission.DEADLY_ACTIVITY"/>
+
    </package>
+
</revoke-policy>
+
 
</pre>
 
</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>
  
= 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.
 
  
== checkfc ==
+
=== buildifwbundle ===
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>buildifwbundle</tt> tool will produce an Android "bundle" for updating the Intent Firewall 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.
  
<tt>checkfc -h</tt> will give the following output:
+
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>
 
<pre>
usage: <nowiki>checkfc [OPTIONS] sepolicy context_file</nowiki>
+
usage: buildifwbundle -k <private key.pk8> [-v <version>] [-r <previous hash>] \
Parses a context file and checks for syntax errors.
+
[-h] -- <ifw.xml>
The context_file is assumed to be a file_contexts file
+
unless explicitly switched by an option.
+
  
    OPTIONS:
+
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:
        -p : context file represents a property_context file.
+
 
 +
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>
 
</pre>
  
Example validating <tt>file_contexts</tt> file:
+
 
 +
==== 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>
 
<pre>
checkfc out/target/product/generic/root/sepolicy out/target/product/generic/root/file_contexts
+
buildsifwbundle -k $ANDROID_BUILD_TOP/build/target/product/security/testkey.pk8 -v 1 -- eops.xml
 +
 
 +
adb push ifw_bundle.zip /sdcard/
 
</pre>
 
</pre>
  
Example validating <tt>property_contexts</tt> file:
+
<tt>logcat</tt> should show whether it was successful:
 
<pre>
 
<pre>
checkfc -p out/target/product/generic/root/sepolicy out/target/product/generic/root/property_contexts
+
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>
 
</pre>
  
== checkseapp ==
+
The new file and its supporting metadata are:
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.
+
<pre>
 +
adb shell su 0 ls -lR /data/system/ifw
  
<tt>checkseapp -h</tt> will give the following output:
+
/data/system/ifw:
<pre>
+
-rw-r--r-- system system 454 2014-07-20 13:14 ifw.xml
<nowiki>checkseapp [options] <input file></nowiki>
+
drwx------ system system 2014-07-20 13:14 metadata
<nowiki>Processes an seapp_contexts file specified by argument <input file> (default stdin) and allows later declarations to
+
 
override previous ones on a match.</nowiki>
+
/data/system/ifw/metadata:
Options:
+
-rw-r--r-- system system 1 2014-07-20 13:14 gservices.version
    -h - print this help message
+
    -v - enable verbose debugging informations
+
    -p policy file - specify policy file for strict checking of output selectors
+
    -o output file - specify output file, default is stdout
+
 
</pre>
 
</pre>
  
An example command with output to <tt>stdout</tt> is:
+
The version number after the update is:
 
<pre>
 
<pre>
checkseapp -p out/target/product/generic/root/sepolicy out/target/product/generic/root/seapp_contexts
+
adb shell su 0 cat /data/system/ifw/metadata/gservices.version
isSystemServer=true domain=system
+
1
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=_app domain=untrusted_app type=app_data_file levelFrom=app
+
user=_app seinfo=platform domain=platform_app type=platform_app_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
+
 
</pre>
 
</pre>
  
== 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>,  <tt>mmac_types.xml</tt> and <tt>content_provider.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.
 
  
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.
+
== 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.
  
<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.
+
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>).
  
<tt>insertkeys.py -h</tt> will give the following output for 4.3 (4.2 does not have the <tt>-d</tt> option):
+
Usage:
 
<pre>
 
<pre>
Usage: insertkeys.py [options] CONFIG_FILE MAC_PERMISSIONS_FILE [MAC_PERMISSIONS_FILE...]
+
post_process_mac_perms [-h] -s SEINFO -d DIR -f POLICY
  
This tool allows one to configure an automatic inclusion of signing keys into the mac_permission.xml file(s) from the pem files.
+
    -s SEINFO, --seinfo SEINFO seinfo tag for each generated stanza
If multiple mac_permission.xml files are included then they are unioned to produce a final version.
+
    -d DIR, --dir DIR Directory to search for apks
 +
    -f POLICY, --file POLICY mac_permissions.xml policy file
 +
</pre>
  
Options:
+
Example:
    --version show program's version number and exit
+
<pre>
    -h, --help show this help message and exit
+
post_process_mac_perms -s netapps -d ./APK -f mac_permissions.xml
    -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
+
 
</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:
+
Before:
 
<pre>
 
<pre>
insertkeys.py -o demo/unioned_mac_permissions.xml external/sepolicy/keys.conf \
+
<?xml version="1.0" encoding="utf-8"?>
external/sepolicy/mac_permissions.xml demo/mac_permissions.xml
+
<policy>
 +
    <signer signature="- certificate here -" ><seinfo value="platform"/></signer>
 +
    <default><seinfo value="default"/></default>
 +
</policy>
 
</pre>
 
</pre>
  
=== keys.conf ===
+
After:
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.
+
<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>
  
<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>.
 
  
An example <tt>keys.conf</tt> file for AOSP 4.3 is as follows (note that the path is now supplied by the <tt>-d</tt> option when calling <tt>insertkeys.py</tt> in the <tt>external/sepolicy/Android.mk</tt> file):
+
== sepolicy_check ==
 +
A tool for auditing a <tt>sepolicy</tt> file for any allow rule that grants a given permission.
 +
 
 +
Usage:
 
<pre>
 
<pre>
#
+
sepolicy-check -s <domain> -t <type> -c <class> -p <permission>
# Maps an arbitrary tag [TAGNAME] with the string contents found in
+
-P out/target/product/<board>/root/sepolicy
# TARGET_BUILD_VARAINT. Common convention is to start TAGNAME with an @ and
+
</pre>
# 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. Typically this is user, eng, and userdebug. Another
+
# option is to use ALL which will match ANY TARGET_BUILD_VARAINT string.
+
#
+
  
[@PLATFORM]
+
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.
ALL : platform.x509.pem
+
  
[@MEDIA]
+
Examples:
ALL : media.x509.pem
+
<pre>
 +
sepolicy-check -s healthd -t system_server_service -c service_manager -p add -P  out/target/product/generic/root/sepolicy
 +
Match found!
 +
</pre>
  
[@SHARED]
+
<pre>
ALL : shared.x509.pem
+
sepolicy-check -s su -t security_prop -c property_service -p set -P out/target/product/generic/root/sepolicy
 
+
echo $?
# Example of ALL TARGET_BUILD_VARIANTS
+
1
[@RELEASE]
+
ENG : testkey.x509.pem
+
USER : testkey.x509.pem
+
USERDEBUG : testkey.x509.pem
+
 
</pre>
 
</pre>
  
The following is an example entry that will use a device specific key for release 4.3 during the build process:
+
 
 +
== 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>
 
<pre>
[@NET_APPS]
+
sepolicy-analyze -e -P out/target/product/<board>/root/sepolicy
ALL : $ANDROID_BUILD_TOP/device/demo_vendor/demo_device/security/net_apps.x509.pem
+
 
</pre>
 
</pre>
  
Should the build fail because of keys.conf entries, check that the following patch is installed:
+
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).
  
[https://android-review.googlesource.com/#/c/63370/ https://android-review.googlesource.com/#/c/63370/]
+
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.
  
If using 4.2, then a device specific example entry would be:
+
Example output:
 
<pre>
 
<pre>
[@NET_APPS]
+
sepolicy-analyze -e -P out/target/product/se4a_device/root/sepolicy
ALL : device/demo_vendor/demo_device/security/net_apps.x509.pem
+
 
 +
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>
 
</pre>
  
== buildsebundle ==
+
=== Type Difference ===
The following text has been extracted from an email that describes this new 4.3 feature:
+
<pre>
New code has been released that allow for policy reloading via Android's new UpdateConfig mechanism. Android 4.3 has brought a new set of OTA update hooks for various policy files including some of the SELinux ones. This is a way forward with reloadable policy support and as such have updated the SEAdmin project (master and seandroid-4.3 branches) with a new but limited reload option as well as updated the sepolicy project (seandroid and seandroid-4.3 branches) with new tooling. Some things to note:
+
sepolicy-analyze -d -P out/target/product/<board>/root/sepolicy
* In order for SEAdmin to reload policy there is a required format imposed by the backed ConfigUpdate code. A new signed policy 'bundle' and metadata file are required; the bundle being a packed version of various selinux policy files. Because of this new format, a new tool called buildsebundle has been developed that will help with the construction of such files. It is not built as standard, therefore need to 'make buildsebundle' first and then see the help menu below along with an example.
+
</pre>
* buildsebundle actually outputs a zip file containing the packed bundle and metadata file. The zip file isn't a direct requirement for the ConfigUpdate code but merely serves as a convenient packaging format to deliver both files to the device. This zip file will need to be pushed to /sdcard for SEAdmin to reload it.
+
* There is a requirement that the resulting bundle be signed for integrity purposes. The buildsebundle tool will help with this but a few caveats are in order. The backend code on the phone requires that an approved OTA cert already be loaded into the Settings secure database to verify the incoming reload request. This means that the cert on the phone must match the key fed the buildsebundle tool. SEAdmin has been changed to insert a key by first reading the entries in otacerts.zip on boot. The otacerts.zip file will include the correct testkey/releasekey when building the system image.
+
* There is no support for reloading mac_permissions.xml via this new reload mechanism. This is a limitation of the back end code which only supports reloading file_contexts, sepolicy, property_contexts and seapp_contexts policy files. The previous option for reloading mac_permissions.xml remains supported in the SEAdmin app however. The project will also continue to support the SEAdmin app as the ConfigUpdate code doesn't presently offer the abilities to switch to enforcing mode or toggle booleans.
+
* AOSP code for the new update mechanism can be found at: <tt>frameworks/base/services/java/com/android/server/updates/*</tt> .
+
* Since the ConfigUpdate code seems to still be under development, the SEAndroid project will most likely move in-step with that code in order to bring ideas together whenever possible. So, updates to both the SEAdmin and sepolicy tooling are possible in the future.
+
  
 +
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.
  
<tt>buildsebundle -h</tt> will give the following output:
+
Example output:
 
<pre>
 
<pre>
usage: buildsebundle -k <private key.pk8> [-v <version>] [-r <previous hash>] [-h] -- <file_contexts>
+
sepolicy-analyze -d -P out/target/product/se4a_device/root/sepolicy
    <property_contexts> <sepolicy> <seapp_contexts>
+
  
This script builds a selinux policy bundle and supporting metadata file capable of being loaded via
+
Types adbd_socket and functionfs differ, starting with:
the ConfigUpdate mechanism. It takes a pkcs8 DER encoded RSA private key that is then used to sign
+
allow adbd_socket rootfs:filesystem { associate };
the bundle. For AOSP development you'll typically want to use the key from the source tree at
+
allow functionfs self:filesystem { associate };
build/target/product/security/testkey.pk8. If building your own cert you should probably use at least
+
a key size of 1024 or greater. The bundle requires that seapp_contexts, file_contexts, property_contexts
+
and sepolicy files all be included and with those exact basenames. The built bundle will be written to
+
selinux_bundle.zip which will include the signature metadata file of the bundle.
+
  
OPTIONS:
+
Types adbd_socket and hci_attach_exec differ, starting with:
  -h      Show this message.
+
allow system_server adbd_socket:sock_file { ioctl read write getattr lock append open };
  -v      Version of the built bundle. Defaults to 1.
+
allow debuggerd hci_attach_exec:file { ioctl read getattr lock open };
  -r      Sha512 hash of the bundle to replace. Defaults to 'NONE'.
+
 
 +
Types adbd_socket and system_server differ, starting with:
 +
allow adbd_socket rootfs:filesystem { associate };
 +
allow system_server rootfs:filesystem { getattr };
 
</pre>
 
</pre>
  
The following example (with policy files in <tt>cwd</tt> will produce an <tt>selinux_bundle.zip</tt> file containing two files <tt>update_bundle</tt> and <tt>update_bundle_metadata</tt>:
+
 
 +
=== Duplicate Allow Rules ===
 
<pre>
 
<pre>
buildsebundle -k $ANDROID_BUILD_TOP/build/target/product/security/testkey.pk8 -- file_contexts \
+
sepolicy-analyze -D -P out/target/product/<board>/root/sepolicy
property_contexts sepolicy seapp_contexts
+
 
</pre>
 
</pre>
  
== setool ==
+
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.
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. It is not supplied in AOSP.
+
  
The entries produced will generally have to be modified because currently:
+
Example output:
# 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 MMAC process (therefore the packages need to be consolidated into on entry).
+
<pre>
# <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 MMAC.
+
sepolicy-analyze -D -P out/target/product/se4a_device/root/sepolicy
# <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.  
+
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.
  
<tt>setool --help</tt> will give the following output:
+
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>:
+
 
 +
The following examples show the generation and verification process:
 
<pre>
 
<pre>
setool --build whitelist RunIsolatedService.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.runisolatedservice">
 
     <package name="com.example.runisolatedservice">
         <allow-permission name="com.se4android.isolatedservice.permission.DEADLY_ACTIVITY" />
+
         <seinfo value="service_app" />
 
     </package>
 
     </package>
 
</signer>
 
</signer>
 
</pre>
 
</pre>
  
 +
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>
 +
setool --policy sepolicy/mac_permissions.xml RunIsolatedService.apk
 +
</pre>
  
= uid To username Utility =
+
The output will then be:
 +
<pre>
 +
seinfo tag service_app assigned to ./RunIsolatedService.apk
 +
</pre>
 +
 
 +
 
 +
= 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>
 +
PRODUCT_PACKAGES += selinux-network.sh
 +
</pre>
 +
 
 +
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>
 +
 
 +
= 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 1,167: Line 1,312:
 
         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 1,191: Line 1,331:
 
         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);

Revision as of 13:53, 28 July 2014

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.

SELinux MAC Configuration Files

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.


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


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.


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


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


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


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!


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>


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.


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>


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


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.

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


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


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


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


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.


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


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


buildeopbundle

The buildeopbundle tool will produce an Android "bundle" for updating the Enterprise Operations 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 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'.


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


buildifwbundle

The buildifwbundle tool will produce an Android "bundle" for updating the Intent Firewall 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 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'.


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


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>


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


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:

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.

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 };


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 };


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


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

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);
}