Mastering Mobile Security: A Guide with Damn Vulnerable Bank

14 min read

May 8, 2024

Securing Android: An In-Depth Exploration
Mastering Mobile Security: A Guide with Damn Vulnerable Bank

Table of contents

Introduction to Mobile Application Security Auditing: Embracing the Challenge with "Damn Vulnerable Bank"

Welcome to the first chapter of my series on Android security concepts, featuring a detailed exploration of mobile application security through "Damn Vulnerable Bank" (DVB), a deliberately insecure Android application. This chapter lays the groundwork for understanding and testing mobile security, offering a structured learning path that follows the OWASP Mobile Application Security Testing Guide (MASTG). As I guide you through various methodologies, tools, and practical challenges, this series will equip you with the expertise needed to audit mobile applications effectively.

Key Takeaways of this chapter:

  • Methodology Grounded in OWASP MASTG: My approach closely follows the comprehensive and accessible guidelines provided by OWASP MASTG, ensuring a robust framework for auditing Android applications. This guide not only teaches the 'how' but also explains the 'why' behind each testing technique, serving as a foundation for the upcoming chapters.
  • Practical Lab Setup: Whether you're using a physical rooted device or a virtual machine, setting up your lab is the first critical step. Tools like Android-x86 on platforms like Proxmox or VMware, combined with network proxying through BurpSuite, provide a controlled and insightful testing environment that we will build upon in subsequent chapters.
  • In-Depth Application Analysis with "Damn Vulnerable Bank": DVB is not just an app; it's an educational tool designed to simulate a real-world banking environment filled with intentional vulnerabilities. By engaging with DVB, learners can safely explore and exploit these weaknesses to gain a deep understanding of common security flaws—a theme that will be expanded in later sections.
  • Technological Insights: DVB is built on common technologies such as Java, Kotlin, SQLite, and the Android SDK, intertwined with a REST API. These technologies, prevalent in many real-world applications, make DVB an excellent model for learning about potential misconfigurations and vulnerabilities, insights that we will apply and explore further in our series.
  • Hands-On Security Testing: From user authentication and account management to transaction security and administrative functions, DVB offers a comprehensive feature set for practical security testing. Each feature not only provides utility but also serves as a potential point of vulnerability, offering myriad opportunities for security analysis which we will continue to uncover.
  • Advanced Techniques in Decompiling and Reverse Engineering: Tools like APKTool and ApkX are instrumental in decompiling APK files to their foundational code, allowing for detailed analysis and modification of the app's behavior. This process is crucial for understanding and mitigating the application’s built-in defense mechanisms, a skill that will be crucial as we delve deeper into specific vulnerabilities and defense strategies.
  • Dynamic Analysis with Frida: Learn to use Frida, a dynamic instrumentation toolkit, to modify application behavior in real-time. This powerful tool facilitates the injection of custom scripts to probe and alter app functionalities, providing a hands-on experience in dynamic application security testing—a technique that will be pivotal in our ongoing exploration of Android security.

By the chapter's conclusion, you’ll not only know how to set up and break down an application but also how to recompile and sign an APK, ensuring it meets security standards before redistribution. Through the structured exploration of "Damn Vulnerable Bank," this chapter aims to instill a profound understanding of mobile application security challenges and how to tackle them effectively. Whether you are a novice eager to dive into the world of app security or an experienced auditor refining your skills, this guide provides the knowledge and tools necessary to navigate the complex landscape of mobile vulnerabilities, setting the stage for more advanced topics in our series.

Methodology

In my previous series, I've dedicated specific articles to methodology. For auditing Android applications, however, I recommend following the OWASP guide—it's comprehensive and straightforward. I typically explore the "techniques" section, applying each test to see how the application reacts. If you're new to Android auditing, this guide will provide essential context and introduce you to the tools most frequently used in the field.

OWASP MASTG - OWASP Mobile Application Security
Android hacking techniques

Lab Setup

First up, we'll set up our lab for testing. You have two main options: using a physical rooted mobile phone or a virtual machine. For simplicity, I'll use a virtual machine in this guide. If you're looking to set it up with Proxmox, I highly recommend following the detailed guidelines provided in the linked article below. This article not only explains how to install everything using Proxmox but also covers essential setups for BurpSuite and getting started with ADB. It's crucial to familiarize yourself with these tools and configurations before continuing with the rest of the series.

Installing Android-x86 on Proxmox and Proxying to BurpSuite
In this post, I show you how to set up an Android-x86 VM in Proxmox and proxy the entire system through BurpSuite.

Alternatively, if you prefer using VMware instead of Proxmox, the same instructions apply with slight modifications for the VMware environment. Once your virtual machine is ready, we'll proceed with installing the application.

Getting to Know Damn Vulnerable Bank

Damn Vulnerable Bank is more than just an app—it's a unique learning tool designed for anyone curious about mobile security. Think of it as your playground for discovering the ins and outs of app security without any real-world risks. This Android app simulates a banking environment filled with deliberate security flaws, providing a perfect, legal sandbox for you to test your hacking skills and learn about vulnerabilities in a hands-on way.

GitHub - rewanthtammana/Damn-Vulnerable-Bank: Damn Vulnerable Bank is designed to be an intentionally vulnerable android application. This provides an interface to assess your android application security hacking skills.
Damn Vulnerable Bank is designed to be an intentionally vulnerable android application. This provides an interface to assess your android application security hacking skills. - rewanthtammana/Damn-…

What's Under the Hood?

Let’s break down the tech stack of Damn Vulnerable Bank:

  • Java and Kotlin: These are the main languages used to bring the app to life, handling everything from the user interface to the complex logic behind the scenes.
  • SQLite: This is where all your data magic happens—user information, transaction details, you name it—all stored safely on your local device... or so you'd hope!
  • Android SDK: This toolkit is the backbone that helps the app interact seamlessly with your Android device’s hardware and software.
  • REST API: The bridge between the app and its backend server, managing all the data exchanges that aren’t handled directly on your device.

These technologies are widely used in real-world apps but often come with their share of misconfigurations and outdated practices, making Damn Vulnerable Bank a great model to learn from.

Key Features to Explore

Damn Vulnerable Bank is packed with features that mimic a real banking app:

  • User Authentication: This includes everything from logging in to managing sessions. It sounds simple, but there's a lot that can go wrong if not done correctly.
  • Account Management: Check balances, transfer money, and set up payments—standard bank stuff that we'll dive into to uncover potential risks.
  • Transaction Security: Features like OTPs (One-Time Passwords) add an extra layer of security for transactions. We'll see how secure these really are when put to the test.
  • Administrative Functions: Reserved for the 'big bosses' of the app, these functions allow control over user accounts and other critical settings.

Each of these features not only makes the app useful, but also a goldmine for learning about common security pitfalls and how to avoid or exploit them in the name of education.

Why This Matters

In essence, Damn Vulnerable Bank is your go-to resource if you’re keen to dive deep into the world of app security. It’s set up to help you understand and tackle real security challenges faced by apps today, all in a fun and safe environment.

Installation of the application

To install the application, we can utilize ADB, a versatile tool discussed in the article referenced during the lab setup. ADB enables various administrative operations on Android systems.

adb connect <ip>
adb shell
Installing the apk via adb

After installation, by navigating to our applications, the new app will be clearly visible within the system.

Application display

Decompilation of the application

One issue that arises when attempting to open the application is that it immediately closes. I've chosen this particular application to teach Android device hacking because it incorporates defense mechanisms that mimic real-world scenarios, thus providing a more authentic learning experience.

In such cases, we need to engage in some reverse engineering to understand the application's architecture. APKTool, an open-source utility, is instrumental for decompiling and recompiling APK files—the installation packages for Android apps. It extracts XML and .dex files from APKs and converts these .dex files into smali, a low-level intermediate representation of Dalvik bytecode used by the Android Virtual Machine. This transformation grants access to the Android app's source code at the bytecode level, allowing for precise modifications. However, working with smali is inherently complex as it is closer to machine code than high-level Java, making it more challenging to read and comprehend. Later in this chapter, we will discuss techniques to convert the code back to Java for more straightforward analysis and modifications.

Decompilation using apktool
Example code in smali

Post-decompilation, we'll conduct an in-depth analysis of the application's components. Typically, the initial step involves examining the "AndroidManifest.xml" file, a critical element within any Android app. It acts as a roadmap, detailing vital information to the operating system about the application, including package name, version, required permissions, activities, services, broadcast receivers, and more.

AndroidManifest.xml

In this scenario, since we're operating in a virtual environment, we will disable the hardware acceleration setting, which could be causing the application to crash. Setting its value to 'false' should rectify the issue.

Disabling GPU acceleration

Subsequently, we will uninstall the current application and compile a new APK with the hardware acceleration disabled:

adb uninstall com.app.damnvulnerablebank
apktool b dvba/ -o dvba-no-gpu.apk

Signing the application

Attempting to install the newly compiled APK without GPU configuration will result in an error, as the application lacks a necessary security certificate. To resolve this, we'll create a keystore containing both a public and a private key:

Attempt to install the application without signature
Key generation
keytool -genkey -v -keystore my-release-key.keystore -alias dvba-no-gpu.apk -keyalg RSA -keysize 2048 -validity 10000

Next, we'll use jarsigner to sign the application using the keys we just generated:

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.keystore dvba-no-gpu.apk dvba-no-gpu.apk

This process will allow you to install the application without encountering security errors. However, you may find that the application still closes immediately upon opening, suggesting the presence of another defense mechanism designed to thwart operation on rooted or emulated mobile devices.

Reverse engineering

To address the immediate closure of the application upon opening, we need to delve into reverse engineering again. The first step is to decompile the application and retrieve the Java source code. For this, ApkX is an excellent choice. Unlike other tools that convert .dex files into lower-level formats like smali (apktool for example), ApkX directly decompiles these files back into Java. This approach provides a code representation that is much closer to the original, making it easier to read, understand, and modify. ApkX not only efficiently unpacks APKs and extracts files and resources but also uses advanced techniques to reconstruct a high-level overview of the application’s functionality, offering quick insights into its coding structure.

GitHub - muellerberndt/apkx: One-Step APK Decompilation With Multiple Backends
One-Step APK Decompilation With Multiple Backends. Contribute to muellerberndt/apkx development by creating an account on GitHub.
Use of APKx to decompile

Next, we need to identify the root cause of the application's behavior. Using tools like grep to search through the code can be highly effective. In this instance, searching for the term "Emulator" reveals relevant matches.

Measurement detection against systems that are being Emulated

Examining the "MainActivity.java" file, it becomes apparent that the application is designed to terminate if it detects that the device is rooted or if tools like Frida are in use.

Code to be executed in case of Frida detection or Emulation

To resolve the issue with the application, we have two options. One approach is to comment out the code that triggers the termination and recompile the application to create a patched version. The alternative, which we will pursue, is to use Frida to dynamically patch the application during runtime, circumventing the need for permanent modifications to the code.

Frida is a dynamic instrumentation toolkit widely used for debugging and analyzing application behaviors across various platforms, including Windows, macOS, Linux, iOS, and Android. It allows developers and security researchers to inject custom scripts into running processes to monitor, modify, and probe their internal operations. This is especially useful for identifying security vulnerabilities, diagnosing issues, or understanding complex software functionalities. Frida operates by attaching to the application process and provides a framework for executing real-time code snippets, intercepting function calls, and manipulating data and control flows within the app. Its capabilities make it an invaluable tool for dynamic analysis and reverse engineering tasks.

Introduction to Frida

To begin using Frida for Android security auditing, the first step is to ensure the Frida server is running on the Android device. To determine the correct version of Frida server needed for your device or emulator, execute the following command:

adb connect <ip>
adb shell
uname -m 
Architecture of my machine

Based on the architecture returned by the command, select the appropriate Frida server version.

Release Frida 14.1.3 · frida/frida
See https://frida.re/news/ for details.
Version selected in my case

After determining the correct version, the next step involves transferring the Frida server binary to the Android device using the ADB tool. Here’s how you can upload the binary:

adb push frida-server /sdcard
adb shell
su
cp sdcard/frida-server /data/local/
chmod +x /data/local/frida-server
/data/local/frida-server -l 0.0.0.0:27042

Once Frida server is running, you can operate Frida from your machine. In the following example I have listed different processes that are running on the mobile phone.

Verifying that Frida is running correctly

The next crucial phase is crafting a Frida script that dynamically patches the application based on your specific needs. This aspect of an Android audit is incredibly powerful, as it allows you to modify virtually any behavior of the application, provided you understand the code.

We’ll use JavaScript for scripting. Below is a sample script with comments to guide you. This script changes the return value of a method so that the application does not terminate on an emulator:

setTimeout(function() {
    Java.perform(function() {
        var className = "a.a.a.a.a"; // Ensure this is the correct class name

        try {
            var targetClass = Java.use(className);
            console.log('Class loaded:', className); // Confirmation that the class is loaded

            // Ensure that the method R exists before attempting to hook it
            if (targetClass.R) {
                var originalMethod = targetClass.R.implementation;

                targetClass.R.implementation = function() {
                    // Direct call to the original implementation within the new implementation
                    var originalReturnValue = this.R();
                    console.log("Original return value =", originalReturnValue); // Debug for original value

                    return !originalReturnValue; // Negate the original return value
                };

                console.log("Method 'R' has been successfully hooked.");
            } else {
                console.log("Method 'R' not found in class " + className);
            }
        } catch (e) {
            console.log("Error while trying to hook the class or method:", e);
        }
    });
}, 10);

The effectiveness of the script is confirmed when we detect that the method returns True, leading to the application's termination. By altering it to False, we bypass this issue. However, the application still terminates because it detects the use of Frida:

frida -U -l bypass-detection.js -f com.app.damnvulnerablebank
Detection of successfully evaded emulation

To overcome this, another script is needed to manipulate the Frida detection mechanism. Below is a script that alters the return value of the Frida detection function, ensuring the application does not terminate:

Java.perform(function () {
    console.log("looking for FridaCheckJNI.fridaCheck()");

    try {
        const FridaCheckJNI = Java.use('com.app.damnvulnerablebank.FridaCheckJNI');

        FridaCheckJNI.fridaCheck.implementation = function() {
            console.log("hooking fridaCheck().");
            var value = this.fridaCheck.call(this);
            console.log("fridaCheck() returned " + value);
            console.log("switching fridaCheck() to 0");
            return 0;  // Always return 0 to bypass checks
        };
    } catch (e) {
        console.log("Failed to hook fridaCheck: " + e.message);
    }
});

Running both scripts together with Frida finally grants access to the application, circumventing the implemented security measures:

frida -U -l bypass-detection.js -l bypass-frida-check.js -f com.app.damnvulnerablebank
Execution of both scripts to evade all detections
Successful access to the application

Conclusions: Empowering Mobile Application Security Through "Damn Vulnerable Bank"

In this opening chapter of our Android security series, we've navigated through "Damn Vulnerable Bank" (DVB), a simulated environment for real-world vulnerabilities. Through robust methodologies, practical labs, and detailed analyses, this chapter has enhanced our ability to identify and exploit vulnerabilities, deepening our understanding of mobile application security's importance.

Adopting the OWASP Mobile Application Security Testing Guide (MASTG) provided a clear framework for auditing, while the setup flexibility of using either a physical device or a virtual machine enabled a realistic testing environment. DVB proved invaluable in demonstrating practical security weaknesses and exploring the technology stack including Java, Kotlin, SQLite, and the Android SDK integrated with a REST API.

Advanced techniques demonstrated with tools like APKTool and ApkX, and dynamic analysis with Frida, have highlighted the necessity of proactive security practices. By the end, not only have you learned to set up and dissect application security features but also understood the nuances of recompiling and signing applications to meet security standards. "Damn Vulnerable Bank" has opened the door to mastering mobile application security, setting the stage for further exploration and skill enhancement in subsequent chapters. Whether you're a beginner or a seasoned professional, the insights from this chapter are essential for anyone looking to improve mobile application security.

Resources

Damn Vulnerable Bank
Damn Vulnerable Bank is designed to be an intentionally vulnerable android application. This provides an interface to assess your android application security hacking skills.