All posts by Matthew Green

How To Hunt For UEFI Malware Using Velociraptor

Post Syndicated from Matthew Green original https://blog.rapid7.com/2024/02/29/how-to-hunt-for-uefi-malware-using-velociraptor/

How To Hunt For UEFI Malware Using Velociraptor

UEFI threats have historically been limited in number and mostly implemented by nation state actors as stealthy persistence. However, the recent proliferation of Black Lotus on the dark web, Trickbot enumeration module (late 2022), and Glupteba (November 2023) indicates that this historical trend may be changing.

With this context, it is becoming important for security practitioners to understand visibility and collection capabilities for UEFI threats. This post covers some of these areas and presents several recent Velociraptor artifacts that can be used in the field. Rapid7 has also released a white paper providing detailed information about how UEFI malware works and some of the most common types.

Background

Unified Extensible Firmware Interface, or UEFI, is the interface between a system’s hardware and its operating system (OS). The technology can be viewed as an updated BIOS capability to improve and add security to the boot process.

The two main types of UEFI persistence are:

  1. Serial Peripheral Interface (SPI) based
  • Firmware payload implant that is resilient to even a hard disk format.
  • Difficult to implement — there are risks associated with implementing and potentially bricking a machine if there are mistakes with the firmware.
  • Difficult to detect at scale — defenders need to extract firmware which typically requires a signed driver, then running tools for analysis.
  • Typically an analyst would dump firmware, then extract variables and other interesting files like PEs for deep dive analysis.

2. EFI System Partition (ESP) based

  • A special FAT partition that stores bootloaders and sits late in the EFI boot process.
  • Much easier to implement, only requiring root privileges and to bypass Secure Boot.
  • Does not survive a machine format.

EFI Secure Variables API visibility

EFI Secure Variables (or otherwise known as NVRAM) is how the system distributes components from the firmware during boot. From an analysis point of view, whilst dumping the firmware is difficult needing manual workflow, all operating systems provide some visibility from user space. This blog will discuss the Windows API; however, for reference Linux and macOS provides similar data.

How To Hunt For UEFI Malware Using Velociraptor

GetFirmwareEnvironmentVariable (Windows) can collect the name, namespace guid and value of EFI secure variables. This collection can be used to check current state including key/signature database and revocation.

Some of the data points it enables extracting are:

  • Platform Key (PK) — top level key.
  • Key Exchange Key (KEK)  — used to sign Signatures Database and Forbidden Signatures Database updates.
  • Signature database (db) — contains keys and/or hashes of allowed EFI binaries.
  • Forbidden signatures database (dbx) — contains keys and/or hashes of denylisted EFI binaries.
  • Other boot configuration settings.

It’s worth noting that this technique is relying on the Windows API and could be subverted with capable malware, but the visibility can provide leads for an analyst around boot configuration or signatures. There are also “boot only” NVRAM variables that can not be accessed outside boot, so a manual chip dump would need to be collected.

How To Hunt For UEFI Malware Using Velociraptor
Example of extracting EFI secure variables

Velociraptor has a community contributed capability: Generic.System.EfiSignatures. This artifact collects EFI Signature information from the client to check for unknown certificates and revoked hashes. This is a great artifact for data stacking across machines and is built by parsing data values from the efivariables() plugin.

How To Hunt For UEFI Malware Using Velociraptor

EFI System Partition (ESP) visibility

The ESP is a FAT partitioned file system that contains boot loaders and other critical files used during the boot process which do not change regularly. As such, it can be a relatively simple task to find abnormalities using forensics.

For example, parsing the File Allocation Table we can review metadata around path, timestamps, and deleted status that may provide leads for analysis.

How To Hunt For UEFI Malware Using Velociraptor
Viewing FAT metadata on *.EFI files

In the screenshot above we observe several EFI bootloader files with timestamps out of alignment. We would typically expect these files to have the same timestamps around operating system install. We can also observe deleted files and the existence of a System32 folder in the temporal range of these entries.

The EFI/ folder should be the only folder in the ESP root so querying for any paths that do not begin with EFI/ is a great hunt that detects our lead above. You can see in my screenshot below, the BlackLotus staging being bubbled to the top adding filtering for this use case.

How To Hunt For UEFI Malware Using Velociraptor
BlackLotus staging: Non ESP/ files

Interestingly, BlackLotus was known to use the Baton Drop exploit so we can compare to the publicly available Baton Drop and observe similarities to deleted files on the ESP.

How To Hunt For UEFI Malware Using Velociraptor
Publicly available Baton Drop iso contents on Github

The final component of ESP-based visibility is checking the bytes of file contents. We can run YARA to look for known malware traits, or obtain additional file type metadata that can provide leads for analysis. The screenshot below highlights the well known Black Lotus certificate information and PE header timestamp.

How To Hunt For UEFI Malware Using Velociraptor
BlackLotus PE header, suspicious Authenticode
How To Hunt For UEFI Malware Using Velociraptor
BlackLotus YARA hit in ESP

Available Velociraptor artifacts for this visibility of the ESP are:

  1. Windows.Forensics.UEFI — This artifact enables disk analysis over an EFI System Partition (ESP). The artifact queries the specified physical disk, parses the partition table to target the ESP File Allocation Table (FAT). The artifact returns file information, and PE enrichment as typical EFI files are in the PE format.
  2. Windows.Detection.Yara.UEFI This artifact expands on basic enumeration of the ESP and enables running yara over the EFI system partition.

Measured Boot log visibility

Bootkit security has always been a “race to the bottom.” If the malware could load prior to security tools, a defender would need to assume they may be defeated. Since Windows 8, Measured Boot is a feature implemented to help protect machines from early boot malware. Measured Boot checks each startup component — from firmware to boot drivers — and stores this information in the Trusted Platform Module (TPM). A binary log is then made available to verify the boot state of the machine. The default Measured Boot log location is C:\Windows\Logs\MeasuredBoot\*.log and a new file is recorded for each boot.

Windows.Forensics.UEFI.BootApplication parses Windows MeasuredBoot TCGLogs to extract PathName of events, which can assist detection of potential ESP based persistence (EV_EFI_Boot_Services_Application). The artifact leverages Velociraptor tools to deploy and execute Matt Graeber’s excellent powershell module TCGLogTools to parse TCGLogs on disk and memory.

How To Hunt For UEFI Malware Using Velociraptor

We can see when running on an infected machine that the BOOT application path has clearly changed from the default: \EFI\Microsoft\Boot\bootmgfw.efi. Therefore, Boot Application is a field that is stackable across the network.

We can also output extended values, including digest hashes for verification.

How To Hunt For UEFI Malware Using Velociraptor

Other forensic artifacts

There are many other generic forensic artifacts analysts could focus on for assisting detection of a UEFI threat. From malware network activity to unexpected errors in the event log associated with Antivirus/Security tools on the machine.

For example: BlackLotus made an effort to evade detection by changing Windows Defender access tokens to SE_PRIVILEGE_REMOVED. This technique keeps the Defender service running but effectively disables it. While Velociraptor may not have protected process privileges to check tokens directly, we can check for other indicators such as errors associated with use.

How To Hunt For UEFI Malware Using Velociraptor

Similarly, Memory integrity (HVCI) is a feature of virtualization-based security (VBS) in Windows. It provides a stronger virtualization environment via isolation and kernel memory allocations.The feature is related to Secure Boot and can be disabled for malware that needs a lower integrity environment to run. It requires setting the configuration registry key value to 0.

HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Scenarios\HypervisorEnforcedCodeIntegrity\Value

0 – disabled

1 – enabled
Windows.Registry.HVCI available on the artifact exchange can be used to query for this key value.

How To Hunt For UEFI Malware Using Velociraptor

Conclusion

Despite UEFI threats possessing intimidating capabilities, security practitioners can deploy some visibility with current tools for remote investigation. Forensically parsing disk and not relying on the Windows API, or reviewing other systemic indicators that may signal compromise, is a practical way to detect components of these threats. Knowing collection capabilities, the gaps, and how to mitigate these is just as important as knowing the threat.

In this post we have covered some of Velociraptor’s visibility for UEFI threats and we have only scratched the surface for those who know their environment and can query it effectively. Rapid7 supports Velociraptor open source, providing the community with Velociraptor and open source features unavailable even in some paid tools.

References:

  1. ESET, Martin Smolar – BlackLotus UEFI bootkit: Myth confirmed
  2. Microsoft Incident Response – Guidance for investigating attacks using CVE-2022-21894: The BlackLotus campaign
  3. Trellix Insights: TrickBot offers new TrickBoot
  4. Palo Alto Unit 42: Diving Into Glupteba’s UEFI Bootkit
  5. Sentinel1: Moving from common sense knowledge about uefi to actually dumping uefi firmware

Automating Qakbot decode at scale

Post Syndicated from Matthew Green original https://blog.rapid7.com/2023/04/14/automating-qakbot-decode/

Automating Qakbot decode at scale

This is a technical post covering practical methodology to extract configuration data from recent Qakbot samples. In this blog, I will provide some background on Qakbot, then walk through decode themes in an easy to visualize manner. I will then share a Velociraptor artifact to detect and automate the decode process at scale.

Automating Qakbot decode at scale
Qak!

Qakbot or QBot, is a modular malware first observed in 2007 that has been historically known as a banking Trojan. Qbot is used to steal credentials, financial, or other endpoint data, and in recent years, regularly a loader for other malware leading to hands on keyboard ransomware.

Typical delivery includes malicious emails as a zipped attachment, LNK, Javascript, Documents, or an embedded executable. The example shown in this post was delivered by an email with an attached pdf file:

Automating Qakbot decode at scale
An example Qakbot infection chain

Qakbot has some notable defense evasion capabilities including:

  1. Checking for Windows Defender sandbox and terminating on discovery.
  2. Checking for the presence of running anti-virus or analysis tools, then modifying its later stage behavior for evasion.
  3. Dynamic corruption of payload on startup and rewrite on system shutdown.

Due to the commodity nature of delivery, capabilities and end game, it is worth extracting configuration from observed samples to scope impact from a given campaign. Hunting enterprise wide and finding a previously missed machine or discovering an ineffective control can be the difference in preventing a domain wide ransomware event, or a similar really bad day.

Configuration

Qakbot has an RC4 encoded configuration, located inside two resources of the unpacked payload binary. The decryption process has not changed significantly in recent times, but for some minor key changes. It uses a SHA1 of a hard coded key that can typically be extracted as an encoded string in the .data section of the payload binary. This key often remains static across campaigns, which can speed up analysis with the maintainance of a recent key list.

Current samples undergo two rounds of RC4 decryption with validation built in. The validation bytes dropped from the data for the second round.

After the first round:

  • The first 20 bytes in hex is for validation and is compared with the
    SHA1 of the remaining decoded data
  • Bytes [20:40] is the key used for the second round of decoding
  • The Data to decode is byte [40:] onwards
  • The same validation process occurs for the second round decoded data: Verification = data[:20] , DecodedData = data[20:]
Automating Qakbot decode at scale
First round of Qakbot decode and verification

Campaign information is located inside the smaller resource where, after this decoding and verification process, data is clear text.

Automating Qakbot decode at scale
Decoded campaign information

The larger resource stores Command and Control configuration. This is typically stored in netaddress format with varying separators. A common technique for finding the correct method is searching for common ports and separator patterns in the decoded data.

Automating Qakbot decode at scale
Easy to spot C2 patterns: port 443

Encoded strings

Qakbot stores blobs of xor encoded strings inside the .data section of its payload binary. The current methodology is to extract blobs of key and data from the referenced key offset which similarly is reused across samples.

Current samples start at offset 0x50, with an xor key, followed by a separator of 0x0000 before encoded data. In recent samples I have observed more than one string blob and these have occurred in the same format after the separator.

Automating Qakbot decode at scale
Encoded strings .data

Next steps are splitting on separators, decode expected blob pairs and drop any non printable. Results are fairly obvious when decoding is successful as Qakbot produces clean strings. I typically have seen two well defined groups with strings aligning to Qakbot capabilities.

Automating Qakbot decode at scale
Decoded strings: RC4 key highlighted

Payload

Qakbot samples are typically packed and need execution or manual unpacking to retrieve the payload for analysis. Its very difficult to obtain this payload remotely at scale, in practice the easiest way is to execute the sample in a VM or sandbox that enables extracting the payload with correct PE offsets.

When executing locally Qakbot typically injects its payload into a Windows process, and can be detected with yara targeting the process for an unbacked section with PAGE_EXECUTE_READWRITE protections.

Below is an example of running PE-Sieve / Hollows Hunter tool from Hasherezade. This helpful tool enables detection of several types of process injection, and the dumping of injected sections with appropriately aligned headers. In this case, the injected process is wermgr.exe but it’s worth to note, depending on variant and process footprint, your injected process may vary.

Automating Qakbot decode at scale
Dumping Qakbot payload using pe-sieve

Doing it at scale

Now I have explained the decode process, time to enable both detection and decode automation in Velociraptor.

I have recently released Windows.Carving.Qakbot which leverages a PE dump capability in Velociraptor 0.6.8 to enable live memory analysis. The goal of the artifact was to automate my decoding workflow for a generic Qakbot parser and save time for a common analysis. I also wanted an easy to update parser to add additional keys or decode nuances when changes are discovered.

Automating Qakbot decode at scale
Windows.Carving.Qakbot: parameters

This artifact uses Yara to detect an injected Qakbot payload, then attempts to parse the payload configuration and strings. Some of the features in the artifact cover changes observed in the past in the decryption process to allow a simplified extraction workflow:

  • Automatic PE extraction and offset alignment for memory detections.
  • StringOffset – the offset of the string xor key and encoded strings is reused regularly.
  • PE resource type: the RC4 encoded configuration is typically inside 2 resources, I’ve observed BITMAP and RCDATA
  • Unescaped key string: this field is typically reused over samples.
  • Type of encoding: single or double, double being the more recent.
  • Hidden TargetBytes parameter to enable piping payload in for analysis.
  • Worker threads: for bulk analysis / research use cases.
Automating Qakbot decode at scale
Windows.Carving.Qakbot: live decode

Research

The Qakbot parser can also be leveraged for research and run bulk analysis. One caveat is the content requires payload files that have been dumped with offsets intact. This typically requires some post collection filtering or PE offset realignment but enables Velociraptor notebook to manipulate post processed data.

Some techniques I have used to bulk collect samples:

  • Sandbox with PE dumping features: api based collection
  • Virustotal search: crowdsourced_yara_rule:0083a00b09|win_qakbot_auto AND tag:pedll AND NOT tag:corrupt (note: this will collect some broken payloads)
Automating Qakbot decode at scale
Bulk collection: IPs seen across multiple campaign names and ports

Some findings from a small data set ~60 samples:

  • Named campaigns are typically short and not longer than a few samples over a few days.
  • IP addresses are regularly reused and shared across campaigns
  • Most prevalent campaigns are BB and obama prefixed
  • Minor campaigns observed: azd, tok and rds with only one or two observed payload samples each.

Strings analysis can also provide insights to sample behavior over time to assist analysis. A great example is the adding to process name list for anti-analysis checks.

Automating Qakbot decode at scale
Bulk collection: Strings highlighting anti-analysis check additions over time

Conclusion

During this post I have explained the Qakbot decoding process and introduced an exciting new feature in Velociraptor. PE dumping is a useful capability and enables advanced capability at enterprise scale, not even available in expensive paid tools. For widespread threats like Qakbot, this kind of content can significantly improve response for the blue team, or even provide insights into threats when analyzed in bulk. In the coming months the Velociraptor team will be publishing a series of similar blog posts, offering a sneak peek at some of the types of memory analysis enabled by Velociraptor and incorporated into our training courses.

I also would like to thank some of Rapid7’s great analysts – Jakob Denlinger and James Dunne for bouncing some ideas when writing this post.

References

  1. Malpedia, Qakbot
  2. Elastic, QBOT Malware Analysis
  3. Hasherezade, Hollows Hunter
  4. Windows.Carving.Qakbot