threat hunting

Hunting for DCOM Lateral Movement

Hunt for DCOM-based lateral movement by detecting abuse of MMC20.Application, ShellBrowserWindow, and ShellWindows COM objects through Sysmon Event ID 1 (process creation) and Event ID 3 (network connection) correlation, WMI event analysis, RPC endpoint mapper traffic on port 135, and DCOM-specific parent-child process relationships.

com-objectsdcomlateral-movementmmc20rpcshellbrowserwindowshellwindowssysmon
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

Authorized Testing Disclaimer: The offensive techniques and attack simulations described in this skill are intended exclusively for authorized penetration testing, red team engagements, purple team exercises, and security research conducted with explicit written permission from the system owner. Unauthorized use of these techniques against systems you do not own or have permission to test is illegal and unethical. Always operate within the scope of your engagement and comply with applicable laws and regulations.

Overview

Distributed Component Object Model (DCOM) enables remote execution of COM objects across a network using RPC. Adversaries abuse specific DCOM objects -- MMC20.Application (CLSID {49B2791A-B1AE-4C90-9B8E-E860BA07F889}), ShellBrowserWindow (CLSID {C08AFD90-F2A1-11D1-8455-00A0C91F3880}), and ShellWindows (CLSID {9BA05972-F6A8-11CF-A442-00A0C90A8F39}) -- to execute commands on remote hosts without dropping files, making this a stealthy lateral movement technique mapped to MITRE ATT&CK T1021.003. This skill provides detection strategies using Sysmon telemetry, Windows Security Event correlation, network monitoring, and SIEM detection rules to identify DCOM abuse in enterprise environments.

When to Use

  • Proactively hunting for lateral movement in Active Directory environments where DCOM is enabled
  • Investigating alerts for suspicious mmc.exe, dllhost.exe, or explorer.exe child process creation on servers
  • Building detection rules for MITRE ATT&CK T1021.003 (Remote Services: Distributed Component Object Model)
  • Correlating Sysmon Event ID 1 (Process Create) and Event ID 3 (Network Connection) to trace DCOM-based command execution chains
  • Auditing DCOM exposure across the domain to reduce lateral movement attack surface
  • During purple team exercises validating detection coverage for DCOM-based techniques

Do not use as a replacement for EDR-based lateral movement detection, without Sysmon or equivalent process telemetry deployed on endpoints, or in isolation without correlating network-level and host-level indicators.

Prerequisites

  • Sysmon deployed on endpoints with configuration capturing Event ID 1 (Process Create), Event ID 3 (Network Connection), Event ID 7 (Image Loaded), and Event ID 10 (Process Access)
  • Windows Security Event Logs forwarded to SIEM (Event IDs 4624, 4672, 4688)
  • SIEM platform (Splunk, Elastic, Microsoft Sentinel) with correlation capability
  • Network monitoring for RPC traffic (TCP 135 and dynamic high ports 49152-65535)
  • Baseline inventory of legitimate DCOM usage in the environment
  • Understanding of MITRE ATT&CK Lateral Movement tactic (TA0008) and T1021.003

Workflow

Step 1: Understand DCOM Lateral Movement Attack Vectors

DCOM lateral movement exploits three primary COM objects. Each has distinct forensic artifacts.

MMC20.Application -- The attacker instantiates the MMC snap-in remotely and calls ExecuteShellCommand to run arbitrary commands on the target. This spawns mmc.exe as a child of svchost.exe (DcomLaunch service) on the target.

ShellBrowserWindow -- Uses the Document.Application.ShellExecute method to execute commands through an existing explorer.exe process. Unlike MMC20, this does not create a new process for the COM server itself, making it stealthier.

ShellWindows -- Similar to ShellBrowserWindow, it activates within an existing explorer.exe instance and executes child processes from explorer.exe. The absence of a new COM server process makes it harder to detect without proper telemetry.

# ATTACK SIMULATION (authorized testing only)
# These commands demonstrate what adversaries execute -- use only in lab environments
 
# MMC20.Application lateral movement
# $dcom = [System.Activator]::CreateInstance(
#     [Type]::GetTypeFromProgID("MMC20.Application", "TARGET_IP"))
# $dcom.Document.ActiveView.ExecuteShellCommand(
#     "cmd.exe", $null, "/c whoami > C:\temp\output.txt", "7")
 
# ShellWindows lateral movement
# $dcom = [System.Activator]::CreateInstance(
#     [Type]::GetTypeFromCLSID(
#         [guid]"9BA05972-F6A8-11CF-A442-00A0C90A8F39", "TARGET_IP"))
# $dcom.item().Document.Application.ShellExecute(
#     "cmd.exe", "/c calc.exe", "C:\windows\system32", $null, 0)
 
# ShellBrowserWindow lateral movement
# $dcom = [System.Activator]::CreateInstance(
#     [Type]::GetTypeFromCLSID(
#         [guid]"C08AFD90-F2A1-11D1-8455-00A0C91F3880", "TARGET_IP"))
# $dcom.Document.Application.ShellExecute(
#     "cmd.exe", "/c net user", "C:\windows\system32", $null, 0)

Step 2: Configure Sysmon for DCOM Detection

<!-- Sysmon configuration excerpt for DCOM lateral movement detection -->
<!-- Add these rules to your existing Sysmon config -->
 
<Sysmon schemaversion="4.90">
  <EventFiltering>
 
    <!-- Event ID 1: Process Creation - Detect DCOM-spawned processes -->
    <RuleGroup name="DCOM_ProcessCreate" groupRelation="or">
      <ProcessCreate onmatch="include">
        <!-- MMC20.Application: mmc.exe spawning child processes -->
        <ParentImage condition="end with">mmc.exe</ParentImage>
        <!-- DcomLaunch service spawning COM servers -->
        <ParentCommandLine condition="contains">DcomLaunch</ParentCommandLine>
        <!-- dllhost.exe spawning suspicious children -->
        <ParentImage condition="end with">dllhost.exe</ParentImage>
        <!-- explorer.exe spawning cmd/powershell (ShellWindows/ShellBrowserWindow) -->
        <Rule groupRelation="and">
          <ParentImage condition="end with">explorer.exe</ParentImage>
          <Image condition="end with">cmd.exe</Image>
        </Rule>
        <Rule groupRelation="and">
          <ParentImage condition="end with">explorer.exe</ParentImage>
          <Image condition="end with">powershell.exe</Image>
        </Rule>
      </ProcessCreate>
    </RuleGroup>
 
    <!-- Event ID 3: Network Connection - Track DCOM RPC connections -->
    <RuleGroup name="DCOM_NetworkConnect" groupRelation="or">
      <NetworkConnect onmatch="include">
        <!-- RPC Endpoint Mapper -->
        <DestinationPort condition="is">135</DestinationPort>
        <!-- DCOM processes making network connections -->
        <Image condition="end with">mmc.exe</Image>
        <Image condition="end with">dllhost.exe</Image>
        <!-- svchost.exe DcomLaunch connections -->
        <Rule groupRelation="and">
          <Image condition="end with">svchost.exe</Image>
          <DestinationPort condition="more than">49151</DestinationPort>
        </Rule>
      </NetworkConnect>
    </RuleGroup>
 
    <!-- Event ID 7: Image Loaded - DCOM-related DLLs -->
    <RuleGroup name="DCOM_ImageLoaded" groupRelation="or">
      <ImageLoad onmatch="include">
        <ImageLoaded condition="end with">comsvcs.dll</ImageLoaded>
        <ImageLoaded condition="end with">ole32.dll</ImageLoaded>
        <ImageLoaded condition="end with">rpcrt4.dll</ImageLoaded>
      </ImageLoad>
    </RuleGroup>
 
  </EventFiltering>
</Sysmon>
# Deploy or update Sysmon configuration
# sysmon64.exe -c dcom-detection-sysmon.xml
 
# Verify Sysmon is capturing DCOM events
# PowerShell: Get-WinEvent -LogName "Microsoft-Windows-Sysmon/Operational" -MaxEvents 10 |
#   Where-Object { $_.Id -in @(1,3) } | Format-Table TimeCreated, Id, Message -Wrap

Step 3: Build SIEM Detection Rules for DCOM Object Abuse

# Sigma Rule: MMC20.Application DCOM Lateral Movement
title: DCOM Lateral Movement via MMC20.Application
id: 8a3b5f2e-c1d4-4a9f-b237-1e6f8d2c3a4b
status: stable
description: >
  Detects remote instantiation of MMC20.Application DCOM object by monitoring
  for mmc.exe spawned by svchost.exe DcomLaunch service with subsequent child
  process creation, indicating T1021.003 lateral movement.
references:
    - https://attack.mitre.org/techniques/T1021/003/
    - https://www.cybereason.com/blog/dcom-lateral-movement-techniques
    - https://www.mdsec.co.uk/2020/09/i-like-to-move-it-windows-lateral-movement-part-2-dcom/
logsource:
    category: process_creation
    product: windows
detection:
    selection_parent:
        ParentImage|endswith: '\mmc.exe'
    selection_child:
        Image|endswith:
            - '\cmd.exe'
            - '\powershell.exe'
            - '\pwsh.exe'
            - '\wscript.exe'
            - '\cscript.exe'
            - '\mshta.exe'
            - '\rundll32.exe'
            - '\regsvr32.exe'
    filter_legitimate:
        ParentCommandLine|contains:
            - 'devmgmt.msc'
            - 'diskmgmt.msc'
            - 'services.msc'
            - 'compmgmt.msc'
    condition: selection_parent and selection_child and not filter_legitimate
level: high
tags:
    - attack.lateral_movement
    - attack.t1021.003
falsepositives:
    - Legitimate remote MMC administration by authorized IT staff
    - SCCM or other management tools using DCOM for remote management
# Sigma Rule: ShellWindows/ShellBrowserWindow DCOM Lateral Movement
title: DCOM Lateral Movement via ShellWindows or ShellBrowserWindow
id: 2f7c9d1e-a8b3-4c5f-9012-3e4d5f6a7b8c
status: stable
description: >
  Detects DCOM lateral movement using ShellWindows (CLSID 9BA05972) or
  ShellBrowserWindow (CLSID C08AFD90) by monitoring for explorer.exe spawning
  cmd.exe or powershell.exe on systems where no user is interactively logged on,
  or where the network logon (Type 3) precedes the process creation.
references:
    - https://attack.mitre.org/techniques/T1021/003/
    - https://www.elastic.co/guide/en/security/8.19/incoming-dcom-lateral-movement-with-shellbrowserwindow-or-shellwindows.html
logsource:
    category: process_creation
    product: windows
detection:
    selection:
        ParentImage|endswith: '\explorer.exe'
        Image|endswith:
            - '\cmd.exe'
            - '\powershell.exe'
            - '\pwsh.exe'
            - '\mshta.exe'
            - '\wscript.exe'
            - '\cscript.exe'
    filter_interactive:
        LogonId: '0x3e7'
    condition: selection and not filter_interactive
level: medium
tags:
    - attack.lateral_movement
    - attack.t1021.003
falsepositives:
    - Users launching command prompts from Explorer context menus
    - Software installers launching child processes from explorer.exe
# Sigma Rule: Sysmon Network Connection to RPC Endpoint Mapper from DCOM Process
title: DCOM Process Inbound RPC Connection Followed by Process Creation
id: 4d9e2f1a-b3c5-4a7f-8901-2c3d4e5f6a7b
status: experimental
description: >
  Correlates Sysmon Event ID 3 (Network Connection) on port 135 with
  subsequent Event ID 1 (Process Create) from DCOM parent processes
  (mmc.exe, dllhost.exe, explorer.exe) within a short time window.
logsource:
    product: windows
    service: sysmon
detection:
    network_connection:
        EventID: 3
        DestinationPort: 135
        Initiated: 'false'
    process_creation:
        EventID: 1
        ParentImage|endswith:
            - '\mmc.exe'
            - '\dllhost.exe'
            - '\svchost.exe'
    timeframe: 30s
    condition: network_connection | near process_creation
level: high
tags:
    - attack.lateral_movement
    - attack.t1021.003

Step 4: Deploy Splunk and KQL Detection Queries

# Splunk: Detect MMC20.Application DCOM Lateral Movement
# Correlates network logon (4624 Type 3) with mmc.exe process creation
 
index=wineventlog sourcetype="XmlWinEventLog:Microsoft-Windows-Sysmon/Operational"
EventCode=1 ParentImage="*\\mmc.exe"
(Image="*\\cmd.exe" OR Image="*\\powershell.exe" OR Image="*\\pwsh.exe"
 OR Image="*\\wscript.exe" OR Image="*\\cscript.exe" OR Image="*\\mshta.exe")
| eval target_host=ComputerName
| join target_host type=inner
    [search index=wineventlog EventCode=4624 LogonType=3
    | where AuthenticationPackageName="NTLM" OR AuthenticationPackageName="Kerberos"
    | eval target_host=ComputerName
    | rename IpAddress as source_ip, TargetUserName as logon_user
    | fields target_host source_ip logon_user _time]
| where abs(_time - relative_time(now(), "-5m")) < 300
| table _time target_host Image ParentImage CommandLine source_ip logon_user
| sort -_time
# Splunk: Detect ShellWindows/ShellBrowserWindow DCOM Lateral Movement
# Identifies explorer.exe spawning suspicious child processes on servers
 
index=wineventlog sourcetype="XmlWinEventLog:Microsoft-Windows-Sysmon/Operational"
EventCode=1 ParentImage="*\\explorer.exe"
(Image="*\\cmd.exe" OR Image="*\\powershell.exe" OR Image="*\\pwsh.exe")
| eval target_host=ComputerName
| join target_host type=inner
    [search index=wineventlog sourcetype="XmlWinEventLog:Microsoft-Windows-Sysmon/Operational"
     EventCode=3 DestinationPort=135 Initiated="false"
    | eval target_host=ComputerName
    | rename SourceIp as dcom_source_ip
    | fields target_host dcom_source_ip _time]
| where abs(_time - relative_time(now(), "-2m")) < 120
| stats count values(Image) as child_processes values(CommandLine) as commands
    by target_host dcom_source_ip
| where count > 0
| table target_host dcom_source_ip child_processes commands count
# Splunk: DCOM RPC Endpoint Mapper Connection Anomaly
# Identifies hosts receiving unusual volumes of inbound RPC connections
 
index=wineventlog sourcetype="XmlWinEventLog:Microsoft-Windows-Sysmon/Operational"
EventCode=3 DestinationPort=135 Initiated="false"
| stats dc(SourceIp) as unique_sources count by ComputerName
| where unique_sources > 3 OR count > 10
| sort -unique_sources
| table ComputerName unique_sources count
-- Microsoft Sentinel KQL: DCOM Lateral Movement via MMC20.Application
 
let dcom_network = SysmonEvent
| where EventID == 3
| where DestinationPort == 135
| where InitiatedConnection == false
| project NetworkTime=TimeGenerated, TargetComputer=Computer,
    SourceIP=SourceIp, DestPort=DestinationPort;
 
let dcom_process = SysmonEvent
| where EventID == 1
| where ParentImage endswith "\\mmc.exe"
    or ParentImage endswith "\\dllhost.exe"
| where Image endswith "\\cmd.exe"
    or Image endswith "\\powershell.exe"
    or Image endswith "\\pwsh.exe"
    or Image endswith "\\wscript.exe"
    or Image endswith "\\mshta.exe"
| project ProcessTime=TimeGenerated, TargetComputer=Computer,
    ParentImage, Image, CommandLine, User;
 
dcom_network
| join kind=inner (dcom_process) on TargetComputer
| where abs(datetime_diff('second', NetworkTime, ProcessTime)) < 60
| project NetworkTime, ProcessTime, TargetComputer, SourceIP,
    ParentImage, Image, CommandLine, User
| sort by NetworkTime desc
-- Microsoft Sentinel KQL: ShellWindows DCOM Lateral Movement
 
SecurityEvent
| where EventID == 4624 and LogonType == 3
| where AuthenticationPackageName in ("NTLM", "Kerberos")
| project LogonTime=TimeGenerated, TargetComputer=Computer,
    SourceIP=IpAddress, LogonUser=TargetUserName
| join kind=inner (
    SysmonEvent
    | where EventID == 1
    | where ParentImage endswith "\\explorer.exe"
    | where Image endswith "\\cmd.exe"
        or Image endswith "\\powershell.exe"
        or Image endswith "\\pwsh.exe"
    | project ProcessTime=TimeGenerated, TargetComputer=Computer,
        Image, CommandLine, User
) on TargetComputer
| where ProcessTime between (LogonTime .. (LogonTime + 2m))
| project LogonTime, ProcessTime, TargetComputer, SourceIP,
    LogonUser, Image, CommandLine
| sort by LogonTime desc

Step 5: WMI Event Correlation for DCOM Activity

# Splunk: Correlate WMI events with DCOM lateral movement
# WMI-Activity operational log captures DCOM-triggered WMI calls
 
index=wineventlog source="WinEventLog:Microsoft-Windows-WMI-Activity/Operational"
| where EventCode IN (5857, 5858, 5859, 5860, 5861)
| eval event_type=case(
    EventCode=5857, "WMI Provider Loaded",
    EventCode=5858, "WMI Query Error",
    EventCode=5859, "WMI Provider Event",
    EventCode=5860, "WMI Temporary Event Registration",
    EventCode=5861, "WMI Permanent Event Registration")
| stats count values(event_type) as wmi_events by ComputerName
| where count > 5
| table ComputerName wmi_events count
# PowerShell: Query WMI operational log for DCOM-related activity
# Run on target systems during investigation
 
Get-WinEvent -LogName "Microsoft-Windows-WMI-Activity/Operational" -MaxEvents 500 |
    Where-Object {
        $_.Id -in @(5857, 5858, 5860, 5861) -and
        $_.Message -match "DCOM|MMC20|ShellWindows|ShellBrowserWindow"
    } |
    Select-Object TimeCreated, Id,
        @{N='Detail'; E={$_.Message.Substring(0, [Math]::Min(200, $_.Message.Length))}} |
    Format-Table -AutoSize
 
# Query Sysmon for DCOM parent-child process chains
Get-WinEvent -LogName "Microsoft-Windows-Sysmon/Operational" -FilterXPath @"
*[System[(EventID=1)]] and
*[EventData[
    (Data[@Name='ParentImage'] and
     (contains(Data[@Name='ParentImage'],'mmc.exe') or
      contains(Data[@Name='ParentImage'],'dllhost.exe')))
]]
"@ -MaxEvents 100 |
    Select-Object TimeCreated,
        @{N='ParentImage'; E={$_.Properties[20].Value}},
        @{N='Image'; E={$_.Properties[4].Value}},
        @{N='CommandLine'; E={$_.Properties[10].Value}},
        @{N='User'; E={$_.Properties[12].Value}} |
    Format-Table -AutoSize

Step 6: Network-Level DCOM Detection with Zeek

# Zeek script for detecting DCOM lateral movement at the network level
# Monitors RPC Endpoint Mapper (port 135) and subsequent high-port connections
 
cat > /opt/zeek/share/zeek/site/custom-detections/dcom-lateral-movement.zeek << 'ZEEKEOF'
@load base/frameworks/notice
@load base/frameworks/sumstats
@load base/protocols/dce-rpc
 
module DCOMLateralMovement;
 
export {
    redef enum Notice::Type += {
        DCOM_Lateral_Movement_Suspected,
        DCOM_RPC_Scan
    };
 
    # Threshold for unique targets receiving RPC connections from single source
    const rpc_target_threshold: count = 3 &redef;
    const rpc_time_window: interval = 10min &redef;
}
 
event zeek_init()
{
    local r1 = SumStats::Reducer(
        $stream="dcom.rpc_targets",
        $apply=set(SumStats::UNIQUE)
    );
 
    SumStats::create([
        $name="detect-dcom-lateral",
        $epoch=rpc_time_window,
        $reducers=set(r1),
        $threshold_val(key: SumStats::Key, result: SumStats::Result) = {
            return result["dcom.rpc_targets"]$unique + 0.0;
        },
        $threshold=rpc_target_threshold + 0.0,
        $threshold_crossed(key: SumStats::Key, result: SumStats::Result) = {
            NOTICE([
                $note=DCOM_RPC_Scan,
                $msg=fmt("Host %s connected to %d hosts on RPC/135 in %s - possible DCOM lateral movement",
                         key$str, result["dcom.rpc_targets"]$unique, rpc_time_window),
                $identifier=key$str
            ]);
        }
    ]);
}
 
event connection_state_remove(c: connection)
{
    if ( c$id$resp_p == 135/tcp && c$id$resp_h in Site::local_nets )
    {
        SumStats::observe("dcom.rpc_targets",
            [$str=cat(c$id$orig_h)],
            [$str=cat(c$id$resp_h)]
        );
    }
}
ZEEKEOF
 
# Monitor DCE-RPC operations related to DCOM objects
cat /opt/zeek/logs/current/dce_rpc.log | \
  zeek-cut ts id.orig_h id.resp_h endpoint operation | \
  grep -iE "IDispatch|IRemoteActivation|IRemUnknown|IObjectExporter" | \
  sort -t$'\t' -k2 | uniq -c | sort -rn
 
# Track RPC endpoint mapper connections between internal hosts
cat /opt/zeek/logs/current/conn.log | \
  zeek-cut ts id.orig_h id.resp_h id.resp_p duration | \
  awk '$4 == 135' | \
  awk '{print $2, "->", $3}' | sort | uniq -c | sort -rn | head -20

Step 7: DCOM Attack Surface Audit and Hardening

# Audit DCOM configuration across the domain
# Enumerate remotely accessible DCOM objects
 
# List DCOM applications registered on local system
Get-CimInstance -ClassName Win32_DCOMApplication |
    Select-Object AppID, Name |
    Sort-Object Name |
    Format-Table -AutoSize
 
# Check DCOM launch permissions for high-risk objects
$clsids = @{
    "MMC20.Application"    = "{49B2791A-B1AE-4C90-9B8E-E860BA07F889}"
    "ShellWindows"         = "{9BA05972-F6A8-11CF-A442-00A0C90A8F39}"
    "ShellBrowserWindow"   = "{C08AFD90-F2A1-11D1-8455-00A0C91F3880}"
    "Excel.Application"    = "{00024500-0000-0000-C000-000000000046}"
    "Outlook.Application"  = "{0006F03A-0000-0000-C000-000000000046}"
}
 
foreach ($name in $clsids.Keys) {
    $clsid = $clsids[$name]
    $regPath = "HKLM:\SOFTWARE\Classes\CLSID\$clsid"
    if (Test-Path $regPath) {
        $launchPermission = (Get-ItemProperty -Path "$regPath" -Name "LaunchPermission" -ErrorAction SilentlyContinue)
        Write-Host "[*] $name ($clsid): $(if ($launchPermission) { 'Custom permissions set' } else { 'DEFAULT permissions (potentially exploitable)' })"
    } else {
        Write-Host "[-] $name ($clsid): Not found on this system"
    }
}
 
# Check if DCOM is enabled (should be restricted on servers that don't need it)
$dcomEnabled = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Ole" -Name "EnableDCOM").EnableDCOM
Write-Host "`n[*] DCOM Enabled: $dcomEnabled"
 
# Check remote launch and activation permissions
$remoteLaunch = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Ole" -Name "DefaultLaunchPermission" -ErrorAction SilentlyContinue)
Write-Host "[*] Default Launch Permission: $(if ($remoteLaunch) { 'Custom' } else { 'System Default' })"
# Hardening: Restrict DCOM remote access via Group Policy
# These settings should be applied via GPO in production
 
# Disable DCOM on systems that do not require it
# Computer Configuration > Administrative Templates > System > Distributed COM >
#   Application Compatibility > Enable Distributed COM on this computer = Disabled
 
# Restrict DCOM launch permissions via registry
# Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Ole" -Name "EnableDCOM" -Value "N"
 
# Block RPC/DCOM at the host firewall for non-admin traffic
# New-NetFirewallRule -DisplayName "Block Inbound DCOM/RPC" `
#     -Direction Inbound -LocalPort 135 -Protocol TCP `
#     -Action Block -RemoteAddress "Any" `
#     -Group "DCOM Hardening"
#
# New-NetFirewallRule -DisplayName "Allow DCOM from Admin Subnets" `
#     -Direction Inbound -LocalPort 135 -Protocol TCP `
#     -Action Allow -RemoteAddress "10.10.0.0/24" `
#     -Group "DCOM Hardening"
 
# Windows Firewall: Restrict dynamic RPC port range
# netsh int ipv4 set dynamicport tcp start=49152 num=1024

Key Concepts

Term Definition
DCOM (T1021.003) Distributed Component Object Model -- extends COM to allow remote object instantiation and method invocation over RPC, abused for lateral movement
MMC20.Application COM object (CLSID {49B2791A-B1AE-4C90-9B8E-E860BA07F889}) controlling MMC snap-ins; ExecuteShellCommand method enables remote command execution
ShellWindows COM object (CLSID {9BA05972-F6A8-11CF-A442-00A0C90A8F39}) that activates within an existing explorer.exe process, executing commands without creating a new COM server process
ShellBrowserWindow COM object (CLSID {C08AFD90-F2A1-11D1-8455-00A0C91F3880}) similar to ShellWindows, uses Document.Application.ShellExecute for stealthy command execution
RPC Endpoint Mapper Service on TCP port 135 that maps RPC interfaces to dynamic ports; all DCOM communication begins with an endpoint mapper query
Sysmon Event ID 1 Process Create event capturing parent-child process relationships, command lines, and user context -- critical for identifying DCOM-spawned processes
Sysmon Event ID 3 Network Connection event capturing source/destination IPs and ports -- used to correlate RPC connections with subsequent process creation
DcomLaunch Windows service (svchost.exe -k DcomLaunch) that manages DCOM server process activation; parent process of COM servers spawned via remote DCOM calls
WMI-Activity ETW Event Tracing for Windows provider that logs WMI method calls, instance creations, and queries -- provides visibility into DCOM-triggered WMI operations

Tools & Systems

Tool Purpose
Sysmon Endpoint telemetry for process creation (EID 1), network connections (EID 3), and image loads (EID 7) essential for DCOM detection
Splunk / Elastic SIEM Log aggregation and correlation platform for DCOM detection rules and threat hunting queries
Microsoft Sentinel Cloud SIEM with built-in KQL queries and analytics rules for DCOM lateral movement detection
Sigma Vendor-agnostic detection rule format for portable DCOM detection rules
Zeek Network security monitor for DCE-RPC protocol analysis and RPC endpoint mapper traffic monitoring
Atomic Red Team MITRE ATT&CK test framework with T1021.003 atomics for validating DCOM detection coverage
Impacket (dcomexec.py) Python-based DCOM execution tool used by attackers and red teamers for testing DCOM lateral movement
CIMSession / PowerShell Native Windows tooling for DCOM object instantiation used in both legitimate administration and attacks

Common Scenarios

Scenario 1: MMC20.Application Lateral Movement to File Server

Context: A SOC analyst receives an alert for mmc.exe spawning cmd.exe on a file server (10.10.20.50) at 03:22 UTC. No administrator activity is scheduled at this time.

Approach:

  1. Query Sysmon Event ID 1 on 10.10.20.50: confirm mmc.exe (parent: svchost.exe -k DcomLaunch) spawned cmd.exe with command line /c net user /domain > C:\temp\users.txt
  2. Query Sysmon Event ID 3 on 10.10.20.50: identify inbound TCP connection on port 135 from 10.10.5.30 at 03:22:01, followed by a high-port connection at 03:22:02
  3. Correlate Event ID 4624 on 10.10.20.50: find LogonType 3 from 10.10.5.30 at 03:22:00 with admin credentials
  4. Investigate 10.10.5.30: check for compromise indicators -- find Mimikatz artifacts in memory, evidence of credential dumping at 03:15
  5. Trace the attack chain: initial phishing compromise at 02:45, credential theft at 03:15, DCOM lateral movement at 03:22
  6. Contain: isolate 10.10.5.30 and 10.10.20.50, force password reset for compromised admin account, block inbound RPC from non-admin subnets

Pitfalls:

  • Dismissing mmc.exe activity as legitimate MMC administration without checking the parent process and command line
  • Not correlating the network logon (4624) with the process creation to identify the true source host
  • Failing to investigate the source host for initial compromise indicators

Scenario 2: ShellWindows Stealthy Lateral Movement

Context: During a threat hunt, an analyst queries for explorer.exe spawning cmd.exe on domain controllers and finds several instances on DC01 with no interactive logon sessions.

Approach:

  1. Verify no interactive sessions: query Event ID 4624 LogonType 2 or 10 on DC01 -- none found during the time window
  2. Query Sysmon Event ID 1: explorer.exe spawning cmd.exe with encoded PowerShell commands at 14:05, 14:12, and 14:18
  3. Decode the PowerShell: reveals reconnaissance commands (Get-ADUser, Get-ADGroup, Get-ADComputer)
  4. Query Sysmon Event ID 3: inbound RPC connections from 10.10.3.15 preceding each process creation
  5. Identify the ShellWindows pattern: no new mmc.exe or dllhost.exe process created -- commands execute through existing explorer.exe, consistent with ShellWindows/ShellBrowserWindow DCOM abuse
  6. Investigate 10.10.3.15: compromised workstation with Cobalt Strike beacon artifacts

Pitfalls:

  • Missing the attack because ShellWindows does not create a separate COM server process -- requires monitoring explorer.exe child processes
  • Not having Sysmon Event ID 3 configured to capture network connections from explorer.exe
  • Filtering out explorer.exe as a legitimate parent process without considering the server context

Output Format

Hunt ID: TH-DCOM-[DATE]-[SEQ]
Alert Severity: High
MITRE Technique: T1021.003 (Remote Services: DCOM)
 
Source Host: [IP/Hostname of attacker's machine]
Target Host: [IP/Hostname where DCOM executed]
DCOM Object: [MMC20.Application | ShellWindows | ShellBrowserWindow]
CLSID: [COM object class identifier]
 
Process Chain:
  Parent: [svchost.exe -k DcomLaunch | explorer.exe | mmc.exe]
  Child:  [cmd.exe | powershell.exe | ...]
  Command Line: [Full command executed]
 
Network Indicators:
  RPC Connection: [Source IP]:port -> [Target IP]:135 at [timestamp]
  DCOM Port: [Source IP]:port -> [Target IP]:[high-port] at [timestamp]
 
Authentication Context:
  Event 4624: LogonType 3 from [Source IP] at [timestamp]
  Account: [Domain\Username]
  Logon ID: [Logon session identifier]
 
Risk Assessment: [Critical/High/Medium]
Recommended Action: [Isolate, investigate source, reset credentials, restrict DCOM]
Source materials

References and resources

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

References 1

api-reference.md5.6 KB

DCOM Lateral Movement Detection API Reference

MITRE ATT&CK Mapping

Technique ID Description
Remote Services: DCOM T1021.003 Adversaries use DCOM to execute commands on remote systems
Lateral Movement TA0008 Tactic covering movement between networked systems
Windows Management Instrumentation T1047 WMI often correlated with DCOM lateral movement

DCOM COM Objects Abused for Lateral Movement

COM Object CLSID Method Parent Process
MMC20.Application {49B2791A-B1AE-4C90-9B8E-E860BA07F889} ExecuteShellCommand mmc.exe via svchost.exe -k DcomLaunch
ShellWindows {9BA05972-F6A8-11CF-A442-00A0C90A8F39} Document.Application.ShellExecute explorer.exe (existing process)
ShellBrowserWindow {C08AFD90-F2A1-11D1-8455-00A0C91F3880} Document.Application.ShellExecute explorer.exe (existing process)
Excel.Application {00024500-0000-0000-C000-000000000046} DDEInitiate / RegisterXLL excel.exe via svchost.exe -k DcomLaunch
Outlook.Application {0006F03A-0000-0000-C000-000000000046} CreateObject outlook.exe via svchost.exe -k DcomLaunch

Sysmon Event IDs for DCOM Detection

Event ID Name DCOM Relevance
1 Process Create Detects DCOM parent (mmc.exe, dllhost.exe, explorer.exe) spawning suspicious children
3 Network Connection Captures inbound RPC (port 135) and dynamic high-port DCOM connections
7 Image Loaded Tracks loading of DCOM-related DLLs (ole32.dll, comsvcs.dll, rpcrt4.dll)
10 Process Access Detects cross-process access patterns from DCOM processes
11 File Create Identifies file drops from DCOM-executed commands

Windows Security Event IDs

Event ID Log DCOM Context
4624 (Type 3) Security Network logon preceding DCOM execution on target
4672 Security Special privileges assigned during DCOM remote activation
4688 Security Process creation (alternative to Sysmon EID 1 if enabled)

WMI-Activity Operational Event IDs

Event ID Description
5857 WMI provider loaded (DCOM can trigger WMI operations)
5858 WMI query error
5860 Temporary WMI event consumer registration
5861 Permanent WMI event consumer registration

Network Indicators

Protocol Port Description
TCP 135 RPC Endpoint Mapper - all DCOM starts here
TCP 49152-65535 Dynamic RPC ports for DCOM data transfer
TCP 445 SMB - may follow DCOM for file operations
TCP 139 NetBIOS Session Service

Splunk SPL - DCOM Detection Queries

# MMC20.Application lateral movement
index=wineventlog sourcetype="XmlWinEventLog:Microsoft-Windows-Sysmon/Operational"
EventCode=1 ParentImage="*\\mmc.exe"
(Image="*\\cmd.exe" OR Image="*\\powershell.exe")
| table _time ComputerName ParentImage Image CommandLine User
 
# Inbound RPC connections (DCOM prerequisite)
index=wineventlog sourcetype="XmlWinEventLog:Microsoft-Windows-Sysmon/Operational"
EventCode=3 DestinationPort=135 Initiated="false"
| stats dc(SourceIp) as sources count by ComputerName
| where sources > 3

KQL - Microsoft Sentinel Queries

// DCOM process creation from mmc.exe or dllhost.exe
SysmonEvent
| where EventID == 1
| where ParentImage endswith "\\mmc.exe" or ParentImage endswith "\\dllhost.exe"
| where Image endswith "\\cmd.exe" or Image endswith "\\powershell.exe"
| project TimeGenerated, Computer, ParentImage, Image, CommandLine, User

python-evtx - Parse Sysmon EVTX

from Evtx.Evtx import FileHeader
from lxml import etree
 
NS = {"evt": "http://schemas.microsoft.com/win/2004/08/events/event"}
with open("Microsoft-Windows-Sysmon%4Operational.evtx", "rb") as f:
    fh = FileHeader(f)
    for record in fh.records():
        root = etree.fromstring(record.xml().encode("utf-8"))
        eid = root.find(".//evt:System/evt:EventID", NS)
        if eid is not None and eid.text == "1":
            data = {e.get("Name"): e.text for e in root.findall(".//evt:EventData/evt:Data", NS)}
            print(data.get("ParentImage"), "->", data.get("Image"))

Atomic Red Team - T1021.003 Test Cases

Atomic Test Description
MMC20.Application Lateral Movement Instantiates MMC20.Application DCOM and calls ExecuteShellCommand
ShellWindows Lateral Movement Uses ShellWindows CLSID for remote command execution
Excel DDE DCOM Creates remote Excel instance and triggers DDE execution

Impacket - dcomexec.py

# Attack tool reference (for detection validation in authorized testing)
# dcomexec.py creates a DCOM connection and executes commands
# Protocol: Uses MMC20.Application, ShellWindows, or ShellBrowserWindow
python3 dcomexec.py domain/user:password@target_ip "whoami"
python3 dcomexec.py -object MMC20 domain/user:password@target_ip "cmd.exe /c ipconfig"
python3 dcomexec.py -object ShellWindows domain/user:password@target_ip "powershell -c Get-Process"

References

Scripts 2

agent.py13.7 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""DCOM Lateral Movement Detection Agent - Hunts for DCOM object abuse via Sysmon event correlation."""

import json
import logging
import argparse
import os
import sys
import subprocess
from collections import defaultdict
from datetime import datetime, timedelta

logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)

# DCOM COM object CLSIDs used for lateral movement
DCOM_CLSIDS = {
    "{49B2791A-B1AE-4C90-9B8E-E860BA07F889}": "MMC20.Application",
    "{9BA05972-F6A8-11CF-A442-00A0C90A8F39}": "ShellWindows",
    "{C08AFD90-F2A1-11D1-8455-00A0C91F3880}": "ShellBrowserWindow",
    "{00024500-0000-0000-C000-000000000046}": "Excel.Application",
    "{0006F03A-0000-0000-C000-000000000046}": "Outlook.Application",
}

DCOM_PARENT_PROCESSES = ["mmc.exe", "dllhost.exe", "explorer.exe"]
SUSPICIOUS_CHILDREN = [
    "cmd.exe", "powershell.exe", "pwsh.exe", "wscript.exe",
    "cscript.exe", "mshta.exe", "rundll32.exe", "regsvr32.exe",
    "certutil.exe", "bitsadmin.exe",
]

SYSMON_NS = "http://schemas.microsoft.com/win/2004/08/events/event"
EVTX_PARSE_TIMEOUT = 300  # seconds


def parse_evtx_records(evtx_path):
    """Parse Sysmon EVTX file into structured events using python-evtx."""
    try:
        from Evtx.Evtx import FileHeader
        from lxml import etree
    except ImportError:
        logger.error("Required packages missing. Install: pip install python-evtx lxml")
        sys.exit(1)

    events = []
    ns = {"evt": SYSMON_NS}
    with open(evtx_path, "rb") as f:
        fh = FileHeader(f)
        for record in fh.records():
            try:
                xml = record.xml()
                root = etree.fromstring(xml.encode("utf-8"))
                event_id_elem = root.find(".//evt:System/evt:EventID", ns)
                if event_id_elem is None:
                    continue
                eid = int(event_id_elem.text)
                if eid not in (1, 3, 7):
                    continue
                data = {}
                for elem in root.findall(".//evt:EventData/evt:Data", ns):
                    data[elem.get("Name", "")] = elem.text or ""
                time_elem = root.find(".//evt:System/evt:TimeCreated", ns)
                timestamp = time_elem.get("SystemTime", "") if time_elem is not None else ""
                comp_elem = root.find(".//evt:System/evt:Computer", ns)
                computer = comp_elem.text if comp_elem is not None else ""
                data["EventID"] = eid
                data["TimeCreated"] = timestamp
                data["Computer"] = computer
                events.append(data)
            except Exception:
                continue
    logger.info("Parsed %d Sysmon events (EID 1,3,7) from %s", len(events), evtx_path)
    return events


def detect_mmc20_lateral(events):
    """Detect MMC20.Application DCOM lateral movement: mmc.exe spawning suspicious children."""
    findings = []
    for ev in events:
        if ev.get("EventID") != 1:
            continue
        parent = ev.get("ParentImage", "").lower()
        image = ev.get("Image", "").lower()
        if "mmc.exe" not in parent:
            continue
        if not any(child in image for child in SUSPICIOUS_CHILDREN):
            continue
        findings.append({
            "detection": "MMC20.Application DCOM Lateral Movement",
            "severity": "HIGH",
            "mitre": "T1021.003",
            "timestamp": ev.get("TimeCreated"),
            "computer": ev.get("Computer"),
            "parent_image": ev.get("ParentImage"),
            "parent_cmdline": ev.get("ParentCommandLine"),
            "child_image": ev.get("Image"),
            "child_cmdline": ev.get("CommandLine"),
            "user": ev.get("User"),
            "clsid": "{49B2791A-B1AE-4C90-9B8E-E860BA07F889}",
        })
    logger.info("MMC20 detections: %d", len(findings))
    return findings


def detect_shell_dcom_lateral(events):
    """Detect ShellWindows/ShellBrowserWindow: explorer.exe spawning cmd/powershell."""
    findings = []
    for ev in events:
        if ev.get("EventID") != 1:
            continue
        parent = ev.get("ParentImage", "").lower()
        image = ev.get("Image", "").lower()
        if "explorer.exe" not in parent:
            continue
        if not any(child in image for child in ["cmd.exe", "powershell.exe", "pwsh.exe",
                                                  "mshta.exe", "wscript.exe", "cscript.exe"]):
            continue
        findings.append({
            "detection": "ShellWindows/ShellBrowserWindow DCOM Lateral Movement",
            "severity": "MEDIUM",
            "mitre": "T1021.003",
            "timestamp": ev.get("TimeCreated"),
            "computer": ev.get("Computer"),
            "parent_image": ev.get("ParentImage"),
            "child_image": ev.get("Image"),
            "child_cmdline": ev.get("CommandLine"),
            "user": ev.get("User"),
            "clsid": "{9BA05972} or {C08AFD90}",
        })
    logger.info("ShellWindows/ShellBrowserWindow detections: %d", len(findings))
    return findings


def detect_dllhost_lateral(events):
    """Detect DCOM via dllhost.exe spawning suspicious children."""
    findings = []
    for ev in events:
        if ev.get("EventID") != 1:
            continue
        parent = ev.get("ParentImage", "").lower()
        image = ev.get("Image", "").lower()
        if "dllhost.exe" not in parent:
            continue
        if not any(child in image for child in SUSPICIOUS_CHILDREN):
            continue
        parent_cmdline = ev.get("ParentCommandLine", "")
        clsid = "Unknown"
        if "/Processid:" in parent_cmdline:
            start = parent_cmdline.find("/Processid:") + len("/Processid:")
            clsid_raw = parent_cmdline[start:].strip().strip("{}")
            clsid = "{" + clsid_raw + "}"
        dcom_name = DCOM_CLSIDS.get(clsid.upper(), "Unknown DCOM Object")
        findings.append({
            "detection": f"DCOM via dllhost.exe ({dcom_name})",
            "severity": "HIGH",
            "mitre": "T1021.003",
            "timestamp": ev.get("TimeCreated"),
            "computer": ev.get("Computer"),
            "parent_image": ev.get("ParentImage"),
            "parent_cmdline": parent_cmdline,
            "child_image": ev.get("Image"),
            "child_cmdline": ev.get("CommandLine"),
            "user": ev.get("User"),
            "clsid": clsid,
            "dcom_object": dcom_name,
        })
    logger.info("dllhost.exe DCOM detections: %d", len(findings))
    return findings


def detect_rpc_connections(events):
    """Detect inbound RPC endpoint mapper connections (port 135) from Sysmon Event ID 3."""
    rpc_connections = []
    for ev in events:
        if ev.get("EventID") != 3:
            continue
        dest_port = ev.get("DestinationPort", "")
        initiated = ev.get("Initiated", "").lower()
        if dest_port == "135" and initiated == "false":
            rpc_connections.append({
                "detection": "Inbound RPC Connection (DCOM Prerequisite)",
                "severity": "LOW",
                "timestamp": ev.get("TimeCreated"),
                "computer": ev.get("Computer"),
                "source_ip": ev.get("SourceIp"),
                "dest_ip": ev.get("DestinationIp"),
                "dest_port": dest_port,
                "image": ev.get("Image"),
            })
    logger.info("Inbound RPC (port 135) connections: %d", len(rpc_connections))
    return rpc_connections


def correlate_rpc_with_process(rpc_events, process_findings, window_seconds=60):
    """Correlate RPC connections with DCOM process creation for high-confidence detections."""
    correlated = []
    for proc in process_findings:
        proc_time_str = proc.get("timestamp", "")
        proc_computer = proc.get("computer", "")
        if not proc_time_str:
            continue
        try:
            proc_dt = datetime.fromisoformat(proc_time_str.replace("Z", "+00:00"))
        except (ValueError, TypeError):
            continue
        for rpc in rpc_events:
            rpc_time_str = rpc.get("timestamp", "")
            rpc_computer = rpc.get("computer", "")
            if not rpc_time_str or rpc_computer != proc_computer:
                continue
            try:
                rpc_dt = datetime.fromisoformat(rpc_time_str.replace("Z", "+00:00"))
            except (ValueError, TypeError):
                continue
            delta = (proc_dt - rpc_dt).total_seconds()
            if 0 <= delta <= window_seconds:
                correlated.append({
                    "detection": "CORRELATED: RPC Connection -> DCOM Process Creation",
                    "severity": "CRITICAL",
                    "mitre": "T1021.003",
                    "computer": proc_computer,
                    "source_ip": rpc.get("source_ip"),
                    "rpc_time": rpc_time_str,
                    "process_time": proc_time_str,
                    "time_delta_seconds": round(delta, 2),
                    "dcom_detection": proc.get("detection"),
                    "child_image": proc.get("child_image"),
                    "child_cmdline": proc.get("child_cmdline"),
                    "user": proc.get("user"),
                })
                break
    logger.info("Correlated RPC->Process chains: %d", len(correlated))
    return correlated


def audit_dcom_config():
    """Audit local DCOM configuration for high-risk COM objects (Windows only)."""
    if sys.platform != "win32":
        logger.info("DCOM config audit only available on Windows")
        return []

    audit_results = []
    for clsid, name in DCOM_CLSIDS.items():
        try:
            result = subprocess.run(
                ["reg", "query", f"HKLM\\SOFTWARE\\Classes\\CLSID\\{clsid}"],
                capture_output=True, text=True, timeout=10
            )
            exists = result.returncode == 0
            audit_results.append({
                "clsid": clsid,
                "name": name,
                "registered": exists,
                "risk": "HIGH" if exists else "N/A",
            })
        except subprocess.TimeoutExpired:
            audit_results.append({"clsid": clsid, "name": name, "registered": "TIMEOUT", "risk": "UNKNOWN"})
        except Exception as e:
            audit_results.append({"clsid": clsid, "name": name, "registered": f"ERROR: {e}", "risk": "UNKNOWN"})

    # Check if DCOM is enabled
    try:
        result = subprocess.run(
            ["reg", "query", "HKLM\\SOFTWARE\\Microsoft\\Ole", "/v", "EnableDCOM"],
            capture_output=True, text=True, timeout=10
        )
        dcom_enabled = "Y" in result.stdout if result.returncode == 0 else "UNKNOWN"
        audit_results.append({"check": "DCOM Enabled", "value": dcom_enabled,
                              "risk": "HIGH" if dcom_enabled == "Y" else "LOW"})
    except (subprocess.TimeoutExpired, Exception):
        pass

    return audit_results


def generate_report(all_findings, dcom_audit, output_path):
    """Generate JSON detection report."""
    report = {
        "scan_timestamp": datetime.utcnow().isoformat() + "Z",
        "mitre_technique": "T1021.003",
        "summary": {
            "total_findings": len(all_findings),
            "critical": len([f for f in all_findings if f.get("severity") == "CRITICAL"]),
            "high": len([f for f in all_findings if f.get("severity") == "HIGH"]),
            "medium": len([f for f in all_findings if f.get("severity") == "MEDIUM"]),
            "low": len([f for f in all_findings if f.get("severity") == "LOW"]),
        },
        "findings": all_findings,
        "dcom_config_audit": dcom_audit,
    }

    with open(output_path, "w") as f:
        json.dump(report, f, indent=2, default=str)
    logger.info("Report saved to %s", output_path)

    s = report["summary"]
    print(f"\nDCOM LATERAL MOVEMENT DETECTION REPORT")
    print(f"  Total findings: {s['total_findings']}")
    print(f"  Critical: {s['critical']}, High: {s['high']}, Medium: {s['medium']}, Low: {s['low']}")
    if s["critical"] > 0:
        print("  [!!!] CRITICAL: Correlated RPC + process creation chains detected")
    return report


def main():
    parser = argparse.ArgumentParser(
        description="DCOM Lateral Movement Detection Agent (T1021.003)"
    )
    parser.add_argument("--evtx", required=True, help="Path to Sysmon .evtx log file")
    parser.add_argument("--output", "-o", default="dcom_detection_report.json",
                        help="Output JSON report path (default: dcom_detection_report.json)")
    parser.add_argument("--correlation-window", type=int, default=60,
                        help="Seconds window for RPC-to-process correlation (default: 60)")
    parser.add_argument("--audit-dcom", action="store_true",
                        help="Audit local DCOM object registration (Windows only)")
    parser.add_argument("--verbose", "-v", action="store_true", help="Enable debug logging")
    args = parser.parse_args()

    if args.verbose:
        logging.getLogger().setLevel(logging.DEBUG)

    if not os.path.isfile(args.evtx):
        logger.error("EVTX file not found: %s", args.evtx)
        sys.exit(1)

    logger.info("Parsing Sysmon events from: %s", args.evtx)
    events = parse_evtx_records(args.evtx)

    mmc_findings = detect_mmc20_lateral(events)
    shell_findings = detect_shell_dcom_lateral(events)
    dllhost_findings = detect_dllhost_lateral(events)
    rpc_connections = detect_rpc_connections(events)

    all_process_findings = mmc_findings + shell_findings + dllhost_findings
    correlated = correlate_rpc_with_process(
        rpc_connections, all_process_findings, args.correlation_window
    )

    all_findings = correlated + all_process_findings
    all_findings.sort(key=lambda x: x.get("severity", ""), reverse=True)

    dcom_audit = audit_dcom_config() if args.audit_dcom else []

    generate_report(all_findings, dcom_audit, args.output)


if __name__ == "__main__":
    main()
detect_dcom_lateral_movement.py18.5 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""
DCOM Lateral Movement Detection Script
Parses Windows Security and Sysmon event logs to detect DCOM-based lateral movement
via MMC20.Application, ShellWindows, and ShellBrowserWindow COM object abuse.

MITRE ATT&CK: T1021.003 (Remote Services: Distributed Component Object Model)

Usage:
    python detect_dcom_lateral_movement.py --evtx <path_to_sysmon_evtx>
    python detect_dcom_lateral_movement.py --evtx <sysmon.evtx> --security <security.evtx>
    python detect_dcom_lateral_movement.py --evtx <sysmon.evtx> --json --output results.json

Requirements:
    pip install python-evtx lxml
"""

import argparse
import json
import sys
import os
from datetime import datetime, timedelta
from collections import defaultdict

try:
    import Evtx.Evtx as evtx
    import Evtx.Views as evtx_views
    from lxml import etree
except ImportError:
    print("[!] Required packages not found. Install with: pip install python-evtx lxml")
    sys.exit(1)


# DCOM-related COM object CLSIDs
DCOM_CLSIDS = {
    "{49B2791A-B1AE-4C90-9B8E-E860BA07F889}": "MMC20.Application",
    "{9BA05972-F6A8-11CF-A442-00A0C90A8F39}": "ShellWindows",
    "{C08AFD90-F2A1-11D1-8455-00A0C91F3880}": "ShellBrowserWindow",
    "{00024500-0000-0000-C000-000000000046}": "Excel.Application",
    "{0006F03A-0000-0000-C000-000000000046}": "Outlook.Application",
}

# Suspicious child processes when spawned by DCOM parent processes
SUSPICIOUS_CHILDREN = [
    "cmd.exe", "powershell.exe", "pwsh.exe", "wscript.exe",
    "cscript.exe", "mshta.exe", "rundll32.exe", "regsvr32.exe",
    "certutil.exe", "bitsadmin.exe", "msbuild.exe",
]

# DCOM parent processes that spawn child processes during lateral movement
DCOM_PARENTS = ["mmc.exe", "dllhost.exe", "explorer.exe", "svchost.exe"]

SYSMON_NS = "http://schemas.microsoft.com/win/2004/08/events/event"


def parse_sysmon_event(record_xml):
    """Parse a Sysmon event record XML into a dictionary."""
    try:
        root = etree.fromstring(record_xml)
    except etree.XMLSyntaxError:
        return None

    ns = {"e": SYSMON_NS}
    event = {}

    system = root.find(".//e:System", ns)
    if system is not None:
        event_id_elem = system.find("e:EventID", ns)
        event["EventID"] = int(event_id_elem.text) if event_id_elem is not None else 0
        time_elem = system.find("e:TimeCreated", ns)
        if time_elem is not None:
            event["TimeCreated"] = time_elem.get("SystemTime", "")
        computer_elem = system.find("e:Computer", ns)
        event["Computer"] = computer_elem.text if computer_elem is not None else ""

    event_data = root.find(".//e:EventData", ns)
    if event_data is not None:
        for data in event_data.findall("e:Data", ns):
            name = data.get("Name", "")
            value = data.text or ""
            event[name] = value

    return event


def is_dcom_parent(image_path):
    """Check if the process image is a known DCOM parent."""
    if not image_path:
        return False
    image_lower = image_path.lower()
    return any(parent in image_lower for parent in DCOM_PARENTS)


def is_suspicious_child(image_path):
    """Check if the process image is a suspicious child for DCOM context."""
    if not image_path:
        return False
    image_lower = image_path.lower()
    return any(child in image_lower for child in SUSPICIOUS_CHILDREN)


def check_dcomllaunch_parent(command_line):
    """Check if the parent command line indicates DcomLaunch service."""
    if not command_line:
        return False
    return "dcomlaunch" in command_line.lower()


def detect_dcom_process_creation(events):
    """
    Detect DCOM lateral movement via Sysmon Event ID 1 (Process Create).
    Looks for DCOM parent processes spawning suspicious children.
    """
    findings = []

    for event in events:
        if event.get("EventID") != 1:
            continue

        parent_image = event.get("ParentImage", "")
        image = event.get("Image", "")
        parent_cmdline = event.get("ParentCommandLine", "")
        cmdline = event.get("CommandLine", "")
        user = event.get("User", "")
        time_created = event.get("TimeCreated", "")
        computer = event.get("Computer", "")

        # Pattern 1: mmc.exe spawning suspicious child (MMC20.Application)
        if "mmc.exe" in parent_image.lower() and is_suspicious_child(image):
            findings.append({
                "timestamp": time_created,
                "computer": computer,
                "detection_type": "MMC20.Application DCOM Lateral Movement",
                "dcom_object": "MMC20.Application",
                "clsid": "{49B2791A-B1AE-4C90-9B8E-E860BA07F889}",
                "parent_image": parent_image,
                "parent_commandline": parent_cmdline,
                "child_image": image,
                "child_commandline": cmdline,
                "user": user,
                "severity": "HIGH",
                "mitre": "T1021.003",
            })

        # Pattern 2: DcomLaunch svchost spawning dllhost or mmc
        if check_dcomllaunch_parent(parent_cmdline) and is_suspicious_child(image):
            findings.append({
                "timestamp": time_created,
                "computer": computer,
                "detection_type": "DcomLaunch Service Spawning Suspicious Process",
                "dcom_object": "Unknown (DcomLaunch)",
                "clsid": "N/A",
                "parent_image": parent_image,
                "parent_commandline": parent_cmdline,
                "child_image": image,
                "child_commandline": cmdline,
                "user": user,
                "severity": "HIGH",
                "mitre": "T1021.003",
            })

        # Pattern 3: explorer.exe spawning cmd/powershell on servers
        # (ShellWindows/ShellBrowserWindow)
        if "explorer.exe" in parent_image.lower() and is_suspicious_child(image):
            # Check if this might be interactive (less suspicious) or DCOM (more suspicious)
            findings.append({
                "timestamp": time_created,
                "computer": computer,
                "detection_type": "ShellWindows/ShellBrowserWindow DCOM Lateral Movement (Requires Correlation)",
                "dcom_object": "ShellWindows or ShellBrowserWindow",
                "clsid": "{9BA05972-F6A8-11CF-A442-00A0C90A8F39} or {C08AFD90-F2A1-11D1-8455-00A0C91F3880}",
                "parent_image": parent_image,
                "parent_commandline": parent_cmdline,
                "child_image": image,
                "child_commandline": cmdline,
                "user": user,
                "severity": "MEDIUM",
                "mitre": "T1021.003",
            })

        # Pattern 4: dllhost.exe spawning suspicious children
        if "dllhost.exe" in parent_image.lower() and is_suspicious_child(image):
            # Extract CLSID from dllhost command line if present
            detected_clsid = "Unknown"
            if "/Processid:" in parent_cmdline:
                clsid_start = parent_cmdline.find("/Processid:") + len("/Processid:")
                detected_clsid = parent_cmdline[clsid_start:].strip().strip("{}")
                detected_clsid = "{" + detected_clsid + "}"

            dcom_name = DCOM_CLSIDS.get(detected_clsid.upper(), "Unknown DCOM Object")

            findings.append({
                "timestamp": time_created,
                "computer": computer,
                "detection_type": "DCOM Object Execution via dllhost.exe",
                "dcom_object": dcom_name,
                "clsid": detected_clsid,
                "parent_image": parent_image,
                "parent_commandline": parent_cmdline,
                "child_image": image,
                "child_commandline": cmdline,
                "user": user,
                "severity": "HIGH",
                "mitre": "T1021.003",
            })

    return findings


def detect_dcom_network_connections(events):
    """
    Detect DCOM-related network connections via Sysmon Event ID 3.
    Looks for inbound RPC connections (port 135) to DCOM processes.
    """
    findings = []

    for event in events:
        if event.get("EventID") != 3:
            continue

        image = event.get("Image", "")
        dest_port = event.get("DestinationPort", "")
        source_ip = event.get("SourceIp", "")
        dest_ip = event.get("DestinationIp", "")
        initiated = event.get("Initiated", "")
        time_created = event.get("TimeCreated", "")
        computer = event.get("Computer", "")

        # Inbound RPC connection (port 135) -- DCOM always starts here
        if dest_port == "135" and initiated.lower() == "false":
            findings.append({
                "timestamp": time_created,
                "computer": computer,
                "detection_type": "Inbound RPC Endpoint Mapper Connection",
                "source_ip": source_ip,
                "destination_ip": dest_ip,
                "destination_port": dest_port,
                "process_image": image,
                "severity": "MEDIUM",
                "mitre": "T1021.003",
                "note": "DCOM communication begins with RPC endpoint mapper query on port 135",
            })

        # DCOM process making outbound connection on high port (dynamic RPC)
        if is_dcom_parent(image) and dest_port and int(dest_port) > 49151:
            findings.append({
                "timestamp": time_created,
                "computer": computer,
                "detection_type": "DCOM Process Dynamic RPC Connection",
                "source_ip": source_ip,
                "destination_ip": dest_ip,
                "destination_port": dest_port,
                "process_image": image,
                "severity": "LOW",
                "mitre": "T1021.003",
                "note": "DCOM process communicating on dynamic RPC port range",
            })

    return findings


def correlate_network_and_process(process_findings, network_findings, window_seconds=60):
    """
    Correlate network connections with process creation events.
    A network connection to port 135 followed by DCOM process creation
    within the time window is a strong indicator of lateral movement.
    """
    correlated = []

    for proc in process_findings:
        proc_time = proc.get("timestamp", "")
        proc_computer = proc.get("computer", "")

        if not proc_time:
            continue

        try:
            proc_dt = datetime.fromisoformat(proc_time.replace("Z", "+00:00"))
        except (ValueError, TypeError):
            continue

        for net in network_findings:
            net_time = net.get("timestamp", "")
            net_computer = net.get("computer", "")

            if not net_time or net_computer != proc_computer:
                continue

            try:
                net_dt = datetime.fromisoformat(net_time.replace("Z", "+00:00"))
            except (ValueError, TypeError):
                continue

            time_diff = abs((proc_dt - net_dt).total_seconds())

            if time_diff <= window_seconds and net_dt <= proc_dt:
                correlated.append({
                    "correlation_type": "DCOM Lateral Movement Chain",
                    "severity": "CRITICAL",
                    "mitre": "T1021.003",
                    "computer": proc_computer,
                    "network_event": {
                        "timestamp": net_time,
                        "source_ip": net.get("source_ip"),
                        "destination_port": net.get("destination_port"),
                    },
                    "process_event": {
                        "timestamp": proc_time,
                        "dcom_object": proc.get("dcom_object"),
                        "parent_image": proc.get("parent_image"),
                        "child_image": proc.get("child_image"),
                        "child_commandline": proc.get("child_commandline"),
                        "user": proc.get("user"),
                    },
                    "time_delta_seconds": round(time_diff, 2),
                })

    return correlated


def parse_evtx_file(filepath):
    """Parse a .evtx file and return list of parsed events."""
    events = []
    try:
        with evtx.Evtx(filepath) as log:
            for record in log.records():
                try:
                    event = parse_sysmon_event(record.xml())
                    if event:
                        events.append(event)
                except Exception:
                    continue
    except Exception as e:
        print(f"[!] Error parsing {filepath}: {e}")
    return events


def print_findings(findings, title):
    """Print findings in a formatted table."""
    if not findings:
        print(f"\n[+] {title}: No findings")
        return

    print(f"\n{'=' * 80}")
    print(f"  {title} ({len(findings)} findings)")
    print(f"{'=' * 80}")

    for i, finding in enumerate(findings, 1):
        print(f"\n  [{i}] {finding.get('detection_type', 'Unknown')}")
        print(f"      Severity: {finding.get('severity', 'N/A')}")
        print(f"      MITRE: {finding.get('mitre', 'N/A')}")
        print(f"      Time: {finding.get('timestamp', 'N/A')}")
        print(f"      Computer: {finding.get('computer', 'N/A')}")

        if "dcom_object" in finding:
            print(f"      DCOM Object: {finding['dcom_object']}")
            print(f"      CLSID: {finding.get('clsid', 'N/A')}")
        if "parent_image" in finding:
            print(f"      Parent: {finding['parent_image']}")
            print(f"      Child: {finding.get('child_image', 'N/A')}")
            print(f"      Command: {finding.get('child_commandline', 'N/A')[:120]}")
        if "source_ip" in finding:
            print(f"      Source IP: {finding['source_ip']}")
            print(f"      Dest Port: {finding.get('destination_port', 'N/A')}")
        if "note" in finding:
            print(f"      Note: {finding['note']}")


def print_correlated(correlated):
    """Print correlated findings."""
    if not correlated:
        print("\n[+] Correlated DCOM Chains: No findings")
        return

    print(f"\n{'=' * 80}")
    print(f"  CORRELATED DCOM LATERAL MOVEMENT CHAINS ({len(correlated)} findings)")
    print(f"{'=' * 80}")

    for i, c in enumerate(correlated, 1):
        net = c["network_event"]
        proc = c["process_event"]
        print(f"\n  [{i}] {c['correlation_type']}")
        print(f"      Severity: {c['severity']}")
        print(f"      Target: {c['computer']}")
        print(f"      Source IP: {net['source_ip']} -> port {net['destination_port']}")
        print(f"      Time Delta: {c['time_delta_seconds']}s")
        print(f"      DCOM Object: {proc['dcom_object']}")
        print(f"      Process Chain: {proc['parent_image']} -> {proc['child_image']}")
        print(f"      Command: {proc.get('child_commandline', 'N/A')[:120]}")
        print(f"      User: {proc.get('user', 'N/A')}")


def main():
    parser = argparse.ArgumentParser(
        description="Detect DCOM lateral movement from Sysmon and Security event logs"
    )
    parser.add_argument(
        "--evtx", required=True,
        help="Path to Sysmon .evtx log file"
    )
    parser.add_argument(
        "--security",
        help="Path to Windows Security .evtx log file (optional, for 4624 correlation)"
    )
    parser.add_argument(
        "--json", action="store_true",
        help="Output results in JSON format"
    )
    parser.add_argument(
        "--output", "-o",
        help="Output file path (default: stdout)"
    )
    parser.add_argument(
        "--correlation-window", type=int, default=60,
        help="Time window in seconds for correlating network and process events (default: 60)"
    )
    args = parser.parse_args()

    if not os.path.exists(args.evtx):
        print(f"[!] File not found: {args.evtx}")
        sys.exit(1)

    print(f"[*] Parsing Sysmon events from: {args.evtx}")
    events = parse_evtx_file(args.evtx)
    print(f"[*] Parsed {len(events)} Sysmon events")

    security_events = []
    if args.security:
        if os.path.exists(args.security):
            print(f"[*] Parsing Security events from: {args.security}")
            security_events = parse_evtx_file(args.security)
            print(f"[*] Parsed {len(security_events)} Security events")
        else:
            print(f"[!] Security log not found: {args.security}")

    print("[*] Analyzing for DCOM lateral movement indicators...")

    process_findings = detect_dcom_process_creation(events)
    network_findings = detect_dcom_network_connections(events)
    correlated = correlate_network_and_process(
        process_findings, network_findings, args.correlation_window
    )

    all_results = {
        "scan_time": datetime.utcnow().isoformat() + "Z",
        "sysmon_log": args.evtx,
        "security_log": args.security or "Not provided",
        "total_events_parsed": len(events) + len(security_events),
        "process_creation_findings": process_findings,
        "network_connection_findings": network_findings,
        "correlated_chains": correlated,
        "summary": {
            "process_detections": len(process_findings),
            "network_detections": len(network_findings),
            "correlated_chains": len(correlated),
            "critical_findings": len([c for c in correlated]),
            "high_findings": len([f for f in process_findings if f.get("severity") == "HIGH"]),
        },
    }

    if args.json:
        output = json.dumps(all_results, indent=2, default=str)
        if args.output:
            with open(args.output, "w") as f:
                f.write(output)
            print(f"[*] JSON results written to: {args.output}")
        else:
            print(output)
    else:
        print(f"\n[*] DCOM Lateral Movement Detection Report")
        print(f"[*] Scan Time: {all_results['scan_time']}")
        print(f"[*] Events Analyzed: {all_results['total_events_parsed']}")

        print_findings(process_findings, "DCOM Process Creation Detections")
        print_findings(network_findings, "DCOM Network Connection Detections")
        print_correlated(correlated)

        print(f"\n{'=' * 80}")
        print(f"  SUMMARY")
        print(f"{'=' * 80}")
        s = all_results["summary"]
        print(f"  Process Creation Detections: {s['process_detections']}")
        print(f"  Network Connection Detections: {s['network_detections']}")
        print(f"  Correlated Lateral Movement Chains: {s['correlated_chains']}")
        print(f"  Critical Findings: {s['critical_findings']}")
        print(f"  High Findings: {s['high_findings']}")

        if args.output:
            with open(args.output, "w") as f:
                json.dump(all_results, f, indent=2, default=str)
            print(f"\n[*] Full results written to: {args.output}")


if __name__ == "__main__":
    main()
Keep exploring