Layakk https://www.layakk.com/ Fri, 12 Aug 2022 10:56:20 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.4 https://www.layakk.com/wp-content/uploads/2020/06/cropped-layakk_favicon-32x32.png Layakk https://www.layakk.com/ 32 32 Wireless Keystroke Injection vulnerability https://www.layakk.com/blog/wireless-keystroke-injection-vulnerability/ Tue, 02 Aug 2022 14:29:13 +0000 https://www.layakk.com/?p=4736 In this post we will show a vulnerability of Microsoft Windows 10 (and 11) that allows an attacker to impersonate a previously-paired Bluetooth Low Energy (BLE) HID device, particularly a BLE keyboard, and to inject unencrypted keystrokes, resulting in code execution. This vulnerability was reported to Microsoft (via MSRC) that catalogued it as RCE (Remote […]

La entrada Wireless Keystroke Injection vulnerability se publicó primero en Layakk.

]]>
In this post we will show a vulnerability of Microsoft Windows 10 (and 11) that allows an attacker to impersonate a previously-paired Bluetooth Low Energy (BLE) HID device, particularly a BLE keyboard, and to inject unencrypted keystrokes, resulting in code execution. This vulnerability was reported to Microsoft (via MSRC) that catalogued it as RCE (Remote Code Execution) and severity “Important”.

The scenario we will be handling in this post is that of a Windows system acting as a BLE Master that has a previously-paired legitimate BLE keyboard. After a period of inactivity, the legitimate keyboard is disconnected to save energy. We will explain how at this point the vulnerability allows impersonating the legitimate keyboard without breaking the BLE cryptographic protection.

Some concepts about Bluetooth Low Energy

Bluetooth Low Energy (BLE) is a Bluetooth protocol used by devices that need to save energy and have low communication requirements. There are many devices that use this communication technology instead of Bluetooth classic. BLE is quite different from Bluetooth classic: it uses simpler channel hopping and less radio channels; the pairing procedure and communication stack is also different… To understand the explanation of the vulnerability, let’s show some BLE concepts such as pairing and connection flow.

First of all, we must understand the BLE stack structure. The protocol stack is divided in 2 parts: The Host part, comprising high-level protocols such as ATT, GATT and SMP; and the Controller part, comprising Link Manager and LE Radio (PHY). Each part can be implemented in one single physical device (as it is the case for a BLE keyboard) or in two different ones (as in a laptop that implements the Host part at the OS level and the Controller part at the firmware level). These two parts can communicate via the HCI interface (Host-Controller-Interface), using commands (Host to Controller) and events (Controller to Host). The following image shows illustrates these two parts:

BLE Stack

Source: Bluetooth 5.2 Core Specification – Vol.1 – Part A (p.203)

In a BLE communication there are two participants: a Slave device, that advertises its presence, and a Master device, that can start a connection upon the reception of the Slave’s advertising. The Slave part has attributes that are exposed to Master and, using these attributes, both can send and receive information. When the connection is started, the devices can choose to first perform the Pairing procedure (if they want to encrypt the communication) or simply start transferring data without Pairing (resulting in an unencrypted connection). For our purposes, we will assume that the two devices perform the Pairing procedure.

BLE pairing procedure is described in Bluetooth 5.2 Core Specification, determining the steps to be followed by master and slave to establish a common key -usually- associated to this pair of devices, which is called LTK (Long Term Key). This procedure is required to provide encryption and authentication for BLE communication. BLE defines two pairing schemes: LE Legacy pairing and LE Secure Paring. Both pairing procedures can be performed to create a Long Term Key (LTK) that will be used on each connection to derive a Session Key (SK). As the LTK is calculated and stored at the Host level, it needs to be passed to the Link Controller to allow for the derivation of the SK. The Link Layer will then use the SK to encrypt the communications.

The following diagram shows the simplified message exchange for the first connection, before the pairing takes place, and the establishment of the encrypted channel, after the pairing is completed.

First BLE Connection

Many Bluetooth Low Energy devices drop their connections if there is no need for further communication, so that they can save energy (that is certainly the case of most HID devices). When two devices that have been previously paired want to re-connect, they will use the same message flow without performing the Pairing procedure. The  vulnerability we found can be exploited in the re-connection phase, as will be explained in the next parts of the post.

The vulnerability

Before encryption is established, Bluetooth specification allows to exchange some unencrypted messages, for example the LL_FEATURE_REQ or LL_VERSION_IND, for the Controller-level; but also GATT and ATT messages, as part of GATT Discovery protocol, that are Host-level messages.

As mentioned above, each time a paired BLE device initiates a connection, encryption can be re-established using LL_ENC_REQ and subsequent messages. The Bluetooth specification also allows unencrypted messages just after LL_ENC_REQ is received by the slave. At this moment, the Slave Controller can empty its buffers of unencrypted data before sending LL_ENC_RSP. This can be found in the Bluetooth 5.2 Core Specification – Vol.1 – Part B – 5.1.3:

" Otherwise, when the Link Layer of the slave receives an LL_ENC_REQ PDU it shall generate the slave’s part of the initialization vector (IVs) and the slave’s part of the session key diversifier (SKDs). IVs shall be a 32 bit random number generated by the Link Layer of the slave. SKDs shall be a 64 bit random number generated by the Link Layer of the slave. Both IVs and SKDs shall be generated using the requirements for  random number generation defined in [Vol 2] Part H, Section 2.
The Link Layer of the slave shall finalize the sending of the current Data Physical Channel PDU and may finalize the sending of additional Data Physical Channel PDUs queued in the Controller. After these Data Physical Channel PDUs are acknowledged, until this procedure is complete or specifies otherwise, the Link Layer of the slave shall only send Empty PDUs, LL_TERMINATE_IND PDUs, and PDUs required by this procedure.
If any of the Data Physical Channel PDUs sent by the slave is an LL Control PDU, the Link Layers shall resume any outstanding procedure(s) after the Encryption Start procedure has completed.
The Link Layer of the slave shall then send an LL_ENC_RSP PDU. The Link Layer of the slave shall then notify the Host with the Rand and EDIV fields. After having sent the LL_ENC_RSP PDU, the Link Layer of the slave can receive an LL_UNKNOWN_RSP PDU corresponding to an LL Control PDU sent by the slave. The slave should not disconnect the link in this case. "

This opens a window of opportunity where the Slave’s controller can send unencrypted data after the encryption procedure has started, but before the encryption channel is established. The following diagram shows the exact moment when these messages are allowed to be processed by the Master:

Window Of Oportunity

Data sent by the Slave in this moment must be processed by Master’s Controller and sent to Master’s Host. The Master’s Host must decide if these messages should be processed or not. The vulnerability is right there: for HID (Human Interface Devices), as keyboards or mouses, that use BLE and are paired with Windows OS (as Master), the Master’s Host accepts and processes these unencrypted messages that contain the keystrokes, instead of waiting for the  HCI_ENCRYPTION_CHANGE confirmation that indicates that the encryption channel is finally established or a fail during this procedure. An attacker can exploit this vulnerability by emulating the legitimate HID device and send unencrypted HID messages containing the keystrokes during this window of opportunity, without knowing the LTK and thus impersonating the real HID device.

Exploiting the vulnerability

Before trying to exploit this vulnerability, we need to know how a keyboard sends the keystrokes in legitimate communication. BLE HID devices use a protocol called HID over GATT, defined in the document HID OVER GATT PROFILE SPECIFICATION (V10r00). Basically, when the keyboard establishes the connection and encryption with a Master device, it sends the HID Report Map with the format and the handles that will be used to send these reports. A HID report is a group of bytes representing one or more keystrokes, differentiating between modifier keys, such as SHIFT, CONTROL or ALT; and normal keys, such as a, s, d or f. Modifier keys are sent as a byte mask (usually occupying 1 byte together). The regular keys are codded into a number and are sent using one byte for each key.

The image above shows an example of message using the report model of a Microsoft 1898 BLE Keyboard. It uses the first byte to encode modifier keys, and the following 10 to encode normal keys. In this example, this report is representing the keystroke Shift + a.

Now, we will show how we tried to exploit this vulnerability following two different approaches: The first, using a Host-level application only, that in the end did not work. The second one, using a Controller-level modification, that was the final exploit.

First attempt: Implementing the exploit at the Host level

At first, we tried to implement the exploit at the host level, and it didn’t work. We used a regular dongle (with chipset CSR8510, that allows to change the BDADDR of the dongle) for the Controller-level and Mirage framework for the Host-level. We used the module ble_slave to create an scenario that catches the “onMasterConnect” signal. When that signal is received, we start sending Keystrokes using HID reports, as explained above. As this approach happens at Host-level, we cannot manipulate the timing and messages sent at the Controller-level. Host can only tell the Controller to send HID reports using HCI, but it is the Controller who decides when, exactly, they will be sent. To illustrate this behavior, we captured (using Sniffle, a Bluetooth Low Energy sniffer that captures Bluetooth communications in the air) the traffic produced by this implementation of the attack:

In the capture we can see that HID Report messages (Handle Value Notification, Handle: 0x0013) are sent when the controller decides to send them, and there is only one that falls into the window of opportunity (between the LL_ENC_REQ and LL_ENC_RSP messages). Using this approach, we managed to inject only one or two keystrokes within a few attempts, which has no real impact.

We realized, therefore, that we had to go down to the Controller-level to improve the stability and reliability of the attack, controlling the order and the timing of the messages at the Link Layer level.

Final exploit: implementation at the Controller level

For the implementation at the Controller-level, or Link Layer, we use Zephyr RTOS as system to be flashed into a Nordic nRF5840 dongle. We modify the Zephyr implementation of USB_HCI example to manipulate the traffic to be sent after LL_ENC_REQ. Using this approach, we have full control of Link Layer messages and the state machine of the controller. When the message LL_ENC_REQ is received by our modified firmware, we manually craft the high-level HID report messages and enqueue them into the controller’s sending queue. We also freeze the sending of any other messages that could be sent by Controller standard implementation. As we have done before, we show now a capture of the traffic produced by the attack using this method, obtained with Sniffle:

Capture Controller Level

The capture illustrates that we have full control of messages sent by the Slave’s Controller, preventing the LL_ENC_RSP message from being sent by it. At this point, we had to face another problem: if we send too many reports too quickly, the reports might not be processed or might be processed by the master in a different order. To solve this problem, we implement an exponential decrement of waiting time between keystrokes. Decremental Waiting Time

After receiving the LL_ENC_REQ, the dongle waits 4 seconds to send the first keystroke. After that, it decreases the waiting time dividing by 2 each time it sends a keystroke until it reaches 20 milliseconds. This allows us to inject more than 3000 HID Reports before the Master decides to close the connection. In the best case, that means that we can write more than 13000 characters before the communication is terminated.

Performing the Attack

There are some preconditions for the attack to be performed:

  • We need to know the HID Report Map or the Handle and the format used by the Keyboard. This can be obtained by analyzing a replica of the paired keyboard with the victim’s PC.
  • Also, we need to know the BDADDR of the legitimate keyboard. For this purpose, we need to listen to the BLE communications (using, for example Sniffle) on keyboard re-connection. The Advertising messages of the keyboard include its MAC.
  • Finally, we need to be within the victim’s PC Bluetooth Low Energy range.

Once we have this, we can program the dongle and use it for performing the attack.

Our firmware modification includes the capability of programming the dongle using HCI vendor messages. These messages can be sent to the controller through the HCI interface using, for example, hcitool. The following vendor messages are available:

  • 0x3f 0x03f0 to program the Handle (two first bytes), the report size (the third byte), and the operation type (the last byte).
  • 0x3f 0x03e1 to clear Keystrokes list.
  • 0x3f 0x03e2 to add keystrokes to the list that will be sent to the Master.
  • 0x3f 0x03e3 to indicate that the keystroke list should be sent in a loop until the Master device closes the connection.

Using this interface is tedious and complicated, so we have created a script (kb_injection.py) to program the dongle with a more user-friendly interface. The script reads a configuration file that looks like this one:

{
"REPORT_HANDLE":"0x0013",
"REPORT_SIZE":11,
"REPORT_OPTYPE":"0x1b",
"TEXT_SCRIPT":"{L_WIN}+rpowershell.exe{ENTER}{SLEEP 500}calc.exe{ENTER}"
}

The configuration file shown in the example is valid to perform the attack against a Windows PC with Microsoft BLE Keyboard 1898. This example shows how to prepare a configuration file to open the “Run” dialog on Windows PC, write powersell.exe, press “ENTER”, wait for 0.5 seconds, write calc.exe and finally press “ENTER” again. The expected result is to open the calculator. For more details on how to configure the dongle you can visit our Github.

After the configuration file is written, we can execute the kb_injection.py script as follows:

kb_injection.py -i <hci_interface_of_dongle> -m <BDADDR> -c <configuration_file>

When the script is executed the nRF5940 dongle starts to send advertising messages. Then, when the legitimate keyboard disconnects, the Windows PC will connect to our dongle and the attack will start. This behavior implies that the attacker does not need to know when the legitimate keyboard disconnects: the attack can be launched at any time and it will start whenever the legitimate keyboard disconnects.

Both the script to program the dongle and the modified firmware can be found in our Github.

Links

References

Used and related Tools

Related documents or publications

La entrada Wireless Keystroke Injection vulnerability se publicó primero en Layakk.

]]>
Android Malware III. Hidden Malware https://www.layakk.com/blog/android-malware-iii-hidden-malware/ Thu, 21 Apr 2022 13:14:33 +0000 https://www.layakk.com/?p=3689 In this post we are going to see a small example of how an Android Malware could be hidden from the user’s view. 1. The sample We have chosen a very simple malware that has quite readable code from a reversing viewpoint. It is identified by the SHA256 hash 48618153df1b2b5be3f83e83e6e1fa6aa5f517b173b10f3f6e925d1598a22b459e1. We have obtained it from […]

La entrada Android Malware III. <br>Hidden Malware se publicó primero en Layakk.

]]>
In this post we are going to see a small example of how an Android Malware could be hidden from the user’s view.

1. The sample

We have chosen a very simple malware that has quite readable code from a reversing viewpoint. It is identified by the SHA256 hash 48618153df1b2b5be3f83e83e6e1fa6aa5f517b173b10f3f6e925d1598a22b459e1. We have obtained it from the AndroidMalware_2019 repository. According to the name given by the repository, Brazilian_androRAT, it must be a Malware of Brazilian origin.

2. Public information.

Let us assume the following scenario: we are sent an apk file called 48618153df1b2b5be3f83e6e1fa6fa6aa5f517b173b10f3f6f6e925d1598a22b459e1.apk and we are asked to see if it performs any malicious activity. The first step will be to see if there is any public information about this hash. In Google we only get 10 results about repositories where it is found or reports from automatic scanners.

VirusTotal has the following results:

It seems that the malware is detected by many antivirus vendors, yet there are still some that don’t. Those that detect it identify it as belonging to a malware family named “Brata”.

Looking for information about Android RAT Malware of Brazilian origin and BRATA we can see some news portals that name this malware. According to these news the malware pretends to be a Whatsapp update and once executed it exploits a known Whatsapp vulnerability with CVE 2019-3568, buffer overflow in the VOIP stack, High severity vulnerability that allows remote execution. Surprisingly, the Malware was hosted in the Play Store for a while.

3. Static Analysis

Let’s go to what concerns us as security technicians. First we are going to decompress the apk, using a script to automate it thus avoiding having to remember the commands every time we decompile an apk:

#!/bin/bash

APK=$1
unzip -q $APK -d ${APK}_unzip
apktool d $APK -o ${APK}_apktool
jadx $APK -d ${APK}_jadx

We will call the script as follows:

./apk_extractor 48618153df1b2b5be3f83e6e1fa6aa5f517b173b10f3f6e925d1598a22b459e1.apk

We already have the code ready to analyze. We may simply use the gui version of jadx to analyze the code (this decompiles it and stores it in memory):

jadx-gui 48618153df1b2b5be3f83e6e1fa6aa5f517b173b10f3f6e925d1598a22b459e1.apk

With jadx-gui a decompilation project is created, then all the actions we perform can be saved for later recovery. Actions that can be saved: function renaming, decompilation level, preferences, etc. The decompilation project is saved as a file with .jobf extension.

Permissions

Looking at the main AndroidManifest.xml file we see that it has the following permissions declared:

<uses-permission android:name=”android.permission.INTERNET”/>
<uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE”/>
<uses-permission android:name=”android.permission.REQUEST_INSTALL_PACKAGES”/>
<uses-permission android:name=”android.permission.REQUEST_DELETE_PACKAGES”/>

You can see that it asks for permissions to install (REQUEST_INSTALL_PACKAGES) and uninstall (REQUEST_DELETE_PACKAGES) applications, to open Internet sockets (INTERNET) and to write to the SD card (WRITE_EXTERNAL_STORAGE).

Entry Points

Within the <application> node we see a Service and an Activity declared:

Due to the declared intent filter (in the entry Android Malware II. Basics. we talked about intent filters) we know that this activity is executed when the app icon is clicked:

<intent-filter>
   <action android:name=”android.intent.action.MAIN”/>
   <category android:name=”android.intent.category.LAUNCHER”/>
</intent-filter>

In this case we have only one activity but if there were many, this helps us to situate ourselves at the starting point. As for the service, we see that it also has an intent filter:

<intent-filter>
   <action android:name=”android.accessibilityservice.AccessibilityService”/>
</intent-filter>
<meta-data android:name=”android.accessibilityservice” android:resource=”@xml/accessibility_service_config”/>

We see that the service is configuring an Accessibility service, which for security purposes, is a critical service because with Android accessibility services you can do many things without depending on the user. The “meta-data” tag is used to configure the types of accessibility events through an xml file that we find among the decompilation files.

Summarizing the entry points we have:

  • Launcher Activity: irifix.MainActivity
  • Servicio: irifix.AccService – When an intent is launched with the action AccessibilityService

Launcher Activity

As this is an Activity, the first function to be executed is onCreate(). It creates a Thread to execute another function that we are going to rename as the input function (jadx-gui by right clicking on the function name we can rename it).

We have indicated our changes in the function names with capital letters. The interesting function and the one that originates this blog entry is the one indicated in the image with number 3. Here the malware is telling the PackageManager via setComponentEnabledSetting to hide the application icon from the user’s eyes. It does not do it directly, it has a delay of 15000ms that it applies at the time of the creation of the Thread, possibly so that the user does not see that the application disappears immediately after clicking the launcher, but after 15 seconds. The second parameter of setComponentEnabled that is set to 2 corresponds to COMPONENT_ENABLED_STATE_DISABLED (value that hides the icon) and the third, value 1, with DONT_KILL_APP to indicate that you do not want to close the application when the state of the component changes. This way the malware would already be hidden.

Following the HTTP_QUERY flow (area indicated as 1 in the previous image) we have the following function:

It looks like some string is being hidden, we apply the algorithm backwards:

Here is the URI that is performed, yemnic[*.*]com. As it is a malware from last year, this domain does not resolve as of today. Because of this the malware no longer behaves as expected by the malware developer.

We return to FUNCION_ENTRADA(). It makes an edit of the shared_preferences, then checks if the accessibility services are configured. If it is not configured it launches a window (what in Android is called alertDialog) with a button that launches the following intent:

public void mo2720onClick(DialogInterface dialogInterface, int i) {
    Intent intent = new Intent(“android.settings.ACCESSIBILITY_SETTINGS”);
    intent.addFlags(268435456);   —-
    intent.addFlags(32768);
    intent.addFlags(8388608);
    context.startActivity(intent);
}

This starts the accessibility services activity for the user to enable the services for the application.

In summary, it makes the user activate the accessibility services and then a service remains started in the background. Let’s move on to dynamic analysis to confirm these behaviors.

4. Dynamic Analysis

Let’s install the malware via adb:

adb install 48618153df1b2b5be3f83e6e1fa6aa5f517b173b10f3f6e925d1598a22b459e1.apk

 

We run Wireshark and Burp to observe communications and press Launcher:

A window appears showing that the update has been applied and the application closes. After a while the icon disappears, as we saw in the static analysis. The application is still installed and remember that it has a listening service. In Burp we have not seen any request, but in Wireshark we see that the Android tries to resolve the address we saw in the static analysis.

Even if the application closes and disappears, it is still running as you can see in the following image:

and watching all of the user’s actions through the accessibility permission.

5. Conclusions

One thing this malware does not do and could be easily achieved is persistence. Through a Broadcast Receiver and the use of the android.permission.RECEIVE_BOOT_COMPLETED permission we could execute our desired code when the device reboots.

We are not going to dig much more into this malware because what we wanted to show is already done. From this malware we can draw the following conclusions/techniques:

  • The use of setComponentEnabledSetting to hide the icon.
  • The type of URI obfuscation (which makes it very difficult to find it automatically).
  • Even if we don’t see it the malware is running, spying on all movements with the accessibility permission.
  • The accessibility permission has a high risk and should not be enabled unless it is necessary.

La entrada Android Malware III. <br>Hidden Malware se publicó primero en Layakk.

]]>
Android Malware II. Android Basics https://www.layakk.com/blog/android-malware-ii-android-basics/ Fri, 18 Feb 2022 07:44:27 +0000 https://www.layakk.com/?p=3682 In this post we will look at some basic concepts about Android in a summarized way before we start analyzing malicious files. Android Architecture Android is based on Linux with the following architecture (very roughly): Android Compile/Reversing When we face reversing in Android applications we have to keep in mind this small map. Starting from […]

La entrada Android Malware II. <br>Android Basics se publicó primero en Layakk.

]]>
In this post we will look at some basic concepts about Android in a summarized way before we start analyzing malicious files.

Android Architecture

Android is based on Linux with the following architecture (very roughly):

Android Compile/Reversing

When we face reversing in Android applications we have to keep in mind this small map. Starting from the compiled Java/Kotlin code we will have the .dex file, a file containing the compiled code (Dalvik Bytecodes) ready to be executed in the Android virtual machine (ART). Then, using tools like apktool, we will get a code “almost” similar to the original. There are methods for developers that allow them to obfuscate the code, making it difficult to decompile the .dex file.

APK File

APK files are just a zip file with the following structure (not always exactly the same):

  • META-INF/: Where certificates are hosted.
  • lib/: Where you can find compiled libraries in C/C++ in different architectures.
  • res/: Contains non-compiled resources such as images, music, “raw binary”…
  • assets/: (Optional) Here you can find extra files, which can be loaded from Java code.
  • AndroidManifest.xml: File that describes the application, its permissions, components, etc.
  • classes.dex: These files are the Java classes compiled to be executed in the Android virtual machine, also called Dalvik Bytecodes.
  • resources.arsc: File containing precompiled XML files.

Android Components

Activity

Activities are nothing more than the screens that users see when interacting with the phone. This component has a specific behavior as shown by Google in the following image:

The image shows that the first method that an activity goes through at startup is the onCreate() method. The code containing this method will be the first to be executed.

Service

Services are processes similar to an Activity but that run in the background, i.e., the user does not see that this process is running. Google also offers us a diagram with the life cycle of a service:

You can see in the image that a service can be called by two methods: startService() and bindService(). In either case, the first code to be executed is the onCreate() method, just like in an Activity.

Broadcast Receiver

It is part of an application that is listening for an event. When this event occurs, its code is executed. They can be declared either in the AndroidManifest or dynamically using registerReceiver() in the application code.

Content Provider

This last component is nothing more than a mechanism/interface, provided by Android, to access data stored in an application. The data can be stored in a SQLite database or in a system folder, etc.

Intents / Intents filters

We should also discuss what these two elements consist of in the Android environment:

An intent is nothing more than a message that is exchanged between the Android components that we discussed earlier. An intent filter is the declaration of an application (usually in the AndroidManifest) to manage the intents. Intents are used to start an activity, a service or to send a broadcast. There are two types of intents:

  • Implicit Intents: intents that do not specify who will be in charge of them, such as an intent with GPS location, when launched, the system searches among all the applications which one has declared in its intent filters that has the capability to manage GPS locations. If it finds several with the same intent filter, it displays a dialog with the options for the user to choose the one he/she wants.
  • Explicit Intents: these intents do indicate the application that will process this message.

APK entry points

When performing the static analysis, as it would be done in a compiled binary, it would be to look for the entry points. In Android, we find quite a few entry points:

  • Launcher Activity: This is the main Activity and it is the one that is launched when we click on the application icon.
  • Exported Components: when any of the Android components are exported, it means that they can be accessed from any other application or event.
  • Broadcast Receiver: The Broadcast Receiver code will be executed when the event to which it is listening is triggered.
  • Services: As above, the Service can have an “intent filter” defined that launches the service. An example of an event would be: when the system has been started.
  • Application Subclass: if the attachBaseContext method is defined, it is called before the OnCreate() method.
  • URL schemes / Deeplinks: This entry point would be more oriented to pentesting, although it is always good to know that it exists. It consists of developers declaring a url scheme such as app:// for their applications. When a link in this format is accessed or clicked, application code will be executed.

Methodology

In coming posts of this series about Android Malware we will follow the same methodology:

  1. Sample: We will talk a bit about the sample, media repercussion, origin, where we obtained it from.
  2. Public information: As an initial step in the reversing process, it is good to soak up as much information as possible before starting.
  3. Static analysis: We will decompile the application and try to get as much information as possible.
  4. Dynamic analysis: We will install the application, we will analyze its behavior, the generated traffic, etc…
  5. Conclusions.

 

With this theoric introduction out of the way, we have the basic notions we need for reversing an APK.

 

SOURCES:

Android Developer – Intents and Intent Filters

Android Developer – Service

Android Developer – Activity

Android Reversing 101

Android Checklist

La entrada Android Malware II. <br>Android Basics se publicó primero en Layakk.

]]>
PRACTICAL EXAMPLES WITH FRIDAFrida VS Anti-Debug Techniques on Windows (II) https://www.layakk.com/blog/practical-examples-with-fridafrida-vs-anti-debug-techniques-on-windows-ii/ Tue, 24 Aug 2021 16:02:44 +0000 https://www.layakk.com/?p=3605 In this second post of the series “PRACTICAL EXAMPLES WITH FRIDA – Frida VS Anti-Debug Techniques on Windows” we will start with showing examples of bypassing anti-debug techniques. As announced in our first post, in this entry we will talk about the first group of anti-debug techniques: “Techniques based on system calls”. These techniques use […]

La entrada PRACTICAL EXAMPLES WITH FRIDA<br>Frida VS Anti-Debug Techniques on Windows (II) se publicó primero en Layakk.

]]>
In this second post of the series “PRACTICAL EXAMPLES WITH FRIDA – Frida VS Anti-Debug Techniques on Windows” we will start with showing examples of bypassing anti-debug techniques. As announced in our first post, in this entry we will talk about the first group of anti-debug techniques: “Techniques based on system calls”.

These techniques use system calls to determine if a process is being debugged by using either functions that provide this information directly, like IsDebuggerPresent, or functions that provide this information indirectly, like FindWindow. Software can use a lot of methods, using these calls, to determine if it’s running under debugger supervision. This kind of functions have in common that they can be found by Frida using Module.findExportByName(null, exportName), and then intercepted, making their instrumentation easy.

In this post we will discuss the techniques based on the following system calls: IsDebuggerPresent, NtQueryInformationProcess and CreateToolhelp32Snapshot. All of them enable us to see how to use Frida in different ways with the objective to bypass these controls.

IsDebuggerPresent

The first check we will try to bypass is a method based on the system call IsDebuggerPresent. As it is indicated in Microsoft documentation, this function does not receive any parameter and returns a boolean value depending on whether the process is being debugged: a return value of “True” means that the process is being debugged and “False” means the opposite. To illustrate this method we have developed a simple program that performs debugging detection using this system call:

 

In the first console, we see how the application indicates that it is being debugged when we execute it from Visual Studio. However, if the application is being executed directly from a terminal, it indicates that it isn’t being debugged. Another way to check this fact could be executing it from a debugger like x64dbg. The only thing that is used to make the decision is the value returned by the function IsDebuggerPresent, therefore, we should develop a script with Frida that intercepts this call and modifies the return value, returning False (0x0) always. The script that follows was developed to do all that:

  • Firstly, it locates the address of the function “IsDebuggerPresent” using Module.findExportByName (line 3).
  • Once this address is obtained, it intercepts this call using Interceptor.attach(…) (line 8).
  • Finally, it replaces the return value by 0x0 (False) just before the function ends (line 13).

 

 

NtQueryInformationProcess

The second system call that we will show is NtQueryInformationProcess. This function lets us obtain different information related with a process. It is more complex than the last one, since it allows us to select the information to query using the ProcessInformationClass parameter, and it will give us this information on the ProcessInformation parameter.

In this example we will show how to bypass 4 checks, each one using a different value of ProcessInformationClass. These values are: ProcessDebugPort, ProcessDebugFlags, ProcessDebugObjectHandle and ProcessBasicInformation.

  • ProcessDebugPort (0x7)
    This class is used to obtain the debugger’s port number, if there is any debugger attached. This value will be different from 0 if a debugger is attached.
  • ProcessDebugFlags (0x1F)
    Using this class we could retrieve a flag that would give us information about the existence of an active debugger. In this case, if the value returned in the ProcessInfomation parameter is 0, it indicates that the application is being debugged.
  • ProcessDebugObjectHandle (0x1E)
    Indicating this value as ProcessInformationClass, this system call will return a valid Handle only if the process is being debugged.
  • ProcessBasicInformation (0x0)
    Using this class we obtain in ProcessInformation parameter an struct called PROCESS_BASIC_INFORMATION that includes, among other data: a pointer to PEB struct (offset 0x4), the PID of the process (offset 0x16) and the parent’s PID (offset 0x20). One anti-debug technique that software could apply using this information is to get the name of the parent process using the parent’s PID and checking it against a list of well-known debugger names.

 

As above, we develop a small C++ application that shows an example of this technique. To evade these checks, we must develop a script using Frida that must do the following operations:

  • Firstly, it must locate the address of the function “NtQueryInformationProcess” using Module.findExportByName.
  • Then, it must intercept the function call using Interceptor.attach(…).
  • Each time that the function “NtQueryInformationProcess” is called (OnEnter), the script must do:
    • Save the parameter ProcessInformationClass, allowing us to select what return information must be modified (line 40).
    • Save the pointer to the return parameter ProcessInformation (lines 44, 48, 52 y 57).
    • Save, also, the arguments needed in each case.

 

 

  • Finally, just before the function ends (OnLeave), the script can use the previously saved information to determine what value needs to be returned using the parameter ProcessInformation. Depending on this.ProcessInformationClass we should return the following values:
    • 0x7 (ProcessDebugPort), ProcessInformation will be replaced by the value 0x0 (line 63).
    • 0x1F (ProcessDebugFlags), ProcessInformation will be replaced by the value 0x1 (line 68).
    • 0x1E (ProcessDebugObjectHandle), in this case, we will check the return value and, if it is successful, the parameter ProcessInformation will be replaced by 0x0. The parameter ReturnLength will also be replaced (lines 72 – 81).
    • 0x0 (ProcessBasicInformation), finally, if this option is selected, we should know the PROCESS_BASIC_INFORMATION struct to replace the parent’s PID (InheritedFromUniqueProcessId, offset 0x20) by a non suspicious PID, like the PID of the process ‘explorer.exe’.

 

 

To obtain the PID of the process ‘explorer.exe’ using Frida we can use Windows API calls, for example, the functions GetShellWindow and GetWintowThreadProcessId. We can declare these functions via Javascript using NativeFunction del API de Frida and, once they are declared, we can use them to obtain the process PID as we show below:

var addr_GetShellWindow = Module.findExportByName(null,’GetShellWindow’);
var addr_GetWindowThreadProcessId = Module.findExportByName(null,’GetWindowThreadProcessId’);var fun_GetShellWindow = new NativeFunction(addr_GetShellWindow, ‘pointer’, []);
var fun_GetWindowThreadProcessId = new NativeFunction(addr_GetWindowThreadProcessId, ‘pointer’, [‘pointer’, ‘pointer’]);var explorerWindow = fun_GetShellWindow();
var explorerPID = Memory.alloc(0x4)
fun_GetWindowThreadProcessId(explorerWindow, explorerPID);
console.log(‘[+] Explorer PID: ‘ + explorerPID.readInt());

Executing this example program with Visual Studio Debugger, we get the following result:

 

If we execute the same application with the same debugger, but injecting the script of Frida described before, we get this other result:

 

CreateToolhelp32Snapshot

To complete this post, we will talk about the function CreateToolhelp32Snapshot. The most common anti-debug technique using this function is to verify the process parent’s name and PID, identifying if the parent is a well-known debugger, but this function can also be used with other purposes. First of all, this function creates an snapshot that contains some system information about processes, threads and modules. The information of this snapshot can be selected using the first argument. The following values are allowed: TH32CS_INHERIT, TH32CS_SNAPALL, TH32CS_SNAPHEAPLIST, TH32CS_SNAPMODULE, TH32CS_SNAPMODULE32, TH32CS_SNAPPROCESS, TH32CS_SNAPTHREAD.

The most basic anti-debug technique using this function is to use only TH32CS_SNAPPROCESS to get the list of running processes. Then, look up our process, identifying our process parent’s PID, and, then, look up the parent process’ information in the list. Finally, verify the information of the parent process. However, with the information given by the function using different flags (or using TH32CS_SNAPALL) we can perform other verifications. For example:

  • Processes related verifications (using TH32CS_SNAPPROCESS):
    • Search for prohibited processes (like VsDebugConsole.exe, devenv.exe, x32dbg.exe…) over the whole list, regardless of whether the process is related or not.
  • Modules related verifications (using TH32CS_SNAPMODULE and TH32CS_SNAPMODULE32):
    • Search for prohibited modules (like frida-agent.dll…) over the module list related with my process.
  • Threads related verifications (using TH32CS_SNAPTHREAD):
    • Verification that all Threads listed have an associated process, trying to detect hidden processes.
    • Verification of the application thread count.
    • Verification that there aren’t any threads of my application that reference a prohibited module.

As you can see, an application, using this function, can verify different things that must be consistent among them. Our task, then, to bypass these checks, must be to find a workaround that allows us to bypass all these checks and keep the consistency of the list. With this objective, we studied what information is exactly returned by this function and how we can manipulate it.

The function CreateToolhelp32Snapshot return a HANDLE of type SECTION. If we analyze the memory section pointed by the HANDLE we can find a non-documented structure with the following parts:

Snapshot Header
* The names and types of this section have been assigned by the author of this post because no related documentation has been found.
DWORD dwHeapListCount; Heap List element count.
DWORD dwProcessListCount; Process List element count.
DWORD dwModuleListCount; Module List element count.
DWORD dwThreadListCount; Thread List element count.
DWORD dwHeapListOffset; Offset (from the section’s base) where Heap List is located.
DWORD dwProcessListOffset; Offset (from the section’s base) where Process List is located.
DWORD dwModuleListOffset; Offset (from the section’s base) where Module List is located.
DWORD dwThreadListOffet; Offset (from the section’s base) where Thread List is located.
DWORD dwHeapListIndex; Index used by Heap32ListFirst and Heap32ListNext functions.
DWORD dwProcessListIndex; Index used by Process32First and Process32Next functions.
DWORD dwModuleListIndex; Index used by Module32First and Module32Next functions.
DWORD dwThreadListIndex; Index used by Thread32First and Thread32Next functions.
Heap List
Array of HEAPLIST32 elements.
Module List
Array of MODULEENTRY32 (or MODULEENTRY32W) elements.
Process List
Array of PROCESSENTRY32 (or PROCESSENTRY32W) elements.
Thread List
Array of THREADENTRY32 elements.

We can use the functions NtQuerySection and NtMapViewOfSection to modify the memory related with Handle, thus modifying the contents of the snapshot returned by the function CreateToolhelp32Snapshot. So we can develop a Frida script that modifies the lists returned by CreateToolhelp32Snapshot, hiding the Processes, Modules and Threads that could be checked to detect the debugger, but keeping its consistency.

First of all, we should define a list of processes and modules that should be hidden. We need to known their names. In this example, we will hide Visual Studio Debugger and the executable and modules related with Frida. So we define 2 lists with the following content:

  • Prohibited Processes list: VsDebugConsole.exe, devenv.exe, frida-winjector-helper-32.exe
  • Prohibited Modules list: frida-agent.dll

Once we are sure which processes and modules we want to hide, we are going to hook the function CreateToolhelp32Snapshot as we did before. In this case, we don’t modify any parameter or return value. We are going to intercept the Handle that will be returned by the function just before the function returns it and execute some code before the return takes place. As we saw before, using the functions NtQuerySection and NtMapViewOfSection, we are going to locate the memory related with the Handle and we will perform the following steps:

  • Process List modifications:
    • We should remove from the list of processes those that are found in the list of prohibited processes.
    • We should remove the references to prohibited processes, to keep the consistency.
      For example, the program that we will be debugging will probably have a prohibited process as parent. Therefore, we should change the Parent’s PID value to the PID of a non suspicious process (like explorer.exe PID).
  • Module List modifications:
    • We should remove from the list of modules those that are found in the list of prohibited modules.
  • Thread List modifications:
    • We should delete from the list of threads those that are owned by a process deleted in the Process List.
    • We should delete from the list of threads those that point to a module deleted from the Module List.
      We can get this information by using the functions OpenThread, with THREAD_QUERY_INFORMATION permission, and NtQueryInformationThread, asking for ThreadQuerySetWin32StartAddress. Comparing the information obtained by this query with the memory associated with prohibited modules we can determine if the thread should be removed from the list or not.

La entrada PRACTICAL EXAMPLES WITH FRIDA<br>Frida VS Anti-Debug Techniques on Windows (II) se publicó primero en Layakk.

]]>
5G Security: Key Aspects https://www.layakk.com/blog/5g-security-key-aspects/ Tue, 27 Jul 2021 16:55:33 +0000 https://www.layakk.com/?p=4660 Since the beginning of our activity, in Layakk we have been studying the security of mobile communications for years, in different areas: network access protocols, core network protocols and specific implementations (in the baseband of the terminals and in different elements of the network of the operator). Apart from the professional services (security assessments and […]

La entrada 5G Security: Key Aspects se publicó primero en Layakk.

]]>
Since the beginning of our activity, in Layakk we have been studying the security of mobile communications for years, in different areas: network access protocols, core network protocols and specific implementations (in the baseband of the terminals and in different elements of the network of the operator). Apart from the professional services (security assessments and consultancy for network operators, specialized and deep technical training, security analysis of products), this has translated in numerous publications and activities: identification of vulnerabilities (“Nuevos escenarios de ataques con estación base falsa” at RootedCon 2012; “Atacando 3G vol. III” at RootedCON 2016), practical demonstrations (“A practical attack against GPRS/EDGE/UMTS/HSPA mobile data communications” at Black Hat DC 2011; “Sistema de localización geográfica de un terminal móvil” at RootedCON 2013; “Seguridad de comunicaciones móviles 3G” at CyberCamp 2015), etc. Our activity in this area has been reinforced with the accreditation of our laboratory to perform security evaluations of products.

Since the birth of the new generation of mobile communications, we have been studying the security of 5G, which has motivated several talks (“5G: Certificación de su seguridad en Europa” at XIV Jornadas STIC CCN-CERT; “5G: Mitos y leyendas” at XIII Jornadas STIC CCN-CERT), training and other activities (assessments, consulting) for our clients.

In this article we want to share our conclusions about the 4 key aspects that need to be addressed to globally improve the security of 5G, which is a task that should involve all relevant actors: operators, manufacturers, regulators and security experts:

  1. CORRECT IMPLEMENTATION: One of the our recurring messages in our talks and also in our consulting activities has always been that 5G Security has been designed as being dependant on the implementation carried out by the network operators of both home networks (those that finalize the USIM cards) and serving networks (e.g. in a roaming scenario). This dependency has important implications regarding aspects such us the confidentiality of the identity of the user, the confidentiality of the communications, the serving networks, the authorization of access to different services of different 5G slices, etc. For this reason we consider critical that operators are aware of their responsibility in implementing the norm correctly. In this regard, initiatives brought forward by regulators, like the draft of the future 5G Cybersecurity Act in Spain, contribute to achive this goal, because they require these security features from a regulatory standpoint. This is one of the pillars encouraged by the European Union (Cybersecurity of 5G networks: EU Toolbox of risk mitigating measures).
  2. AUDIT: Just as in other areas of IT, we consider a fact that the security of 5G needs to be audited. Here we differentiate 2 work areas:

    Audit of 5G products: the products that make the 5G ecosystem are susceptible to presenting implementation defects. We are talking about products that compose the 5G networks themselves and also consumer products that, with this new generation, broaden enormously their spectrum beyond the mobile terminals (IoT, industrial devices, vehicles, etc.), which may cause that manufacturers that originally did not expose their interfaces now they do and thus have to tackle the complex task of protecting them properly.
    Audit of deployed 5G networks: with the goal of verifying that their implementation is correct and secure.

    In Layakk we are working on broadening our capabilities in that area and we have created a laboratory that helps us deliver this type of services, both for product security audits and for collateral tests associated to auditing operator networks. In this laboratory we have implemented the NESAS methodology and we are committed to keeping it always up to date and evolving it towards the upcoming new 5G Cybersecurity Certification Scheme that will soon be approved by the European Union.

  3. DEPLOYMENT OF COLLATERAL PRODUCTS: One reality being observed nowadays is that some aspects of the security of 5G are dependant on services that are not defined in the standards and which implementation corresponds to the operator. Lately we are seeing vulnerabilities associated to access authorization, control and accounting, filtering of operations, etc. We think that a key factor in the improvement of the security must be the development and adoption of products that supply the necessary security characteristics of 5G that have been delegated by the standards. This aspect must be embraced as soon as possible to make it possible that those security characteristics get developed and implemented together with the rest during the massive deployment or the networks.
  4. KNOWLEDGE MANAGEMENT: The last aspect that we consider key is the management of the knowledge on 5G security that operators and regulagors need to have. We think it is of paramount importance that they hold a level of technical knowledge regarding security that enables them to be manage correctly the deployments of this technology. Also, this knowledge will be reusable in the future with the arrival of new generations (6G) shich are already in the works.

At Layakk we are commited to this objectives and we invest permanently to guarantee that we are able to offer related services, always with our devotion to quality, responsibility and honesty.

La entrada 5G Security: Key Aspects se publicó primero en Layakk.

]]>
Android Malware I. Lab Setup https://www.layakk.com/blog/android-malware-i-lab-setup/ Wed, 02 Jun 2021 07:33:37 +0000 https://www.layakk.com/?p=3680 This series of articles in our blog is motivated by the amount of news circulating with headlines like “Android malware steals your bank details”, “Malware that won’t uninstall from your Android”, “Malware that reinstalls without you noticing”…. The question is, how does it work at the system level, how do they get out of the […]

La entrada Android Malware I. <br>Lab Setup se publicó primero en Layakk.

]]>
This series of articles in our blog is motivated by the amount of news circulating with headlines like “Android malware steals your bank details”, “Malware that won’t uninstall from your Android”, “Malware that reinstalls without you noticing”…. The question is, how does it work at the system level, how do they get out of the sandbox that is generated when the App is installed, do they only use social engineering or are there more interesting technical aspects? For this reason, we decided to set up a laboratory to analyze in detail the techniques used by these pieces of malware.

We use an infrastructure similar to the one that will be described in our laboratory accredited to perform Security Evaluations of IT products and in our Red Team activities.

1.Virtual machine installation in VirtualBox

As we are going to execute malicious code it will be important to be able to return the system to a pre-infection state at any time. Although this can be done with physical devices, it is much more convenient to do it with virtual machines, because at any time we can take a snapshot of the system, and at any time we can return the system to the state of any of the snapshots almost immediately.

As a virtualization platform we will use Virtualbox and for android emulation on Virtualbox we will use the Open Source project Android_x86 which is actively maintained and updated. There are alternatives, for example Genymotion which has better performance but we lose control because these Genymotion machines raise a Host-Only interface on your host, which is a risk we prefer to avoid. There is also CuckooDroid which is a sandbox for Android malware analysis that we may try in the future.

We will install a machine through which all network requests made by Android will pass, and where we will install all the necessary software for the analysis. We will use a Debian based system. The scheme to follow will be as follows:

1.1. Linux Analysis & Transparent Proxy Virtual Machine

1.1.1. Machine specifications

In the center of the previous scheme we will have the analysis machine that through a network interface, in bridge mode, will be connected to the internet (eth0) and through the other interface (eth1) will be connected to the internal network of Virtualbox. Since we are going to run a lot of software at the same time on the analysis machine, we have to dedicate more than 2GB of RAM, in our case 4GB. We also have to add one more interface (eth1) where the DHCP server will be configured and where the Android machine will be connected.

1.1.2. Tools

There are hundreds of tools for both dynamic and static analysis of Android applications. Here is the installation of the tools that we have found most relevant.

  • Proxy/Sistema:
    • adb
    • docker
    • android-sdk
    • Java 8
    • Iptables
    • isc-dhcp-server
    • Wireshark

sudo apt install adb docker docker.io docker-compose android-sdk openjdk-8-jre wireshark -y

  • Static Analysis:

wget https://github.com/skylot/jadx/releases/download/v1.2.0/jadx-1.2.0.zip
sudo mv jadx-1.2.0.zip /usr/local/bin/jadx-1.2.0.zip
sudo unzip /usr/local/bin/jadx-1.2.0.zip -d /usr/local/bin/jadx-1.2.0
sudo rm /usr/local/bin/jadx-1.2.0.zip
sudo ln -s /usr/local/bin/jadx-1.2.0/bin/jadx /usr/local/bin/jadx
sudo ln -s /usr/local/bin/jadx-1.2.0/bin/jadx-gui /usr/local/bin/jadx-gui

wget https://raw.githubusercontent.com/iBotPeaches/Apktool/master/scripts/linux/apktool
wget https://bitbucket.org/iBotPeaches/apktool/downloads/apktool_2.5.0.jar
mv apktool_2.5.0.jar apktool.jar
sudo mv apktool.jar /usr/local/bin
sudo mv apktool /usr/local/bin
sudo chmod +x /usr/local/bin/apktool.jar
sudo chmod +x /usr/local/bin/apktool

  • Dynamic Analysis:

sudo apt install python3-pip
pip3 install frida-tools

wget https://raw.githubusercontent.com/JakeWharton/pidcat/master/pidcat.py
chmod +x pidcat
mv pidcat /bin/

chmod +x burpsuite_community_linux_v2020_12_1.sh
./burpsuite_community_linux_v2020_12_1.sh

sudo docker pull opensecurity/mobile-security-framework-mobsf
echo “alias mobsf=’sudo docker run -it -p 8000:8000 opensecurity/mobile-security-framework-mobsf:latest'” >> ~/.bashrc

1.1.3. DHCP server installation and configuration

To install:

sudo apt install isc-dhcp-server

Add the interface, in the file /etc/default/isc-dhcp-server, where you want to let the dhcp running. Modify the line INTERFACESv4="" to INTERFACESv4="eth1"

Then in the file /etc/dhcp/dhcpd.conf it must be modified as follows:

option domain-name-servers 8.8.8.8, 8.8.4.4;
default-lease-time 600;
max-lease-time 7200;
ddns-update-style none;
authoritative;

subnet 10.0.0.0 netmask 255.255.255.0 {
    range 10.0.0.10 10.0.0.20;
    option domain-name-servers 8.8.8.8;
    option subnet-mask 255.255.255.0;
    option routers 10.0.0.1;
    option broadcast-address 10.0.0.255;
    default-lease-time 600;
    max-lease-time 7200;
}

It is highly recommended to disable network-manager: service network-manager stop. Also install net-tools and ifupdown for the configuration of the network interfaces, which sometimes does not come with some distros.

For our eth1 interface to work, it must have an IP.  We set it in /etc/network/interfaces as follows:

auto eth0
iface eth0 inet dhcp 
auto eth1 iface eth1 
inet static address 10.0.0.1
netmask 255.255.255.0

And now restart the service: service isc-server-dhcp restart

1.1.4. Transparent Proxy with iptables

First we clean up the rules, to make sure we start from zero:

iptables -F
iptables -X
iptables -Z
iptables -t nat -F

We set the default policy:

iptables -P INPUT ACCEPT
iptables -P OUTPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -t nat -P PREROUTING ACCEPT
iptables -t nat -P POSTROUTING ACCEPT

First we have to enable traffic forwarding through the machine with:

echo 1 > /proc/sys/net/ipv4/ip_forward

We will post the other rules later:

## FORWARD CHAIN
iptables -A FORWARD -i eth0 -o eth1 -m state –state ESTABLISHED,RELATED -j ACCEPT
iptables -A FORWARD -i eth1 -o eth0 -m state –state NEW -j ACCEPT

## NAT
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

## HTTP and HTTPS for Burpsuite
iptables -t nat -A PREROUTING -p tcp –dport 80 -j REDIRECT –to-port 8082
iptables -t nat -A PREROUTING -p tcp –dport 443 -j REDIRECT –to-port 8082

We will configure Burp later to finish configuring the proxy, but now let’s go to the Android machine.

 

1.2. Android_x86 Virtual Machine

Download the Android-x86 version from the official site. A 64-bit version is strongly recommended. The steps to install these systems in Virtualbox are described in the following link.

To make a quick summary of what is indicated in the link:

  • Create a virtual machine of Linux type and Linux version 2.6/3.x/4.x (64bits).
  • Dedicate more than one processor to the machine.
  • Important step: It is mandatory to configure VBoxVGA instead of VBSVGA in the Display options dialog box.

Then some options that we added for the lab:

  • Also add as much video memory as possible (128MB).
  • In the network interfaces, leave only one, in internal_network mode with the same name as the proxy’s internal_network (they will be on the same network).

Boot the machine with the downloaded .iso disk. The operating system installation wizard will start. From here you have to follow the next steps:

  • Choose the option “Installation – Install Android-x86 to harddisk”.
  • On the question of the use of GPT choose no
  • Now you have to create a partition. Press New>Primary>Select the whole disk>Bootable>Write>Confirm and wait, then Quit

  • Select the new partition we have just created, choose the “ext4” format, then confirm.
  • To the GRUB installation question choose yes.
  • Important step: When asked whether to install the /system directory as read-write choose yes.

And Android will then be finally installed in a Virtualbox virtual machine.

 

2. Burp Suite and CA install

We are going to use the Burp Suite Community version as a web proxy for viewing HTTP/S calls. In order to work with Burp Suite as a transparent proxy on Android you have to install the Burp certificate as a Root CA. To do this you need to follow the steps below:

  • Open Burp
  • Import the certificate in .cer format from Burp. Proxy>Options>Import/export CA certificate> Select the option “Certificate in DER format”> Save in the desired location.
  • Execute in bash to install the certificate (replace with the variables between <>):

openssl x509 -inform DER -in <CERTIFICATE_BURP> -out cacert.pem
hash=`openssl x509 -inform PEM -subject_hash_old -in cacert.pem | head -1`
cert_hash=$hash.0
mv cacert.pem $cert_hash
adb connect <IP_ANDROID_MACHINE>
adb root
adb connect <IP_ANDROID_MACHINE>
adb remount
adb push $cert_hash /sdcard/
adb shell “mv /sdcard/$cert_hash /system/etc/security/cacerts/”
adb shell “chmod 644 /system/etc/security/cacerts/$cert_hash”
adb shell “reboot”

If we go to Settings on the Android machine and look for the “Trusted credentials” section we can see how our certificate has been installed as the system CA:

The proxy also has to be configured in Burp.

  • In the Proxy>Intercerpt tab, turn off intercerpt for now.
  • Then in Proxy>Options>Proxy Listeners>Add
  • In Bind to port: 8082
  • In Bind to address: All interfaces
  • In the “Request handling” tab of the same window enable the option “Support invisible proxying (enable only if needed)”.

Burp would already be listening on port 8082 for all HTTP/S requests that it will receive thanks to the Iptables rules that we have configured previously:

NOTE: It is possible that HTTP/S requests are made through ports that are not the common ones and in our case we have only added to Iptables the requests that have port 80/443 as destination. In this case, it would be necessary to look at the Wireshark frames and detect which ports are used and then add a rule to Iptables with this port.

In coming articles of this series we will be looking at examples of malware that use specific techniques, theory or tools that we find interesting.

 

SOURCES:

Internal Networking – Virtualbox [Malware Lab]

Configuring Burp Suite With Android Nougat

Using Burp’s Invisible Proxy Settings to Test a Non-Proxy-Aware Thick Client Application

Iptables incluyendo para proxy transparente

Proxying Android app traffic – Common issues / Checklist

 

La entrada Android Malware I. <br>Lab Setup se publicó primero en Layakk.

]]>