Research Notes: WMI and Living off the Land Persistence Techniques
This is previously unpublished deep dive research I did into WMI persistence with a focus on malware examples attributed to threat actor APT29. I explain what WMI is and how it can be leveraged to maintain persistent access to a target. I also include some ideas for defenders.
I have updated it to include new malware analyses and additional detection techniques.
APT29
APT29, a threat group attributed to the Russian government, is also known as YTTRIUM, The Dukes, Cozy Bear, CozyDuke.
Windows Management Instrumentation (WMI)
WMI data is stored in the WMI common information model (CIMv2) repository, which consists of files in C:\Windows\System32\wbem\Repository\. The CIM repository is stored in the objects.data file.
wmic.exe, used to interact with WMI from the command line, is a trusted Windows binary–also known as a LOLBin (living off the land binary).
WMI supports several scripting languages, including Windows Script Host, VBScript, JScript, and PowerShell.
WMI uses HTTP primarily for communications. By default DCOM and MSRPC are used and this traffic can be captured and analyzed. If WinRM is invoked, (or PowerShell is used) HTTPS is default.
WMI can be used effectively for every phase of offensive activity from recon to actions on objectives.
Classes
The primary structure within WMI is the WMI class, which can contain:
- methods (code)
- properties (data)
Custom Classes
Users with system level privileges can define new classes or extend default classes. A benign-sounding custom class with a benign-sounding property full of malicious script content can be created in one line using the New-WMIProperty cmdlet from the WMI-Module.psm1 PowerShell module. A malicious class can be called with PowerShell’s Invoke-Expression cmdlet.
Why WMI for Persistence?
- Process call create is magical
- Tools are trusted
- With an ActionScriptEventConsumer, an attacker can instantiate IE using ActiveX (via VBScript/JScript) for C2 traffic that blends easily, inherits cached proxy creds, and has a typical user agent
- Lack of easily scalable methods to determine if scripts in MOF files are malicious
Managed Object Format (MOF)
Allows extension of WMI with custom namespaces and classes–can also extend new methods or properties with existing standard WMI classes
MOF files contain all the WMI query data to be altered. The files are compiled on system with mofcomp.exe and can be created once and deployed on many systems.
Autorecover: WMI supports autorecovery via pragma autorecover statements within the MOF. If the database gets corrupted later, the system will recover the MOF file from the autorecover location.
The Binary Tree Index is the text file that records the MOF files used by WMI for configuration.
It may be difficult for defenders to discern between malicious and benign behavior if administrators use this functionality. Documentation is critical.
Subscriptions
WMI permanent event subscriptions can trigger actions when conditions are met and are often used by attackers to persist the execution of backdoors at startup.
A WMI subscription consists of three WMI classes:
- Filter: defines conditions to trigger the Consumer
- Consumer: specifies an action to be performed (as LOCAL SERVICE)
- FilterToConsumerBinding: associates Consumers to Filters
Filters
_EventFilter classes include Win32_LocalTime, Win32_Directory, Win32_Service, and many more (about 400), allowing attackers to get creative. This can make it difficult for defenders to determine the source of beaconing traffic/behavior from a system or even to determine that a system is beaconing due to the flexible nature of WMI Query Language (WQL).
Consumers
_EventConsumer objects have a name and one of the following:
- Script contained in objects.data
- Path to an external script on disk
- Path to an executable on disk
Most useful standard consumers:
- CommandLineEventConsumer: executes a command and arguments
- ActionScriptEventConsumer: uses Windows Script Host and runs JScript and VBScript
Creating permanent event subscriptions requires administrative privileges.
Malware
Microsoft has categorized fileless threats into three major types. WMI malware is categorized as Type II, described as follows:
Type II: No files written on disk, but some files are used indirectly. There are other ways that malware can achieve fileless presence on a machine without requiring significant engineering effort. Fileless malware of this type do not directly write files on the file system, but they can end up using files indirectly.
POSHSPY
POSHSPY is a Windows backdoor attributed to APT29 that is likely reserved for use if other backdoors are no longer available. The tools it uses (abuses) are common to the APT29 toolkit:
- PowerShell
- Windows Management Instrumentation (WMI)
In the sample of POSHSPY analyzed by FireEye, WMI was used to persist and store the code for the PowerShell backdoor by adding a new custom WMI class with a text property containing an encrypted and base64-encoded string of PowerShell.
A WMI event subscription was created to execute the backdoor by reading, decrypting, and executing the code directly from the string in the WMI property from the custom WMI class.
An event filter called BfeOnServiceStartTypeChange
was implemented to execute the PowerShell code regularly. In this sample, execution of the backdoor code was hardcoded for certain days and times. This filter was bound to an event consumer called WindowsParentalControlsMigration
which executed a base64-encoded PowerShell command. Upon execution, this command extracted, decrypted, and executed the PowerShell backdoor stored in the text property of the custom class. The PowerShell command contained the payload location and encryption keys.
The event consumer used by POSHSPY is of class CommandLineEventConsumer, a standard WMI Consumer class which starts an arbitrary process on the system when it receives an event. Microsoft has a prominent note in its documentation regarding the security of CommandLineEventConsumer executables:
When using the CommandLineEventConsumer class, secure the executable that you want to start. If the executable is not in a secure location, or secured with a strong access control list (ACL), an unauthorized user can replace your executable with a malicious executable.
In this instance of POSHSPY, the CommandLineTemplate executed by the event consumer looks like what one would expect: a base64-encoded script block being passed to PowerShell. The backdoor has a full suite of capabilities such as downloading and executing additional binaries and scripts, deriving C2 from a domain generation algorithm (DGA), and encrypting communications.
POSHSPY WMI component | Function | Relationship |
---|---|---|
Event Filter | checks for time-based conditions and sends event to Consumer when met | triggers Consumer action |
Event Consumer | execute a base64-encoded PowerShell command to load, decrypt, and execute POSHSPY backdoor | bound to Filter; instance of the CommandLineEventConsumer class |
CommandLineTemplate | base64-encoded PS block passed to PowerShell—e.g., powershell.exe -ep bypass -noninteractive -encodedcommand AAAAAA |
defines the action of this CommandLineEventConsumer, which runs a base64-encoded PowerShell script loading POSHSPY |
RegDuke
RegDuke is a first-stage Windows backdoor attributed to APT29 that is also likely reserved for use if other access is lost. Similarly to POSHSPY, it consists of an initial loader and an encrypted backdoor payload. In this case, both components are written in .NET.
In the RegDuke sample analyzed by ESET, WMI is used for persistence using an event consumer called MicrosoftOfficeUpdates
. The event filter triggers when winword.exe is launched. Though earlier versions contained a hardcoded encryption key, later versions of RegDuke’s loader read the encryption key from one of three possible registry keys. The backdoor is unique in that it uses Dropbox for C2 and receives encrypted data (EXEs, DLLs, or PowerShell scripts) hidden in PNG images using steganography.
RegDuke would often be used to load a heftier backdoor like MiniDuke or, interestingly, Process Explorer, part of the Sysinternals suite.
SeaDuke (bonus)
Mentioned in the WMI Offense, Defense, and Forensics paper listed in References below, another of the Dukes’ backdoors, SeaDuke, also uses WMI for persistence. The event filter triggers 200-320 seconds after startup. The event consumer executes a previously dropped executable.
TEARDROP (NEW!)
Not included in my original research gist but worth mentioning
TEARDROP is a custom second stage in memory Cobalt Strike loader. In the TEARDROP analysis listed below, Microsoft notes that a WMI event filter was used to invoke a backdoor with rundll32.exe at boot time. Additionally, when the rundll32.exe variant of TEARDROP was executed via lateral movement, it was spawned using WMIC or Invoke-WMIMethod.
Detection and Defense
Detection
- Native Windows logging: (WMI-activity operation log available on server 2012+) Event ID 5861: new permanent event consumer
- CommandLineTemplate values for CommandLineEventConsumers can be retrieved for endpoints with osquery and possibly other EDR tooling
- WMI Consumer, Filter, and FilterToConsumerBindings may together be defined in .mof files which could still exist as artifacts on system or may appear in EDR logs
- Powershell
get-wmiobject
cmdlet can be used to return _EventFilters, _EventConsumers, and _FilterToConsumerBindings
Endpoint Behavior
- File modification/creation/deletion of *.mof files
- mofcomp.exe execution
- Autorecover MOFs registry modification
- rundll32.exe spawned by wmiprvse.exe
- Microsoft DFE alerts: Low-reputation arbitrary code executed by signed executable, Suspicious ‘Atosev’ behavior was blocked, Suspicious Remote WMI Execution, A WMI event filter was bound to a suspicious event consumer
On Disk
- MOF (.mof) files may still exist on disk:
- in original location,
- in autorecovery (C:\Windows\System32\wbem\autorecovery[RANDOM].mof),
- or in the binary tree index (C:\Windows\System32\wbem\Repository\index.btr) - .mof file listed without full path could be a signal
- Prefetch files may capture command references
CIM
CIM repository is stored in objects.data (CIM parser: https://github.com/fireeye/flare-wmi)
- Can string search for Wscript.shell, EventConsumer, etc. but there is a bunch of ugly binary data in there as well
- Interesting search terms for CIM hunting with a focus on consumers:
- file extensions: .exe, .dll, .vbs, .ps1, .eval
- strings: powershell, ActiveXObject, CommandLineTemplate, ScriptText
Some common false positives:
be well aware that attackers want to blend and everything is fair game
- SCMEventLog
- TSLogonFilter
- KernCap.vbs
- RAevent.vbs
- NTEventLogConsumer
- TSLogonEvents.vbs
- RmAssistEventFilter
- WSCEAA.exe (Dell)
- BVTConsumer and BVTFilter are common but could be overwritten by attacker
Suspicious patterns within CIM:
wmic process call create
- /node: - pass the hash
- Invoke-WmiMethod / Invoke-CimMethod
- wmiprvse.exe with parent process not svchost.exe
- wmiprvse.exe with unusual child processes (sometimes PowerShell)
- scrcons.exe - ActiveScript consumer
- PowerShell, especially encoded
Memory
- Pieces of WMI commands may be found within process memory for wmiprvse.exe, svchost.exe, csrss.exe, or conhost.exe
Registry
- AppCompatCache key may record binaries executed on remote systems - look at cscript.exe, wscript.exe, etc.
- List of MOF files for autorecovery is stored in the registry at HKLM\SOFTWARE\Microsoft\WBEM\CIMOM\Autorecover MOFs
- Registering an event filter that uses Win32_LocalTime causes this empty registry key to be created: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WBEM\ESS\//./root/CIMV2\Win32ClockProvider
- enable WMI trace logs:
wevtutil.exe sl Microsoft-Windows-WMI-Activity/Trace /e:true
- Sysinternals EULA registry key: HKCU\SOFTWARE\Sysinternals<tool_name>\EulaAccepted
OSquery
Autorecover MOFs in registry
SELECT name, data
FROM registry
WHERE PATH like 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WBEM\CIMOM\Autorecover MOFs';
ActiveScriptEventConsumers
SELECT *
FROM wmi_script_event_consumers
CommandLineEventConsumers
SELECT *
FROM wmi_cli_event_consumers
FilterToConsumerBindings
SELECT *
FROM wmi_filter_consumer_binding
EventFilters
SELECT *
FROM wmi_event_filters
Defense
- Block Persistence through WMI Event Subscription - Microsoft Defender for Endpoint Attack Surface Reduction
- Document legitimate WMI and MOF file usage to aid in investigation of suspicious WMI activity
- Use endpoint security tools integrated with the Antimalware Scan Interface (AMSI)
- Windows Defender Application Control and User Mode Code Integrity (UMCI) can be used to prevent unsigned binaries from running
- Windows 10 S mode provides an operating environment further hardened against fileless threats
References:
- Dissecting One of APT29’s Fileless WMI and PowerShell Backdoors (POSHSPY)
- OPERATION GHOST: The Dukes aren’t back — they never left
- Event Triggered Execution: Windows Management Instrumentation Event Subscription
- There’s Something about WMI (SANS DFIR Summit 2015) - SLIDES
- WMI Offense, Defense, and Forensics
- Out of sight but not invisible: Defeating fileless malware with behavior monitoring, AMSI, and next-gen AV
- Investigating WMI Attacks (SANS DFIR 2019)
- Deep dive into the Solorigate second-stage activation: From SUNBURST to TEARDROP and Raindrop
For Further Reading and Review: