Android Hacking 101 - Tryhackme Notes

What is Native And Hybrid Applications?

Native: They are those developed applications only and exclusively for mobile operating systems, either Android or IOS. In Android you use the Java or kotlin programming language, while in IOS you make use of Swift or Objective-C. These programming languages are the official ones for the respective operating systems.

Hybrid: These applications use technologies such as HTML, CSS and JavaScript, all of these linked and processed through frameworks such as Apache Cรณrdova "PhoneGap", Ionic, among others.

What is android's SMALI code?

When you create an application code, the apk file contains a .dex file, which contains binary Dalvik bytecode. Smali is an assembly language that runs on Dalvik VM, which is Android's JVM.

Smali Registers

In dalvik's bytecode, registers are always 32 bits, and can hold any type of value. 2 registers are used to hold 64 bit types (Long and Double).

There are two ways to specify how many registers are available in a method. the .registers directive specifies the total number of registers in the method, while the alternate .locals directive specifies the number of non-parameter registers in the method. The total number of registers would therefore include the registers needed to hold the method parameters.

When a method is invoked, the parameters to the method are placed into the last n registers. If a method has 2 arguments, and 5 registers (v0-v4), the arguments would be placed into the last 2 registers - v3 and v4.

The first parameter to a non-static methods is always the object that the method is being invoked on.

For static methods it's the same thing, except there isn't an implicit this argument.

For example, let's say you are writing a non-static method LMyObject;->callMe(II)V. This method has 2 integer parameters, but it also has an implicit LMyObject; parameter before both integer parameters, so there are a total of 3 arguments to the method.

Let's say you specify that there are 5 registers in the method (v0-v4), with either the .registers 5 directive or the .locals 2 directive (i.e. 2 local registers + 3 parameter registers). When the method is invoked, the object that the method is being invoked on (i.e. the this reference) will be in v2, the first integer parameter will be in v3, and the second integer parameter will be in v4.

Application Structure (APK)

AndroidManifest.xml: the manifest file in binary XML format.

classes.dex: application code compiled in the dex format.

resources.arsc: file containing precompiled application resources, in binary XML.

res/: folder containing resources not compiled into resources.arsc

assets/: optional folder containing applications assets, which can be retrieved by AssetManager.

lib/: optional folder containing compiled code - i.e. native code libraries.

META-INF/: folder containing the MANIFEST.MF file, which stores meta data about the contents of the JAR. which sometimes will be store in a folder named original.The signature of the APK is also stored in this folder.

AndroidManifest.xml

Every APK file includes an AndroidManifest.xml file which declares the applicationโ€™s package name, version components and other metadata. Full detail of Android manifest specs file can be view here. Below is just some common attributes that can identify in AndroidManifest.

AttributesDescription

Manifest tag

contains android installation mode, package name, build versions

Permissions

custom permission and protection level

uses-permissions

requests a permission that must be granted in order for it to operate, full list of permission API can refer here.

uses-feature

Declares a single hardware or software feature that is used by the application.

Application

The declaration of the application. Will contains all the activity

Activity

Declares an activity that implements part of the application visual user interface.

intent-filter

Specifies the types of intents that an activity, service, or broadcast receiver can respond to.

service

Declare a service as one of the application components.

receiver

Broadcast receivers enable applications to receive intents that are broadcast by the system or by other applications, even when other components of the application are not running.

provider

Declares a content provider component. A content provider is a subclass of ContentProvider that supplies structured access to data managed by the application.

Setup the Envirnoment

  • Java Development Kit

  • Java

  • Emulator (GenyMotion or Android Studio)

  • Enable Developer options(Debug usb): Settings > About Phone > Build number > Tap it 7 times to become developer; Then: Settings > Developer Options > USB Debugging

Pentesting Methodology

  1. Information Gathering

  2. Reversing

  3. Static Analysis

  4. Dinamyc Analysis

  5. Report

Information Gathering

Information collection is the first thing we need to do, as this information will guide us to the next stage in our penetration tests.

Black Box: In penetration testing, black-box testing refers to a method where an ethical hacker has no knowledge of the system being attacked.

White Box: White box penetration testing can also be called glass box penetration testing or clear box penetration testing. In any case, it's an approach to penetration testing that relies on the knowledge of the target system's internal configuration. It uses this information for the test cases.

In a real scenario the client it will give us the mobile app, users and passwords to perform the login and also a user manual of how the application works.

in other cases, such as bug bounties we will use the application that are exposed to the public and analyse it from there.

Not use an online services for download the apk file, don't knows if we're analyzing the real app. Always download the application from trusted sources such as play store.

Reversing

In this section we will use adb(Android Debug Bridge) to extract the source code of a legitimate apk so we can analyse it.

adb is a development tool that facilitates communication between an Android device and a personal computer.

List Devices: adb devices

Extract apk:

To extract the apk you first need to have the application installed on the emulator.

  • This command print the path to the APK of the given: adb shell pm path package_name

  • This command pulls the file remote to local, if no local is specified it will upload the apk to the current directorie: adb pull <remote> [<locaDestination>]

Get the source code:

To get the source code we can use jadx. In a nutshell what it does is that we load an apk and it gives you the java source code.

What it does is converting the apk to smali and then smali to java.

jadx -d [path-output-folder] [path-apk-or-dex-file]

If the goal is to just see the source code we can use the jadx-gui. Jadx-gui its almost like an idea that shows you the source code and lets you find code blocks with keywords.

You have dex2jar too. With that you can convert the APK to a JAR file and then open with a GUI like JD-GUI to see the source code.

d2j-dex2jar.sh base.apk

To obatin the source code in SMALI we can use apktool.

apktool d file.apk

Apktool is a very handy tool because we can make changes in the smali code and then use the following command to recreate a new APK:

apktool b extracted_apk -o app-release-mod.apk --use-aapt2

To sign the application we can use this:

java -jar uber-apk-signer.jar --apks app-name.apk

Static Analysis

  • Weak or improper cryptography use

  • Exported Preference Activities

  • Apps which enable backups

  • Apps which are debuggable

  • App Permissions.

  • Firebase Instance(s)

  • Sensitive data in the code

Weak or improper cryptography use

Incorrect uses of encryption algorithm may result in sensitive data exposure, key leakage, broken authentication, insecure session and spoofing attack.

We can search with "grep" for keywords like "iv" for the initial vector or "secret key" for the key used in symetric ciphers.

The application should use a cryptography asymmetric.

Exported Preference Activities

As we know, Android's activity component is application screen(s) and the action(s) that applied on that screen(s) when we use the application. When an activity is found to be shared with other apps on the device, it can be accessible to any other application on the device and can be an entry point. To see what activities are open to this, we can go to AndroidManifest.xml and look at what activities have the android:exported="true".

Apps which enable backups

This is considered a security issue because people could backup your app via ADB and then get private data of your app into their PC.

  1. Shared preference.

  2. directory returned by getFilesDir().

  3. getDataBase(path) also includes files created by SQLiteOpenHelper.

  4. files in directories created with getDir(Sring, int).

  5. files on external storage returned by getExternalFilesDir (String type).

How identify this? Go to AndroidManifest.xml and then look for .

You should disable backups with android:allowBackup=false.

Apps which are debuggable

Debugging was enabled on the app which makes it easier for reverse engineers to hook a debugger to it. This allows dumping a stack trace and accessing debugging helper classes.

How identify this? Go to AndroidManifest.xml and search for android:debuggable=true.

App Permissions

System permissions are divided into two groups: โ€œnormalโ€ and โ€œdangerous.โ€ Normal permission groups are allowed by default, because they donโ€™t pose a risk to your privacy. (e.g., Android allows apps to access the Internet without your permission.) Dangerous permission groups, however, can give apps access to things like your calling history, private messages, location, camera, microphone, and more. Therefore, Android will always ask you to approve dangerous permissions.

To analyse the permissions go to AndroidManifest.xml and look for "uses-permission".

A list of permissions can be found in here: https://developer.android.com/reference/android/Manifest.permission

Firebase Instance(s)

Last year, security researchers have discovered unprotected Firebase databases of thousands of iOS and Android mobile applications that are exposing over 100 million data records, including plain text passwords, user IDs, location, and in some cases, financial financial records such as banking and cryptocurrency transactions.

Google's Firebase service is one of the most popular back-end development platforms for mobile and web applications that offers developers a cloud-based database, which stores data in JSON format and synced it in the real-time with all connected clients.

How identify this?

FireBase Scanner, The scripts helps security analsts to identify misconfigured firebase instances.

python FireBaseScanner.py -p /path/apk

Sensitive data in the code

Users, passwords, internal IP and more...

Use grep or jadx-gui to filter for keywords such as "secret", "password" or "url".

How to automatize this process?

It is very entertaining to do this manually, but in a real pentest the time is not our friend.

Static Analysis Frameworks

  • Mara Framework(https://github.com/xtiankisutsa/MARA_Framework): 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.

  • QARK(https://github.com/linkedin/qark): Is a static code analysis tool, designed to recognize potential security vulnerabilities and points of concern for Java-based Android applications. QARK was designed to be community based, available to everyone and free for use. QARK educates developers and information security personnel about potential risks related to Android application security, providing clear descriptions of issues and links to authoritative reference sources. QARK also attempts to provide dynamically generated ADB (Android Debug Bridge) commands to aid in the validation of potential vulnerabilities it detects. It will even dynamically create a custom-built testing application, in the form of a ready to use APK, designed specifically to demonstrate the potential issues it discovers, whenever possible.โ€

  • MobSF(https://github.com/MobSF/Mobile-Security-Framework-MobSF):Mobile Security Framework (MobSF) is an automated, all-in-one mobile application (Android/iOS/Windows) pen-testing, malware analysis and security assessment framework capable of performing static and dynamic analysis.

Static Analysis(Obfuscation)

Obfuscate Code

is the process of modifying an executable so that it is no longer useful to a hacker but remains fully functional. While the process may modify actual method instructions or metadata, it does not alter the output of the program.

To be clear, with enough time and effort, almost all code can be reverse engineered. However, on some platforms (such as Java, Android, iOS and .NET) free decompilers can easily reverse-engineer source code from an executable or library in virtually no time and with no effort. Automated code obfuscation makes reverse-engineering a program difficult and economically unfeasible.

Proguard:

To obfuscate the code, use the Proguard utility, which makes these actions:

  • Removes unused variables, classes, methods, and attributes;

  • Eliminates unnecessary instructions;

  • Removes Tutorial information: obfuscate Android depuracion code;

  • Renames classes, fields, and methods with illegible names.

DEXGUARD:

The enhanced commercial version of Proguard. This tool is capable of implementing the text encryption technique and renaming classes and methods with non-ASCII symbols.

Deguard(http://apk-deguard.com/):

It is based on powerful probabilistic graphical models learned from thousands of open source programs. Using these models, Deguard retrieves important information in Android APK, including method and class names, as well as third-party libraries. Deguard can reveal string decoders and classes that handle sensitive data in Android malware.

Dynamic Analysis

Burpsuite: We have many options when it comes to proxy listeners out there. We will use Burpsuite but we could use ZAP as well. To configure Burpsuite: https://portswigger.net/support/configuring-an-android-device-to-work-with-burp. To install a certificate just download the certificate by browsing http://burpsuite or by export the certificate in burpsuite and copy to the phone. Then go to "install certificate from sd card" in settings and choose "CA certificate" then select the certificate you download.

PID CAT(https://github.com/JakeWharton/pidcat):Tool for shows log entries for a specific application package when debug=true is enable in the app.

Drozer(https://github.com/FSecureLABS/drozer): drozer helps to provide confidence that Android apps and devices being developed by, or deployed across, your organisation do not pose an unacceptable level of risk. By allowing you to interact with the Dalvik VM, other appsโ€™ IPC endpoints and the underlying OS. NOTE: I have tried to install drozer but it keeps needing old dependencies and since the lsat release is from 2017, I will not spend the time to try to install it since there are some other good tools.

Inspeckage: A good tool to replace Drozer is Inspeckage. Inspeckage is a tool developed to offer dynamic analysis of Android applications. By applying hooks to functions of the Android API, Inspeckage will help you understand what an Android application is doing at runtime. Inspeckage will let you interact with some elements of the app, such as activities and providers (even unexported ones), and apply some settings on Android.

Android Package Inspeckage Features:

  • Requested Permissions;

  • App Permissions;

  • Shared Libraries;

  • Exported and Non-exported Activities, Content Providers,Broadcast Receivers and Services;

  • Check if the app is debuggable or not;

  • Version, UID and GIDs;

  • Shared Preferences (log and file);

  • Serialization;

  • Crypto;

  • Hashes;

  • SQLite;

  • HTTP (an HTTP proxy tool is still the best alternative);

  • File System;

  • Miscellaneous (Clipboard, URL.Parse());

  • WebView;

  • IPC.

  • etc..

Insecure Data Storage

All apps (root or not) have a default data directory, which is /data/data/<package_name>.

  • databases/: here go the app's databases

  • lib/: libraries and helpers for the app

  • files/: other related files

  • shared_prefs/: preferences and settings

  • cache/: well, caches

For interact with device or emulator: adb shell

Note: It may be give you permission denied while trying to access the data directory inside the shell with or without root user. It's becasue you need a phone emulator without Google Play Store. You need to choose the Google API.

SQLITE database file

Once you are able to access the SQLite database file on an emulator, rooted device or via adb shell / run as [package name], there are a few options to inspect the schema and your SQLite database on device.

Pull the file from device first, then use a GUI software to look the schema and content. I use SQLite browser which allows you to see the database schema, table content, as well as executing some simple SQL scripts.

adb pull /data/data/package-name/databases/sqlitedatabse

Inspect SQLite db via sqlite3 command line tool

cd data/data/package-name/databases/

sqlite3 db-name

.tables

.schema table-name

Shared Preferences Files

The SharedPreferences API is commonly used to permanently save small collections of key-value pairs. Data stored in a SharedPreferences object is written to a plain-text XML file. The SharedPreferences object can be declared world-readable (accessible to all apps) or private. Misuse of the SharedPreferences API can often lead to exposure of sensitive data.

Once the activity has been called, the file key.xml will be created with the provided data.

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
  <string name="username">administrator</string>
  <string name="password">supersecret</string>
</map>

Dynamic Analysis โ€“ Complications

Root Detection in Android device

Check for Test-Keys: Test-Keys has to do with how the kernel is signed when it is compiled. By default, stock Android ROMs from Google are built with release-keys tags. Test-Keys means it is signed with a custom key generated by a third-party developer. Specifically, it will check in build properties(โ€œandroid.os.Build.TAGSโ€) for test-keys.

Check for โ€œsuโ€ binary: Su binary check is to identify the superuser in the device. This binary is installed when you try to root your phone using apps like kinguser or via fastboot in Android. These files are necessary so that one can root their phone and become the superuser. The existence of this binary can be checked from the following paths.

Check for โ€œbusyboxโ€ binary: If a device has been rooted, more often than not Busybox has been installed as well. Busybox is a binary that provides many common Linux commands. Running busybox is a good indication that a device has been rooted.

The following paths, Su and busybox binaries are often looked for on rooted devices:

    "/data/local/",
    "/data/local/bin/",
    "/data/local/xbin/",
    "/sbin/",
    "/su/bin/",
    "/system/bin/",
    "/system/bin/.ext/",
    "/system/bin/failsafe/",
    "/system/sd/xbin/",
    "/system/usr/we-need-root/",
    "/system/xbin/",
    "/system/app/Superuser.apk",
    "/cache",
    "/data",
    "/dev"

Emulator Detection

First you need to check the the pre-decompiled source code and check for functions that contains strings like โ€œgeneric | emulator | google_sdkโ€ and functions like โ€œisEmulator | emulatorDetectionโ€ฆetcโ€

SSL Pinning

Is a technique that we use in the client side to avoid man-in-the-middle attack by validating the server certificates again even after SSL handshaking. The developers embed (or pin) a list of trustful certificates to the client application during development, and use them to compare against the server certificates during runtime.

If there is a mismatch between the server and the local copy of certificates, the connection will simply be disrupted, and no further user data will be even sent to that server. This enforcement ensures that the user devices are communicating only to the dedicated trustful servers.

After you have taken in the illustration above, note that certificate pinning attempts to ensure that the client is not exchanging messages with any other server than the one they hold a public key for. Therefore, the client is not exposed to attacks where a rogue Certificate Authority (CA) validates the authenticity of a malicious host serving content with a sham certificate.

Bypass Complications in Dynamic Analysis

Frida

In short, it is a dynamic instrumentation framework, which enables function hooking and allows to provide a definition to it during runtime. Basically, it injects JavaScript code into a process. Suppose, there is a function called โ€œfooโ€ in a program with a specific body/implementation.

Using โ€œFridaโ€, one can change the body/implementation of the โ€œfooโ€ function during runtime. โ€œFridaโ€ supports a variety of platforms like Windows, macOS, GNU/Linux, iOS, Android, and QNX. More information on โ€œFridaโ€ can be found here.

pip install frida-tools

frida --version

adb push /path/serverfrida /data/local/tmp

adb shell chmod 777 /data/local/tmp/frida-server

adb shell /data/local/tmp/frida-servername&

frida-ps -U

Bypass SSL pinning tutorial

Link for tutorial: https://infosecwriteups.com/hail-frida-the-universal-ssl-pinning-bypass-for-android-e9e1d733d29

Sources:

Last updated