Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Null Mumbai Meet_Android Reverse Engineering by Samrat Das


Published on

Android Reverse Engineering by Samrat Das
• Intro to Reverse Engineering
• Short walkthough with Windows RE
• Introduction to Mobile Security Assessments
• Dalvik Virtual Machine vs JVM
• APK Walkthrough
• Components of Android
• Steps of Reverse Engineering Android Applications
• Hands-on demos on manual reversing of android apps
• Introduction to APPuse VM for droid assessments
• Detecting developer backdoors
• Creating Infected Android Applications
• Anti-Reversing | Obfuscation

Published in: Technology
  • Be the first to comment

Null Mumbai Meet_Android Reverse Engineering by Samrat Das

  1. 1. Headline Verdana Bold Reverse Engineering | Android Penetration Testing 13th August 2016 Samrat Das Consultant |Cyber-Security Protection Deloitte Touche Tohmatsu India LLP. NULL MEET-MUMBAI 13th August , 2016
  2. 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. 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. 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. 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. 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. 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. 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. 9. Demo for windows exe reversing Live Example: •Using Crack-me utility
  10. 10. • Analysing • Attacking • Identifying • Writing Secure Application/ Mitigations Mobile Penetration & Reverse Engineering Methodology:
  11. 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. 12. Mobile Reverse Engineering Android Reverse Engineering
  13. 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/ 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. 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. 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. 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.
  17. 17. 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.
  18. 18. •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.
  19. 19. 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
  20. 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.
  21. 21. Things we need Dex2Jar ( JD-GUI( APK-tool( A intentionally vulnerable application for hands-on ( InsecureBankv2/zip/master)
  22. 22. Demo for android reversing Live Example: •Decompiling a sample android application
  23. 23. 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
  24. 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
  25. 25. 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!
  26. 26. 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
  27. 27. 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:
  28. 28. 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:
  29. 29. 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.
  30. 30. 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:
  31. 31. Introduction to Appuse- VM
  32. 32. 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.
  33. 33. 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.
  34. 34. Anti-reverse engineering protection for android 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. (trail)
  35. 35. 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.
  36. 36. 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 38
  37. 37. 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: 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
  38. 38. 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
  39. 39. 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
  40. 40. 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.
  41. 41. 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
  42. 42. 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.
  43. 43. References: Mobile Hackers Handbook Thankyou! -> Questions ?