The Art of Defense
How vulnerabilities help shape security features and mitigations inAndroid

Nick Kralevich
August 4th, 2016

$ whoami●

Nick Kralevich●Android Security since December 2009●

Android Platform Security Team Lead

Proprietary + Confidential

AgendaQuick overview of the Android Security Architecture
Vulnerabilities that affected Android and Android’s response
Where do we go from here?

Proprietary + ConfidentialProprietary + Confidential

Android Security Ecosystem

Proprietary + ConfidentialGoogle Play
Unknown
SourcesWarning

InstallConfirmation
Verify Apps
Consent
Verify Apps
Warning
Runtime
Security ChecksSandbox &permissions

Google PlayApps

Knowledge
PHA or not
Best practices

Install Apps

Application Analysis

Apps

StaticDynamic
Reputation
Etc.

Knowledge
PHA or not

Other Google
Services
SearchDriveAds
Etc.
Knowledge
Risk Signal

App X

App Y
Data
Rare Apps

ChromeApp Z

Smart Lock
Device Manager

Attest API

Safe Browsing
Android
App Sandbox
Verified Boot
Encryption
Etc.

Data
App installs
InstallSource

Knowledge
PHA or Not

Protections
Warnings
Configuration changes
Etc

SafetyNet
App Install Checks

Verify Apps

Device Data
EventsMeasurements
Configurations
Etc.

SafetyNet
Analysis
Exploit Detection
ACE
SIC
Etc.

Learn More●https://source.android.com/security/●

Android Security 2015 Annual Report○●https://security.googleblog.com/2016/04/android-security-2015-annual-report.html

Android Security State of the Union○

Black Hat 2015 - Adrian Ludwig○

https://goo.gl/JrncdFProprietary + Confidential

Android Platform Overview

Proprietary + Confidential

High Level Overview
User 1

User 2

Google Play

Google Play

Google Security
Services

SafetyNet

Contacts

Game X

Contacts

Game Y

Verify Apps

Safe Browsing

EmailGame Y

EmailGame Z

DeviceManagerSmart LockSystemSystemSystemSystemSystemSystemSystemRootRootRootRoot

Root

Trust Zone
KernelHardware

Key Android Security Principles●Exploit Mitigation●Exploit Containment●Principle of Least Privilege●

Architectural Decomposition●Attack Surface Reduction●

Safe by design APIs●

Defense-in-depthProprietary + Confidential

Software Flaws

Proprietary + Confidential

PingPong Root (CVE-2015-3636)●

Public Disclosure○●

Presented at Black Hat 2015○●

oss-security

Wen Xu / @K33nTeam

Result: Kernel code execution

diff --git a/net/ipv4/ping.c b/net/ipv4/ping.c
index a93f260..05ff44b 100644--- a/net/ipv4/ping.c+++ b/net/ipv4/ping.c@@ -158,6 +158,7 @@ void ping_unhash(struct sock *sk)
if (sk_hashed(sk)) {write_lock_bh(&ping_table.lock);hlist_nulls_del(&sk->sk_nulls_node);+
sk_nulls_node_init(&sk->sk_nulls_node);
sock_put(sk);isk->inet_num = 0;
isk->inet_sport = 0;

https://www.blackhat.com/docs/us-15/materials/us-15-Xu-Ah-Universal-Android-Rooting-Is-Back.pdf

PingPong Root (CVE-2015-3636)●An attempt at security hardening made the vulnerable code reachable

commit be341cc348257a07c68bcbfdc526835d49283329
Author: Nick Kralevich <nnk@google.com>
Date:
Thu Feb 21 18:36:43 2013 -0800
init.rc: allow IPPROTO_ICMP support
Allow userspace programs to create IPPROTO_ICMP sockets.
This socket type allows an unprivileged program to safely
send ICMP_ECHO messages and receive the corresponding
ICMP_ECHOREPLY messages, without relying on raw sockets orsetuid programs.

PingPong Root (CVE-2015-3636)●First priority: Fix the bug!

●

Next step: How do we protect against similar bugs?

Solely fixing bugs isn’t
acceptable.

PingPong Root - Mitigation●Exploit Mitigation - Move LIST_POINTER out of user-space

From: Jeff Vander Stoep <jeffv@google.com>
Date: Tue, 18 Aug 2015 20:50:10 +0100
Subject: [PATCH] arm64: kconfig: Move LIST_POISON to a safe value
Move the poison pointer offset to 0xdead000000000000, a
recognized value that is not mappable by user-space exploits.
Cc: <stable@vger.kernel.org>
Acked-by: Catalin Marinas <catalin.marinas@arm.com>
Signed-off-by: Thierry Strudel <tstrudel@google.com>
Signed-off-by: Will Deacon <will.deacon@arm.com>--arch/arm64/Kconfig | 4 ++++
1 file changed, 4 insertions(+)

PingPong Root - Mitigations●Disallow access to unusual socketfamilies○●

Bluetooth socket family,
AF_MSM_IPC, etc…

○

Backported as CVE-2016-3762.
Android Security Bulletin—July
2016○

Other common socket families
were blocked in previous Androidversions.

Whitelist allowable ioctls# Restrict socket ioctls. Either# 1. disallow privileged ioctls,# 2. disallow the ioctl permission, or# 3. disallow the socket class.
neverallowxperm untrusted_app domain:{ rawip_socket
tcp_socket udp_socket } ioctl priv_sock_ioctls;
neverallow untrusted_app *:{ netlink_route_socket
netlink_selinux_socket } ioctl;
neverallow untrusted_app *:{socket netlink_socket packet_socket key_socket
appletalk_socket netlink_firewall_socket
netlink_tcpdiag_socket netlink_nflog_socket
netlink_xfrm_socket netlink_audit_socket
netlink_ip6fw_socket
netlink_dnrt_socket netlink_kobject_uevent_socket
tun_socket netlink_iscsi_socket
netlink_fib_lookup_socket netlink_connector_socket
netlink_netfilter_socket netlink_generic_socket
netlink_scsitransport_socket
netlink_rdma_socket netlink_crypto_socket} *;PingPong Root - TL;DR

PingPong Root: 1 bug, 3 mitigations!

Learn more: http://android-developers.blogspot.com/2016/07/protecting-android-with-more-linux.html

PingPong Root - Mitigation●The mitigations are effective at blocking or reducing the severity of a number of unrelated bugs○

CVE-2016-2059 - Linux IPC router binding any port as a control port○

CVE-2015-6642 - Security Vulnerability in AF_MSM_IPC socket:
IPC_ROUTER_IOCTL_LOOKUP_SERVER ioctl leaks kernel heap memory to userspace○

CVE-2016-2474 - Security Vulnerability - Nexus 5x wlan driver stack overflow○etc...

Stagefright●

Series of bugs reported by Joshua “jduck” Drake●

Private disclosure with embargo●

Public disclosure via NPR / blog post / PR / ads / etc...

●

For this presentation, focusing on CVE-2015-3824○

MP4 'tx3g' Integer Overflow

https://www.blackhat.com/docs/us-15/materials/us-15-Drake-Stagefright-Scary-Code-In-The-Heart-Of-Android.pdf

Stagefright - A “successful failure”●

Monthly patching cycle●

Public security bulletins●No evidence of malicious exploitation●

Exploit mitigations (ASLR, etc) worked as intended and bought time●

Device diversity complicated exploitation and bought time

●Exploit containment (UID sandbox, SELinux) forced vulnerability chaining and bought time●

Widespread patch distribution: 57-89% of population [1]●Significant architectural improvements (more later)●

Enhanced visibility of Android Vulnerability Rewards Program[1] Source: Zimperium.com, March 22nd, 2016

Monthly Security Updates to Flagship Android Models (Last 3 months)
OEMSamsung

LGE

Huawei
MotorolaNexusModel

July 2016

June 2016

May 2016

Galaxy S7 Edge

111Galaxy S7111Galaxy S6 Edge+

111Galaxy S6 Edge

111Galaxy S6111Galaxy Note5

111Galaxy Note4

1

11Galaxy A5(2016)1

11Galaxy S6 Active

111Galaxy Note Edge

111Galaxy S7 Active

1V10

111LG G5

1

1

1LG G4

1

1

1LG G3

1

1

1P9

1

1

1P8

1

1Mate S

11

Mate 811

1Moto X Style

1Moto X PlayNexus 9111Nexus 6P

111Nexus 61

11Nexus 5X111Nexus 511

1

Note: Based on active user devices that have installed updates as of August 3, 2016. Updates may not be available for all
versions of these devices, and/or in all regions. Please contact your OEM for details about updates for specific devices.

Stagefright●●Mediaserver architected for containment○“Android: Securing a Mobile
Platform from the Ground Up” (RichCannings, Usenix Security 2009)○Charlie Miller - oCERT-2009-002

Stagefright exploit was contained○●

Required vulnerability chaining

Mediaserver grew up. More features =>more capabilities

https://twitter.com/jduck/status/756197298355318784

Stagefright●First Priority: Fix the bugs!
7 patches provided by vulnerability reporter (yay!)○@@ -1948,6 +1948,9 @@ status_t MPEG4Extractor::parseChunk(off64_t *offset, int depth) {size = 0;}+++

if (SIZE_MAX - chunk_size <= size)
return ERROR_MALFORMED;
uint8_t *buffer = new (std::nothrow) uint8_t[size + chunk_size];if (buffer == NULL) {return ERROR_MALFORMED;

Stagefright●

Unfortunately, fix was incomplete: CVE-2015-3864

CVE-2015-3824+++if (SIZE_MAX - chunk_size <= size)
return ERROR_MALFORMED;
uint8_t *buffer = new (std::nothrow) uint8_t[size + chunk_size];if (buffer == NULL) {return ERROR_MALFORMED;

size = 0;}

CVE-2015-3864+

if (SIZE_MAX - chunk_size <= size) {if ((chunk_size > SIZE_MAX) || (SIZE_MAX - chunk_size <= size)) {return ERROR_MALFORMED;}

Stagefright

Solely fixing bugs isn’t
acceptable.

mediaserver - Architectural Improvements●Mediaserver refactoring●Integer overflow protections●

ASLR enhancements○Increase kernel randomness○

Link time randomization●Mediaserver seccomp●Remove mediaserver execmem

Android M - Services per process

Android N - Services per process

MediaServer

AudioServer

MediaServer

AudioFlinger
AudioPolicyService
CameraService
MediaPlayerService
RadioService
ResourceManagerService
SoundTriggerHwService

AudioFlinger
AudioPolicyService
RadioService
SoundHwTrigger

MediaPlayingService
ResourceManagerService

MediaCodecService

MediaDrmServer

CodecService

MediaDrmService

CamerServer

ExtractorService

CameraService

ExtractorService

Android M - Capabilities per process

Android N - Capabilities per process

MediaServer

AudioServer

MediaServer

Audio devices
Bluetooth
Camera Device
Custom Vendor Drivers
DRM hardware
FM RadioGPU
IPC connection to Camera daemon
mmap executable memory
Network sockets
Read access to app-provided files
Read access to conf files
Read/Write access to media
Secure storage
Sensor Hub connection
Sound Trigger Devices

Audio Devices
Bluetooth
Custom vendor drivers
FM radio
Read/Write access to media

GPUNetwork Sockets
Read access to app-provided
files
Read access to conf files

MediaCodecService

MediaDrmServer

GPUDRM hardware
Mmap executable memory
Network socketsSecure storage

CamerServer

ExtractorService

Camera DeviceGPU
IPC connections to Camera
daemonSensor Hub Connection

Nonemediaserver - Refactoring results●

Vastly improved architectural decomposition●

Vastly improved separation of privileges●

Riskiest code moved to strongly sandboxed process●

Containment model significantly more robust

Everyone is safer!

Stagefright - Integer Overflow Protections●

Majority of stagefright bugs were integer overflow●

In C & C++:○For unsigned values: the result is taken modulo 2bits○For signed values: the result is undefined

UBSan to the rescue!

Stagefright before patch

Stagefright before patch v1, sanitizedStagefright after patch v1, sanitizedlibstagefright with UBSan●In Summary:○

UBSan with original patch: no integer overflow, stops exploit!

○

UBSan with no patch: no integer overflow, stops exploit!

Learn More: https://android-developers.blogspot.com/2016/05/hardening-media-stack.html

ASLR Enhancements

ASLR Patch #1 - Increased randomness from kernel
commit d07e22597d1d355829b7b18ac19afa912cf758d1
Author: Daniel Cashman <dcashman@google.com>
Date:
Thu Jan 14 15:19:53 2016 -0800
mm: mmap: add new /proc tunable for mmap_base ASLR
[deleted]
Concretely, the attack was against the mediaserver process, which waslimited to respawning every 5 seconds, on an arm device. The hard-coded
8 bits used resulted in an average expected success rate of defeating
the mmap ASLR after just over 10 minutes (128 tries at 5 seconds apiece). With this patch, and an accompanying increase in the entropy
value to 16 bits, the same attack would take an average expected time ofover 45 hours (32768 tries), which makes it both less feasible and more
likely to be noticed.

https://lwn.net/Articles/667790/

ASLR Patch #2 - Library Load Order Randomization●

Compliments and enhances
randomized mmap base address

Random baseaddress
1.so
2.so

Dependent shared libraries aremapped into memory in random
order

2.so

●

Effectiveness depends on numberof shared library dependencies

3.so

1.so

4.so

4.so

●

No impact on initial executable nor
dynamic linker load●

https://android-review.googlesource.com/178130

3.soASLR Patch #3 - Random gap between *.so files●Random baseaddress

Checked in 15 days ago. :-)○Targeting future Android
release

1.so

1.so

2.so

●

Adds more gaps between sharedlibraries.

2.so

●

Allow a lot more compact CFI
shadow implementation

3.so
4.so

3.so
4.so

https://android-review.googlesource.com/248499

mediaserver: additionalchanges●

Remove “execmem”○●

open("/system/lib/libnetd_client.so",
O_RDONLY) = 3
mmap2(NULL, 12904, PROT_READ|PROT_EXEC,MAP_PRIVATE, 3, 0) = 0xb6d9f000
open("/data/data/com.foo.bar/libnetd_client.
so", O_RDONLY) = 4
mmap2(NULL, 12904, PROT_READ|PROT_EXEC,
MAP_PRIVATE|MAP_FIXED, 4, 0) = -1 EACCES(Permission denied)No anonymous executable memory○

No loading executable code fromoutside /system (not new in Nougat)○

Executable content can only comefrom dm-verity protected partitionseccomp enforcement

mmap2(NULL, 20,
PROT_READ|PROT_WRITE|PROT_EXEC,
MAP_PRIVATE|MAP_ANONYMOUS, 4, 0) = -1 EACCES(Permission denied)finit_module(5, "", 0) = ?
ERESTART_RESTARTBLOCK (Interrupted bysignal)--- SIGSYS {si_signo=SIGSYS,
si_code=SI_USER, si_pid=20745, si_uid=2000}--+++ killed by SIGSYS +++Bad system call

Stagefright - TL;DR

Stagefright: 7 mitigations!

Proprietary + Confidential

Data in Transit Protection

Proprietary + Confidential

Data In Transit Protection●●The network is not to be trusted.
○ This has always been true but is especially for mobile devices.
○ But you already know this.
Too much unencrypted trafficData In Transit Protection Marshmallow

StrictMode.VmPolicy policy =new StrictMode.VmPolicy.Builder().detectCleartextNetwork().penaltyDeath()

In order to help you accurately and easily
determine if your application is making cleartext
traffic in Marshmallow we added two newfeatures.
1.
2.

Strict mode cleartext detection to help you
while testing.
usesCleartextTraffic application manifest
attribute to block accidental regressionson user devices.

Note: These are not limited to HTTP/HTTPS.build();
StrictMode.setVmPolicy(policy);<application
android:usesCleartextTraffic="false" />Data In Transit Protection●●●The network is not safe
○ But you already know that
Too much unencrypted traffic
Too much badly encrypted traffic

https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=android+x.509

Badly Encrypted Traffic●What causes bad encryption bugs?
○ Code testing in non-production environments○ Third party libraries changing global state○ Insecure code samples online○ Connection to legacy servers

Badly Encrypted Traffic
Do not use these code samples!
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {public boolean verify(String hostname, SSLSession session) { return true; }});

SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[] {new X509TrustManager() {public void checkClientTrusted(X509Certificate[] chain, String authType) {}public void checkServerTrusted(X509Certificate[] chain, String authType) {}public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[]{}; } } }, null);HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());

Network Security Config
●
●
●
●

●
●

Customizing TLS through the current APIs is too error prone
Network Security Config: Safer and easier API
Fine grain blocking of insecure traffic in your app
Eliminate debugging-related code in your release build○ Connect to your development infrastructure without any code
○ Avoid writing custom code that removes security for debug builds and accidentally
shipping it
Limit the CAs you want to trust
Easy to configure cert pinningNetwork Security Config - Block insecure traffic<network-security-config><domain-config cleartextTrafficPermitted="false"><domain includeSubdomains="true">secure.example.com</domain></domain-config></network-security-config>

Network Security Config - Debug only CAs<network-security-config><debug-overrides><trust-anchors><certificates src="@raw/debug_cas"/></trust-anchors></debug-overrides></network-security-config>

Network Security Config - Pinning<network-security-config><domain-config><domain includeSubdomains="true">example.com</domain><pin-set expiration="2018-01-01"><pin digest="SHA-256">7HIpactkIAq2Y49orFOOQKurWxmmSFZhBCoQYcRhJ3Y=</pin><!-- backup pin --><pin digest="SHA-256">fwza0LRMXouZHRC8Ei+4PyuldPDcf3UKgO/04cDM1oE=</pin></pin-set></domain-config></network-security-config>

Data In Transit Protection - User Installed Certificates●●●

Question: How should user installed certificates be handled?
○ Opportunity to revisit old assumptions
App files/memory/processes are protected by default○ Why not network traffic?
Interest from nation states
https://www.eff.org/deeplinks/2015/12/kazakhstan-considers-plan-snoop-all-internet-trafficData In Transit Protection - User Installed Certificates●●

Most application developers unaware secure traffic can be intercepted
User installable certificates not commonly used

Applications targeting “Nougat” or greater no longer trust user installed certs bydefault.

Proprietary + Confidential

Where do we go from here?

Proprietary + Confidential

Languages●

Safe by design: As an industry, we need to move towards memory safe languages○ This includes sacred cows such as the Linux kernel
Bug root cause for all of Android (including kernel and other components)

Invest in Defense●

Invest in defenses: As an industry, we need to look beyond attacks and short term solutions, andinvest in architectural improvements in all these areas:● Exploit Mitigation● Exploit Containment● Principle of Least Privilege● Architectural Decomposition● Attack Surface Reduction● Safe by design APIs
● Defense-in-depthProprietary + Confidential

Black Hat Sound Bytes

Proprietary + Confidential

Black Hat Sound Bytes●Android has a robust, multi-layered defense designed to mitigate
and contain vulnerabilities.

●

Android is investing heavily in learning from vulnerabilities andapplying those lessons in new releases.

●Vulnerabilities will never go away, but they can be contained andmanaged.

THANK YOU
Nick Kralevich
nnk@google.com