Analysis of Malware in Android

1. Introduction and Objectives


In this article, we will conduct the analysis of a well-known malware targeting Android. Specifically, we will examine a “Meterpreter” originated using the “Msfvenom” tool belonging to the Metasploit framework.

For those unfamiliar with a “Meterpreter” application, it’s a command interpreter that allows interaction with the victim machine, offering high flexibility and reliability. In other words, it’s malware that provides the attacker with complete control over the infected machine, enabling command execution, webcam viewing, microphone listening, and numerous other fascinating functions. We will define what a “Meterpreter session” is later on. I recommend reading the book “Metasploit for Pentesters” to learn more.

As we will see throughout this article, this application encompasses a multitude of functionalities aimed at trojanizing the victim’s system and launching post-exploitation modules to carry out tasks such as privilege escalation, credential theft, exfiltration of information to a command and control (C2) system, and more.

For guidance on setting up an analysis lab, you can refer to my article titled “Vulnerability Analysis in Android Applications.


2. Creating a Malicious APK: Android Meterpreter


We will proceed to create malware for the purpose of later analyzing it for educational purposes. To create the malware, we will utilize the “msfvenom” tool from the Metasploit framework.

Below is a screenshot depicting how to create the mentioned malware and how, once created, we sign it in order to bypass certain filters from programs that verify the legitimacy of the source of the new executable. These programs include antivirus software and intrusion detection systems.



The parameters that need to be passed as arguments to “msfvenom” are as follows:

  • -p: The payload we want to launch on the victim machine. In this case, we have chosen for the victim to connect to our attacking machine, providing us with its command shell through a “Meterpreter” session.
  • LHOST: (Local HOST) Here, we need to specify our IP address, i.e., that of the attacking machine.
  • LPORT: (Local PORT) We should indicate the port on our attacking machine to which we want the victim to connect in order to hand over its command shell.
  • -R >: Output specification. We provide the name of the output file. We specify that the new binary file will be in “Raw” format. This ensures flexibility for making subsequent changes, such as securely signing it.

Subsequently, we see how by configuring these parameters, “msfvenom” will generate a malicious binary that will execute the defined payload and establish a connection with the IP address and port we have specified. It’s important to note that the use of this information should be responsible and legal, and should only be performed with permission in controlled and ethical environments.


3. Analysis of the Malicious Application “Android Meterpreter”


To fulfill the analysis of this malware, we will make use of the “Santoku” virtual machine for VMware, which can be downloaded from its official repository.

We start from the premise that the app created in the previous section has been installed on our smartphone.

Conducting a network analysis of the smartphone, we have detected a connection to an IP address whose code is within the package “com.metasploit.stage”.

If we navigate to the list of running apps on Android (Settings → Applications), we can indeed observe that an app named “MainActivity” is running, with its process belonging to the package “com.metasploit.stage”.

Furthermore, we can see that following its execution, a reverse shell from the victim machine (the smartphone) has been received by our attacking machine.



Among the installed apps, you can find one named “MainActivity.” Upon executing it, we can observe that it seemingly doesn’t carry out any visible action. However, we can confirm that it is indeed running.



Next, we proceed to download the app for analysis. In the terminal of the device, to locate the app for download, we execute the following commands:

$ pm list packages | grep meta

package:com.metasploit.stage

$ pm path com.metasploit.stage package:/data/app/com.metasploit.stage/mai.apk

Once the path to the location of the APK to be analyzed is identified, we proceed to download it into our LAB using the “adb pull” command, as shown below:

$ adb pull /data/app/com.metasploit.stage/mai.apk

[100%] /data/app/com.metasploit.stage/mai.apk

Once we have the “APK” in our LAB, we initiate the analysis.


3.1 Preliminary Analysis


To conduct the preliminary analysis of the app, we will utilize “drozer.” It’s important to clarify that “drozer” is not a malware detection tool, but rather a vulnerability assessment tool. However, it can provide information that might aid in malware detection. Once “drozer” is executed, we can obtain basic information about the app as well as the list of permissions it requires using the following command:

dz> run app.package.info -a com.metasploit.stage

Package: com.metasploit.stage Application Label: MainActivity Process

Data Directory: /data/data/com.metasploit.stage

APK Path: /data/app/com.metasploit.stage/mai.apk

Permissions:

  • Android.permission.INTERNET
  • Android.permission.ACCESS_WIFI_STATE
  • Android.permission.CHANGE_WIFI_STATE
  • Android.permission.ACCESS_NETWORK_STATE
  • Android.permission.ACCESS_COURSE_LOCATION
  • Android.permission.ACCESS_FINE_LOCATION
  • Android.permission.READ_PHONE_STATE
  • Android.permission.SEND_SMS
  • Android.permission.RECEIVE_SMS
  • Android.permission.RECORD_AUDIO
  • Android.permission.CALL_PHONE
  • Android.permission.READ_CONTACTS
  • Android.permission.WRITE_CONTACTS
  • Android.permission.WRITE_SETTINGS
  • Android.permission.CAMERA
  • Android.permission.READ_SMS
  • Android.permission.WRITE_EXTERNAL_STORAGE
  • Android.permission.RECEIVE_BOOT_COMPLETED
  • Android.permission.SET_WALLPAPER
  • Android.permission.READ_CALL_LOG
  • Android.permission.WRITE_CALL_LOG
  • Android.permission.READ_EXTERNAL_STOR

To identify potential vulnerabilities in the app, we can utilize the following command:

dz> run app.package.attacksurface com.metasploit.stage

1 Activities exported

1 broadcast receivers exported

0 content providers exported

0 services exported

The app exports components, making it possible for them to be invoked by external apps. These components could be vulnerable to external attacks: a GUI activity, which will always be exportable for execution by the operating system; a Service, running in the background to perform specific tasks; and a broadcast receiver that handles system events for processing.


3.2 APK Analysis


The first step involves unpacking the APK. This will be done using the tools “apktool” and “unzip/dex2jar/jd-gui.” Subsequently, the APK is decompressed using “unzip,” and “dex2jar” is employed to analyze the source code with “jd-gui.”



Once “dex2jar” is executed on “classes.dex,” you will obtain the jar package, which can then be used with “jd-gui” to analyze the source code.

However, to streamline all these steps, you can create a simple script or make use of existing tools available on platforms like GitHub. In this particular case, the tool “apkext” is quite useful. You can install it from its repository at https://github.com/blukat29/apkext.



After installing it following the instructions on its GitHub repository, you can initiate the APK extraction and witness how it automates the entire process for you.



Once the APK has been unpacked and you have obtained the “jar” package, proceed to open it with JD-GUI to analyze the source code.



Here, you can already observe all the source files that make up the APK. We will delve into a more detailed analysis in subsequent sections.

3.3 Certificate Analysis


Using the following command, you can verify the information of the certificate used to sign the “mai.apk” app.



As we can see, the certificate cannot be securely validated due to being a self-signed certificate.


3.4 Analysis of the Application’s Source Code


3.4.1 Analysis of AndroidManifest


First, we will proceed to locate in the “AndroidManifest.xml” file the activity that contains the “MAIN” entry point. This means finding the activity that has the “Android.intent.category.MAIN” category set, as it will dictate the execution flow of the app in question.



In the lower section, you can observe the code we are looking for:

<activity Android:label=”@string/app_name” Android:name=”.MainActivity” Android:theme=”@Android:style/Theme.NoDisplay”>

<intent-filter>

<action Android:name=”Android.intent.action.MAIN”/>

<category Android:name=”Android.intent.category.LAUNCHER”/>

</intent-filter>

As we can see, this activity is named “MainActivity.”


3.4.2 Analysis of MainActivity


Studying the code of the class, we can see that it simply executes the “MainService” service.



We can define a service as a component that performs tasks in the background, and there are three types:

  1. Scheduled: These are executed at specific scheduled times.
  2. Started: These are executed through an Activity using the “startService()” method. Once started, they continue running indefinitely until the “stopSelf()” method is called.
  3. Bound: These are executed when invoked using the “bindService()” method. They remain active as long as the invoking activity continues to run.

Analyzing the provided source code, we can see that the “Service” is initiated using the “startService()” call, which means the launched service is of the “Started” type. This implies that the service will run indefinitely in the background without the user’s awareness, as long as the app is active. The service’s functionality and behavior should be examined more closely to ascertain its intended purpose and impact.


3.4.3 Payload Analysis







As we can see, the source code has been obfuscated to make it more difficult to understand. We can observe how the method “a(DataInputStream, OutputStream, Object[])” loads a class into memory that doesn’t appear anywhere in the APK package. Specifically, it’s the class “com.metasploit.meterpreter.AndroidMeterpreter.”

By using specific online search tools, we’ve been able to find the deobfuscated source code of this class. This significantly facilitates the analysis of the malware. Below, we’ll detail how the code functions.

Analyzing according to the execution flow, after invoking the “start” method of “Payload,” the “/data/data/<package>/files” directory is passed as a parameter through the “getFilesDir()” function. A new thread is created to invoke its “Main” method.




As we can see below, the “Main” method is initiated by defining certain variables. Depending on the value of the URL (whether it starts with “tcp” or “http”), their respective protocols are used to open input and output channels for the connection with a server (host). Once these channels (DataOutputStream and DataInputStream in) are established, both methods call the socket creation method.




Below is the method for creating channels for a secure HTTPS connection:



Once the connection is established, the application proceeds to download a library (“xxxxx.jar”) from the server, which is saved to the previously obtained path, and then loaded into memory.

Below, we can see how it reads the class name and downloads the package:



It reads the class name to be loaded and stores it in the “str1” string. Subsequently, it reads the library and stores it as “xxxxx.jar”. At this point, the library is loaded into memory using an object of the “DexClassLoader” class, which allows loading “jar” libraries or directly an “apk” for subsequent execution. The following parameters are passed to it:

  • dexPath: the path of the library to be loaded (“xxxxx.jar”).
  • optimizedDirectory: the path where the optimized “xxxxx.dex” file will be generated from “xxxxx.jar”.
  • librarySearchPath: directory where native libraries are located.
  • parent: the class loader.

Once the “DexClassLoader” is initialized, the class that was previously downloaded from the host is loaded, and an instance of it is created:

  • localObject2=((Class)localObject1).newInstance();

With the class loaded, it proceeds to delete the downloaded “xxxxx.jar” file and the “xxxxx.dex” file generated as optimization from “xxxxx.jar”. This is a measure to eliminate possible traces of intrusion in the system:

  • localFile.delete();
  • new File(str1).delete();

Finally, it invokes a method named “start” from the loaded class.


3.4.4 Dynamic analysis of the functions performed by the app


To verify that the download and deletion of the mentioned files actually occur, we will proceed to install the app on the device using the command “adb install app.apk”. Through a root shell session using “adb shell”, we will continuously check the content of the directory where these actions are supposed to take place in real time. We will set up a loop that refreshes the directory continuously, allowing us to accurately monitor the ongoing actions in real time.



We launch the command for execution after the application has been installed and before executing it. Additionally, we set up Metasploit to listen for the reverse connection.

root@generic:/data/data/com.metasploit.stage# while true; do > date;pwd;ls files; sleep 0.2; echo “\n”; done



Once executed with the prepared scenario, we can observe that we successfully receive the reverse Meterpreter session, and certain folders and files are created in the directory as expected.



Now, we are going to do the same thing but monitor the “files” folder that is created after execution. To do this, we will restore the directory to only contain the “lib” folder, and then proceed to execute the “MainActivity” app.



Everything happens very quickly. After starting the loop to monitor the “files” folder located at “/data/data/com.metasploit.stage/files”, we can observe that once the “MainActivity” app is executed, “.jar” files are downloaded and optimized to create “.dex” files. Once loaded into memory and executed, the “reverse Meterpreter” session is initiated, and the downloaded files are deleted.

In an attempt to retrieve the downloaded files “met.jar” and “payload.jar”, you can run a similar loop as before, but instead of listing the directory, try moving the files to another directory. Simultaneously, start the exploit on the host, which will be waiting to receive requests from the mobile device, in this case, for the app to be initiated.

root@generic:/data/data/com.metasploit.stage# while true; do cp –R files/ /data/;sleep 0.1;done

By starting the application while the loop is already running, the loop can copy the “jar” files to the “/data/” directory, preventing them from being permanently deleted from the mobile device.




At this point, we can now move the files to our lab for analysis.


3.4.5 Analysis of the “sri8sg.jar” file.


First, let’s analyze “sri8sg.jar,” as it is the first file that gets downloaded and loaded into memory for execution.



It is decompressed, and the binary package “.dex” is transformed into “.jar” using “dex2jar”:



We proceed to load the resulting file in “jd-gui”:



Next, we can see that the package contains an interface named “Stage” and a class named “Meterpreter.” Similar to before, this class is responsible for downloading the “met.jar” file from the server and executing it.



In the provided code, we can see that once “met.jar” has been downloaded, the “AndroidMeterpreter” class is loaded into memory. Then, the constructor of this class is invoked, passing the parameters of input and output streams, “DataInputStream” and “OutputStream,” which were previously opened during the initial execution.



3.4.6 Analysis of the “met.jar” File


Now, upon analyzing the “met.jar” file, we can see that it contains the class “com.metasploit.meterpreter.AndroidMeterpreter”. In the next section, we will delve deeper into the composition of a “Meterpreter” session.



On the left-hand side, we can notice the functions that this malware possesses:



Continuing with the analysis of the application, we can see that “met.jar” is composed of different classes and functions, among which stand out:


3.4.6.1 Class “AndroidMeterpreter”


It is the main class of the payload module. It is responsible for coordinating and executing the other modules of the trojan. Its functionality extends to the “Meterpreter” class, which is responsible for executing the components in charge of the data flow channels and the command manager (CommandManager), among others.



If we examine the source code of “Meterpreter,” we can see the following:



3.4.6.2 The command manager class “CommandManager”:


This module is responsible for managing the commands sent by the attacker to the victim machine. Each command is registered with its name and the corresponding implementing class. If a command is not defined, the error contained in “NotYetImplementedCommand” is triggered.



3.4.6.3 The “Command” interface


It’s responsible for implementing the “execute” method for command execution and providing the result of the execution.



3.4.6.4 Class”Channel”


Responsible for establishing communication between the victim machine and the attacker through previously studied communication streams: “InputStream” and “DataStream”.



3.4.7 Definition and Composition of a “Meterpreter”


If we were to define a “Meterpreter” session, we could say that it’s a framework consisting of various tools executed as “payloads.” A “payload” can be defined as a piece of malicious code specially developed to carry out its actions silently. Typically, all malware adheres to certain behavioral standards by installing a small-sized program on the victim’s machine. This program is responsible for later downloading different “payloads” from the attacker’s server, which are then loaded directly into memory to avoid leaving traces on the victim’s disk.

In the context of “Metasploit,” these small-sized programs that are installed on the victim’s machine to subsequently download “payload” modules (“stages”) for in-memory loading are referred to as “stagers.” The “stages” are generally heavier and are responsible for giving the attacker control over the victim’s machine.

If we apply this to the case we’ve analyzed, we can assert that the installed app on the smartphone serves as the “apk stager,” while the downloaded payload “met.jar,” which, upon execution, hands over control of the victim’s machine to the attacker, is the “stage.” Therefore, as a general rule, we can state that this type of malware:

  • It consists of a small-sized module known as the “stager.”
  • The initial artifact (“stager”) downloads a “payload” from a remote server owned by the attacker and subsequently loads it into memory.
  • After loading into memory, the downloaded file is deleted to eliminate traces and avoid leaving a trace. The downloaded “payload” or “stage” (in our case, “met.jar”) is considerably larger in size as it contains all the necessary functions in its source code for the proper functioning of the Trojan.

In this way, we can affirm that the victim’s device contains only the initial artifact (application) of minimal weight (small size), and in terms of connections, only those established to the attacker’s server. It’s important to note that these connections can use secure channels to encrypt the information, making analysis considerably more challenging. This approach could even allow the malware to go unnoticed alongside other connections made by the device.

That’s why, in terms of forensic analysis, to find clearer evidence of malicious code, one should perform a memory dump of the device’s RAM using tools like “Volatility,” “Autopsy,” “DumpIt,” or “FTK Imager,” depending on the specific operating system.


4. Conclusions


In conclusion, based on the analysis conducted, we can affirm that this is a remote administration malware targeting Android devices. It downloads malicious files (“payloads”) from an external server and uses reflection techniques to execute the downloaded payloads in memory. This approach aims to avoid leaving traces on the disk, remain unnoticed in its activities, and eliminate footprints on the victims’ devices.

This type of malware targeting Android systems typically spreads using social engineering methods and/or by introducing malicious code into an application, often with seemingly legitimate credentials (digital signatures, etc.) to deceive users.

Regarding the potential impact of such malware, given its required permissions for operation, the negative impact or damage it can cause to a victim’s device is significant.

To learn more about malware analysis on smartphones, you can consider enrolling in our course on “Security and Malware Analysis in Android.

Spain

No puedes copiar el contenido