SlideShare a Scribd company logo
Headline Verdana Bold
Reverse Engineering | Android Penetration Testing
13th August 2016
Samrat Das
Consultant |Cyber-Security Protection
Deloitte Touche Tohmatsu India LLP.
samratd@deloitte.com
www.deloitte.com
NULL MEET-MUMBAI
13th August , 2016
• Introduction to Reverse Engineering
• Why learn reverse engineering?
• Short intro to Reverse Engineering fundamentals and Assembly Language
• Reverse Engineering Windows executables
• What is Dalvik Virtual Machine? | DVM vs JVM
• Reverse Engineering Android Applications- Manual step by step
• Android Emulators
• Reverse engineering android on Windows
• Reverse engineering android on AppUse
• Components in Android Forensics
• Detect Backdoors in Android applications
• How are malicious Android Applications created?
• Proxying android traffic | Burp Suite
• Exploiting Content Provider | Intent Sniffing | Broadcast Receiver | Weak
cryptography
• Tools intro: Apk tool | JD-GUI | Dex2Jar | Drozer | Appuse
Contents
Decipher algorithms from exes, identify design construct and loopholes.
Retrieve source and origins of software for advanced analysis and
documentation
Inspect internal workings of an virus/ malware
What is reverse engineering?
Applications of RE:
• Security Auditing/Vulnerability Research
• Virus /malware analysis
- Software copy-protection removal (cracking)
- Analyzing binary executables for modifications and comparisons
- Cryptography and Encryption Research
There are two broad types in Operating Systems RE:-
1) User level debugging in RE
2) Kernel level debugging in RE
Some important concepts:
1) 32 bit and 64 bit applications:
2) Registers: Small set of data holding places that are part of a
computer processor.
A register may hold a computer instruction, a storage address, or any kind of
data 32-bit data registers: EAX, EBX, ECX, EDX. Lower halves of the 32-bit
registers can be used as four 16-bit data registers: AX, BX, CX and DX.
3) Disassembler:
Translates machine language into assembly language
4) Decompiler:
Takes as input an executable file, and attempts to create a high
level, compilable source file
5) Debugger:
Used to test and debug other programs.
6) Crackmes:
In simple words, a crack-me is a small program designed to test a
programmer's reverse engineering skills.
They are programmed by other reversers as a legal way to "crack"
software, since showing how to crack commercial software is illegal;
Crackmes are a great way to approach the same in legitimate
fashion.
Most of the commercial software is cracked in a similar
fashion, though with recent higher end software, the code is
usually “obfuscated”or “packed”to prevent reversing
(Security-measures applied as anti-reversing)
The CPU’s registers
The Intel 32-bit x86 registers:
ESPEAX
EBPEBX
ESIECX
EDIEDX
EIP
accumulator
base
counter
data
instruction pointer
destination index
source index
base pointer
stack pointer
Demo for windows exe reversing
Live Example:
•Using Crack-me utility
• Analysing
• Attacking
• Identifying
• Writing Secure
Application/ Mitigations
Mobile Penetration & Reverse Engineering
Methodology:
•Weak Server Side Controls
•Insecure Data Storage
•Insufficient Transport Layer Protection
•Unintended Data Leakage
•Poor Authorization and Authentication
•Broken Cryptography
•Client Side Injection
•Security Decisions Via Untrusted Inputs
•Improper Session Handling
•Lack of Binary Protections
Mobile OWASP Top 10 Checklist
Mobile Reverse Engineering
Android Reverse Engineering
What’s is an APK file? Anatomy of APK
13
Android applications are distributed in the form of a zipped archive with the file extension of
.apk, which stands for Android Package.
The official mime-type of an Android Package is application/vnd.android.package-archive.
These packages are nothing more than zip files containing the relevant compiled application
code, resources, and application metadata required to define a complete application.
Anatomy of Apk
A typical application package contains
Classes.dex (file)
AndroidManifest.xml (file)
META-INF (folder)
resources.arsc (file)
res (folder)
assets (folder)
lib (folder)
Assets—Allows the developer to place files in this directory that they would like
bundled with the application.
Res—Contains all the application activity layouts, images used, and any other
files in a structured way. These files are placed in the raw/ subdirectory.
Lib—Contains any native libraries that are bundled with the application. These
are split by architecture under this directory and loaded by the application
according to the detected CPU architecture; for example, x86, ARM, MIPS.
META-INF—This folder contains the certificate of the application and files that
hold an inventory list of all included files in the zip archive and their hashes.
classes.dex—The executable file containing the Dalvik bytecode of the
application. It is the actual code that will run on the Dalvik Virtual Machine.
AndroidManifest.xml—the manifest file containing all configuration
information about the application and defined security parameters. This will be
explored in detail later in this chapter.
Resources.asrc—Resources can be compiled into this file instead of being put
into the res folder. Also contains any application string
Steps: Android reverse engineering includes five steps:
1.Extraction
2.Decoding
3.Modifying
4.Encoding and
5.Packing
1. Extraction
Separating an .apk file into multiple files.
2. Decoding
Converting the .dex, dalvik bytecode into java class files, baksmali
files
3. Modification
Altering the application bytecode, AndroidManifest.xml, application
assets, and resources.
Null Mumbai Meet_Android Reverse Engineering by Samrat Das
4.Encoding
1. Modified .xml files must be covered back into their binary formats.
2.New classes.dex are created from the modified .smali files.
3.Assembled directory is produced with all .smali files into a single .dex file.
5. Packing
All application files such as the assembled .dex files, binary .xml files, and
application assets, must be stored in a Zip archive.
The process to sign an .apk file is based on the JAR signing process.
The jarsigner utility is used to sign .apk files with RSA certificates.
The packing step aligns the contents of the .apk file performed with the zipalign
utility.
•Some exploitatation / reverse engineering tools for android
•Dex2jar
•Java decompiler
•Apktool
•Apk Analyser
•Drozer
Apktool Alternate : Virtuous Ten Studio (VTS) GUI Tool
The main advantage of Apktool over JD-GUI, recompile it back using
Apktool, it will recompile perfectly and will generate a new .apk file.
Drozer
drozer is an Android assessment tool created to test each aspect of an Android application in a
dynamic way.
Finding vulnerabilities in applications or devices—It allows you to assume the role of an
installed Android application
and interact with other apps and the underlying operating system in search of vulnerabilities.
Providing exploits and useful payloads for known vulnerabilities—It does this by building
malicious files or web pages that exploit known vulnerabilities to install drozer as a remote
administration tool.
How drozer Works
drozer is a distributed system that makes use of some key components:
Agent— A lightweight Android application that runs on the device or emulator being used for
testing. There are two versions of the agent, one that provides a user interface and embedded
server and another that does not contain a graphical interface and can
be used as a Remote Administration Tool on a compromised device.
Console—A command-line interface running on your computer that allows you to interact with
the device through the agent.
Server—Provides a central point where consoles and agents can rendezvous, and routes
sessions between them
20
Various components of android:
Activities: The visual screens which a user could interact with.
(buttons, images, TextView etc
Services: Components which run in the background
Broadcast Receivers: Receivers that listen to the incoming broadcast messages by the
Android system. Once they receive a broadcast message, a particular action could be
triggered depending on the predefined conditions.
Shared Preferences: Used by an application in order to save small sets of
data for the application. This data is stored inside a folder named shared_prefs. These small
datasets may include name value pairs such as the user's score in a game and login
credentials.
Intents: Components which are used to bind two or more different Android components
together.
Content Providers: Used to provide access to a structured set of data to be used by the
application. An application can access and query its own data or the data stored in the
phone using the Content Providers.
Things we need
Dex2Jar (https://sourceforge.net/projects/dex2jar/)
JD-GUI(https://github.com/java-decompiler/jd-gui)
APK-tool(https://ibotpeaches.github.io/Apktool/)
A intentionally vulnerable application for hands-on
(https://codeload.github.com/dineshshetty/Android-
InsecureBankv2/zip/master)
Demo for android reversing
Live Example:
•Decompiling a sample android application
Preliminary step of Conversion of Dex file to Jar file:
Open up dex2jar folder
In windows, select the d2j-dex2jar.bat file keeping the apk file
in the same folder for ease.
Alternatively, you can select the dex file directly obtained by
extracting the apk as zip, as show below
24
1) Once you use the d2j-dex2jar.bat InsecureBankv2-dex2jar.jar , the
following jar file will be created
Once you receive the Jar file, we can proceed for getting the
class files and get the source code for class files
Next step: Viewing class files from jar file:
26
1)Launch JD-GUI and import the jar file inside it
As you can see, we get the class files from where we can get idea
of the source code!
Null Mumbai Meet_Android Reverse Engineering by Samrat Das
The next step is getting to know the application further by going into the
resource files!
At this point, we can use the powerful apktool for analysing the apk.
Apktool has multiple switches and can be used for decompiling files as well as
recompiling them into modified versions.
d stands for decode
b stands for build
You can look for more info on
https://ibotpeaches.github.io/Apktool/documentation/
Here we will use the d option now to decode the apk and analyse its
contents.
Once you do this, we can see the following output:
As you can see here, we have got the different files of the apk, the sections of
which I have already describe above.
Analyzing manifest.xml file will give us the information of what all system level
access can the application gather. For example the above application’s
manifest.xml file gives:
As you can see above, the application and read your storage memory, write
data, send sms, read your contacts, as well as network state , call logs. From a
hacker’s point of view, backdoor the application and steal complete
information from the users phone!
We till now we have explored the analysis and code-deciphering of apk files,
lets see further what we can do.
Detecting Backdoors in Android App
Many a times, malicious developers leave malicious backdoors in applications, by
which they can get access to your machines, inspecting the code can give
you hints as well as the code by which they have done so. The same app
which we are inspecting allows us to use a backdoored credential to perform
a login! Let’s see:
Introduction to Appuse- VM
Creating infected version of the apps:
1. Decompile the application using apktool
2. Decompile the malicious application to generate the smali
files of the Java classes. Here, we
need to put all the malicious activities in the service.
Eg: We created a malicious service “malware.smali”
3.Copy the malware.smali file to the smali folder inside the
folder in which we have decompiled the legitimate app.
4.Change references of the package name in malware.smali to
the package name of the legitimate application.
Useful Hacking Tools
List of additional tools useful in Android Phone Testing:
 Android Debug Bridge
• A client-server program .It includes a client (that runs on the
system), a server handling the communication (also running on the
system), and a daemon running on the emulator and devices as a
background process.
Burp Suite
• We will use this in order to intercept and analyze the network traffic.
Anti-reverse engineering protection for android
http://proguard.sourceforge.net/
ProGuard is a free Java class file shrinker, optimizer, obfuscator,
and preverifier. It detects and removes unused classes, fields,
methods, and attributes.
It optimizes bytecode and removes unused instructions. It
renames the remaining classes, fields, and methods using short
meaningless names.
It makes much harder to read the decompiled code. For
example, "DescriptiveClassName.descriptiveMethodName()"
becomes "A.b()".
DexProtector is the protector and obfuscator for Android
platform. It helps you secure your Android applications and
Android libraries (AARs) against unauthorized or illegal use,
reverse engineering, and cracking.
https://dexprotector.com/ (trail)
Rooting Android
37
Rooting Objectives
A typical objective of rooting an Android device is so that you can put a su binary in a directory on the PATH (for example,
/system/bin or /system/xbin). The job of the su binary is to allow a user to switch security contexts and become another user,
including root
#include <stdio.h>
#include <unistd.h>
int main(int argc, char **argv)
{
if (setgid(0) || setuid(0))
fprintf(stderr, "su: permission deniedn");
else
{
char *args[argc + 1];
args[0] = "sh";
args[argc] = NULL;
int i;
for (i = 1; i < argc; i++)
args[i] = argv[i];
execv("/system/bin/sh", args);
}
} T
Using setuid(0) and setgid(0) to change to the root user’s context, which means that any application that executes su will
receive root context and no checks are performed or prompts shown to the user.
Using an Exploit
Android uses the Linux kernel and also contains code added by device manufacturers.
Like most code these implementations could
contain bugs. These bugs could be anything from a simple mistake in the permissions
of a particular file or driver code that does not
handle certain user input securely.
GINGERBREAK—EXPLOITING AOSP KERNEL CODE
The vulnerability exploited by Gingerbreak exists in the Volume Manager (vold) on
Android versions 2.2 (Froyo)—and 3.0 (Honeycomb).
Vold manages the mounting of external storage volumes on Android. The vulnerability
was an out-of-bounds array access that allowed the exploit author to overwrite entries
in the Global Offset Table (GOT) to trick the system into
executing a copy of the sh binary as root
http://c-skills.blogspot.com/2011/04/yummy-yummygingerbreak.html.
38
EXYNOS ABUSE—EXPLOITING CUSTOM DRIVERS
Device manufacturers sometimes have to include custom device drivers in order to interface
with included hardware. The standard of the code or configuration in some cases is not of the
highest quality and discovered vulnerabilities can be used to gain root access.
An exploit for an issue discovered in devices using exynos processors, such as the Samsung
Galaxy S3, appeared in the following forum post:
http://forum.xda-developers.com/showthread.php?t=2048511.
The forum post detailed that a block device located at /dev/exynos-mem allowed the mapping
of kernel memory into user space by any user.
The exploitation technique used was to patch a comparison made in the setresuid() function.
This comparison is normally cmp
r0, #0 and was altered to cmp r0,#1 as a result of having complete access to the memory
space, which meant that when
sysresuid(0) was called later on the code, access was granted to change to root context. This
exploit also elegantly bypassed
the kptr_restrict memory protection, which does not allow applications to read /proc/kallsyms
and obtain kernel pointers. It
did so by changing the enforcing flag of this check in live memory
39
Intent Sniffing
Intent sniffing is when a broadcast receiver can register to receive
broadcasts that may have been intended for other applications.
This is possible because some applications broadcast intents and do not
define a required permission that a broadcast receiver must
hold in order to receive the intent or do not provide a destination package
for the intent.
You can review the source code of an application in search of intents being
sent using the sendBroadcast() method and then register
a receiver that catches this information from a non-privileged application.
You can catch these intents in drozer using the
app.broadcast.sniff module.
40
Fragment Injection attack:
Smaller UI elements named fragments are present in android. A security researcher publicized a
vulnerability that affected all applications with exported activities that extend the PreferenceActivity class.
In the onCreate() method of the PreferenceActivity class, it was discovered to be retrieving an extra named
:android:show_fragment from the user-supplied bundle. This extra can be provided by the application that
sent the intent and the name of a fragment within the target application specified to be loaded.
This allows the loading of any chosen fragment within the activity, which may have only been used inside
non-exported activities under normal use.
All exported activities that extend PreferenceActivity and are running on Android 4.3 or prior are vulnerable.
Performing poor validation on the fragment name supplied to this method or simply returning true in this
method without performing any checks would still result in fragment injection attacks being possible.
41
Secure coding for ANDROID
42
Principle of Least Exposure
Application Components
An application should reduce its exported application components down to the
essentials. The fewer exported components, the
better. In the following application only its main activity is exported so that it can be
launched
Data Storage
If the storage of any application data is not absolutely necessary, simply don't store it.
This includes storing data in the application's
private data directory or on the SD card.
Interacting with Untrusted Sources
An application that retrieves information from the SD card, the Internet, Wi-Fi,
Bluetooth, or any other source that is not directly
under the control of the application should be scrutinized for authenticity.
Requesting Minimal Permissions
Request the fewest permissions necessary for your application to function
correctly. Performing a task in a way that does not require
an extra permission would generally be considered the most secure option. In
addition to this, requesting as few permissions as
possible helps put more security-minded users at ease.
Doing so also reduces the impact of someone exploiting your application.
Bundling Files Inside the APK
Before releasing your app to the world, take the time to unzip the APK and check
what is inside because you might find other files
unintentionally included inside your APK
Task Manager Snooping
Two configurations enable you to avoid having the contents of your application's activities from
appearing in the recent application
list: You can choose to show a blank screen in the Recent list, or remove the entry from the list
altogether. To make an activity show
as a blank screen, implement the following code inside the onCreate()method of the activity:
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
The FLAG_SECURE parameter ensures that the contents will not appear in screenshots.
Tapjacking
To ensure that performing tapjacking attacks on sensitive activities within your application is not
possible, you can apply attributes to
a View. You can set the following attribute in the layout file of your activity on each item that inherits
from a View:
android:filterTouchesWhenObscured="true"
Ensuring Secure Trust BoundariesIf your application contains a login screen or any other form of trust
boundary, then take care as to how it is handled. If your login
activity contains a way to start activities that were only intended for trusted users, the authentication
model of the application may
be defeated.
References: Mobile Hackers Handbook
Thankyou! -> Questions ?

More Related Content

PDF
Null 14 may_lesser_known_attacks_by_ninadsarang
PPTX
Fuzzing | Null OWASP Mumbai | 2016 June
PPTX
Drozer - An Android Application Security Tool
PPT
Reverse Engineering Android Application
PDF
Droidcon Greece '15 - Reverse Engineering in Android: Countermeasures and Tools
PPTX
Reverse engineering android apps
PPT
Steelcon 2015 Reverse-Engineering Obfuscated Android Applications
PDF
Android reverse engineering: understanding third-party applications. OWASP EU...
Null 14 may_lesser_known_attacks_by_ninadsarang
Fuzzing | Null OWASP Mumbai | 2016 June
Drozer - An Android Application Security Tool
Reverse Engineering Android Application
Droidcon Greece '15 - Reverse Engineering in Android: Countermeasures and Tools
Reverse engineering android apps
Steelcon 2015 Reverse-Engineering Obfuscated Android Applications
Android reverse engineering: understanding third-party applications. OWASP EU...

What's hot (20)

PDF
How to reverse engineer Android applications
PDF
Introduction to Dynamic Analysis of Android Application
PPTX
SSRF For Bug Bounties
PDF
Android reverse engineering - Analyzing skype
PDF
Improving DroidBox
PPT
IEEE Day 2013 - Reverse Engineering an Android Application
PDF
Effectiveness of AV in Detecting Web Application Backdoors
PDF
Learning by hacking - android application hacking tutorial
PDF
Reverse Engineering iOS apps
PPTX
Server Side Template Injection by Mandeep Jadon
PDF
(CISC 2013) Real-Time Record and Replay on Android for Malware Analysis
PDF
.Net Hijacking to Defend PowerShell BSidesSF2017
PDF
NIframer - CPanel IFrame Injector (Bash based) - Virus Bulletin Magazine
PDF
ProbeDroid - Crafting Your Own Dynamic Instrument Tool on Android for App Beh...
PDF
Continuous Integration: Live Static Analysis with Puma Scan
PPTX
Anti-Virus Evasion Techniques and Countermeasures
DOCX
[DOC] Java - Code Analysis using SonarQube
PDF
Breaking iOS Apps using Cycript
PDF
BlackHat 2014 Briefings - Exploiting Fundamental Weaknesses in Botnet C&C Pan...
PDF
The Hookshot: Runtime Exploitation
How to reverse engineer Android applications
Introduction to Dynamic Analysis of Android Application
SSRF For Bug Bounties
Android reverse engineering - Analyzing skype
Improving DroidBox
IEEE Day 2013 - Reverse Engineering an Android Application
Effectiveness of AV in Detecting Web Application Backdoors
Learning by hacking - android application hacking tutorial
Reverse Engineering iOS apps
Server Side Template Injection by Mandeep Jadon
(CISC 2013) Real-Time Record and Replay on Android for Malware Analysis
.Net Hijacking to Defend PowerShell BSidesSF2017
NIframer - CPanel IFrame Injector (Bash based) - Virus Bulletin Magazine
ProbeDroid - Crafting Your Own Dynamic Instrument Tool on Android for App Beh...
Continuous Integration: Live Static Analysis with Puma Scan
Anti-Virus Evasion Techniques and Countermeasures
[DOC] Java - Code Analysis using SonarQube
Breaking iOS Apps using Cycript
BlackHat 2014 Briefings - Exploiting Fundamental Weaknesses in Botnet C&C Pan...
The Hookshot: Runtime Exploitation
Ad

Viewers also liked (20)

PPTX
Seguridad en Android
PPTX
Analysis of database tampering
PDF
Basic concept cybersecurity
PPT
Basic knowledge of cyber security
PPT
CYBERCRIMES AND DUE DILIGENCE
PDF
Meetup6 microservices for the IoT
PPT
How web 2.0 is changing medicine
PPTX
Cyber Security of Power grids
PPT
Wireless
PPTX
Comp 107 cep 8
PPT
Elementary µprocessor tutorial
PPTX
Cybersecurity 2 cyber attacks
PDF
Smartphone based ADAS
PPT
Cyberlaw
PDF
The Game of Bug Bounty Hunting - Money, Drama, Action and Fame
PPTX
PPT on Android Applications
PDF
The Evolution of Cyber Attacks
PDF
Practice of Android Reverse Engineering
PPTX
Software reverse engineering
PPT
8 Bit A L U
Seguridad en Android
Analysis of database tampering
Basic concept cybersecurity
Basic knowledge of cyber security
CYBERCRIMES AND DUE DILIGENCE
Meetup6 microservices for the IoT
How web 2.0 is changing medicine
Cyber Security of Power grids
Wireless
Comp 107 cep 8
Elementary µprocessor tutorial
Cybersecurity 2 cyber attacks
Smartphone based ADAS
Cyberlaw
The Game of Bug Bounty Hunting - Money, Drama, Action and Fame
PPT on Android Applications
The Evolution of Cyber Attacks
Practice of Android Reverse Engineering
Software reverse engineering
8 Bit A L U
Ad

Similar to Null Mumbai Meet_Android Reverse Engineering by Samrat Das (20)

PDF
Beginners guide-to-reverse-engineering-android-apps-pau-oliva-fora-viaforensi...
PDF
hashdays 2011: Tobias Ospelt - Reversing Android Apps - Hacking and cracking ...
PDF
2013 Toorcon San Diego Building Custom Android Malware for Penetration Testing
PPTX
From Reversing to Exploitation
PPTX
From Reversing to Exploitation: Android Application Security in Essence
PDF
Mobile Penetration Testing: Episode III - Attack of the Code
PDF
Null Dubai Humla_Romansh_Yadav_Android_app_pentesting
PPTX
Decompiling Android
PDF
Android "Fight Club" : In pursuit of APPiness -- null Humla Delhi Chapter
PPTX
Reverse Engineering 101
PDF
Cracking the mobile application code
PDF
Hacking your Android (slides)
PPTX
Security Vulnerabilities in Mobile Applications (Kristaps Felzenbergs)
PPTX
Hacker Halted 2014 - Reverse Engineering the Android OS
PPTX
PDF
MobSecCon 2015 - Dynamic Analysis of Android Apps
PPTX
Basic reverse engineering steps about .apk file
PPTX
Android village @nullcon 2012
PPTX
Android pen test basics
PDF
CNIT 128 6. Analyzing Android Applications (Part 1)
Beginners guide-to-reverse-engineering-android-apps-pau-oliva-fora-viaforensi...
hashdays 2011: Tobias Ospelt - Reversing Android Apps - Hacking and cracking ...
2013 Toorcon San Diego Building Custom Android Malware for Penetration Testing
From Reversing to Exploitation
From Reversing to Exploitation: Android Application Security in Essence
Mobile Penetration Testing: Episode III - Attack of the Code
Null Dubai Humla_Romansh_Yadav_Android_app_pentesting
Decompiling Android
Android "Fight Club" : In pursuit of APPiness -- null Humla Delhi Chapter
Reverse Engineering 101
Cracking the mobile application code
Hacking your Android (slides)
Security Vulnerabilities in Mobile Applications (Kristaps Felzenbergs)
Hacker Halted 2014 - Reverse Engineering the Android OS
MobSecCon 2015 - Dynamic Analysis of Android Apps
Basic reverse engineering steps about .apk file
Android village @nullcon 2012
Android pen test basics
CNIT 128 6. Analyzing Android Applications (Part 1)

More from nullowaspmumbai (20)

PDF
ELK in Security Analytics
PPTX
Switch security
PPTX
Radio hacking - Part 1
PPTX
How I got my First CVE
PPTX
Power forensics
PPTX
Infrastructure security & Incident Management
PPTX
Middleware hacking
PPTX
Internet censorship circumvention techniques
PPTX
How i got my first cve
PPTX
Adversarial machine learning updated
PPTX
PPTX
Adversarial machine learning
PPTX
Dll Hijacking
PPTX
Abusing Target
PDF
NTFS Forensics
PPTX
Middleware hacking
PDF
Ganesh naik linux_kernel_internals
PDF
Buffer overflow null
PDF
Null mumbai Session on ransomware by_Aditya Jamkhande
ELK in Security Analytics
Switch security
Radio hacking - Part 1
How I got my First CVE
Power forensics
Infrastructure security & Incident Management
Middleware hacking
Internet censorship circumvention techniques
How i got my first cve
Adversarial machine learning updated
Adversarial machine learning
Dll Hijacking
Abusing Target
NTFS Forensics
Middleware hacking
Ganesh naik linux_kernel_internals
Buffer overflow null
Null mumbai Session on ransomware by_Aditya Jamkhande

Recently uploaded (20)

PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
KodekX | Application Modernization Development
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
cuic standard and advanced reporting.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Modernizing your data center with Dell and AMD
PPTX
Big Data Technologies - Introduction.pptx
PPTX
A Presentation on Artificial Intelligence
Encapsulation_ Review paper, used for researhc scholars
Diabetes mellitus diagnosis method based random forest with bat algorithm
KodekX | Application Modernization Development
“AI and Expert System Decision Support & Business Intelligence Systems”
Mobile App Security Testing_ A Comprehensive Guide.pdf
cuic standard and advanced reporting.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
Spectral efficient network and resource selection model in 5G networks
Network Security Unit 5.pdf for BCA BBA.
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Understanding_Digital_Forensics_Presentation.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
MYSQL Presentation for SQL database connectivity
Modernizing your data center with Dell and AMD
Big Data Technologies - Introduction.pptx
A Presentation on Artificial Intelligence

Null Mumbai Meet_Android Reverse Engineering by Samrat Das

  • 1. Headline Verdana Bold Reverse Engineering | Android Penetration Testing 13th August 2016 Samrat Das Consultant |Cyber-Security Protection Deloitte Touche Tohmatsu India LLP. samratd@deloitte.com www.deloitte.com NULL MEET-MUMBAI 13th August , 2016
  • 2. • Introduction to Reverse Engineering • Why learn reverse engineering? • Short intro to Reverse Engineering fundamentals and Assembly Language • Reverse Engineering Windows executables • What is Dalvik Virtual Machine? | DVM vs JVM • Reverse Engineering Android Applications- Manual step by step • Android Emulators • Reverse engineering android on Windows • Reverse engineering android on AppUse • Components in Android Forensics • Detect Backdoors in Android applications • How are malicious Android Applications created? • Proxying android traffic | Burp Suite • Exploiting Content Provider | Intent Sniffing | Broadcast Receiver | Weak cryptography • Tools intro: Apk tool | JD-GUI | Dex2Jar | Drozer | Appuse Contents
  • 3. Decipher algorithms from exes, identify design construct and loopholes. Retrieve source and origins of software for advanced analysis and documentation Inspect internal workings of an virus/ malware What is reverse engineering?
  • 4. Applications of RE: • Security Auditing/Vulnerability Research • Virus /malware analysis - Software copy-protection removal (cracking) - Analyzing binary executables for modifications and comparisons - Cryptography and Encryption Research
  • 5. There are two broad types in Operating Systems RE:- 1) User level debugging in RE 2) Kernel level debugging in RE Some important concepts: 1) 32 bit and 64 bit applications: 2) Registers: Small set of data holding places that are part of a computer processor. A register may hold a computer instruction, a storage address, or any kind of data 32-bit data registers: EAX, EBX, ECX, EDX. Lower halves of the 32-bit registers can be used as four 16-bit data registers: AX, BX, CX and DX.
  • 6. 3) Disassembler: Translates machine language into assembly language 4) Decompiler: Takes as input an executable file, and attempts to create a high level, compilable source file 5) Debugger: Used to test and debug other programs.
  • 7. 6) Crackmes: In simple words, a crack-me is a small program designed to test a programmer's reverse engineering skills. They are programmed by other reversers as a legal way to "crack" software, since showing how to crack commercial software is illegal; Crackmes are a great way to approach the same in legitimate fashion. Most of the commercial software is cracked in a similar fashion, though with recent higher end software, the code is usually “obfuscated”or “packed”to prevent reversing (Security-measures applied as anti-reversing)
  • 8. The CPU’s registers The Intel 32-bit x86 registers: ESPEAX EBPEBX ESIECX EDIEDX EIP accumulator base counter data instruction pointer destination index source index base pointer stack pointer
  • 9. Demo for windows exe reversing Live Example: •Using Crack-me utility
  • 10. • Analysing • Attacking • Identifying • Writing Secure Application/ Mitigations Mobile Penetration & Reverse Engineering Methodology:
  • 11. •Weak Server Side Controls •Insecure Data Storage •Insufficient Transport Layer Protection •Unintended Data Leakage •Poor Authorization and Authentication •Broken Cryptography •Client Side Injection •Security Decisions Via Untrusted Inputs •Improper Session Handling •Lack of Binary Protections Mobile OWASP Top 10 Checklist
  • 12. Mobile Reverse Engineering Android Reverse Engineering
  • 13. What’s is an APK file? Anatomy of APK 13 Android applications are distributed in the form of a zipped archive with the file extension of .apk, which stands for Android Package. The official mime-type of an Android Package is application/vnd.android.package-archive. These packages are nothing more than zip files containing the relevant compiled application code, resources, and application metadata required to define a complete application.
  • 14. Anatomy of Apk A typical application package contains Classes.dex (file) AndroidManifest.xml (file) META-INF (folder) resources.arsc (file) res (folder) assets (folder) lib (folder)
  • 15. Assets—Allows the developer to place files in this directory that they would like bundled with the application. Res—Contains all the application activity layouts, images used, and any other files in a structured way. These files are placed in the raw/ subdirectory. Lib—Contains any native libraries that are bundled with the application. These are split by architecture under this directory and loaded by the application according to the detected CPU architecture; for example, x86, ARM, MIPS. META-INF—This folder contains the certificate of the application and files that hold an inventory list of all included files in the zip archive and their hashes. classes.dex—The executable file containing the Dalvik bytecode of the application. It is the actual code that will run on the Dalvik Virtual Machine. AndroidManifest.xml—the manifest file containing all configuration information about the application and defined security parameters. This will be explored in detail later in this chapter. Resources.asrc—Resources can be compiled into this file instead of being put into the res folder. Also contains any application string
  • 16. Steps: Android reverse engineering includes five steps: 1.Extraction 2.Decoding 3.Modifying 4.Encoding and 5.Packing 1. Extraction Separating an .apk file into multiple files. 2. Decoding Converting the .dex, dalvik bytecode into java class files, baksmali files 3. Modification Altering the application bytecode, AndroidManifest.xml, application assets, and resources.
  • 18. 4.Encoding 1. Modified .xml files must be covered back into their binary formats. 2.New classes.dex are created from the modified .smali files. 3.Assembled directory is produced with all .smali files into a single .dex file. 5. Packing All application files such as the assembled .dex files, binary .xml files, and application assets, must be stored in a Zip archive. The process to sign an .apk file is based on the JAR signing process. The jarsigner utility is used to sign .apk files with RSA certificates. The packing step aligns the contents of the .apk file performed with the zipalign utility.
  • 19. •Some exploitatation / reverse engineering tools for android •Dex2jar •Java decompiler •Apktool •Apk Analyser •Drozer Apktool Alternate : Virtuous Ten Studio (VTS) GUI Tool The main advantage of Apktool over JD-GUI, recompile it back using Apktool, it will recompile perfectly and will generate a new .apk file. Drozer drozer is an Android assessment tool created to test each aspect of an Android application in a dynamic way. Finding vulnerabilities in applications or devices—It allows you to assume the role of an installed Android application and interact with other apps and the underlying operating system in search of vulnerabilities. Providing exploits and useful payloads for known vulnerabilities—It does this by building malicious files or web pages that exploit known vulnerabilities to install drozer as a remote administration tool.
  • 20. How drozer Works drozer is a distributed system that makes use of some key components: Agent— A lightweight Android application that runs on the device or emulator being used for testing. There are two versions of the agent, one that provides a user interface and embedded server and another that does not contain a graphical interface and can be used as a Remote Administration Tool on a compromised device. Console—A command-line interface running on your computer that allows you to interact with the device through the agent. Server—Provides a central point where consoles and agents can rendezvous, and routes sessions between them 20
  • 21. Various components of android: Activities: The visual screens which a user could interact with. (buttons, images, TextView etc Services: Components which run in the background Broadcast Receivers: Receivers that listen to the incoming broadcast messages by the Android system. Once they receive a broadcast message, a particular action could be triggered depending on the predefined conditions. Shared Preferences: Used by an application in order to save small sets of data for the application. This data is stored inside a folder named shared_prefs. These small datasets may include name value pairs such as the user's score in a game and login credentials. Intents: Components which are used to bind two or more different Android components together. Content Providers: Used to provide access to a structured set of data to be used by the application. An application can access and query its own data or the data stored in the phone using the Content Providers.
  • 22. Things we need Dex2Jar (https://sourceforge.net/projects/dex2jar/) JD-GUI(https://github.com/java-decompiler/jd-gui) APK-tool(https://ibotpeaches.github.io/Apktool/) A intentionally vulnerable application for hands-on (https://codeload.github.com/dineshshetty/Android- InsecureBankv2/zip/master)
  • 23. Demo for android reversing Live Example: •Decompiling a sample android application
  • 24. Preliminary step of Conversion of Dex file to Jar file: Open up dex2jar folder In windows, select the d2j-dex2jar.bat file keeping the apk file in the same folder for ease. Alternatively, you can select the dex file directly obtained by extracting the apk as zip, as show below 24
  • 25. 1) Once you use the d2j-dex2jar.bat InsecureBankv2-dex2jar.jar , the following jar file will be created Once you receive the Jar file, we can proceed for getting the class files and get the source code for class files
  • 26. Next step: Viewing class files from jar file: 26 1)Launch JD-GUI and import the jar file inside it As you can see, we get the class files from where we can get idea of the source code!
  • 28. The next step is getting to know the application further by going into the resource files! At this point, we can use the powerful apktool for analysing the apk. Apktool has multiple switches and can be used for decompiling files as well as recompiling them into modified versions. d stands for decode b stands for build You can look for more info on https://ibotpeaches.github.io/Apktool/documentation/
  • 29. Here we will use the d option now to decode the apk and analyse its contents. Once you do this, we can see the following output:
  • 30. As you can see here, we have got the different files of the apk, the sections of which I have already describe above. Analyzing manifest.xml file will give us the information of what all system level access can the application gather. For example the above application’s manifest.xml file gives:
  • 31. As you can see above, the application and read your storage memory, write data, send sms, read your contacts, as well as network state , call logs. From a hacker’s point of view, backdoor the application and steal complete information from the users phone! We till now we have explored the analysis and code-deciphering of apk files, lets see further what we can do.
  • 32. Detecting Backdoors in Android App Many a times, malicious developers leave malicious backdoors in applications, by which they can get access to your machines, inspecting the code can give you hints as well as the code by which they have done so. The same app which we are inspecting allows us to use a backdoored credential to perform a login! Let’s see:
  • 34. Creating infected version of the apps: 1. Decompile the application using apktool 2. Decompile the malicious application to generate the smali files of the Java classes. Here, we need to put all the malicious activities in the service. Eg: We created a malicious service “malware.smali” 3.Copy the malware.smali file to the smali folder inside the folder in which we have decompiled the legitimate app. 4.Change references of the package name in malware.smali to the package name of the legitimate application.
  • 35. Useful Hacking Tools List of additional tools useful in Android Phone Testing:  Android Debug Bridge • A client-server program .It includes a client (that runs on the system), a server handling the communication (also running on the system), and a daemon running on the emulator and devices as a background process. Burp Suite • We will use this in order to intercept and analyze the network traffic.
  • 36. Anti-reverse engineering protection for android http://proguard.sourceforge.net/ ProGuard is a free Java class file shrinker, optimizer, obfuscator, and preverifier. It detects and removes unused classes, fields, methods, and attributes. It optimizes bytecode and removes unused instructions. It renames the remaining classes, fields, and methods using short meaningless names. It makes much harder to read the decompiled code. For example, "DescriptiveClassName.descriptiveMethodName()" becomes "A.b()". DexProtector is the protector and obfuscator for Android platform. It helps you secure your Android applications and Android libraries (AARs) against unauthorized or illegal use, reverse engineering, and cracking. https://dexprotector.com/ (trail)
  • 37. Rooting Android 37 Rooting Objectives A typical objective of rooting an Android device is so that you can put a su binary in a directory on the PATH (for example, /system/bin or /system/xbin). The job of the su binary is to allow a user to switch security contexts and become another user, including root #include <stdio.h> #include <unistd.h> int main(int argc, char **argv) { if (setgid(0) || setuid(0)) fprintf(stderr, "su: permission deniedn"); else { char *args[argc + 1]; args[0] = "sh"; args[argc] = NULL; int i; for (i = 1; i < argc; i++) args[i] = argv[i]; execv("/system/bin/sh", args); } } T Using setuid(0) and setgid(0) to change to the root user’s context, which means that any application that executes su will receive root context and no checks are performed or prompts shown to the user.
  • 38. Using an Exploit Android uses the Linux kernel and also contains code added by device manufacturers. Like most code these implementations could contain bugs. These bugs could be anything from a simple mistake in the permissions of a particular file or driver code that does not handle certain user input securely. GINGERBREAK—EXPLOITING AOSP KERNEL CODE The vulnerability exploited by Gingerbreak exists in the Volume Manager (vold) on Android versions 2.2 (Froyo)—and 3.0 (Honeycomb). Vold manages the mounting of external storage volumes on Android. The vulnerability was an out-of-bounds array access that allowed the exploit author to overwrite entries in the Global Offset Table (GOT) to trick the system into executing a copy of the sh binary as root http://c-skills.blogspot.com/2011/04/yummy-yummygingerbreak.html. 38
  • 39. EXYNOS ABUSE—EXPLOITING CUSTOM DRIVERS Device manufacturers sometimes have to include custom device drivers in order to interface with included hardware. The standard of the code or configuration in some cases is not of the highest quality and discovered vulnerabilities can be used to gain root access. An exploit for an issue discovered in devices using exynos processors, such as the Samsung Galaxy S3, appeared in the following forum post: http://forum.xda-developers.com/showthread.php?t=2048511. The forum post detailed that a block device located at /dev/exynos-mem allowed the mapping of kernel memory into user space by any user. The exploitation technique used was to patch a comparison made in the setresuid() function. This comparison is normally cmp r0, #0 and was altered to cmp r0,#1 as a result of having complete access to the memory space, which meant that when sysresuid(0) was called later on the code, access was granted to change to root context. This exploit also elegantly bypassed the kptr_restrict memory protection, which does not allow applications to read /proc/kallsyms and obtain kernel pointers. It did so by changing the enforcing flag of this check in live memory 39
  • 40. Intent Sniffing Intent sniffing is when a broadcast receiver can register to receive broadcasts that may have been intended for other applications. This is possible because some applications broadcast intents and do not define a required permission that a broadcast receiver must hold in order to receive the intent or do not provide a destination package for the intent. You can review the source code of an application in search of intents being sent using the sendBroadcast() method and then register a receiver that catches this information from a non-privileged application. You can catch these intents in drozer using the app.broadcast.sniff module. 40
  • 41. Fragment Injection attack: Smaller UI elements named fragments are present in android. A security researcher publicized a vulnerability that affected all applications with exported activities that extend the PreferenceActivity class. In the onCreate() method of the PreferenceActivity class, it was discovered to be retrieving an extra named :android:show_fragment from the user-supplied bundle. This extra can be provided by the application that sent the intent and the name of a fragment within the target application specified to be loaded. This allows the loading of any chosen fragment within the activity, which may have only been used inside non-exported activities under normal use. All exported activities that extend PreferenceActivity and are running on Android 4.3 or prior are vulnerable. Performing poor validation on the fragment name supplied to this method or simply returning true in this method without performing any checks would still result in fragment injection attacks being possible. 41
  • 42. Secure coding for ANDROID 42 Principle of Least Exposure Application Components An application should reduce its exported application components down to the essentials. The fewer exported components, the better. In the following application only its main activity is exported so that it can be launched Data Storage If the storage of any application data is not absolutely necessary, simply don't store it. This includes storing data in the application's private data directory or on the SD card. Interacting with Untrusted Sources An application that retrieves information from the SD card, the Internet, Wi-Fi, Bluetooth, or any other source that is not directly under the control of the application should be scrutinized for authenticity.
  • 43. Requesting Minimal Permissions Request the fewest permissions necessary for your application to function correctly. Performing a task in a way that does not require an extra permission would generally be considered the most secure option. In addition to this, requesting as few permissions as possible helps put more security-minded users at ease. Doing so also reduces the impact of someone exploiting your application. Bundling Files Inside the APK Before releasing your app to the world, take the time to unzip the APK and check what is inside because you might find other files unintentionally included inside your APK
  • 44. Task Manager Snooping Two configurations enable you to avoid having the contents of your application's activities from appearing in the recent application list: You can choose to show a blank screen in the Recent list, or remove the entry from the list altogether. To make an activity show as a blank screen, implement the following code inside the onCreate()method of the activity: getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE); The FLAG_SECURE parameter ensures that the contents will not appear in screenshots. Tapjacking To ensure that performing tapjacking attacks on sensitive activities within your application is not possible, you can apply attributes to a View. You can set the following attribute in the layout file of your activity on each item that inherits from a View: android:filterTouchesWhenObscured="true" Ensuring Secure Trust BoundariesIf your application contains a login screen or any other form of trust boundary, then take care as to how it is handled. If your login activity contains a way to start activities that were only intended for trusted users, the authentication model of the application may be defeated.
  • 45. References: Mobile Hackers Handbook Thankyou! -> Questions ?