Physical attacks
Pentesting

Android Applications Pentesting

Android Application Fundamentals

This introduction is taken from https://maddiestone.github.io/AndroidAppRE/app_fundamentals.html

Fundamentals Review

  • Android applications are in the APK file format. APK is basically a ZIP file. (You can rename the file extension to .zip and use unzip to open and see its contents.)

  • APK Contents (Not exhaustive)

    • AndroidManifest.xml

    • META-INF/

      • Certificate lives here!

    • classes.dex

      • Dalvik bytecode for application in the DEX file format. This is the Java (or Kotlin) code that the application will run by default.

    • lib/

      • Native libraries for the application, by default, live here! Under the lib/ directory, there are the cpu-specific directories.

        • armeabi: compiled code for all ARM based processors only

        • armeabi-v7a: compiled code for all ARMv7 and above based processors only

        • x86: compiled code for X86

        • mips: compiled code for MIPS processors only

    • assets/

      • Any other files that may be needed by the app.

      • Additional native libraries or DEX files may be included here. This can happen especially when malware authors want to try and “hide” additional code, native or Dalvik, by not including it in the default locations.

    • res/

      • the directory containing resources not compiled into resources.arsc

    • classes.dex: The classes compiled in the dex file format understandable by the Dalvik virtual machine

    • resources.arsc: a file containing precompiled resources, such as binary XML for example.

Dalvik & Smali

Most Android applications are written in Java. Kotlin is also supported and interoperable with Java. For ease, for the rest of this workshop, when I refer to “Java”, you can assume that I mean “Java or Kotlin”. Instead of the Java code being run in Java Virtual Machine (JVM) like desktop applications, in Android, the Java is compiled to the Dalvik Executable (DEX) bytecode format. For earlier versions of Android, the bytecode was translated by the Dalvik virtual machine. For more recent versions of Android, the Android Runtime (ART) is used. If developers, write in Java and the code is compiled to DEX bytecode, to reverse engineer, we work the opposite direction. Flowchart of Developer's process. Java to DEX bytecode Flowchart of Reverse Engineer's process. DEX bytecode to SMALI to Decompiled Java

Smali is the human readable version of Dalvik bytecode. Technically, Smali and baksmali are the name of the tools (assembler and disassembler, respectively), but in Android, we often use the term “Smali” to refer to instructions. If you’ve done reverse engineering or computer architecture on compiled C/C++ code. SMALI is like the assembly language: between the higher level source code and the bytecode.

Application Entry Points

One of the most important points of reverse engineering is knowing where to begin your analysis and entry points for code execution is an important part of that.

Launcher Activity and other activities

An Android activity is one screen of the Android app's user interface. In that way an Android activity is very similar to windows in a desktop application. An Android app may contain one or more activities, meaning one or more screens.

The launcher activity is what most people think of as the entry point to an Android application. The launcher activity is the activity that is started when a user clicks on the icon for an application. You can determine the launcher activity by looking at the application’s manifest. The launcher activity will have the following MAIN and LAUNCHER intents listed.

Keep in mind that not every application will have a launcher activity, especially apps without a UI. Examples of applications without a UI (and thus a launcher activity) are pre-installed applications that perform services in the background, such as voicemail.

<activity android:name=".LauncherActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

Activities can be exported allowing other processes on the device to launch the activity. By default, they aren't exported but you can export them setting:

<service android:name=".ExampleExportedService" android:exported="true"/>

Content Provider

  • Content Provider component supplies data from one application to others on request.

  • You can store the data in the file system, an SQLite database, on the web, or any other persistent storage location your app can access.

  • Through the content provider, other apps can query or even modify the data (if the content provider allows it).

  • Content Provider is useful in cases when an app want to share data with another app.

  • It is much similar like databases and has four methods.

    • insert()

    • update()

    • delete()

    • query()

Services

Services run in the background without a UI. There are a myriad of ways that they can be started and thus are an entry point for applications. The default way that a service can be started as an entry point to an application is through Intents.

When the startService API is called to start a Service, the onStart method in the Service is executed.

For example, a service might play music in the background while the user is in a different application, or it might fetch data over the network without blocking user interaction with an activity.

A service can be exported which allows other processes on the device to start the service. By default services aren't exported but it can be configured in the Manifest:

<service android:name=".ExampleExportedService" android:exported="true"/>

Broadcast Receivers

Broadcasts can be thought of a messaging system and broadcast receivers are the listeners. If an application has registered a receiver for a specific broadcast, the code in that receiver is executed when the system sends the broadcast. There are 2 ways that an app can register a receiver: in the app’s Manifest or dynamically registered in the app’s code using the registerReceiver() API call.

In both cases, to register the receiver, the intent filters for the receiver are set. These intent filters are the broadcasts that should trigger the receiver.

When the specific broadcasts are sent that the receiver is registered for are sent, onReceive in the BroadcastReceiver class is executed.

An application may register a receiver for the low battery message for example, and change its behavior based on that information.

Application Subclass

Android applications can define a subclass of Application. Applications can, but do not have to define a custom subclass of Application. If an Android app defines a Application subclass, this class is instantiated prior to any other class in the application.

If the attachBaseContext method is defined in the Application subclass, it is called first, before the onCreate method.

Other App components

Application Signing

  • Android requires that all apps be digitally signed with a certificate before they can be installed. Android uses this certificate to identify the author of an app.

  • To run application on the device ,it should be signed.When application is installed on to an device then package manager verifies that whether the application has been properly signed with the certificate in the apk file or not.

  • Application can be self signed or can be signed through CA.

  • Application signing ensures that one application can’t access any other application except through well-defined IPC and also that it is passed unmodified to the device.

Application Verification

  • Android 4.2 and later support application verification. Users can choose to enable “Verify Apps” and have applications evaluated by an application verifier prior to installation.

  • App verification can alert the user if they try to install an app that might be harmful; if an application is especially bad, it can block installation.

Android Sandbox

Once installed on a device, each Android app lives in its own security sandbox: – The Android operating system is a multi-user Linux system in which each app is a different user.

  • By default, the system assigns each app a unique Linux user ID (the ID is used only by the system and is unknown to the app). The system sets permissions for all the files in an app so that only the user ID assigned to that app can access them.

  • Each process has its own virtual machine (VM), so an app’s code runs in isolation from other apps.

  • By default, every app runs in its own Linux process. Android starts the process when any of the app’s components need to be executed, then shuts down the process when it’s no longer needed or when the system must recover memory for other apps.

Static Analysis

First of all, for analysing an APK you should take a look to the to the Java code using a decompiler. Please, read here to find information about different available decompilers.

Looking for interesting Info

Just taking a look to the strings of the APK you can search for passwords, URLs, api keys an anything interesting that could be there...

Basic understanding of the application - Manifest.xml

Using any of the decompilers mentioned here you will be able to read the Manifest.xml. You could also rename the apk file extension to .zip and unzip it:

Reading the manifest an the code related with it you can find vulnerabilities:

Looking for interesting functions

  • Code execution: Runtime.exec(), ProcessBuilder(), native code:system()

  • Send SMSs: sendTextMessage, sendMultipartTestMessage

Smali Code - Modify and Re-Compile

Sometimes it is interesting to modify the application code to access hidden information for you (maybe well obfuscated passwords or flags). Then, it could be interesting to decompile the apk, modify the code and recompile it.

Opcodes reference: http://pallergabor.uw.hu/androidblog/dalvik_opcodes.html

Decompile the APK

Using APKTool you can access to the smali code and resources:

apktool d APP.apk

If apktool gives you any error, try installing the latest version

Some interesting files you should look are:

  • res/values/strings.xml (and all xmls inside res/values/*)

  • AndroidManifest.xml

  • Any file with extension .sqlite or .db

Change smali code

You can change instructions, change the value of some variables or add new instructions. I change the Smali code using VisualCode, you then download the plugin for the smali extension and the editor will tell you if any instruction is incorrect. Some examples can be found here:

Recompile theAPK

After modifying the code you can recompile the code using:

apktool b . #In the folder generated when you decompiled the application

It will compile the new APK inside the dist folder.

If apktool throws an error, try installing the latest version

Sing the new APK

Then, you need to generate a key (you will be asked for a password and for some information that you can fill randomly):

keytool -genkey -v -keystore key.jks -keyalg RSA -keysize 2048 -validity 10000 -alias <your-alias>

Finally, sign the new APK:

jarsigner -keystore key.jks path/to/dist/* <your-alias>

Optimize new application

zipalign is an archive alignment tool that provides important optimisation to Android application (APK) files. More information here.

zipalign [-f] [-v] <alignment> infile.apk outfile.apk
zipalign -v 4 infile.apk

Sign the new APK (again?)

If you prefer to use apksigner instead of jarsigner, you should sing the apk after applying the optimization with zipaling. BUT NOTICE THAT YOU ONLY HAVE TO SIGN THE APPLCIATION ONCE WITH jarsigner (before zipalign) OR WITH aspsigner(after zipaling).

Dynamic Analysis

ADB

It allows you to control your device over USB or Network from a computer, copy files back and forth, install and uninstall apps, run shell commands, and more.

ADB Commands

Online Dynamic analysis

You can create a free account in: https://appetize.io/. This platform allows you to upload and execute APKs, so it is useful to see how an apk is behaving.

You can even see the logs of your application in the web and connect through adb.

Thanks to the ADB connection you can use Drozer and Frida inside the emulators.

Local Dynamic Analysis

You can use some emulator like:

  • Genymotion (Free version: Personal Edition, you need to create an account.)

  • Nox (Free, but it doesn't support Frida or Drozer).

Or you could use a physical device (you need to activate the debugging options and it will be cool if you can root it):

  1. Settings.

  2. (FromAndroid 8.0) Select System.

  3. Select About phone.

  4. Press Build number 7 times.

  5. Go back and you will find the Developer options.

Burp Suite

You can prepare the APK to make a MITM using: https://github.com/shroudedcode/apk-mitm Or you can use Burp+Frida+Genymotion: https://spenkk.github.io/bugbounty/Configuring-Frida-with-Burp-and-GenyMotion-to-bypass-SSL-Pinning/

I am not going to explain what is Burp Suite or how to use it. But here you have a tutorial of how to configure Android so you can capture all the HTTP requests being made by the (emulated) device.

Drozer

Drozer allows you to assume the role of an Android app and interact with other apps. It can do anything that an installed application can do, such as make use of Android’s Inter-Process Communication (IPC) mechanism and interact with the underlying operating system. From Drozer Guide.

It very useful to exploit exposed:

It could also find debuggeable applications.

Learn how to use it reading the Drozer Tutorial.

Frida

Dynamic instrumentation toolkit for developers, reverse-engineers, and security researchers. Learn more at www.frida.re.

Basically: Amazing, hook methods, run code inside the applications and play with the application while it is running. If you want to pentest Android applications you need to know how to use Frida.

Learn how to use Frida: Frida tutorial Some "GUI" for actions with Frida: https://github.com/m0bilesecurity/RMS-Runtime-Mobile-Security

Android Application Analyzer

This tool could help you managing different tools during the analysis dynamic: https://github.com/NotSoSecure/android_application_analyzer

Automatic Analysis

MobSF

Vulnerability assessment of the application using a nice web-based frontend. You can also perform dynamic analysis (but you need to prepare the environment).

docker pull opensecurity/mobile-security-framework-mobsf
docker run -it -p 8000:8000 opensecurity/mobile-security-framework-mobsf:latest

Qark

This tool is designed to look for several security related Android application vulnerabilities, either in source code or packaged APKs. The tool is also capable of creating "Proof-of-Concept" deployable APKs and/or ADB commands, capable of exploiting many of the vulnerabilities it finds. There is no need to root the test device, as this tool focuses on vulnerabilities that can be exploited under otherwise secure conditions.

pip install --user qark # --user is only needed if not using a virtualenv
qark --apk path/to/my.apk
qark --java path/to/parent/java/folder
qark --java path/to/specific/java/file.java

  • Displays all extracted files for easy reference

  • Automatically decompile APK files to Java and Smali format

  • Analyze AndroidManifest.xml for common vulnerabilities and behavior

  • Static source code analysis for common vulnerabilities and behavior

    • Device info

    • Intents

    • Command execution

    • SQLite references

    • Logging references

    • Content providers

    • Broadcast recievers

    • Service references

    • File references

    • Crypto references

    • Hardcoded secrets

    • URL's

    • Network connections

    • SSL references

    • WebView references

reverse-apk relative/path/to/APP.apk

SUPER is a command-line application that can be used in Windows, MacOS X and Linux, that analyzes .apk files in search for vulnerabilities. It does this by decompressing APKs and applying a series of rules to detect those vulnerabilities.

All rules are centered in a rules.json file, and each company or tester could create its own rules to analyze what they need.

Download the latest binaries from in the download page

super-analyzer {apk_file}

StaCoAn

StaCoAn is a crossplatform tool which aids developers, bugbounty hunters and ethical hackers performing static code analysis on mobile applications*.

The concept is that you drag and drop your mobile application file (an .apk or .ipa file) on the StaCoAn application and it will generate a visual and portable report for you. You can tweak the settings and wordlists to get a customized experience.

Download latest release:

./stacoan

AndroBugs

AndroBugs Framework is an Android vulnerability analysis system that helps developers or hackers find potential security vulnerabilities in Android applications.

Windows releases

python androbugs.py -f [APK file]
androbugs.exe -f [APK file]

Androwarn

Androwarn is a tool whose main aim is to detect and warn the user about potential malicious behaviours developped by an Android application.

The detection is performed with the static analysis of the application's Dalvik bytecode, represented as Smali, with the androguard library.

This tool looks for common behavior of "bad" applications like: Telephony identifiers exfiltration, Audio/video flow interception, PIM data modification, Arbitrary code execution...

python androwarn.py -i my_application_to_be_analyzed.apk -r html -v 3

MARA is a Mobile Application Reverse engineering and Analysis Framework. It is a tool that puts together commonly used mobile application reverse engineering and analysis tools, to assist in testing mobile applications against the OWASP mobile security threats. Its objective is to make this task easier and friendlier to mobile application developers and security professionals.

It is able to:

Obfuscating/Deobfuscating code

ProGuard

ProGuard is an open source command-line tool that shrinks, optimizes and obfuscates Java code. It is able to optimize bytecode as well as detect and remove unused instructions. ProGuard is free software and is distributed under the GNU General Public License, version 2.

ProGuard is distributed as part of the Android SDK and runs when building the application in release mode.

From: https://en.wikipedia.org/wiki/ProGuard_(software)

DeGuard

DeGuard reverses the process of obfuscation performed by Android obfuscation tools. This enables numerous security analyses, including code inspection and predicting libraries.

You can upload an obfuscated APK to their platform.

Simplify

It is a generic android deobfuscator. Simplify virtually executes an app to understand its behavior and then tries to optimize the code so it behaves identically but is easier for a human to understand. Each optimization type is simple and generic, so it doesn't matter what the specific type of obfuscation is used.

APKiD

APKiD gives you information about how an APK was made. It identifies many compilers, packers, obfuscators, and other weird stuff. It's PEiD for Android.

Labs

Androl4b

AndroL4b is an Android security virtual machine based on ubuntu-mate includes the collection of latest framework, tutorials and labs from different security geeks and researchers for reverse engineering and malware analysis.

OWASP

Git Repos

https://github.com/riddhi-shree/nullCommunity/tree/master/Android

References

For more information visit: