Hack An Android App Finding Forensic Artifacts
Hack An Android App Finding Forensic Artifacts
raywenderlich.com/3419415-hack-an-android-app-finding-forensic-artifacts
So you’ve just completed your app and you’re ready to release it. However, you’re storing
some user credentials and some code you want to keep secret, and you’re not sure if your
app is secure enough.
How can you check? It’s time to take a look from the outside to see what vulnerabilities are
lurking, as you learn how to hack an Android app. So put on your forensic examiner’s hat!
The purpose of this tutorial is to help you become a security-conscious app developer. It’s
1/31
also an introduction for anyone interested in pursuing the area of mobile forensics.
Since dealing with a variety of devices is a tutorial in and of itself, you’ll use the Pixel XL
API Q Emulator to start with the basics.
Note: This tutorial assumes that you’re already familiar with the basics of Android
development and Android Studio. If Android development is new to you, first read through
the Beginning Android Development and Kotlin for Android tutorials.
Getting Started
Download and unzip the materials for this tutorial using the Download Materials button at
the top or bottom of this page. You’ll notice this tutorial only has a final project. That’s
because the scenario is that you’ve finished your project and you’re now focused on
extracting the data.
Open and run the starter project in Android Studio 3.3.0 or higher to see what you’ll work
with.
You’ll use a sample app called Snitcher, which lets users send anonymous tips about crimes
to law enforcement. OK, it doesn’t really send the information to law enforcement. But this
kind of app gives you plenty of motivation for privacy.
You’ll see a simple sign-up screen. Once you enter a password and choose SIGN UP, you’ll
need to enter that password when you launch the app in the future.
2/31
After that step, you’ll get a list of wrongdoings
to report. Oh wait, all the reports are for
animals! Well, who doesn’t want to protect a
furry friend from harm?
3/31
Extracting Data From a Real Device
4/31
You’ll start off with an example walk-
through for a real device. This will give
you a sense of the process and the
complications you’ll encounter along the
way.
adb shell
pm list packages -f
exit
1. The first command starts the adb shell, letting you run commands on the device.
2. The second line lists the installed packages on the device.
You should see a long list of installed packages on the device. If you’ve installed the
Snitcher app on your device, you should see a similar line in your output:
package:/data/app/com.raywenderlich.android.snitcher-
ei0L3AJk3xo5M3Gs9SVuTQ==/base.apk=com.raywenderlich.android.snitcher
It’s easy to retrieve data from apps that allow external install locations or that save data to
public areas, but in most cases, you’ll need to get at the data that’s in the private storage
5/31
area.
On some versions, you can access the private storage of debuggable versions of the app:
adb shell
adb exec-out run-as com.raywenderlich.android.snitcher cat databases/reports-db > reports-db
Here, you’re using run-as to execute commands with the same permissions as the app.
If that doesn’t work, you can also try to change file permissions or use the adb pull
command:
adb shell
run-as com.raywenderlich.android.snitcher
chmod 666 databases/reports-db
exit
cp /data/data/com.raywenderlich.android.snitcher/databases/reports-db /sdcard/
run-as com.raywenderlich.android.snitcher
chmod 600 databases/reports-db
adb pull /sdcard/reports-db .
And just like that, you’ve got a copy of an app’s local database on your computer.
But many devices disable these features for security reasons. If that’s the case, the next
thing you’d look to is a device backup. Device backups can include the APKs as well as the
private data for each app:
Here, you use the backup command to write an archive of the app and its data to the
working directory of your computer. The default filename is backup.adb.
Feel free to experiment and do research if you’re comfortable doing so on a test device. But
for the sake of time and safety, this tutorial will use the Android Emulator to skip to the
next step.
6/31
Extracting Data From the Emulator
Now that you have access to the file system of a device, it’s time to extract the data. Build
and run the app in the emulator, then go ahead and make a report.
On the report screen, fill in the details and tap the SEND REPORT button. In Android
Studio, select View ▸ Tool Windows ▸ Device File Explorer then choose Emulator
Pixel_XL_API_Q in the drop-down:
–
Here are
some
locations
where
Android
keeps
important data:
7/31
WhatsApp stores their messages in /databases/msgstore.db. Forensic companies take
advantage of that to backup the database and recover messages.
Knowing where apps store information also makes it easy to look for artifacts or to
undelete data. In the case of WhatsApp, forensic examiners have been able to recover
deleted messages that their users thought were gone for good.
To try your hand at saving Snitcher’s data to your device, navigate to /data/data. You’ll see
a list of all the packages:
Find the
com.raywenderlich.android.snitcher entry:
8/31
Right
click on
it and
choose
Save
As…:
Save
the file
to a
location
on your
computer and open it to view its contents. You’ll see important directories such as:
shared_prefs
files
databases
9/31
Examining SharedPreferences
Open the MyPrefs.xml file inside the shared_prefs folder. You’ll notice at least one entry
with a timestamp. Score!
Timestamps are very important to any kind of forensic or criminal investigation, since they
give you evidence of the user doing something at a particular time!
Android serializes objects in a specific record format, but you can still search for strings
using the strings utility, which is already included in Mac and Linux.
In the terminal, type strings and a space followed by the path to the users.dat file. After
you press space, you can drag the users.dat file into the terminal window to populate the
path. Press enter and you’ll get an output of items.
10/31
If you are using Windows, you can download the strings utility.
Upon looking at the output, you’ll see extrat followed by nameq and passwordq. You can
use that order to deduce that you’re looking at the extra info about each account, followed
by a login name and password!
There are a
few other tools
that you can
use to help
extract data:
A hex
and text
viewer
comes in
handy to
search
In the movies, forensic investigators show up to crime scenes drinking martinis and
leaping from trains while fighting villains. In reality, forensic investigators spend much of
their time peering into a text viewer. You could still try leaping from trains while peering
into a text viewer. :]
Next, navigate to the databases folder. It looks like there are some files in there; here’s how
to examine them.
Analyzing Databases
Now that you’ve downloaded the database files, head over to the sqlitebrowser homepage.
Click the download button at the top of the page. Choose your OS, download the file and
install the program. Launch DB Browser and choose the Open Database button at the top:
11/31
In the folder you downloaded via the Device File Explorer, choose the reports-db file from
the databases directory.
If it doesn’t show up in the list, choose All files from the Filter option at the bottom. If
there’s no reports-db file, look for the reports-master-db file:
12/31
Assuming everything worked, you should see the database tables show up in the Database
Structure tab. Click the Browse Data tab:
13/31
Now click the Table selector right under the tab and choose reports:
14/31
You’ll see all the secret reports!
15/31
This is an example of why you should never store the user’s sensitive information in
plaintext. A much better solution is to encrypt the data before you store it.
16/31
The data you’ve recovered so far exists inside a saved SQLite block. For SQLite, there are
unallocated blocks and free blocks. When you delete something from the database, SQLite
doesn’t overwrite the block immediately. Instead, it simply marks the block as free. To read
that data block, you’d use a hex viewer that also displays ASCII to search for keywords that
may still be present.
Experts call the process of finding and extracting data when you don’t have access to the
file structure file carving. Sometimes, searching for a particular string of content helps.
Other times, you’d look for the header of a known file format.
For example, say you’re searching deleted data for images. In the JPEG format, the first
two bytes and last two bytes are always FF D8 and FF D9. So searching for those headers
can help you identify the images.
Reverse Engineering
So now you’ve looked at all the user data inside the app, but the investigation doesn’t stop
there. You can get a lot of information by analyzing the app itself. This includes the code
and files Android Studio bundles with the APK.
When you build your app, Android Studio produces an APK file. This is like a zip file that
has a structure of Java’s jar archives. Inside the archive are resources along with a DEX file.
DEX stands for Dalvik Executable.
When Android Studio compiles your app, it puts the code into that DEX file and names it
classes.dex. It contains bytecode, an intermediary set of instructions that a Java Virtual
Machine (JVM) runs or that ART (the Android Runtime) later converts to native code. So
what are JVM and ART?
Apps run on a Java Virtual Machine. Traditionally on Android, the JVM was Dalvik. In
recent years, Android has replaced Dalvik with ART for performance reasons. ART
converts the DEX into native code by running the Dex2Oat tool to create a native ELF
binary.
17/31
So now you’re thinking, because this is a Kotlin app, reverse engineering it must be
complex.
But the good news is that like Java, Kotlin is a JVM language. While Kotlin has its own
syntax, the kotlinc compiler transforms the code into a DEX file that contains Java
bytecode. Because kotlinc compiles Kotlin to the same bytecode as Java, most of the
reverse engineering tools are the same as for apps built in Java!
Understanding Bytecode
Open the ReportDetailActivity file in Android Studio. Find sendReportPressed() at the
bottom.
Go to the top of the file and note that you’ve added the authorization details inside the
companion object:
18/31
You might think this is fine, because Android Studio compiles the code and the end user
never sees it. However, any forensic investigators can easily find and use these
authorization details to steal data. You can even use Android studio to find it!
Android Studio includes a tool called the APK Analyzer, which lets you inspect your
finalized app. It presents a view with a breakdown of what’s inside your bundle. It also
allows you to view the bytecode of your app.
Launch the analyzer by selecting Build ▸ Analyze APK to open a dialog for your filesystem.
If necessary, navigate to the debug folder snitcher-final/app/build/outputs/apk/debug.
Select the app-debug.apk file and click OK to open the APK Analyzer:
Note: If the apk file is missing, choose Build ▸ Build Bundle(s) / APK(s) ▸ Build APK(s) to
generate it.
19/31
In the APK Analyzer, select the classes.dex file. Navigate to com ▸ raywenderlich ▸ android
▸ snitcher:
20/31
You’ll see the #static fields section:
21/31
Notice that the secret token is clearly displayed! This allows someone to impersonate you
making the network API call.
Attackers also reverse engineer apps in hopes of patching or hooking security checks out of
the code.
A good example is when a feature is only available with a paid subscription or after a user
achieves a level in a game. By reverse engineering the app, the hacker can find ways to
access those levels without having to go through the security checks.
Sometimes, hackers reverse engineer apps to steal intellectual property or to clone the app.
Or they might want to abuse a private API.
22/31
This is why you should never store sensitive API keys, tokens or passwords anywhere in the
APK. Instead, have those items sent to the app encrypted upon authentication.
As long as you’re able to get ahold of an APK, whether by using the methods you previously
learned or by downloading an APK from a site like APKMirror, you can reverse engineer
the code without having the Android Studio project.
ApkTool will reverse engineer the entire Android package back to a workable form,
including all resources and original source code. There are even online versions that will
do this.
smali/baksmali is a set of tools to transform bytecode into another intermediate, but more
readable, language. From there, you can convert the code back into Java.
Android Asset Packaging Tools can dump the Android Manifest file.
You can use AXMLPrinter2 to parse Android binary XML formats.
Use Dex2Jar to convert a DEX file to a standard Java CLASS file.
You can get all the class names and most source code by opening a jar folder in JD-
GUI.
Dextra supports ART and OAT.
Jadx lets you browse decompiled DEX code. It also decompiles most of the entire
project.
JAD will convert Java Class files back to source files.
As you can see, it’s relatively easy for anyone to do this. That’s why it’s also a good idea to
rename sensitive methods, such as setUserAuthenticated() , with something more
innocent-sounding.
Obfuscating Code
Developers use obfuscation to hide or obscure proprietary logic or secret algorithms.
Sometimes, developers apply manual obfuscation like string splitting, dummy code,
disguising the names of methods or using reflection to muddy the app flow.
Check out the Getting Started With ProGuard tutorial to learn how to obfuscate your code.
There is a trade-off between acquiring access and altering part of the device that secures it.
Even so, almost all solutions for obtaining access to a locked device involve rooting it.
There are many tools to root a device, such as OneClickRoot, KingoRoot and
SuperUserDownload.
Rooting usually involves flashing a partition on the device, such as a custom recovery
image. Some examples are twrp.me or ClockworkMod Recovery.
These tools don’t work if the manufacturer has locked the boot loader. A locked boot loader
prevents anyone from modifying the firmware.
Usually, the manufacturer signs the image with a private key. That way, you can’t flash
unsigned code onto the device. There are OEM bootloader unlock commands, but they
perform a wipe of the device.
To perform a root with a locked bootloader, you’ll need to exploit a security vulnerability in
the OS. This is also true for iOS, where most of the jailbreaks stem from a known exploit.
24/31
You can often find help with these types of things at XDA-Developers.
g2root-kmod
mempodroid
dirtycow
gingerbreak
While you don’t want to alter evidence, on some devices you can bypass the lock screen by
deleting the files. You can also experiment with LiME to extract passwords and keys from
memory.
To learn how to secure that data, continue on to the Encryption Tutorial For Android and
App Hardening Tutorial For Android.
Code protection tools like DexGuard offer obfuscation and encrypt the classes and strings
as well as assets and resource files. DexGuard also provides app integrity checking which is
important for keeping malicious users out of your app.
Reverse engineers also look at the data an app sends and receives over the network to
understand how the app works. To learn about how that works and how to secure that data,
see the Securing Network Data tutorial.
IDA Pro: You can disassemble and debug Dalvik code since IDA Pro v6.1. IDA works
well because of its support for scripting and because it has a graph view which
unwinds the flow of the app. There are also lots of scripts people write to assist in
unwinding obfuscated code.
JEB: JEB can understand ARM and ELF formats. It has a powerful UI for both
Dalvik and native code.
Last but not least, check out Drozer. It allows you to assume the role of an Android app and
interact with other apps. One of the modules in Drozer, app.package.manifest, will parse
the manifest file and display it on-screen.
If you have any questions, feel free to ask in the discussion below.
raywenderlich.com Weekly
The raywenderlich.com newsletter is the easiest way to stay up-to-date on everything you
need to know as a mobile developer.
Get a weekly digest of our tutorials and courses, and receive a free in-depth email course as
a bonus!
Average Rating
4.7/5
26/31
Learn more
27/31
Sending Push Notifications With Vapor Server-Side Swift
Adding push notifications to your app enriches the user experience by delivering data to
their devices when it becomes available. In this article, you’ll learn how to send push
notifications with Vapor.
28/31
New Mastering Git with Chris Belanger – Podcast S10 E11 iOS & Swift
On this episode, Chris Belanger walks us through the wonderful world of Git. After, Dru
looks back on WWDC(Virtual)2020.
29/31
New Apple Augmented Reality by Tutorials: New Chapters Available! iOS & Swift
We’re excited to announce that Apple Augmented Reality by Tutorials has three new
chapters available on RealityKit, Face Tracking and Facial Blending!
30/31
New RxJava Filtering Operators Android & Kotlin
In this tutorial, you will learn about a group of powerful RxJava operators that will allow
you to work only with the data you require at a certain step of the data transformation
process: the RxJava Filtering Operators.
31/31