top of page
Search

frida, drozer, diva

  • Writer: Abhilasha
    Abhilasha
  • Jul 12, 2024
  • 13 min read

Drozer Overview

  • Version: 2.4.4

  • Type: Community edition

  • License: Open-source (3-clause BSD license)

  • Maintained by: MWR InfoSecurity

  • Download: Available on GitHub and F-Secure Labs

Installation Steps

Requirements:

  1. Drozer Client: Pre-installed in Santoku Linux.

  2. Drozer Server: Download the drozer APK from F-Secure Labs and install it on Genymotion Emulator.

Steps:

  1. Start the Drozer Server:

  • Install and run the drozer APK on Genymotion Emulator.

  • Turn on the server in the drozer app (default port: 31415).

  1. Set up the Drozer Client:

  • Open a command prompt or shell in Santoku.

  • Run drozer.

  1. Connect Drozer Client to Server:

  • Check network connection: ping [ip of Genymotion emulator].

  • Connect ADB: adb connect [ip of emulator].

  • Forward port: adb forward tcp:31415 tcp:31415.

  • Connect to drozer console: drozer console connect.

Using Drozer

Basic Commands:

  • List Modules: dz> ls (Shows all available modules).

  • List Installed Apps: dz> run app.package.list.

Example Commands:

  • Find Specific Package: dz> run app.package.list -f diva (Searches for packages containing "diva").

  • Get Package Info: dz> run app.package.info -a [package name].

  • Identify Attack Surface: dz> run app.package.attacksurface jakhar.aseem.diva.

SQL Injection Testing:

  1. Find URIs: dz> run app.provider.finduri jakhar.aseem.diva.

  2. Query URIs:

  • dz> run app.provider.query content://jakhar.aseem.diva.provider.notesprovider/notes.

  1. Automated Injection Scan: dz> run scanner.provider.injection -a jakhar.aseem.diva.

Injection Examples:

  • Projection Injection:

  • dz> run app.provider.query content://jakhar.aseem.diva.provider.notesprovider/notes/ --projection "'"

  • Selection Injection:

  • dz> run app.provider.query content://jakhar.aseem.diva.provider.notesprovider/notes/ --selection "'"

  • SQL Injection to List Tables:

  • dz> run app.provider.query content://jakhar.aseem.diva.provider.notesprovider/notes/ --projection "* FROM SQLITE_MASTER WHERE type='table'; --"

  • dz> run app.provider.query content://jakhar.aseem.diva.provider.notesprovider/notes/ --selection "* FROM SQLITE_MASTER WHERE type='table'; --"




Frida Installation on Genymotion Emulator

Here’s a simplified step-by-step guide for installing Frida on a Genymotion Android device:

Prerequisites

  1. Python: Ensure you have the latest Python 3.x installed.

  2. Genymotion: Create an Android virtual device (AVD) with API level > 7.0 to avoid installation issues.

Steps to Install Frida Server on Genymotion

  1. Ping Genymotion AVD from Host:

  • Ensure connectivity: ping [Genymotion AVD IP]

  1. Identify CPU Architecture:

  • Get Android device properties: adb shell getprop

  • Find CPU architecture:

  • adb shell getprop | grep abi

  • adb shell getprop ro.product.cpu.abi

  • Genymotion Emulator typically shows X86 CPU architecture.

  1. Download Frida Server:

  • Visit the Frida releases page.

  • Search for frida-server and download the version matching your CPU architecture (e.g., x86).

  1. Prepare Frida Server:

  • Unzip the downloaded Frida server file: unzip frida-server-15-14-1-android.xz

  • Rename the unzipped file to frida-server.

  1. Push Frida Server to Genymotion:

  • Connect to Genymotion AVD: adb connect [Genymotion AVD IP]

  • Verify connection: adb devices

  • Push Frida server to device: adb push frida-server /data/local/tmp

  1. Set Permissions and Start Frida Server:

  • Open shell: adb shell

  • Navigate to the location: cd /data/local/tmp

  • Ensure Frida server file is present: ls

  • Set execute permissions: chmod 755 frida-server

  • Start Frida server: ./frida-server

  • If you encounter an error related to getauxval, it indicates using an outdated Android version.

Install Frida Tools on Host Machine

  1. Install Frida Python Package:

  • For Python 2.x: sudo pip install frida

  • For Python 3.x: sudo pip3 install frida

  • Install Frida tools: sudo pip install frida-tools

  1. Verify Installation:

  • List processes on the connected device: frida-ps -U

  • If you see a list of modules, Frida is working correctly.

Common Uses of Frida

  • Spy on Crypto APIs: Monitor and analyze cryptographic operations.

  • Modify Function Outputs: Change the results of functions for testing or bypassing security checks.

  • Bypass AES Encryption: Circumvent encryption mechanisms.

  • Bypass SSL Pinning and Root Detection: Overcome security measures to enable debugging.

  • Trace Private Code: Analyze and understand proprietary application code.

  • Bypass Software Locks: Disable security features like app locks.


Frida Tools Overview

Frida is a powerful toolkit for dynamic analysis of Android, iOS, and Windows applications. It allows developers and security researchers to hook into target functions, inspect and modify parameters, and alter the function logic. Here's a simplified overview of some of the most useful Frida tools:

Key Features

  • Dynamic Analysis:

  • Set up hooks on target functions.

  • Inspect and modify function parameters and return values.

  • Alter the logic of hooked functions.

Commonly Used Frida Tools

  1. Frida CLI (Command Line Interface):

  • A REPL interface aimed at rapid prototyping and easy debugging.

  • Usage: frida -h for help and more options.

  1. frida-trace:

  • A tool for dynamically monitoring and tracing method calls.

  • Useful for debugging method calls and events in mobile applications.

  • Reference: Frida Trace Documentation.

  1. frida-ps:

  • A command-line tool for listing processes on a remote system.

  • Usage: frida-ps -U to list processes on a connected device.

  1. frida-discover:

  • A tool for discovering internal functions in a program.

  • These functions can then be traced using frida-trace.

  1. frida-ls-devices:

  • Lists all attached devices.

  • Useful when interacting with multiple devices.

  1. frida-kill:

  • A command-line tool for terminating processes.

Practical Usage Scenario

  • Hooking Functions:

  • You can set hooks on specific functions within an application to intercept and modify the input parameters or the return values.

  • Example: Hooking a login function to bypass authentication.

  • Dynamic Analysis:

  • Inspect how functions behave at runtime.

  • Example: Monitoring API calls in a mobile application to understand data flow and potential security issues.

Example Code Snippets

Setting a Hook:

javascript
Copy code
// Example of setting a hook on a target function
Java.perform(function() {
    var targetClass = Java.use('com.example.targetClass');
    targetClass.targetFunction.implementation = function(arg) {
        console.log('Hooked function called with argument: ' + arg);
        var returnValue = this.targetFunction(arg);
        console.log('Original return value: ' + returnValue);
        return 'Modified return value'; // Modify the return value
    };
});

Using frida-trace:

sh
Copy code
# Tracing methods in a specific class
frida-trace -U -i "com.example.targetClass.*" -f com.example.app

Listing Processes with frida-ps:

sh
Copy code
# List processes on the connected device
frida-ps -U

Summary

Frida is a versatile toolkit that simplifies the process of dynamic analysis for various platforms. It provides a range of tools that allow you to hook functions, monitor method calls, list processes, discover internal functions, and manage multiple devices. These tools are essential for debugging, security testing, and understanding the behavior of applications.

Here is a Python script that uses the Frida Python bindings to inject the provided JavaScript code into an Android application. This script sets up Frida, attaches to a target application, and loads the JavaScript code that intercepts calls to the System.exit function, logging the stack trace when it's called.

Python Script for Frida

python
Copy code
import frida
import sys

# Define the JavaScript code to be injected
js_code = """
Java.perform(function () {
    // declare classes that are going to be used
    const System = Java.use('java.lang.System');
    const Log = Java.use("android.util.Log");
    const Exception = Java.use("java.lang.Exception");

    System.exit.implementation = function() {
        console.log(Log.getStackTraceString(Exception.$new()));
    };
});
"""

# Function to handle messages from the script
def on_message(message, data):
    if message['type'] == 'send':
        print("[*] {0}".format(message['payload']))
    elif message['type'] == 'error':
        print("[!] {0}".format(message['stack']))

# Connect to the target device
device = frida.get_usb_device(timeout=5)

# Attach to the target app (replace 'com.example.app' with your target app's package name)
pid = device.spawn(['com.example.app'])
session = device.attach(pid)

# Create a script with the JavaScript code
script = session.create_script(js_code)

# Set the message handler
script.on('message', on_message)

# Load the script into the app
script.load()

# Resume the app
device.resume(pid)

print("[*] Script loaded successfully. Press Ctrl+C to quit.")

# Keep the script running
sys.stdin.read()

Explanation

  1. JavaScript Code: The js_code variable contains the JavaScript code to be injected into the target application. This code hooks the System.exit method and logs the stack trace whenever it is called.

  2. Message Handler: The on_message function processes messages sent from the injected JavaScript code. It prints messages and errors to the console.

  3. Connecting to the Device: frida.get_usb_device connects to a USB-connected Android device. If you are using an emulator or a different connection method, you may need to adjust this.

  4. Attaching to the Target App: The script spawns the target app (replace 'com.example.app' with your actual app's package name) and attaches a Frida session to it.

  5. Loading the Script: The script is loaded into the target application, and the app is resumed to continue its execution.

  6. Keeping the Script Running: sys.stdin.read() keeps the Python script running, allowing the Frida script to continue intercepting and logging System.exit calls.

Running the Script

  1. Install Frida Tools:

sh
Copy code
pip install frida frida-tools
  1. Run the Script:

sh
Copy code
python script_name.py

Replace script_name.py with the filename of your script. Make sure your target application is installed on the device or emulator, and the device is properly connected.

Here’s a step-by-step guide to hooking different methods in Java using Frida, as described by Dr. Digvijaysinh Rathod. This example demonstrates hooking the onCreate() method of an Android activity to change its behavior when the activity is created.

Step-by-Step Guide to Hooking Methods in Java with Frida

  1. Extract the APK:

  • First, find the path of the APK using ADB:

sh
Copy code
adb shell pm path jakhar.aseem.diva
  1. Pull the APK from the device:

sh
Copy code
adb pull /data/app/jakhar.aseem.diva-dxAm4hRxYY4VgIq2X5zU6w==/base.apk
  1. Decompile the APK:

  • Use apktool to decompile the APK:

sh
Copy code
apktool d base.apk
  1. Use dex2jar to convert the APK to a JAR file:

sh
Copy code
d2j-dex2jar.sh base.apk
  1. Use jd-gui to view the decompiled source code:

sh
Copy code
jd-gui base-dex2jar.jar
  1. Hook the onCreate() Method:

  • Write a Frida script (mainactivityhook.js) to hook the onCreate() method:

javascript
Copy code
console.log("Script loaded!");

Java.perform(function() {
    var mainapp = Java.use("jakhar.aseem.diva.MainActivity");

    mainapp.onCreate.implementation = function(bundle) {
        console.log("My script called!");

        var ret = this.onCreate.overload("android.os.Bundle").call(this, bundle);

        return ret;
    };

    send("Hooks installed");
});
  1. Explanation of the Frida Script:

  • Perform Function: The main implementation of the hook is put inside Java.perform(function() { <code> }).

  • Use Method: The activity we want to hook (MainActivity) is accessed using Java.use("jakhar.aseem.diva.MainActivity") and assigned to a variable (mainapp).

  • Implementation: onCreate.implementation sets a new implementation of the onCreate() method.

  • Log Message: Insert any code you want to run in the onCreate() method. Here, a log function outputs “My script called!” every time onCreate is called.

  • Overload Method: The overload method is used to specify the method signature (with android.os.Bundle as a parameter). The call method is used to call the original method with this and bundle as parameters.

  • Send Function: The send() function outputs text to the current Frida command line.

  1. Launch the Frida Script:

  • Use Frida to load the script into the target application:

sh
Copy code
frida -U -l mainactivityhook.js -f jakhar.aseem.diva

This command connects to a USB device (-U), loads the mainactivityhook.js script (-l), and starts the application (-f jakhar.aseem.diva).

Running the Hook

When the script is running and the target activity (MainActivity) is created, the console will display "My script called!" indicating that the hook is successfully installed and the custom behavior is executed.

Summary

By following these steps, you can dynamically analyze and modify the behavior of Android applications without access to their source code. This method is useful for various purposes, such as security assessments, debugging, and understanding the inner workings of an application.


Here's a guide on how to hook a custom-defined method using Frida, specifically targeting the startChallenge() method in the Diva app, as described by Dr. Digvijaysinh Rathod. This method demonstrates how to intercept and modify the behavior of custom methods in Android applications.

Step-by-Step Guide to Hooking a Custom-Defined Method with Frida

  1. Inspect the Decompiled Code:

  • After decompiling the APK as shown in previous steps, inspect the code to find the custom method startChallenge() in the MainActivity.

  • Identify the method signature, which in this case is startChallenge(android.view.View).

  1. Hook the startChallenge() Method:

  • Create a Frida script (main_startchallenge.js) to hook the startChallenge() method:

javascript
Copy code
console.log("Hooked startChallenge() function");

Java.perform(function(){
    var newstart = Java.use("jakhar.aseem.diva.MainActivity");

    newstart.startChallenge.overload("android.view.View").implementation = function(v) {
        // Enter any implementation of startChallenge you want
        // For demo, I'm just sending an alert on Frida console
        send("MainActivity.startChallenge() is now started");

        // Call the original method
        var ret = this.startChallenge.overload("android.view.View").call(this, v);

        // Return the result
        return ret;
    };
});
  1. Explanation of the Frida Script:

  • Console Log: A log statement to indicate that the script has been loaded and the function has been hooked.

  • Java Perform: The main implementation of the hook is put inside Java.perform(function() { <code> }).

  • Use Method: The activity we want to hook (MainActivity) is accessed using Java.use("jakhar.aseem.diva.MainActivity") and assigned to a variable (newstart).

  • Overload Method: The startChallenge method with the android.view.View parameter is identified and hooked.

  • Custom Implementation: Any code you want to execute when startChallenge is called is placed inside the implementation function. Here, it sends a message to the Frida console.

  • Call Original Method: The original method is called using the overload method and passing the android.view.View parameter.

  • Return Result: The result of the original method call is returned.

  1. Launch the Frida Script:

  • Use Frida to load the script into the target application without pausing the app:

sh
Copy code
frida -U -l main_startchallenge.js -f jakhar.aseem.diva --no-pause

This command connects to a USB device (-U), loads the main_startchallenge.js script (-l), and starts the application (-f jakhar.aseem.diva) without pausing it (--no-pause).

Running the Hook

When the script is running and the startChallenge() method is called (e.g., when the user presses a button to start a challenge), the console will display "MainActivity.startChallenge() is now started," indicating that the hook is successfully installed and the custom behavior is executed.

Summary

By following these steps, you can intercept and modify the behavior of custom methods in Android applications. This method is useful for dynamic analysis, security assessments, and understanding the functionality of custom-defined methods in apps.


To hook and intercept the exit() method in an Android application using Frida, follow these steps as outlined by Dr. Digvijaysinh Rathod. This method allows you to prevent the application from exiting when the exit() function is called.

Step-by-Step Guide to Hooking the exit() Method with Frida

  1. Identify the exit() Method:

  • Determine which class contains the exit() method. Typically, it is java.lang.System.

  1. Create the Frida Script:

  • Develop a Frida script (avoidexit.js) to hook the exit() method:

javascript
Copy code
console.log("Hooking on exit function");

Java.perform(function(){
    var sysexit = Java.use("java.lang.System");

    // Hook the exit() method
    sysexit.exit.overload("int").implementation = function(var_0) {
        send("I've stopped java.lang.System.exit() now!");
    };
});
  1. Explanation of the Frida Script:

  • Console Log: Indicates that the script has successfully hooked the exit() function.

  • Java Perform: The main implementation of the hook is put inside Java.perform(function() { <code> }).

  • Use Method: Accesses the java.lang.System class and assigns it to sysexit.

  • Overload Method: Hooks the exit() method using overload("int"), which specifies the parameter type (in this case, an integer).

  • Implementation Function: Defines what happens when the exit() method is called. Here, it sends a message to the Frida console indicating that the exit() method has been intercepted.

  1. Launch the Frida Script:

  • Execute Frida to load the script into the target application without pausing:

sh
Copy code
frida -U -l avoidexit.js -f com.example.harshitrajpal --no-pause
  1. Replace com.example.harshitrajpal with the package name of your target application.

Running the Hook

When the script is loaded and running, every time the exit() method is invoked within the target application (e.g., when the user presses an "Exit" button), the message "I've stopped java.lang.System.exit() now!" will be sent to the Frida console. This demonstrates that the exit process has been intercepted and modified by the Frida script.

Summary

By following these steps, you can effectively intercept and modify the behavior of critical methods like exit() in Android applications using Frida. This capability is crucial for dynamic analysis, debugging, and testing purposes, allowing you to manipulate and understand application behavior without modifying its source code directly.


To hook and manipulate the return value of a method in an Android application using Frida, you can follow these steps as outlined by Dr. Digvijaysinh Rathod. This method allows you to change the returned value from a method call within the application.

Step-by-Step Guide to Hooking and Manipulating Return Values with Frida

  1. Identify the Target Method:

  • Determine the method whose return value you want to intercept and modify. For example, returnValue() in com.example.harshitrajpal.MainActivity.

  1. Create the Frida Script:

  • Develop a Frida script (retValueHook.js) to hook the returnValue() method and manipulate its return value:

javascript
Copy code
console.log("Hook for implementation of method");

Java.perform(function() {
    var myClass = Java.use("com.example.harshitrajpal.MainActivity");

    myClass.returnValue.implementation = function() {
        // Manipulate the return value here
        var ret = 100; // Change the return value to 100
        return ret;
    };
});
  1. Explanation of the Frida Script:

  • Console Log: Indicates that the script has successfully hooked the method.

  • Java Perform: Executes the hook implementation within Java.perform(function() { ... }).

  • Use Method: Accesses the com.example.harshitrajpal.MainActivity class and assigns it to myClass.

  • Implementation Function: Defines what happens when returnValue() is called. Here, it replaces the original return value with 100.

  1. Launch the Frida Script:

  • Execute Frida to load the script into the target application without pausing:

sh
Copy code
frida -U -l retValueHook.js -f com.example.harshitrajpal --no-pause
  1. Replace com.example.harshitrajpal with the package name of your target application.

Running the Hook

When the script is loaded and running, every time the returnValue() method is called within the target application, it will return 100 instead of its original return value. This demonstrates how you can intercept and modify return values dynamically using Frida.

Summary

By following these steps, you can effectively manipulate return values of methods in Android applications using Frida. This capability is useful for various purposes such as debugging, testing, or modifying application behavior without needing to modify the application's source code directly.

It seems like you're discussing some important Frida APIs related to Android application analysis and manipulation. Here's a breakdown of the APIs you mentioned:

Java.available

  • Purpose: Checks if Frida is running on an Android device.

  • Usage: Useful for creating scripts that behave differently based on the operating system (Android or iOS).

  • Return: Returns true if Frida is running on Android (Dalvik or ART), otherwise false.

Java.androidVersion

  • Purpose: Retrieves the Android version of the device.

  • Usage: Allows scripts to adapt behavior based on the Android version running on the device.

  • Return: Returns the Android version as a string or number.

Java.enumerateLoadedClasses(callback)

  • Purpose: Enumerates all loaded classes in the current Java VM.

  • Usage: Enables scripts to interact with or hook specific classes dynamically.

  • Parameters:

  • callback: Specifies functions to handle each loaded class (onMatch(name, handle)) and completion (onComplete()).

  • Behavior:

  • onMatch(name, handle): Called for each loaded class, providing the class name that can be passed to use() to create a JavaScript wrapper.

  • onComplete(): Called when enumeration of all classes is complete.

Example Use Case

javascript
Copy code
console.log("Checking Frida availability on Android...");
if (Java.available) {
    console.log("Frida is available on Android!");
    var androidVersion = Java.androidVersion;
    console.log("Android version:", androidVersion);

    Java.enumerateLoadedClasses({
        onMatch: function(className) {
            console.log("Found class:", className);
            // Example: Hook a specific class
            if (className === "com.example.MyClass") {
                var myClass = Java.use(className);
                // Perform hooks or modifications here
            }
        },
        onComplete: function() {
            console.log("Enumeration of classes complete.");
        }
    });
} else {
    console.log("Frida is not available on this device.");
}

Summary

These Frida APIs (Java.available, Java.androidVersion, Java.enumerateLoadedClasses) are powerful for dynamic analysis and manipulation of Android applications. They allow you to determine Frida's presence, gather device information, and interact with loaded Java classes, enabling sophisticated script behavior based on runtime conditions.

DIVA (Damn Insecure and Vulnerable App) is a purposely designed vulnerable Android application created for security professionals, developers, and enthusiasts to practice and learn about mobile application security. Developed by Payatu, DIVA contains various vulnerabilities for users to identify and exploit, making it an excellent resource for hands-on training in mobile security.

Overview of DIVA

DIVA has several built-in challenges that simulate real-world vulnerabilities. These challenges are categorized into different levels and types of vulnerabilities, allowing users to practice and understand a wide range of security issues that can affect Android applications.

Key Features and Vulnerabilities

  1. Insecure Data Storage:

  • Challenges related to improper handling and storage of sensitive data.

  • Users learn about the risks associated with storing sensitive information in plaintext on the device.

  1. Hardcoding Issues:

  • Challenges where sensitive information (e.g., passwords, keys) is hardcoded in the source code.

  • Users practice extracting and exploiting these hardcoded values.

  1. Insecure Communication:

  • Challenges involving insecure transmission of data between the app and servers.

  • Users can learn about intercepting and tampering with data using tools like Burp Suite.

  1. Insecure Logging:

  • Challenges where sensitive data is logged inappropriately.

  • Users learn to find and exploit these logging issues.

  1. Access Control Issues:

  • Challenges related to improper access control mechanisms.

  • Users learn about bypassing access controls to gain unauthorized access.

  1. Vulnerable Components:

  • Challenges involving the use of outdated or vulnerable third-party libraries.

  • Users learn to identify and exploit these vulnerabilities.

Tools and Techniques

To work with DIVA and exploit its vulnerabilities, several tools and techniques are commonly used:

  • Static Analysis: Analyzing the app's source code or decompiled code to identify vulnerabilities.

  • Tools: JADX, APKTool, etc.

  • Dynamic Analysis: Running the app in a controlled environment to observe its behavior and identify vulnerabilities.

  • Tools: Frida, Xposed Framework, etc.

  • Network Analysis: Intercepting and analyzing network traffic between the app and backend servers.

  • Tools: Burp Suite, Wireshark, etc.

Getting Started with DIVA

  1. Download and Install:

  1. Setup Environment:

  • Set up necessary tools for analysis and exploitation, such as Android Studio, Burp Suite, JADX, etc.

  1. Begin with Challenges:

  • Start with basic challenges and progressively move to advanced ones.

  • Document findings and understand the implications of each vulnerability.

Practical Example

Let's go through a basic example of exploiting an insecure data storage vulnerability in DIVA:

  1. Identify the Vulnerability:

  • Open DIVA and navigate to the challenge related to insecure data storage.

  1. Analyze the Code:

  • Use a decompiler like JADX to inspect the source code.

  • Look for where sensitive data is stored (e.g., SharedPreferences, SQLite database).

  1. Exploit the Vulnerability:

  • Use tools like ADB (Android Debug Bridge) to access the device's file system.

  • Locate the file where sensitive data is stored and extract it.

  1. Verify the Exploit:

  • Confirm that the extracted data is readable and sensitive (e.g., passwords, personal information).

Conclusion

DIVA is a powerful learning tool for anyone interested in mobile application security. By working through its challenges, users can gain hands-on experience with a variety of vulnerabilities, enhancing their skills in identifying and mitigating security issues in real-world Android applications.


 
 
 

Recent Posts

See All
PE internals

Linked Libraries and Functions Imported Functions: Definition: These are functions used by a program that are actually stored in...

 
 
 
OS internals

Privilege Separation Concept: Modern operating systems separate user applications (untrusted) from critical operating system components...

 
 
 
Memory Management in short

Address Space CPU Access: To run instructions and access data in main memory, the CPU needs unique addresses for that data. Definition:...

 
 
 

Comments


Subscribe Form

Thanks for submitting!

©2021 by just dump 1. Proudly created with Wix.com

bottom of page