A step-by-step Android penetration testing guide for beginners
2023-11-11 15:54:15 Author: infosecwriteups.com(查看原文) 阅读量:12 收藏

Sandeep Vishwakarma

InfoSec Write-ups

Greetings fellow hackers, my name is Sandy, Security Analyst and Bug bounty hunter.

As I’m presently engaged in Android penetration testing, I’d like to relay my experiences with you, as they may prove beneficial in addressing some of the inquiries, I had difficulty resolving answers too, without more introductions let’s get started.

Android application security testing, commonly referred to as Android pentesting, encompasses the assessment of an Android app’s security by uncovering vulnerabilities and weaknesses within it. This comprehensive evaluation includes the scrutiny of the application’s source code, binary files, and network traffic to unearth potential security flaws. The evaluation process consists of two key components: Static Analysis and Dynamic Analysis.

Static analysis revolves around the inspection of an application’s code and configuration files without initiating its execution. Conversely, dynamic analysis entails the examination of the application while it’s in a running state, allowing for the observation of its real-time behavior and interactions. Both of these approaches are vital components of assessing the security of an Android application.

This blog will encompass all of these elements.

Table of Contents

Set up the Environment

To initiate Android pentesting, it’s essential to establish a virtual environment for your Android device. There are several Android emulators to choose from, including Genymotion, Memu, and NOX Player.

Among these options, NOX Player stands out for their user-friendly setup process. Personally, I favor NOX Player for testing due to their ease of configuration.

NOX Player

How to install the application

  1. Install from playstore — straightforward
  2. Open the filename.apk using memu apk install option / Drag and drop the apk in the nox player

3. adb install filename.apk

ADB and ADB commands

Android Debug Bridge (ADB) is a command-line utility designed to facilitate communication between a computer and an Android device. ADB offers a range of commands that empower developers and security testers to engage with an Android device, facilitating actions such as file transfers, application installation or removal, as well as the gathering of diagnostic and security-related information.

Here are some common ADB commands:

  1. adb devices: Enumerates all linked Android devices and their current statuses..
  2. adb shell: Enables the initiation of a shell session on the Android device, granting the user the ability to directly execute commands on the device.
  3. adb install [path of APK]: Deploys an Android application to the device currently connected.
  4. adb uninstall [ name of package]: Removes an application from the currently connected device.
  5. adb pull [remote path] [local path]: Duplicating a file from the Android device to the local computer.
  6. adb push [local path] [remote path]: Copying a file from an Android device to the local computer.
  7. adb bugreport: Produces a comprehensive bug report for the Android device, encompassing system logs, application data, and device details.
  8. adb screenrecord: Captures the Android device’s screen in real-time and stores it as a video file on the local computer.
  9. Start/ Stop ADB server: When a device is connected, initiate the adb server to enable interaction with the device:

adb start-server

adb kill-server

To capture logs of a specific app:

The command “adb shell pidof com.example.app” provides the Process ID (PID) of a specific app.

adb logcat — pid 15236 displays log of that app’s pid only) you can also append -f <filename> to adb logcat command

adb logcat packagename:[priority level: V, D, I, W, E, F, S]Filter log files by priority e.g. Execute ‘db logcat com.myapp:E’ to display all error logs for the ‘com.myapp’ application.

  1. adb shell: Enable direct interaction with the command-line interface of an Android device from your computer.
  2. adb shell pm list packages: Enumerates all packages currently installed on the Android device.
  3. adb shell am start [intent]: Initiates an activity on the Android device by utilizing an intent.
  4. adb shell am force-stop com.android.settings: Terminates an action on an Android device through an intent.
  5. adb shell input text [text]: Emulates the process of entering text on the keyboard of an Android device.

Extracting the APK from the device

Let’s now assume that the application is not available in the Google Play store. When an application is already installed on the device:

  1. The directory houses the APK file of an installed application.

/data/app/<package name>-1/Diva.apk

2. To get the package name, use the command adb shell pm list packages | grep exampleapp the app name is often part of the package name.

3. Once you have the package name, use the command adb shell pm path com.example.exampleapp to get the full path of the APK file.

4. Finally, retrieve the Diva.apk file using adb pull /data/app/com.example.exampleapp-1/Diva.apk

Static Analysis

Static analysis is the process of examining an application’s code, resources, and configuration files without actually running the application. It is commonly carried out by inspecting the application’s source code or its compiled binary file (APK) using tools like APKtool and dex2jar. The primary objective of static analysis is to detect potential vulnerabilities within the code, which may include insecure coding practices, data leaks, or the presence of hard-coded credentials.

Android Package (APK)

An Android Package (APK) file serves as a compressed archive housing all the necessary files for running an Android application on an Android device. Essentially, the APK file can be likened to a ZIP file, encompassing multiple components such as:

  1. AndroidManifest.xml: This file contains information about the application, including its package name, version number, required permissions, and components such as activities, services, and broadcast receivers.
  2. Classes.dex: This file contains the compiled Java bytecode for the application’s classes, which are executed by the Android Runtime (ART).
  3. Resources.arsc: This file comprises compiled assets, including strings, images, and layouts, which the application utilizes.
  4. lib/: This directory houses precompiled native code libraries tailored for distinct device architectures, including ARM and x86.
  5. META-INF/: In this folder, you will find the manifest file, the APK signature certificate, and a comprehensive list of all the APK’s files, complete with their respective checksums.
  6. assets/: This directory houses supplementary application data files, including sound and video files, which have not been integrated into the APK.
  7. res/: This directory houses the application’s resources, including layouts, strings, and images, in their initial, uncompiled state, prior to their incorporation into the Resources.arsc file.
  8. Android System Files: This directory houses critical system-level files, including the Android runtime, framework libraries, and various system components that the application might rely on.

Reverse Engineering

Mainly there are 2 Methods : DEX → JAR → JAVA and APK → JAVA

  1. DEX -> JAR -> JAVA

Dex2Jar

To install : sudo apt install dex2jar

Dex files utilize the Dalvik executable file format, which is not designed for human readability. Therefore, we must transform them into a more human-friendly language.

How to get the .dex file?

UNZIP, WINRAR

Transform the .apk file into a .zip file, and subsequently unzip it. Inside the unzipped folder, you will discover a “classes.dex” file alongside various other files.

We will employ a utility known as dex2jar, enabling the conversion of .dex files into JAR files.

We receive an executable JAR file as depicted below.

jd-gui

To Install: sudo apt install jd-gui

To access the classes.dex2jar file, you’ll require a tool known as jdgui.

For that we just open the tool and add the classes.dex2jar file in it.

  1. APK → JAVA

Using jadx Tool

To install : sudo apt install jadx

We directly transform the APK file into its corresponding Java files, offering the significant advantage of simplifying the process. This is achieved by employing the Android decompiler JADX, which enables us to effortlessly extract and view the source code from the binary app.

What to check in the code?

  1. Cryptography: Search for instances of encryption algorithms and ensure their proper implementation. Check for any hardcoded keys, weak encryption methods, or use of insecure cryptographic algorithms.
  2. Code Obfuscation: Examine for the presence of obfuscation methods employed to obscure the code and render it challenging to comprehend. These obfuscation techniques not only increase the difficulty of reverse engineering but can also conceal potentially malicious code.
  3. API Usage: Ensure that the application is free from insecure APIs or APIs with documented vulnerabilities. Examine for APIs that may permit unauthorized access or unintentional data exposure.
  4. Reflection: Examine the presence of reflection, a capability enabling the execution of code on the fly. Ensure that reflection is employed securely to prevent any potential exploitation by malicious actors attempting to inject harmful code.
  5. Dynamic Code Loading: Ensure the presence of dynamic code loading, a functionality that enables an application to load code during runtime. Confirm that the application does not load code from untrusted origins and refrains from executing any code that lacks proper verification.
  6. Access Control: Confirm that the application has effectively established appropriate access controls for sensitive features and data. Look for any hardcoded credentials or access tokens.
  7. Hardcoded sensitive information: Inspect your system for potential vulnerabilities related to the insecure storage of sensitive information, including but not limited to passwords, user credentials, and personal data. Look for instances of hardcoding in your codebase, such as database queries (SQL), passwords, encryption keys, sensitive information, and URLs.
  8. External Libraries: Ensure that the application is free from the use of insecure third-party libraries or libraries known to have vulnerabilities.
  9. Integrity Checks: Search for any measures taken by the application to verify the integrity of the code and prevent unauthorized modifications.
  10. Native Code: Ensure that the native code in the application is compiled securely and devoid of vulnerabilities if it is utilized.
  11. Web view related checks:

setJavaScriptEnabled(): This method enables or disables the use of JavaScript in a web view.When this setting is enabled, the web view gains the capability to run JavaScript code, allowing it to interact with the web page or communicate with the native Android code.However, if the application does not properly validate the input data sent to the web view, it could Enable a malicious actor to insert harmful JavaScript code.

setAllowFileAccess(): This method allows or denies access to local files in the device file system from the web view. When this option is enabled, the web view gains the ability to interact with local files, facilitating the display of local HTML files and access to data stored in the device’s file system. Nevertheless, it’s crucial to ensure that the application effectively validates the input data provided to the web view; failure to do so might expose security vulnerabilities, potentially allowing an attacker to gain access to or manipulate local files.

addJavascriptInterface(): This method allows JavaScript code in the web view to access the native Android code by exposing a Java object to JavaScript. This functionality can be harnessed to extend capabilities or interface with the underlying Android code. However, if the application does not properly validate the input data sent to the web view, it could allow an attacker to execute arbitrary Java code.

runtime.exec(): This method is used to execute shell commands on the device. If an attacker can inject malicious input data into a web view and exploit an application vulnerability, it could allow the attacker to execute arbitrary shell commands on the device.

12. Root Detection Implementation details

13. SSL Pinning Implementation details

Decompiling and Recompiling

ApkTool

APKTool is a versatile tool designed for decompiling Android APKs. It empowers users to meticulously debug smali code in a step-by-step fashion. Furthermore, it facilitates the creation of language packs by translating the .xml strings embedded within APK files.

To Install : sudo apt install apktool

Decompile an APK

Run command (for example consider Diva.apk) apktool d Diva.apk

A new folder will be created by the same name of the apk file (here example Diva)

The directory includes the AndroidManifest.xml file, the apktool.yml file, and the smali folder. This is decompiled form of apk.

Re-compiling and Signing

  1. Smali file before modification

2. Smali file after modification

Smali file after modification

3. Recompile / re-build the apk : apktool b <folder>

4. Sign the APK jarsigner.

Prior to installing the modified APK on a device, it must undergo a cryptographic signing process. To sign the app_modified.apk APK file, you should follow these steps:

1.Generate the private key.

$ keytool -genkey -v -keystore my-release-key.keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000

2.Utilize the generated private key to sign the APK.

$ jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.keystore <app_modified.apk>

If you encounter a request to specify an alias name, employ the following command instead:

$ jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.keystore <app_modified.apk> alias_name

The updated APK is now signed for a period of 10,000 days and is prepared for installation on the Android device. To proceed, make sure that USB debugging is enabled on the device, and then connect the device to the computer’s USB port before running the following command:

$ jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.key

Manifest File Analysis

Open AndroidManifest.xml using any text editor

Here we check for:-

Permissions: Check if the application requests any sensitive permissions like camera, microphone, location, SMS, or call logs.When the app asks for permissions it doesn’t genuinely need, it might raise concerns about potential privacy breaches or security vulnerabilities.

Components: Attackers can potentially exploit Android components such as activities, services, receivers, and providers to achieve unauthorized access or initiate malicious actions. Check if any of the components are exposed to other applications or if they are exported with overly permissive access.

android:exported: The default value of the attribute is true. (should be set to false)

Intents: Intents serve as the means of communication between various Android components. They enable the launching of activities, services, or the broadcasting of messages. It is essential to assess whether the app employs any implicit intents that might be vulnerable to interception or manipulation by potential attackers.

Allow debugable: true — It is not possible to extract data or execute arbitrary code with application permissions on an unrooted phone. The default value is set to “false.”

Allow backup: true — The initial setting for this attribute is set to “true”. This setting defines whether application data can be backed up and restored by a user who has enabled usb debugging.(Should be false)

Application information: Determine whether the application contains any embedded authentication details, confidential data, or debugging functionalities that might be vulnerable to exploitation by malicious actors.

Malware signatures: Determine whether the application exhibits any signs of malware, which may suggest that the app is malicious or poses a potential risk.

Target SDK version: Verify whether the application is designed for an outdated Android SDK version. Failing to target the most recent version may expose the app to well-documented security risks.

Please take the time to review all the permissions requested by the application to ensure they do not pose a security risk.

Dynamic Analysis

How to setup proxy

Configure the Burp Proxy Listener

Setting up proxy configurations for Burp Suite Professional:

  1. Launch Burp Suite Professional and then click on “Settings” to access the Settings dialog.
  2. Go to Tools > Proxy.
  3. In Proxy Listeners, click Add.
  4. In the Binding tab, set Bind to port to 8089 (or another port that is not in use).
  5. Select All interfaces and click OK.
  6. At the prompt, click Yes.

Configuring the proxy listener

Configure your device to use the proxy

  1. On your Android device, navigate to the “Network & Internet” section in the Settings menu.

2. Choose the Internet option and hold down on your Wi-Fi network’s name.

3. Select Modify.

4. Choose “Manual” from the Advanced options menu in the Proxy settings.

5. Set Proxy hostname to the IP of the computer running Burp Suite Professional.

6. Set Proxy port to the port value that you configured for the Burp Proxy listener, in this example 8089.

7. Touch Save

Set up a CA certificate on your Android device

To engage with HTTPS traffic on your Android device, it is essential to install a CA certificate from Burp Suite Professional.

To download the CA certificate

  1. In your Android device, Open any browser and Enter http://burp

2. Click on the CA certificate

3. cacert.der is available for download

4. rename the file as cacert.cer

5. Click on Download

To install the CA certificate

  1. On your Android device, navigate to Settings and then select Network & Internet.
  2. Navigate to the upper right corner and click the three dots, then choose ‘Advanced’.
  3. Select Install Certificates from Advanced Wi-Fi
  4. Select the downloaded cacert.cer file
  5. Enter a name to the certificate and click on OK
  6. Certificate installed successfully.

Installation of the CA certificate may vary depending on your Android version and device model. If the method described here doesn’t work for your specific version, please consult the following links for alternative approaches.

Link: How to Install a CA Certificate on Your Android Device.

https://blog.yarsalabs.com/setting-up-burp-for-android-application-testing/

External link: Chrome Browser Configuration for Version 99 and Higher.

Test the configuration/ Intercepting the request

To test the configuration:

Open Burp Suite Professional.

Navigate to the “Proxy” tab, then access the “Intercept” section and activate intercept by clicking the “Turn On Intercept” button.

Launch the web browser on your Android device and navigate to a webpage using HTTPS.

The page should load without any security warnings. You can observe the associated requests in Burp Suite Professional.

Local Data Storage Enumeration

To list the file structure of an installed application, you must first gain access to a physical or virtual device. This can be accomplished by utilizing the Android Debug Bridge (ADB), which is a command-line utility facilitating direct communication with the device. Using ADB, we can install and debug applications, while the Unix shell it provides can be used to run commands on the device.

Connecting via ADB

Enable the USB Debugging function on the device.

Access the settings menu, which may be labeled as “About Device” or “About Phone,” depending on your device. Next, scroll down and tap the “Build Number” option seven times until the message “You have achieved developer status!” appears.

Next, tap the back button one time and navigate to Developer Options.

After obtaining the device’s IP address, proceed to establish a connection with it using adb connect.

adb connect <ip>:5555

We can utilize the localhost IP address 127.0.0.1 when using an emulator.

This instruction will initiate a local adb server that is ready to accept new connections. As per the official ADB documentation, the adb server employs port 5555, which serves as the initial port in a sequence that the emulator will try to connect to. Once the connection is established, you can employ the “adb devices” command to enumerate the devices that are currently connected.

Important directories

Here are several crucial directories you should acquaint yourself with on an Android device:

  1. /data/data: This directory contains all user-installed applications.
  2. /data/user/0: This directory houses app-specific private data inaccessible to other applications.
  3. /data/app: This directory houses APK files for applications that have been installed by users.
  4. /system/app: This directory contains pre-installed system applications.
  5. /system/bin: This directory contains binary files.
  6. /data/local/tmp: This directory has global write permissions, which may pose a security risk.
  7. /data/system: This directory contains system configuration files.
  8. /etc/apns-conf.xml: This directory holds the default Access Point Name (APN) settings for the device, enabling it to establish a connection with the network of the current carrier.
  9. /data/misc/wifi: This directory contains WiFi configuration files.
  10. /data/misc/user/0/cacerts-added: This directory contains user-added certificates.
  11. /etc/security/cacerts/: This directory houses the system certificate store, accessible exclusively to root users.
  12. /sdcard: This directory contains a symbolic link

In the Android operating system, the ‘/data/data/’ directory houses the installation directories for all installed applications on the device. This directory is strictly private and inaccessible to other applications or non-root users. With root access granted through ADB, it is possible to enumerate the contents of this directory.

Applications that are stored in the internal memory of the device reside in the directory /data/data/.

During the installation process, directories such as databases and shared_prefs are automatically generated.

The database directory is usually populated when the app is first run, storing structured data in a private database.

With ADB access to the device, we can use the sqlite3 client to list all the accessible databases.. Or else we can pull the data to the system and analyze using sqlite viewers

For instance, when the package com.app.damnvulnerablebank is installed, a database is utilized to store data.. In that case, the database can be found under the directory /data/data/com.app.damnvulnerablebank/databases/.

Once the database is identified, we can use the sqlite3 tool to read its content.https://sqlitebrowser.org/dl/

Open Source Frameworks

Drozer is an Android security testing framework designed to empower security researchers in uncovering vulnerabilities and potential exploits within Android applications.

Ghidra is a software reverse engineering framework that helps to analyze the security of Android applications.

Androbugs is a static code analysis tool that identifies security issues and potential vulnerabilities in Android applications.

QARK is an automated analysis tool designed to perform dynamic scans of Android applications, identifying security vulnerabilities.

MobSF is a dynamic and static analysis tool that provides an all-in-one solution for mobile application security testing on Android and iOS platforms.

References

https://www.maketecheasier.com/run-android-on-desktop-with-genymotion-android-emulator/

https://azurecloudai.blog/2020/09/22/setting-up-an-android-emulator-for-testing-intune-features/

For personalize training Contact : [email protected]


文章来源: https://infosecwriteups.com/a-step-by-step-android-penetration-testing-guide-for-beginners-8435e5e969a3?source=rss----7b722bfd1b8d--bug_bounty
如有侵权请联系:admin#unsafe.sh