0% found this document useful (0 votes)
14 views71 pages

06 Security Architecture IV

The document discusses Android security architecture, focusing on the need for defense in depth and the challenges of critical system exploits and update distribution. It highlights the importance of compartmentalization, mandatory access control with SELinux, and the modularization of Android to enhance security. Various approaches to address vulnerabilities, including faster updates and secure programming practices, are also presented.

Uploaded by

hehee.caught.you
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views71 pages

06 Security Architecture IV

The document discusses Android security architecture, focusing on the need for defense in depth and the challenges of critical system exploits and update distribution. It highlights the importance of compartmentalization, mandatory access control with SELinux, and the modularization of Android to enhance security. Various approaches to address vulnerabilities, including faster updates and secure programming practices, are also presented.

Uploaded by

hehee.caught.you
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

Android Security

Architecture IV
Dr.-Ing. Sven Bugiel

Mobile Security | WS24/25 | 2024-11-15


From the last lectures

• Compartmentalization:
− Isolation & Principle of least privilege
− Android’s UID-based sandboxing
− IPC/ICC as a controlled channel between app
sandboxes
− Zygote as parent process for all app processes
• Android’s middleware services and apps as reference
monitors for system and user resources
− “encapsulating” resources and exposing API via
Binder IPC
• Role of Binder driver: Provide services and apps with UID
of calling processes
− Use UID to enforce permission checks
Sandbox

2
Android Security
Architecture
Need for Defense in Depth
Problem of critical system exploits [126,130]

• Critical vulnerabilities on Android:

and more recent ones (Quadrooter,


Stagefright, Dirty Cow, af_packet.c race
condition…)

Source: https://www.statista.com/statistics/271774/share-of-android-platforms-
4
on-mobile-devices-with-android-os/
Problem of critical system exploits [126]

• Security patches for the system may take a


long time to reach the end-user devices
− …if at all
− Ecosystem fragmentation a contributing
factor: Dependencies on various actors to
deploy patches

Flow of updates from upstream projects into Flow of updates between participants in
Android the Android ecosystem
(latency between the upstream release and the release of the first (Number edge: Patches shipped in dataset;
Android version containing it in the dataset) Number box: #entities in dataset)

5
Problem of distributing updates [171]

• Data from Google’s monthly security bulletins, security update


announcements from top U.S. carriers between Aug 2015—Dec 2019, and
user IDs/agent strings from a U.S. social network
• Insights:
− Manufacturers and carriers introduce a median latency of 24 days before
rolling out security updates
− Additional median delay of 11 days before end user device update

Delay between security announcement from carrier to Android Security Bulletin

6
Problem of distributing updates [171]

• Data from Google’s monthly security bulletins, security update


announcements from top U.S. carriers between Aug 2015—Dec 2019, and
user IDs/agent strings from a U.S. social network
• Insights:
− Relationship between manufacturer and carrier influences the delay of
updates

Update latency per carrier: Security announcement vs Android Security Bulletin Update latency for models supported by all four carriers

7
Root providers [130]

• Users might want root access but don’t always have the ability or possibility
to flash a custom ROM with root access
− Entire ecosystem of “soft root providers” established that build and tailor
“one-click root methods” for various devices, usually exploiting known or
zero-day root exploits
− Business model: More and better exploits for more supported devices
• Potential problem: How well do the providers protect their solutions? Can
malware easily use them or adapt their exploits?
Root providers

A: Anti-debug
C: Tamper-detection
N: Code Protection with JNI.
O: Obfuscation
P: Packing
S: String Encryption.

8
Approaches to address the vulnerabilties

• Various approaches thinkable


− Faster updates and patches
− Defense-in-depth
− Secure programming languages
− Hardening system
− …

9
Approaches to address the vulnerabilties

• Various approaches thinkable


− Faster updates and patches
− Defense-in-depth
− Secure programming languages
− Hardening system
− …

https://source.android.com/docs/setup/build/rust/building-rust-modules/overview
10
Approaches to address the vulnerabilties

• Various approaches thinkable


− Faster updates and patches
This lecture
− Defense-in-depth
− Secure programming languages
− Hardening system
− …

11
Recap: Fundamental security design principles

• Perfectly secure does not exist (yet)


• But: Fundamental design principles to guide development of protection
mechanisms

• Least privilege: Every process and every user of the system should operate
using the least set of privileges necessary to perform their tasks. Compromise
only yields minimum set of privileges.
• Least common mechanism: Minimize the functions shared by different users,
providing mutual security.
• Modularity / Compartmentalization: Modular system architecture and security
mechanisms as isolated, protected modules. Helps protecting individual
modules from tampering.
• Defense-in-depth: Use multiple, overlapping protection approaches, the failure
or circumvention of any individual protection approach will not leave the
system unprotected. No single point of failure.

12
Modularization of Android: Treble

• Android 8.0 re-architected the OS framework


− Reduce effort/costs/delay to update devices
− Problem: Updating the Android Framework required complete device
updates via the vendor
− HAL interface definition language (HIDL) specifies interface between HAL
and its users
Legacy Android (Pre-8.0) Android (8.0+)
-> now: replace Android framework w/o rebuilding HAL

13 https://www.androidauthority.com/project-treble-818225/
https://source.android.com/devices/architecture
Modularization of Android: Treble

• Android 8.0 re-architected the OS framework


− Reduce effort/costs/delay to update devices
− HAL interface definition language (HIDL) specifies the interface between
HAL and its users
− Now: replace the Android framework w/o rebuilding HAL

14 https://www.androidauthority.com/project-treble-818225/
https://source.android.com/devices/architecture
Modularization of Android: Modular System Components
(Project Mainline)
• Android 10 modularizes some Android system components and enables them to
be updated via Google Play outside of the normal Android release cycle
− New APEX container format introduced for lower-level system modules that
do not fit into standard Android application model
− Examples: Runtime, DNS Resolver, Media Codecs, Network Components,
Permission Controller,...

15 https://source.android.com/devices/architecture/modular-system
Kernel Fragmentation

• Problem: long supply chains for kernel and fragmentation of kernels (as
much as 50% of the code running on a device is out-of-tree code, i.e., not
from upstream Linux or from AOSP common kernels)
Linux kernel from kernel.org

Additional Android-specific patches from


AOSP common kernels

SoC and peripheral enablement and


optimization patches from vendors

Additional device drivers and customizations

16 https://source.android.com/devices/architecture/kernel/generic-kernel-image
Generic Kernel Images

• Generic Kernel Image (GKI) addresses kernel fragmentation by unifying the


core kernel and moving SoC and board support out of the core kernel into
loadable modules
− Kernel Module Interface (KMI) for kernel modules
− modules and kernel can be updated independently

17 https://source.android.com/devices/architecture/kernel/generic-kernel-image
Hardening the system

• System increasingly hardened against software exploits as well as reducing


the attack surface (“defense-in-depth”)
− Memory management security enhancements
− Use of seccomp-bpf
− Hardening crucial system daemons, libraries, and kernel
− Secure USB debugging and USB access control
− Hardware-isolated security and verified boot
− Coming back to this in the last lectures of this course
− Updates to WebView with OTA
− Different encryption options
− Integration and improvement of SELinux-based mandatory access
control

18 https://source.android.com/security/index.html
Android Security
Architecture
Mandatory Access Control
with SELinux
Android’s security principle
System Service/App
• Android’s security design relies on the OS to
(UID S)
enforce the application sandbox based on App IPC Application
the app’s UID (UID A) Framework API
Permission check

Privileged code
• Problems:
User space syscalls syscalls
− Misconfigured kernel level access control
Kernel space
− Attacker/App escalates its privileges to a System resource
e.g., files, drivers, etc.
higher privileged UID
Compliant access Non-compliant access
− In particular: Root exploits
Kernel level access control
− Kernel exploits

20
Defense in depth

• Layered security mechanism to protect resources


− Benefit: redundancy if one (higher-level) mechanism fails; re-enforce
higher layers’ protection goals

Gained root
privileges

Linux DAC
SELinux (MAC)
Should still be
Kernel driver
prevented!

21
Mandatory Access Control (MAC)

• Based on security contexts assigned to subjects and objects


• A central security policy defines how security contexts can interact
− Users cannot change the security policy! (=Mandatory)

22
Implementations of MAC

• Windows: Mandatory Integrity Control (MIC)


• Extensible kernel security frameworks for implementing MAC on Linux and
BSD/Mac OS X:
− For example: Linux Security Modules (LSM), TrustedBSD MAC Framework

• Label-based MAC
− Subjects and objects labeled with a security context
− Example implementations: SELinux, SMACK (Simplified Mandatory Access
Control Kernel), Windows MIC
• Pathname-based MAC
− Policies based on the path of executables and objects instead of label
− Example implementations: TOMOYO, grsecurity, AppArmor

23
SELinux on Android overview [128,129]

• SELinux (Security Enhanced Linux)


− Primarily developed by the NSA, part of Linux kernel since 2008
− Used in RedHat Linux and Fedora
− Ported to Android by the SEAndroid project (also NSA)
− Core parts of SEAndroid integrated upstream into AOSP and fully enforced
since Android v5.0
− Integration into Zygote, PackageManagerService, and other core services
− Nowadays, deployed on pretty much every Android device
− With newer versions increasingly fine-grained, stricter policies and new
features
• Security policies and enforcement based on type enforcement
− Supports further access control models, including role-based access control
(RBAC) and multi-level access control (MLS)
− RBAC not used in Android, MLS for multi-user feature

24
Mandatory Access Control Models: Domain-type
enforcement (DTE) model
• Enhanced type enforcement (TE) mechanism
− Deployed in operating systems but also firewalls
− Can support variety of security policies
• Access control decisions based on domain and type
− Subjects associated with a domain and objects with a type
− Policy maps each (domain, type) and (domain, domain) pair to a set of
allowed permissions
− E.g., domains root and user: (root, user)→(create, kill) would allow
processes in the root domain to create and kill processes in the user
domain
− E.g., domain user and type userdata: (user, userdata)→(create, read,
write) would allow a process in the user domain to create, read, and
write an object (e.g., file) with the userdata type

25
Linux Security Modules [127]

• Implemented as a kernel module for the Linux Security Modules framework


(LSM)

26
Original figure from: Frank Meyer “SELinux by Example: Using Security Enhanced Linux: Using Security Enhanced Linux”
LSM Concept

• Common architecture: Decouples policy enforcement from policy decision


making
• Object Manager (=PEP, Policy Enforcement Point)
− Responsible for requesting and enforcing policy decisions from a Security
Server for the resources the OM manages
− Kernel: Various subsystems that manage kernel-level objects
− File system, IPC, process management,...
− More than 200 hooks
− LSM: OMs represented by LSM hooks; truncate or continue control flow
based on policy decision
• Security Server (=PDP, Policy Decision Point)
− Makes policy decisions based on information provided by the LSM hooks
− Implemented in the LSM module(s)

27
SELinux policy concept

• All subjects and objects in the system are labeled with a security context:
user : role : type : security level
• type: most important attribute! Type of objects and subjects (i.e., subject’s
domain) used for domain-type enforcement
• role: only relevant for processes/domains; used to group types (implement
Role-Based Access Control with type enforcement), i.e., which types a
process can reach
• user: to group roles (usually by user, system, root)
• security level: used for Multi-level Security (MLS), defines the sensitivity
(clearance level) and category for implementing the Bell-LaPadula model

28
SELinux policy concept

• All subjects and objects in the system are labeled with a security context:
user : role : type : security level
• Values just strings assigned by the OM
− security interpretation up to the security server
− semantic of OM and Security Server must be in sync!
• Context stored with subject/object:
− File: Usually in extended file system attribute
− Process: Extended task struct in process management of kernel
• Tool support to get security context of subjects/objects
− id, ps -Z, ls -Z

29
Example: Fedora Linux with SELinux
[sven@mbpc05 ~]$ ls –lZ
total 172
drwxr-xr-x. 2 sven sven unconfined_u:object_r:user_home_t:s0 4096 Dec 7 12:52 Desktop
drwxr-xr-x. 2 sven sven unconfined_u:object_r:user_home_t:s0 4096 Dec 7 12:52 Documents
drwxr-xr-x. 2 sven sven unconfined_u:object_r:user_home_t:s0 4096 Dec 7 12:52 Downloads
drwxr-xr-x. 2 sven sven unconfined_u:object_r:audio_home_t:s0 4096 Dec 7 12:52 Music
drwxr-xr-x. 2 sven sven unconfined_u:object_r:user_home_t:s0 4096 Dec 7 12:52 Pictures
drwxr-xr-x. 2 sven sven unconfined_u:object_r:user_home_t:s0 4096 Dec 7 12:52 Public
-rw-r--r--. 1 sven sven unconfined_u:object_r:user_home_t:s0 143331 Dec 9 13:16 sepolicy

sven@mbpc05 ~]$ ls -lZ /usr/bin/passwd


-rwsr-xr-x. 1 root root system_u:object_r:passwd_exec_t:s0 27872 Feb 4 2016 /usr/bin/passwd

[sven@mbpc05 ~]$ ls -lZ /etc/selinux/


total 12
-rw-r--r--. 1 root root system_u:object_r:selinux_config_t:s0 548 Nov 15 22:48 config
-rw-r--r--. 1 root root system_u:object_r:selinux_config_t:s0 2321 Oct 4 15:18 semanage.conf
drwxr-xr-x. 5 root root system_u:object_r:selinux_config_t:s0 4096 Dec 7 13:01 targeted

[sven@mbpc05 ~]$ ps axZ


LABEL PID TTY STAT TIME COMMAND
system_u:system_r:init_t:s0 1 ? Ss 0:01 /usr/lib/systemd/systemd ...
system_u:system_r:kernel_t:s0 2 ? S 0:00 [kthreadd]
system_u:system_r:udev_t:s0-s0:c0.c1023 544 ? Ss 0:00 /usr/lib/systemd/systemd-udevd
unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 3090 pts/0 Ss 0:00 /bin/bash

[sven@mbpc05 ~]$ id
uid=1000(sven) gid=1000(sven) groups=1000(sven),10(wheel) context=unconfined_u:unconfined_r:unconfined_t:s0-
s0:c0.c1023

user : role : type : security level


30
Type Enforcement

• Primary attribute: type (a.k.a. “domain”)


− Simply a string, the policy gives meaning to this attribute
• Type enforcement rule stated as:
allow subject_type object_type: object_class operation
− Object class: “file”, “socket”, … as provided by the LSM hook
− Operation: “read”, “write”, “open”, … (object-specific) as provided by the LSM
hook
• Only if a rule is defined, access is allowed, otherwise denied (“allowlisting”)
• Much more fine-grained access control polices than with Linux DAC
• SELinux MAC outranks the Linux DAC: Root processes are only as powerful as
their SELinux type (effectively removes an all-powerful root account)
• Helps with enforcing the principle of least-privilege at the process level (not UID)

31
SELinux Reference Monitor

Reference monitor

secctxP Request ‘write’ If authorized


authorized? File
Process X to file
secctxF
What is the secctxP of the process?
What is the secctxF of the file?
Does the policy allow write a file
from secctxP to secctxF?

SELinux Security Policy

32
Short example rule

allow untrusted_app sdcard_external: file { create open read }


• untrusted_app: Subject type, e.g., assigned to the process of the app
• sdcard_external: Object type, e.g., assigned to a file
• file: Object class, i.e., a file object
• {create open read}: Operations, i.e., “create a file”, “open a file”, “read a
file”

• The rule states that a process with the type “untrusted_app” can create,
open, and read file objects with the type “sdcard_external”
− If the system ensures that all files stored on the SDcard get the type
“sdcard_external” and that all untrusted programs get the type
“untrusted_app”, then this rule governs how untrusted programs can
operate on files stored on the SDcard independently of the UID

33
SELinux on Android

• Where are the policy source files located?


− Android reference policy: <AOSP>/system/sepolicy/
− Device-specific policies when building for different devices
− Compiled into one monolithic, binary policy

• Tools for investigating


− grep
− apol (“SELinux Policy Analysis” with GUI)
− seinfo, sesearch, findcon command line tools

34
How are subjects and objects labeled

• How does a file or a process get its security context (type)?


• Four basic mechanisms exist in SELinux
− Policy statements that govern 1) how newly created objects (files, etc)
should be labeled based on creator process’ type and parent object type
or 2) how newly created processes should be labeled based on creator’s
type and executed binary type
− Hard-coded defaults
− Program-requested labeling via the SELinux API of the kernel
− Initial Security Identifiers (SIDs): Fail-safe defaults if an object would
otherwise have no label (e.g., when policy not yet loaded during early
boot)

35
General object labeling (extract)

• file_contexts
− initial file contexts for setting the filesystem
− apps and their data stores handled separately in seapp_contexts
• property_contexts
− default contexts for Android property services
− Used by <AOSP>/system/core/init/property_service.cpp and
<AOSP>/system/core/init/init.cpp
• service_contexts
− default contexts for Android services
− Used by
<AOSP>/frameworks/native/cmds/servicemanager/ServiceManager.cpp
• initial_sids and initial_sid_contexts
− Fail-safe default contexts

36
Example Security Contexts
• Files labeled during system build
• File system SELinux security contexts:
drwxrwx--- system cache u:object_r:cache_file:s0 cache
dr-x------ root root u:object_r:rootfs:s0 config
drwxrwx--x system system u:object_r:system_data_file:s0 data
-rw-r--r-- root root u:object_r:rootfs:s0 default.prop
drwxr-xr-x root root u:object_r:device:s0 dev
lrwxrwxrwx root root u:object_r:rootfs:s0 etc -> /system/etc
-rw-r--r-- root root u:object_r:rootfs:s0 file_contexts
-rwxr-x--- root root u:object_r:rootfs:s0 init
dr-xr-xr-x root root u:object_r:proc:s0 proc
drwx------ root root u:object_r:rootfs:s0 root
drwxr-x--- root root u:object_r:rootfs:s0 sbin
lrwxrwxrwx root root u:object_r:rootfs:s0 sdcard ->
/storage/self/primary
-rw-r--r-- root root u:object_r:rootfs:s0 seapp_contexts
-rw-r--r-- root root u:object_r:rootfs:s0 selinux_version
-rw-r--r-- root root u:object_r:rootfs:s0 sepolicy
-rw-r--r-- root root u:object_r:rootfs:s0 service_contexts
drwxr-xr-x root root u:object_r:storage_file:s0 storage
dr-xr-xr-x root root u:object_r:sysfs:s0 sys
drwxr-xr-x root root u:object_r:system_file:s0 system

37
User Space Object Managers (USOM)

• Object managers concerned with user space objects in contrast to kernel


space objects

38
Original figure from: Frank Meyer “SELinux by Example: Using Security Enhanced Linux: Using Security Enhanced Linux”
libselinux

• Simple interface to the SELinux security server via the selinuxfs


• Most important: requesting access control decision from the Security Server
checkSELinuxAccess(String scon, String tcon, String tclass, String
perm)
• Other management functions such as requesting types for new objects
• Labeling user space objects and enforcing object-specific policy decisions is
task of USOM, but policy in kernel must be aware of the user space
objects/types
− For example: sePostgreSQL
− Custom classes: schema, table, column, view, …
− Database labels DB objects with security context
− Access to DB objects governed by kernel policy

39
Libselinux on Android

• Fixed part of the Android application runtime libandroid_runtime.so


• Integrated via the Java Native Interface (JNI)

Access to selinuxfs in
kernel controlled by
SELinux policy

40
USOMs on Android

Several classes specifically for USOMs defined in


<AOSP>/system/sepolicy/security_classes
# Property service
class property_service # userspace
# Service manager
class service_manager # userspace
# hardware service manager # userspace
class hwservice_manager
# Legacy Keystore key permissions
class keystore_key # userspace
# Keystore 2.0 permissions
class keystore2 # userspace

# Keystore 2.0 key permissions


class keystore2_key # userspace
class drmservice # userspace

41
Example USOM: ServiceManager

• SELinux type enforcement when registering a new service with the


ServiceManager (recap: last lecture on Binder IPC)

Service Manager system_server


Cannot be based on ServiceName Binder
permissions, since AMS “location” handle1
not even running … …
LocationMgrSrv BinderLM

ServiceMgrSrv BinderSM1 ServiceMgr.Proxy handle0


Only authorized processes
should be allowed to
register core services like
AMS, LMS, …
addService(“location”, handle1) ServiceMgr.Proxy.addService(“location”, BinderLM)

Process Handle Binder Binder driver


* handle0 BinderSM1
service_manager handle1 BinderLM

42
app_process handle2 BinderLM
Example USOM: ServiceManager

• SELinux type enforcement when registering a new service with the


ServiceManager (recap: last lecture on Binder IPC)
− <AOSP>/frameworks/native/cmds/servicemanager/ServiceManager.cpp

43
Example USOM: ServiceManager

• SELinux type enforcement when registering a new service with the


ServiceManager
− <AOSP>/frameworks/native/cmds/servicemanager/Access.cpp

Security Context of caller provided


by Binder, akin to UID/PID

In libselinux:
Retrieves security
context for a given PID

44
Example USOM: ServiceManager

• SELinux type enforcement when registering a new service with the


ServiceManager
− <AOSP>/frameworks/native/cmds/servicemanager/ServiceManager.cpp

45
Example USOM: ServiceManager

• SELinux type enforcement when registering a new service with the


ServiceManager: <AOSP>/frameworks/native/cmds/servicemanager/Access.cpp

Android-specific addition to libselinux:


Map a name to a security context string,
here defined in service_contexts

Only runtime
parameters

From callingSID/ From name in


callingPID service_contexts “service_manager” “add”

46
Check SELinux policy for allow rule for < subject type, object type, object class, operation>
Example USOM: ServiceManager

• SELinux type enforcement when registering a new service with the


ServiceManager
− <AOSP>/system/sepolicy/private/service_contexts
Service name Security context of the service
accessibility u:object_r:accessibility_service:s0
account u:object_r:account_service:s0
activity u:object_r:activity_service:s0
activity_task u:object_r:activity_task_service:s0
adb u:object_r:adb_service:s0
aidl_lazy_test_1 u:object_r:aidl_lazy_test_service:s0
aidl_lazy_test_2 u:object_r:aidl_lazy_test_service:s0
alarm u:object_r:alarm_service:s0
android.os.UpdateEngineService u:object_r:update_engine_service:s0
android.os.UpdateEngineStableService u:object_r:update_engine_stable_service:s0
android.security.identity u:object_r:credstore_service:s0
android.security.keystore u:object_r:keystore_service:s0
android.service.gatekeeper.IGateKeeperService u:object_r:gatekeeper_service:s0
android.system.keystore2 u:object_r:keystore_service:s0
app_binding u:object_r:app_binding_service:s0
app_integrity u:object_r:app_integrity_service:s0
app_prediction u:object_r:app_prediction_service:s0
app_search u:object_r:app_search_service:s0
apexservice u:object_r:apex_service:s0
blob_store u:object_r:blob_store_service:s0
...

47
Example USOM: ServiceManager

• SELinux type enforcement when registering a new service with the


ServiceManager
− <AOSP>/system/sepolicy/private/service_contexts
Service name Security context of the service
accessibility u:object_r:accessibility_service:s0
account u:object_r:account_service:s0
activity u:object_r:activity_service:s0
activity_task u:object_r:activity_task_service:s0
adb u:object_r:adb_service:s0
aidl_lazy_test_1 u:object_r:aidl_lazy_test_service:s0
aidl_lazy_test_2 u:object_r:aidl_lazy_test_service:s0
alarm u:object_r:alarm_service:s0
android.os.UpdateEngineService u:object_r:update_engine_service:s0
android.os.UpdateEngineStableService u:object_r:update_engine_stable_service:s0
android.security.identity u:object_r:credstore_service:s0
android.security.keystore u:object_r:keystore_service:s0
android.service.gatekeeper.IGateKeeperService u:object_r:gatekeeper_service:s0
android.system.keystore2 u:object_r:keystore_service:s0
app_binding u:object_r:app_binding_service:s0
app_integrity u:object_r:app_integrity_service:s0
app_prediction u:object_r:app_prediction_service:s0
Return value for
app_search u:object_r:app_search_service:s0
selabel_lookup(“android.system.keystore2”)
apexservice u:object_r:apex_service:s0
blob_store u:object_r:blob_store_service:s0
...

48
Example USOM: ServiceManager, add KeyStore service

• What are the relevant allow rules for adding this service?
android.security.keystore u:object_r:keystore_service:s0
android.system.keystore2 u:object_r:keystore_service:s0

system/sepolicy/public/te_macros system/sepolicy/public/keystore.te

allow keystore keystore_service: service_manager add

Last question: Which processes have type keystore? Those can add their
Binder as “android.security.keystore” or “android.system.keystore2” service!
49
Example USOM: ServiceManager, add KeyStore service

• Which processes have type keystore? Those can add their Binder as
“android.security.keystore” or “android.system.keystore2” service!
allow keystore keystore_service: service_manager add

system/sepolicy/public/te_macros system/sepolicy/private/keystore.te

Init process automatically changes its type to $1 when


executing a binary with type $1_exec.
$1=“keystore” ⇒ $1_exec=“keystore_exec”

system/sepolicy/private/file_contexts

Rules not shown here have to allow a process with type


init to open/read/execute the type keystore_exec
50
Example USOM: ServiceManager, add KeyStore service

• Which processes can register themselves as KeyStore?

• Answer:
− Only when the init process executes the /system/bin/keystore{2}
executables the resulting process can register itself as a service in
ServiceManager with the name “android.security.keystore” or
“android.system.keystore2”
− Since no other process than init can execute these executables, no
other process can register itself; init is started by the kernel during
system boot
− neverallow rule prevents any other type than keystore from adding the
service keystore_service

51
Principle of Tranquility

• Principle of tranquility: subjects and objects may not change their security
levels once they have been instantiated
− Violation of tranquility would violate fundamental restrictions
− Raising the classification of an object means that available information
is no longer available
− Lowering the classification means that information previously
considered restricted is now available to all (declassification problem)
• The tranquility principle has two forms:
− Principle of strong tranquility: security levels do not change during the
lifetime of the system
− Principle of weak tranquility: security levels do not change in a way that
violates the rules of a given security policy
− SELinux type transitions allow policy-controlled type changes

52
Zygote USOM: Labeling Android applications

• PackageManagerService requests a type for a newly installed app from the


SELinux policies, stores the type in the package management
− For instance, based on signature key or other app attributes
• When starting a new app, ActivityManagerService requests the app’s type
from PackageManagerService and passes the type as argument to Zygote.
Zygote labels the newly created application process.
− Policy must give Zygote higher privileges to be able to label other
processes
− Zygote must check which process wants to set the type and whether the
process is allowed to do so (Only system server process running
ActivityManagerService should be allowed)

53
SELinux integration into zygote

Zygote Dalvik VM
(UID A, security
(root) context A)
2) Load
App Code
APK

Core libs Core libs

1) Fork() 3) setUID(A)
4) Set SELinux context A
(dynamic domain transition)
5) Give control flow to
54 VM process
Dynamic domain transition

• Permission dyntransition allows a running process to switch its own security context
− Abstractly like the setuid() call
• Very dangerous! Processes can change their type at any point! Possible target domains
for source domain specified in the policy but can more easily break tranquility
• Android: Allowed exclusively to the Kernel domain and zygote
− Kernel must dynamically transition into init domain for init process
− Zygote must dynamically transition into the application domain on app start after
forking
− Remember: Zygote does not “execve() application binaries” (no process hierarchy
as on a normal Linux), but instead “forks and loads” the application code
• Mostly restricted with neverallow rules. For example, in init.te:
# The init domain is only entered via setcon from the kernel domain,
# never via an exec-based transition.
neverallow { domain -kernel} init:process dyntransition;
neverallow domain init:process transition;
neverallow init { file_type fs_type }:file entrypoint;

55
Zygote USOM: Determining the type for an Application

• SE Android introduced new install policy definitions to define the mapping from
package information to security type
− Based on developer signature and AID/UID
− <AOSP>/system/sepolicy/private/mac_permissions.xml
− Define developer signature to “seinfo” mapping
− <AOSP>/system/sepolicy/private/seapp_contexts
− Defines rules to assign type to app based on AID, seinfo value, others
isSystemServer=true domain=system_server_startup
user=system seinfo=platform domain=system_app type=system_app_data_file
user=bluetooth seinfo=platform domain=bluetooth type=bluetooth_data_file
user=nfc seinfo=platform domain=nfc type=nfc_data_file
user=radio seinfo=platform domain=radio type=radio_data_file
user=shell seinfo=platform domain=shell name=com.android.shell type=shell_data_file
user=webview_zygote seinfo=webview_zygote domain=webview_zygote
user=_app domain=untrusted_app type=app_data_file levelFrom=all
− Used by SElinux user-space tools, called from Zygote, in order set the type
of the new app process

56
Example Security Contexts
• Process list showing security contexts:
root@generic_x86:/ $ ps –Z
LABEL USER PID PPID NAME
u:r:init:s0 root 1 0 /init
u:r:kernel:s0 root 2 0 kthreadd
u:r:kernel:s0 root 3 2 ksoftirqd/0
u:r:kernel:s0 root 4 2 kworker/0:0
u:r:kernel:s0 root 5 2 kworker/0:0H
u:r:kernel:s0 root 7 2 kworker/u:0H
u:r:kernel:s0 root 8 2 migration/0

u:r:system_server:s0 system 1533 1240 system_server
u:r:sdcardd:s0 media_rw 1629 1176 /system/bin/sdcard
u:r:platform_app:s0:c512,c768 u0_a14 1631 1240 com.android.systemui
u:r:sdcardd:s0 media_rw 1686 1176 /system/bin/sdcard
u:r:radio:s0 radio 1879 1240 com.android.phone
u:r:system_app:s0 system 2300 1240 com.android.settings
u:r:untrusted_app:s0:c512,c768 u0_a21 2339 1240 com.android.calendar
u:r:system_app:s0 system 2421 1240 com.android.keychain
u:r:untrusted_app:s0:c512,c768 u0_a31 2525 1240 com.android.exchange
u:r:platform_app:s0:c512,c768 u0_a50 2548 1240 com.android.messaging
u:r:su:s0 root 2846 1227 /system/bin/sh

57
Example Security Contexts
• Listing other processes in su security context:
root@generic_x86:/ $ id
uid=0(root) gid=0(root)
groups=0(root),1004(input),1007(log),1011(adb),1015(sdcard_rw),1028(sdcard_r),300
1(net_bt_admin),3002(net_bt),3003(inet),3006(net_bw_stats) context=u:r:su:s0

root@generic_x86:/ top
PID PR CPU% S #THR VSS RSS PCY UID Name
1233 0 1% S 11 132904K 10636K fg media /system/bin/mediaserver
1533 0 0% S 73 1393552K 87392K fg system system_server
1875 0 0% S 29 1289024K 45992K fg radio com.android.phone
1228 0 0% S 6 10032K 512K fg root /sbin/adbd
1231 0 0% S 4 9224K 1704K fg radio /system/bin/rild
2824 1 0% R 1 3980K 1108K fg root top
9 0 0% S 1 0K 0K fg root rcu_bh
10 0 0% S 1 0K 0K fg root rcu_sched
11 1 0% S 1 0K 0K fg root migration/1
...
1235 0 0% S 1 7600K 2256K fg keystore /system/bin/keystore
...
2318 0 0% S 17 1271556K 29588K fg u0_a21 com.android.calendar

58
Example Security Contexts

• Listing other processes in untrusted_app security context:


root@generic_x86:/ $ runcon u:r:untrusted_app:s0:c512,c768 /system/bin/sh
root@generic_x86:/ # id
uid=0(root) gid=0(root)
groups=0(root),1004(input),1007(log),1011(adb),1015(sdcard_rw),1028(sdcard_r),3001(net_bt_adm
in),3002(net_bt),3003(inet),3006(net_bw_stats) context=u:r:untrusted_app:s0:c512,c768
root@generic_x86:/ top
PID PR CPU% S #THR VSS RSS PCY UID Name
2823 0 1% R 1 3980K 1108K fg root top
2451 1 0% S 10 1266208K 26996K fg u0_a5 com.android.dialer
2523 1 0% S 15 1277404K 34016K fg u0_a29 com.android.email
2543 0 0% S 11 1267476K 27588K fg u0_a31 com.android.exchange
2707 1 0% S 14 1399472K 54872K fg u0_a8 com.google.android.gms.unstable
2820 1 0% S 1 4084K 1476K fg root /system/bin/sh
1837 0 0% S 12 1273700K 37440K fg u0_a35 com.android.inputmethod.latin
1859 0 0% S 33 1428252K 79508K fg u0_a8 com.google.android.gms.persistent

Entries for system services,


processes, or daemons are missing
because no read access to their
/proc entries in this context!
59
Protection by SELinux on Android (Examples)

• Tighter controls which processes/apps can read/write where on file-system


or other processes. For instance:
− write to /system only allowed to recovery, rootfs can never be written, no
execute to files outside of the rootfs or /system partition
− Ptrace disallowed for almost all types; init process and keystore can never
be ptraced; app-to-app ptrace disallowed
− Installd or system_server can only write the files necessary for operation,
not the entire filesystem anymore, including keystore, drm, etc
− Removing access to app data and sdcard by system daemons

Source: Stephen Smalley. “Protecting the Android TCB with SELinux”. Linux Security Summit’14
60 Source: Stephen Smalley. “SELinux in Android Lollipop and Marshmallow”. Linux Security Summit’15
Protection by SELinux on Android (Examples)

• Protecting system services:


− Preventing malicious symlink attacks (no reading symlinks created by
apps or shell), preventing use of sockets by apps or shell
− All system services run in confined types (least privilege)
• Protecting kernel. For instance:
− No type can map low memory or read/write /dev/kmem or /dev/mem
− Only init can reload SELinux policy, no type can switch SELinux to
permissive mode (=allow everything, log access)
• USOM:
− Keystore checks type of caller for requests; re-enforce the Chrome
sandbox; lockdown Binder service manager

Source: Stephen Smalley. “Protecting the Android TCB with SELinux”. Linux Security Summit’14
61 Source: Stephen Smalley. “SELinux in Android Lollipop and Marshmallow”. Linux Security Summit’15
Protection by SELinux on Android (Case-study)

• setuid() vulnerability of Zygote:


− Zygote did not check setuid() failure, allowed apps to retain root UID ⇒
RageAgainstTheCage (Zygote) / Zimperlich exploit
• Zimperlich:
− Fork repeatedly until RLIMIT_NPROC for app UID reached
− Next setuid() fails, the app continues with root UID
• SELinux mitigation:
− No mitigation against failed setuid() handling
− But the app’s SELinux type does not change with failed setuid(), the app
remains in its restricted SELinux domain untrusted_app

Source: Stephen Smalley. “The Case for SELinux: Enhanced (SE) ANdroid”. Android Builder Summit’12
62
Problem: Least privilege policy

• Hard problem: Develop a least privilege policy


− Ideal:
All benign operations allowed; no malicious operation permitted
− Policy development can be error prone and needs lengthy refinements
(using audit logs from devices)
− Problem: Accept denied benign operations while preventing all
malicious operations
− Result: Benign apps/services might fail due to denied access
− Problem: Coarser allow rules that allow more operations
− Result: Violation of least privilege
− If denied access was logged: How to distinguish benign from
malicious denied operations?
− Only benign operations should be allowed in refined policy

63
Research insights: ML-based Audit SELinux logs [149]

• Machine learning to classify audit logs


− Results can be used to refine the SELinux policy
• Example: 1.3M access logs from Samsung devices in 2014

64
Research insights: Impact of vendor customizations [188]

• Vendor customization can compromise the SELinux policy

65
SELinux as Reference Monitor

• Non-bypassable
− Part of the LSM architecture inside the Linux kernel
− Processes are not able to access kernel space resources (files, etc.)
without going through the LSM hooks

• Tamperproof
− Depends on the integrity of the kernel
− Kernel exploits exist
− What is the trusted computing base of SELinux policy enforcement?
− User-space processes enforcing policies (USOMs)
− Most importantly: Linux kernel

66
Problem of critical system exploits [126,130]

• Critical vulnerabilities on Android:

and more recent ones (Quadrooter,


Stagefright, Dirty Cow, af_packet.c race
condition…)
AOSP version Linux kernel
4.4 Kit Kat 3.10
5.x Lollipop 3.16.1 Vendors might deviate
6.x Marshmallow 3.18.10 (before Android 8) or
7.x Nougat 4.4.1 customize
8.x Oreo 4.4 / 4.9
9.x Pie 4.4 / 4.9 / 4.14
10 4.9 / 4.14 / 4.19
11 4.14 / 4.19
Source: https://www.statista.com/statistics/271774/share-of-android-platforms-
67
on-mobile-devices-with-android-os/
Attacking SELinux

• The trusted computing base of SELinux policy enforcement:


− User-space processes enforcing policies (USOMs)
− Most importantly: Linux kernel

• Attacking SELinux by attacking the kernel


− Kernel exploits: Old and unpatched kernels are vulnerable targets
− OS updates not yet frequent enough to provide sufficient protection
(→ fragmentation problem)
− e.g., large root provider services specifically craft their kernel exploits
to not only change the UID but also the SELinux type in order gain
“real root” privileges

68
Root exploits and Permissions

• Root processes are constrained by SELinux type enforcement for accessing


low-level resources
• What about permission enforcement within the application framework?
− <AOSP>/frameworks/base/core/java/android/app/ActivityManager.java

public static int checkComponentPermission(String permission, int uid, int owningUid,


boolean exported) {
// Root, system server get to do everything.
final int appId = UserHandle.getAppId(uid);
if (appId == Process.ROOT_UID || appId == Process.SYSTEM_UID) {
return PackageManager.PERMISSION_GRANTED;
}

}

− The protection level of the permission does not matter

69
Research insights: FlaskDroid [170]

• Extends type enforcement into


application framework
− Kernel alone cannot implement
rules that cover ICC (e.g., two-hop
Intent delivery)
• Dedicated user space security server
− Extensions to type enforcement
specifically to the middleware
semantics and to allow more
dynamic, context-aware policies

70
Research insights: SEApp

• Allows apps to assign custom SELinux types to their processes (e.g.,


components in their own processes) and home directory files/folders
− Use SELinux PEP in Binder module: Control IPC to system services

71

You might also like