endpoint security

Detecting Fileless Attacks on Endpoints

Detects fileless malware and in-memory attacks that execute entirely in RAM without writing persistent files to disk, evading traditional antivirus. Use when building detections for PowerShell-based attacks, reflective DLL injection, WMI persistence, and registry-resident malware. Activates for requests involving fileless malware detection, in-memory attacks, PowerShell exploitation, or living-off-the-land techniques.

detection-engineeringendpointfileless-malwarememory-attackspowershell
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

When to Use

Use this skill when:

  • Building detection rules for fileless malware that operates entirely in memory
  • Hunting for PowerShell-based attacks, reflective DLL injection, and WMI abuse
  • Configuring endpoint telemetry (Sysmon, AMSI, PowerShell logging) to capture fileless indicators
  • Investigating incidents where traditional AV found no malicious files

Do not use for detecting file-based malware or for malware reverse engineering.

Prerequisites

  • Sysmon with process creation and WMI event logging enabled
  • PowerShell Script Block Logging and Module Logging enabled
  • AMSI (Antimalware Scan Interface) enabled for script content inspection
  • EDR with behavioral detection capabilities (MDE, CrowdStrike, SentinelOne)

Workflow

Step 1: Enable Required Telemetry

# Enable PowerShell Script Block Logging (GPO or registry)
New-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" `
  -Name EnableScriptBlockLogging -Value 1 -PropertyType DWORD -Force
 
# Enable PowerShell Module Logging
New-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging" `
  -Name EnableModuleLogging -Value 1 -PropertyType DWORD -Force
 
# Enable PowerShell Transcription
New-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\Transcription" `
  -Name EnableTranscripting -Value 1 -PropertyType DWORD -Force
 
# Sysmon config for fileless detection (key events):
# Event ID 1: Process creation (captures CommandLine)
# Event ID 7: Image loaded (DLL loading)
# Event ID 8: CreateRemoteThread (injection)
# Event ID 10: Process access (LSASS access)
# Event ID 19/20/21: WMI events

Step 2: Detect PowerShell-Based Attacks

# Indicators of malicious PowerShell:
 
# Encoded command execution
EventID: 1
CommandLine contains: "powershell" AND ("-enc" OR "-e " OR "-encodedcommand" OR "FromBase64String")
 
# Download cradle patterns
CommandLine contains: "IEX" AND ("Net.WebClient" OR "DownloadString" OR "Invoke-WebRequest")
CommandLine contains: "Invoke-Expression" AND "New-Object"
 
# AMSI bypass attempts (Event ID 4104 - Script Block)
ScriptBlock contains: ("Amsi"+"Utils") OR ("amsi"+"InitFailed") OR "SetValue.*amsi"
 
# Splunk query for suspicious PowerShell:
index=windows source="WinEventLog:Microsoft-Windows-PowerShell/Operational" EventCode=4104
| where match(ScriptBlockText, "(?i)(iex|invoke-expression|downloadstring|net\.webclient|frombase64|bypass|amsi.utils)")
| table _time host ScriptBlockText

Step 3: Detect Process Injection Techniques

# Reflective DLL injection - loads DLL from memory without touching disk
# Detection: Sysmon Event 7 (ImageLoaded) where image path is unusual
EventID: 7
ImageLoaded NOT starts with: "C:\Windows\" AND NOT starts with: "C:\Program Files"
 
# Process hollowing - creates process in suspended state, replaces memory
# Detection: Process creation followed by immediate memory write
EventID: 1 + 10 correlation
# Process created then accessed with PROCESS_VM_WRITE
 
# APC injection - queues code to thread's async procedure call queue
# Detection: Sysmon CreateRemoteThread from non-system process
EventID: 8
SourceImage NOT IN (known_legitimate_sources)
 
# MDE KQL:
DeviceEvents
| where ActionType in ("CreateRemoteThreadApiCall", "NtAllocateVirtualMemoryApiCall")
| where InitiatingProcessFileName !in ("MsMpEng.exe", "svchost.exe")
| project Timestamp, DeviceName, ActionType, InitiatingProcessFileName,
    InitiatingProcessCommandLine, FileName

Step 4: Detect WMI-Based Persistence

# Sysmon Event IDs 19/20/21 for WMI events
EventID: 19  # WmiEventFilter activity detected
EventID: 20  # WmiEventConsumer activity detected
EventID: 21  # WmiEventConsumerToFilter activity detected
 
# Any WMI event subscription creation is suspicious unless expected
# Common malicious WMI persistence:
Consumer contains: "CommandLineEventConsumer" OR "ActiveScriptEventConsumer"
 
# Query for WMI subscriptions via osquery or PowerShell:
Get-WMIObject -Namespace root\Subscription -Class __EventFilter
Get-WMIObject -Namespace root\Subscription -Class __EventConsumer
Get-WMIObject -Namespace root\Subscription -Class __FilterToConsumerBinding

Step 5: Detect Registry-Based Execution

# Malware stored in registry values and executed via PowerShell
# Sysmon Event 13 - Registry value set with encoded content
EventID: 13
TargetObject contains: "CurrentVersion\Run"
Details: unusually long value or Base64-encoded content
 
# Detection query:
index=sysmon EventCode=13
| where match(Details, "[A-Za-z0-9+/=]{100,}")
| table _time host TargetObject Details Image

Key Concepts

Term Definition
Fileless Malware Malware that operates entirely in memory without writing executable files to disk
AMSI Antimalware Scan Interface; Windows API allowing security products to inspect script content before execution
Reflective DLL Injection Loading a DLL from memory rather than disk, avoiding file-based detection
Process Hollowing Creating a legitimate process in suspended state and replacing its memory with malicious code
Script Block Logging PowerShell logging feature that captures deobfuscated script content (Event ID 4104)

Tools & Systems

  • Sysmon: Kernel-level process, DLL, and WMI monitoring
  • AMSI: Windows script content inspection API
  • PowerShell Logging: Script Block, Module, and Transcription logging
  • Microsoft Defender for Endpoint: Behavioral detection for fileless techniques
  • Volatility 3: Memory forensics for post-incident fileless malware analysis

Common Pitfalls

  • Relying on file-based AV: Traditional AV that scans files on disk will miss fileless attacks entirely. Behavioral detection and AMSI are required.
  • Disabled PowerShell logging: Without Script Block Logging, deobfuscated PowerShell commands are invisible to defenders.
  • AMSI bypass not detected: Sophisticated attackers bypass AMSI before executing payloads. Detect AMSI bypass attempts as a high-priority alert.
  • Not monitoring WMI events: WMI persistence is a favored technique of APT groups. Sysmon events 19-21 must be enabled.
Source materials

References and resources

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

References 3

api-reference.md1.9 KB

API Reference: Detecting Fileless Attacks on Endpoints

Key Event Sources

Source Event ID Detection
PowerShell Script Block 4104 Malicious script content
Sysmon Process Create 1 Encoded command execution
Sysmon CreateRemoteThread 8 Reflective DLL injection
Sysmon WMI EventFilter 19 WMI persistence
Sysmon WMI EventConsumer 20 WMI persistence
Sysmon WMI Binding 21 WMI persistence

python-evtx Usage

import Evtx.Evtx as evtx
with evtx.Evtx("PowerShell-Operational.evtx") as log:
    for record in log.records():
        xml = record.xml()
        # Parse Event 4104 ScriptBlockText

Suspicious PowerShell Patterns

# Dynamic execution
r"Invoke-Expression|IEX\s*\("
# Reflective loading
r"System\.Reflection\.Assembly.*Load"
# Memory injection APIs
r"VirtualAlloc|VirtualProtect|CreateThread"
# WMI persistence
r"Register-WMI|__EventFilter|__EventConsumer"
# Encoded commands
r"-enc\s|-encodedcommand\s"

Splunk SPL - Fileless Detection

index=powershell EventCode=4104
| where match(ScriptBlockText, "(?i)(Invoke-Expression|IEX|VirtualAlloc|FromBase64)")
| stats count by ScriptBlockText, Computer, UserID

AMSI (Anti-Malware Scan Interface)

# Enable AMSI logging
Set-MpPreference -EnableNetworkProtection Enabled
# Check AMSI status
Get-MpComputerStatus | Select AMServiceEnabled, AntispywareEnabled

WMI Persistence Detection

# List WMI event subscriptions
Get-WMIObject -Namespace root\Subscription -Class __EventFilter
Get-WMIObject -Namespace root\Subscription -Class __EventConsumer
Get-WMIObject -Namespace root\Subscription -Class __FilterToConsumerBinding

CLI Usage

python agent.py --ps-log PowerShell-Operational.evtx
python agent.py --sysmon-log Sysmon.evtx --check-wmi --check-injection
standards.md0.5 KB

Standards & References

workflows.md0.3 KB

Workflows

Fileless Attack Detection

[Enable telemetry (Sysmon, PS logging, AMSI)] → [Build detection rules per technique]
  → [Deploy rules in SIEM] → [Threat hunt for historical fileless indicators]
  → [Triage alerts] → [Investigate memory for confirmed incidents]
  → [Extract IOCs from memory analysis] → [Tune detections]

Scripts 2

agent.py6.3 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Fileless attack detection agent for endpoint logs.

Detects in-memory attacks by analyzing PowerShell script block logs (Event 4104),
WMI persistence events, and reflective DLL injection indicators from Sysmon.
"""

import argparse
import json
import re
from datetime import datetime

try:
    import Evtx.Evtx as evtx
except ImportError:
    evtx = None

SUSPICIOUS_PS_PATTERNS = {
    r"Invoke-Expression|IEX\s*\(": ("T1059.001", "HIGH", "Dynamic code execution"),
    r"Invoke-Mimikatz|Invoke-Kerberoast": ("T1003", "CRITICAL", "Credential tool"),
    r"System\.Reflection\.Assembly.*Load": ("T1620", "HIGH", "Reflective assembly load"),
    r"Net\.WebClient.*Download(String|Data|File)": ("T1105", "HIGH", "Remote download"),
    r"FromBase64String|Convert.*Base64": ("T1140", "MEDIUM", "Base64 decode"),
    r"VirtualAlloc|VirtualProtect|CreateThread": ("T1055", "CRITICAL", "Memory injection APIs"),
    r"New-Object.*IO\.MemoryStream": ("T1620", "HIGH", "In-memory stream"),
    r"-enc\s|-encodedcommand\s": ("T1027", "HIGH", "Encoded PowerShell"),
    r"Invoke-Shellcode|Invoke-ReflectivePEInjection": ("T1055", "CRITICAL", "Injection framework"),
    r"Win32_Process.*Create|WMI.*Process": ("T1047", "HIGH", "WMI process creation"),
    r"Register-WMI|__EventFilter|__EventConsumer": ("T1546.003", "CRITICAL", "WMI persistence"),
    r"HKCU:\\.*\\Run|HKLM:\\.*\\Run": ("T1547.001", "HIGH", "Registry run key"),
    r"Add-MpPreference.*ExclusionPath": ("T1562.001", "HIGH", "Defender exclusion"),
}

WMI_PERSISTENCE_EVENTS = {
    19: "WMI EventFilter created",
    20: "WMI EventConsumer created",
    21: "WMI EventConsumerToFilter binding",
}


def parse_powershell_scriptblock(filepath):
    if evtx is None:
        return {"error": "python-evtx not installed: pip install python-evtx"}
    findings = []
    with evtx.Evtx(filepath) as log:
        for record in log.records():
            xml = record.xml()
            if "<EventID>4104</EventID>" not in xml:
                continue
            script_block = re.search(r'<Data Name="ScriptBlockText">([^<]+)', xml)
            if not script_block:
                continue
            script = script_block.group(1)
            time_match = re.search(r'SystemTime="([^"]+)"', xml)

            for pattern, (mitre, severity, desc) in SUSPICIOUS_PS_PATTERNS.items():
                if re.search(pattern, script, re.IGNORECASE):
                    findings.append({
                        "event_id": 4104,
                        "timestamp": time_match.group(1) if time_match else "",
                        "pattern": desc,
                        "mitre": mitre,
                        "severity": severity,
                        "script_excerpt": script[:300],
                    })
    return findings


def parse_sysmon_wmi_persistence(filepath):
    if evtx is None:
        return {"error": "python-evtx not installed"}
    findings = []
    with evtx.Evtx(filepath) as log:
        for record in log.records():
            xml = record.xml()
            event_id_match = re.search(r'<EventID[^>]*>(\d+)</EventID>', xml)
            if not event_id_match:
                continue
            event_id = int(event_id_match.group(1))
            if event_id not in WMI_PERSISTENCE_EVENTS:
                continue
            time_match = re.search(r'SystemTime="([^"]+)"', xml)
            name = re.search(r'<Data Name="Name">([^<]+)', xml)
            operation = re.search(r'<Data Name="Operation">([^<]+)', xml)
            consumer = re.search(r'<Data Name="Destination">([^<]+)', xml)
            user = re.search(r'<Data Name="User">([^<]+)', xml)

            findings.append({
                "event_id": event_id,
                "type": WMI_PERSISTENCE_EVENTS[event_id],
                "timestamp": time_match.group(1) if time_match else "",
                "name": name.group(1) if name else "",
                "operation": operation.group(1) if operation else "",
                "destination": consumer.group(1) if consumer else "",
                "user": user.group(1) if user else "",
                "severity": "CRITICAL",
                "mitre": "T1546.003",
            })
    return findings


def parse_sysmon_injection(filepath):
    if evtx is None:
        return {"error": "python-evtx not installed"}
    findings = []
    with evtx.Evtx(filepath) as log:
        for record in log.records():
            xml = record.xml()
            if "<EventID>8</EventID>" not in xml:
                continue
            source = re.search(r'<Data Name="SourceImage">([^<]+)', xml)
            target = re.search(r'<Data Name="TargetImage">([^<]+)', xml)
            time_match = re.search(r'SystemTime="([^"]+)"', xml)

            findings.append({
                "event_id": 8,
                "timestamp": time_match.group(1) if time_match else "",
                "source_image": source.group(1) if source else "",
                "target_image": target.group(1) if target else "",
                "severity": "HIGH",
                "mitre": "T1055",
                "description": "CreateRemoteThread - possible reflective injection",
            })
    return findings


def main():
    parser = argparse.ArgumentParser(description="Fileless Attack Detector")
    parser.add_argument("--ps-log", help="PowerShell EVTX file (Event 4104)")
    parser.add_argument("--sysmon-log", help="Sysmon EVTX file")
    parser.add_argument("--check-wmi", action="store_true", help="Check WMI persistence")
    parser.add_argument("--check-injection", action="store_true", help="Check injection")
    args = parser.parse_args()

    results = {"timestamp": datetime.utcnow().isoformat() + "Z", "findings": []}

    if args.ps_log:
        ps = parse_powershell_scriptblock(args.ps_log)
        if isinstance(ps, dict) and "error" in ps:
            results["error"] = ps["error"]
        else:
            results["findings"].extend(ps)

    if args.sysmon_log and args.check_wmi:
        wmi = parse_sysmon_wmi_persistence(args.sysmon_log)
        if not isinstance(wmi, dict):
            results["findings"].extend(wmi)

    if args.sysmon_log and args.check_injection:
        inj = parse_sysmon_injection(args.sysmon_log)
        if not isinstance(inj, dict):
            results["findings"].extend(inj)

    results["total_findings"] = len(results["findings"])
    print(json.dumps(results, indent=2))


if __name__ == "__main__":
    main()
process.py2.2 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Fileless Attack Detector - Scans PowerShell logs for fileless attack indicators."""

import json, csv, re, sys, os
from collections import Counter
from datetime import datetime

FILELESS_PATTERNS = {
    "encoded_command": r"(?i)(-enc\s|-e\s|-encodedcommand|frombase64string)",
    "download_cradle": r"(?i)(downloadstring|invoke-webrequest|net\.webclient|wget\s|curl\s)",
    "amsi_bypass": r"(?i)(amsiutils|amsiinitfailed|amsi\.dll)",
    "reflection": r"(?i)(system\.reflection|loadassembly|gettype.*invoke)",
    "wmi_abuse": r"(?i)(win32_process.*create|wmiclass|managementclass)",
    "credential_access": r"(?i)(mimikatz|invoke-mimikatz|sekurlsa|logonpasswords)",
    "invoke_expression": r"(?i)(iex\s|invoke-expression)",
}


def scan_powershell_logs(csv_path: str) -> list:
    detections = []
    with open(csv_path, "r", encoding="utf-8-sig") as f:
        for row in csv.DictReader(f):
            script = row.get("ScriptBlockText", row.get("Message", ""))
            for pattern_name, pattern in FILELESS_PATTERNS.items():
                if re.search(pattern, script):
                    detections.append({
                        "timestamp": row.get("TimeCreated", row.get("Date and Time", "")),
                        "host": row.get("Computer", row.get("MachineName", "")),
                        "technique": pattern_name,
                        "script_excerpt": script[:300],
                    })
                    break
    return detections


def generate_report(detections: list, output_path: str) -> None:
    by_technique = Counter(d["technique"] for d in detections)
    report = {
        "report_generated": datetime.utcnow().isoformat() + "Z",
        "total_detections": len(detections),
        "by_technique": dict(by_technique),
        "detections": detections[:100],
    }
    with open(output_path, "w") as f:
        json.dump(report, f, indent=2)


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python process.py <powershell_logs.csv>")
        sys.exit(1)
    detections = scan_powershell_logs(sys.argv[1])
    out = os.path.join(os.path.dirname(sys.argv[1]) or ".", "fileless_detection_report.json")
    generate_report(detections, out)
    print(f"Detections: {len(detections)}")

Assets 1

template.mdtext/markdown · 0.5 KB
Keep exploring