Drag
0

Enterprise-Grade SIEM & EDR Lab with Elastic Stack: Real-World Threat Detection Using Elastic EDR, Packetbeat, Sysmon, and Windows Telemetry

Portfolio Thumbnail

Overview

In this lab, I built a realistic and isolated SIEM & EDR environment using the Elastic Stack, Elastic EDR, Packetbeat, Sysmon, osquery, and native Windows telemetry to simulate, detect, and respond to real-world security threats. The project showcases how to configure data forwarding via the Elastic Agent, write advanced detection queries using Kibana and the Elastic Query Language (EQL/KQL), and validate detections through live attack simulationsβ€”mirroring the workflow of a professional Security Operations Center (SOC).

Objectives

  1. + Deploy and configure a comprehensive SIEM and EDR lab environment leveraging the Elastic Stack, integrating Elastic EDR, Packetbeat, and Windows telemetry
  2. + Collect and centralize high-fidelity telemetry using Sysmon, native Windows Event Logs, and Osquery for enhanced endpoint visibility
  3. + Develop advanced Elasticsearch Query DSL and Kibana detection rules to identify and investigate attacker behaviors
  4. + Simulate real-world adversary techniques including PowerShell abuse, process injection within a controlled lab environment
  5. + Configure and validate real-time detection alerts and automated workflows to provide actionable intelligence to security operations teams
  6. + Implement enterprise-grade network segmentation and isolation using OPNsense to replicate realistic security architecture

Lab Overview

> Initializing Elastic Stack SIEM & EDR lab overview...
[βœ“] Loading telemetry and detection modules...
ComponentDetails
SIEM & EDR PlatformElastic Stack (Elasticsearch, Kibana, Elastic EDR)
Telemetry SourcesSysmon (modular config), Windows Event Logs, Osquery, Packetbeat
Log ForwardingElastic Agent installed on endpoints for unified telemetry collection
EndpointsWindows 11 Workstation (primary telemetry source)
Network SegmentationOPNsense Firewall isolates Windows workstation from the internet (except for logging)
Logging ServerUbuntu 22.04 server running Elasticsearch and Kibana on a dedicated subnet
> Lab environment ready βœ…

🌐 Elastic Stack Network Architecture Overview

Endpoint (Windows 11)
Agent: Elastic Agent with Osquery & Sysmon
Role: Main telemetry generator and endpoint monitoring
Elastic Fleet Server / EDR
Role: Centralized agent management and policy enforcement
Function: Collects and processes telemetry from endpoints
Purpose: Enables detection, response, and threat hunting
Elasticsearch Cluster
Service: Data indexing, storage, and search engine
Role: Aggregates logs and telemetry from agents and network
Usage: Backend for Kibana SIEM and analytics dashboards
Summary: This network topology simulates a real-world Elastic Stack SOC lab, enabling comprehensive endpoint telemetry collection, centralized management, threat detection, and incident response without exposing the lab to external networks.

Comprehensive Installation Guide: Docker, Splunk, Elastic Stack

Step 1: Install Docker

Docker enables containerization, allowing you to run complex applications like Splunk and Elastic Stack in isolated, reproducible environments. This simplifies deployment, scaling, and maintenance.

For production environments, ensure Docker is installed following best security practices such as limiting root access and enabling TLS for Docker API.

# On Ubuntu/Debian
sudo apt update
sudo apt install -y docker.io docker-compose
sudo systemctl start docker
sudo systemctl enable docker

# Verify Docker installation
docker --version
docker-compose --version

# On Windows or macOS
# Download Docker Desktop from https://www.docker.com/get-started

Step 2: Install Splunk Enterprise with Docker Compose

Splunk Enterprise is a powerful platform for searching, monitoring, and analyzing machine-generated data via a web-style interface. Running Splunk inside Docker containers provides flexibility and isolation, making deployments cleaner and easier to manage.

Security tip: Always set a strong, complex password for the admin account, and consider integrating Splunk with LDAP or SSO for enterprise authentication.

version: '2.4'

volumes:
  opt-splunk-etc: {}
  opt-splunk-var: {}

services:
  splunkenterprise:
    container_name: splunk
    hostname: splunkenterprise
    image: splunk/splunk:latest
    mem_limit: 2G
    environment:
      - SPLUNK_START_ARGS=--accept-license
      - SPLUNK_ENABLE_LISTEN=9997
      - SPLUNK_ADD=tcp 1514
      - SPLUNK_PASSWORD=your_password
    volumes:
      - opt-splunk-etc:/opt/splunk/etc
      - opt-splunk-var:/opt/splunk/var
    ports:
      - "8000:8000"
      - "9997:9997"
      - "8088:8088"
      - "1514:1514"
      - "8089:8089"

Step 3: Explanation for Splunk Docker Compose Setup

  • Persistent Volumes: Volumes opt-splunk-etc and opt-splunk-var persist Splunk configurations and indexed data outside the container lifecycle.
  • Memory Limit: Restricting memory to 2GB ensures stable container operation without overwhelming host resources.
  • Port Exposure: Common ports exposed allow web UI access, receiving data from forwarders, HTTP event collection, and syslog ingestion.
  • Environment Variables: Accepts license and configures admin password to allow automated startup without manual intervention.

This reflects a professional approach to containerized enterprise software deployment, essential for infrastructure and security roles.

Step 4: Install Elastic Stack Using the Elastic Container Repo

Elastic Stack (Elasticsearch, Kibana, Beats, Logstash) is an open-source suite for centralized logging, analytics, and visualization. This containerized setup includes security best practices like TLS encryption, password management, and health checks.

To simplify installation, clone the GitHub repository below which contains the Docker Compose files, certificate generation logic, and setup scripts:

git clone https://github.com/mohamdhajji/elastic-secure-docker.git
cd elastic-secure-docker
cp .env.example .env # then set your passwords and stack version
./install.sh

The setup service handles automated certificate creation and secure password setup for the elastic and kibana_system users before starting the main services.

services:
  setup:
    image: docker.elastic.co/elasticsearch/elasticsearch:${STACK_VERSION}
    container_name: ecp-elasticsearch-security-setup
    volumes:
      - certs:/usr/share/elasticsearch/config/certs:z
    user: "0"
    command: >
      bash -c '
        if [ x${ELASTIC_PASSWORD} == x ]; then
          echo "Set the ELASTIC_PASSWORD environment variable in the .env file";
          exit 1;
        elif [ x${KIBANA_PASSWORD} == x ]; then
          echo "Set the KIBANA_PASSWORD environment variable in the .env file";
          exit 1;
        fi;
        if [ ! -f certs/ca.zip ]; then
          echo "Creating CA";
          bin/elasticsearch-certutil ca --silent --pem -out config/certs/ca.zip;
          unzip config/certs/ca.zip -d config/certs;
        fi;
        if [ ! -f certs/certs.zip ]; then
          echo "Creating certs";
          echo -ne           "instances:\n"          "  - name: elasticsearch\n"          "    dns:\n"          "      - ecp-elasticsearch\n"          "      - localhost\n"          "    ip:\n"          "      - 127.0.0.1\n"          "  - name: kibana\n"          "    dns:\n"          "      - ecp-kibana\n"          "      - localhost\n"          "    ip:\n"          "      - 127.0.0.1\n"          "  - name: fleet-server\n"          "    dns:\n"          "      - ecp-fleet-server\n"          "      - localhost\n"          "    ip:\n"          "      - 127.0.0.1\n"          > config/certs/instances.yml;
          bin/elasticsearch-certutil cert --silent --pem -out config/certs/certs.zip --in config/certs/instances.yml --ca-cert config/certs/ca/ca.crt --ca-key config/certs/ca/ca.key;
          unzip config/certs/certs.zip -d config/certs;
          cat config/certs/elasticsearch/elasticsearch.crt config/certs/ca/ca.crt > config/certs/elasticsearch/elasticsearch.chain.pem
        fi;
        echo "Setting file permissions"
        chown -R root:root config/certs;
        find . -type d -exec chmod 750 {} \;;
        find . -type f -exec chmod 640 {} \;;
        echo "Waiting for Elasticsearch availability";
        until curl -s --cacert config/certs/ca/ca.crt https://ecp-elasticsearch:9200 | grep -q "missing authentication credentials"; do sleep 30; done;
        echo "Setting kibana_system password";
        until curl -s -X POST --cacert config/certs/ca/ca.crt -u elastic:${ELASTIC_PASSWORD} -H "Content-Type: application/json" https://ecp-elasticsearch:9200/_security/user/kibana_system/_password -d "{\"password\":\"\KIBANA_PASSWORD\"}" | grep -q "^{}"; do sleep 10; done;
        echo "All done!";
      '
    healthcheck:
      test: ["CMD-SHELL", "[ -f config/certs/elasticsearch/elasticsearch.crt ]"]
      interval: 1s
      timeout: 5s
      retries: 120

  elasticsearch:
    depends_on:
      setup:
        condition: service_healthy
    image: docker.elastic.co/elasticsearch/elasticsearch:${STACK_VERSION}
    container_name: ecp-elasticsearch
    volumes:
      - certs:/usr/share/elasticsearch/config/certs
      - esdata01:/usr/share/elasticsearch/data
    ports:
      - ${ES_PORT}:9200
    restart: always
    environment:
      - node.name=ecp-elasticsearch
      - cluster.name=${CLUSTER_NAME}
      - ELASTIC_PASSWORD=${ELASTIC_PASSWORD}
      - bootstrap.memory_lock=true
      - discovery.type=single-node
      - xpack.security.enabled=true
      - xpack.security.http.ssl.enabled=true
      - xpack.security.http.ssl.key=certs/elasticsearch/elasticsearch.key
      - xpack.security.http.ssl.certificate=certs/elasticsearch/elasticsearch.chain.pem
      - xpack.security.http.ssl.certificate_authorities=certs/ca/ca.crt
      - xpack.security.http.ssl.verification_mode=certificate
      - xpack.security.http.ssl.client_authentication=optional
      - xpack.security.transport.ssl.enabled=true
      - xpack.security.transport.ssl.key=certs/elasticsearch/elasticsearch.key
      - xpack.security.transport.ssl.certificate=certs/elasticsearch/elasticsearch.crt
      - xpack.security.transport.ssl.certificate_authorities=certs/ca/ca.crt
      - xpack.security.transport.ssl.verification_mode=certificate
      - xpack.security.transport.ssl.client_authentication=required

volumes:
  certs:
  esdata01:

Alert Showcase: 10 High-Fidelity Detections

Multiple Failed Local Login Attempts (Event ID 4625) – Elastic SIEM

HighRisk Score: 70Brute ForceWindowsAuthentication

Overview

Detects brute-force attacks against Windows local accounts by tracking excessive failed logins (Event ID 4625). This rule helps identify credential stuffing, password spraying, and lateral movement attempts.

Why it matters: 81% of hacking-related breaches involve brute force or stolen credentials (Verizon DBIR 2023).

Use Cases

  • Credential stuffing attacks
  • Internal brute-force attempts
  • Service account compromise

Data Sources

Windows Security Logs

Event ID 4625 (Failed Logon) via Winlogbeat or Elastic Agent

Elastic EDR

Endpoint process correlation for attack context

Prerequisites

  • Windows Event Forwarding or Winlogbeat configured
  • Elastic Agent deployed on endpoints
  • system.security index populated in Elasticsearch

Detection Objectives

  • Detect β‰₯5 failed logins per user in 10 minutes
  • Exclude known service accounts (optional)
  • Correlate with source IP geolocation

Step-by-Step Creation Guide

  1. Navigate to Security β†’ Detection Rules in Kibana
  2. Create a new Threshold rule
  3. Paste the KQL query below
  4. Set threshold to 5 events per 10m
  5. Add exceptions for backup/service accounts

Detection Logic

Elastic Detection Rule (Production Ready)YAML
id: windows-failed-logins-bruteforce
name: "Multiple Failed Windows Logins (Brute Force)"
description: "Detects 5+ failed login attempts (Event ID 4625) per user in 10 minutes."
severity: "high"
risk_score: 75
type: "threshold"
index: ["winlogbeat-*", "logs-windows.*"]
query: |
  event.code: "4625" and 
  winlog.event_data.SubStatus: 
    ("0xC000006A" or  # Wrong password
     "0xC000006D" or  # User doesn't exist 
     "0xC0000070" or  # Account disabled
     "0xC0000071" or  # Expired password
     "0xC0000234")    # Account locked
  and not user.name: ("SYSTEM", "ANONYMOUS LOGON", "NETWORK SERVICE")
threshold:
  field: "user.name"
  value: 5
  timeframe: "10m"
tags: ["Windows", "Brute Force", "Credential Access", "MITRE T1110"]
references:
  - "https://www.elastic.co/guide/en/security/current/detection-engine-overview.html"
false_positives:
  - description: "Service account password rotation"
    items: ["svc_*", "sql_*"]
  - description: "Penetration testing"
    items: ["testuser"]
actions:
  - group_by: ["user.name", "source.ip"]
    throttle: "1h"
    webhook:
      target_url: "https://your-soc-tool.com/alerts"
      method: "POST"
enabled: true
exceptions_list:
  - id: "service-accounts"
    namespace_type: "single"
    type: "endpoint"
Complete YAML rule for Elastic Security. Deploy via Kibana UI or API. Includes status code filtering and exception handling.
Kibana Investigation QueryKQL
event.dataset: "windows.security" and 
event.id: 4625 and 
winlog.event_data.SubStatus: "0xC000006A" 
| stats 
    count() as failed_attempts, 
    values(source.ip) as source_ips 
    by user.name, winlog.computer_name
| where failed_attempts > 5
| sort -failed_attempts
Ad-hoc query for SOC analysts to investigate brute force patterns.
Winlogbeat Configuration (Enhanced)YAML
winlogbeat.event_logs:
  - name: Security
    processors:
      - script:
          lang: javascript
          source: >
            function process(event) {
              // Standardize Event ID 4625 fields
              if (event.Get("winlog.event_id") === 4625) {
                event.Put("event.code", "4625");
                event.Put("event.type", "authentication_failure");
                
                // Enrich with MITRE Tactic
                if (event.Get("winlog.event_data.SubStatus") === "0xC000006A") {
                  event.AppendTo("tags", "Credential Access");
                }
              }
            }
output.elasticsearch:
  hosts: ["https://your-elastic-cluster:9200"]
  pipeline: "winlogbeat-%{[agent.version]}-routing"
Enhanced Winlogbeat config with field normalization and MITRE tagging.
Simulate Attacks (Test Validation)POWERSHELL
# Generate test failed logins (run on domain controller)
1..10 | ForEach-Object {
  $randomUser = "user" + (Get-Random -Minimum 1 -Maximum 50)
  $eventParams = @{
    LogName = 'Security'
    Source = 'Microsoft-Windows-Security-Auditing'
    EventID = 4625
    Message = "Failed login for $randomUser from 192.168.1.$_ (Status: 0xC000006A)"
  }
  Write-EventLog @eventParams
}
PowerShell script to generate test events that trigger the detection.

Key Field Analysis

winlog.event_data.SubStatus

Failure reason codes (e.g., 0xC000006A = Wrong Password).

source.ip

Attacker's IP address for blocking.

Threshold & Tuning Guidance

Recommended Thresholds:

EnvironmentThresholdTime Window
Sensitive Servers3 attempts5m
Workstations10 attempts30m

MITRE ATT&CK Mapping

Credential Access (TA0006)

Brute Force (T1110)

Example:

Hydra or CrackMapExec attacks against SMB/RDP

Detection Tips:

Look for repeating patterns (e.g., 1 attempt every 2 seconds).

False Positives

  • Users forgetting passwords
  • Misconfigured service accounts
  • Automated system tests

Attack Simulation & Testing

Simulation Commands (Testable):

1. Manual RDP Brute Force

2. PowerShell Spray Attack

Incident Investigation Steps

SOC Analyst Playbook:

  1. Verify the alert:
  2. Identify the attacker:
    • Source IP (source.ip)
    • Target usernames (user.name)
  3. Check for successful logins:

Protection & Mitigation

  • Account Lockout Policy:
  • Block Attacker IPs:

Process Hollowing Detection (Windows) – Elastic EDR

CriticalRisk Score: 90T1055Process InjectionDefense Evasion

Overview

Detects the stealthy "Process Hollowing" technique where malware creates a legitimate process (e.g.,Β svchost.exe) in suspended state, then replaces its memory with malicious code.

Why it matters: Used by 68% of advanced malware (Carbon Black Threat Report) including Emotet, TrickBot, and state-sponsored APTs.

Use Cases

  • Malware evasion detection
  • APT defense
  • Incident response triage

Data Sources

Elastic EDR

Process creation/modification events with memory attributes

Sysmon Event ID 10

Process access events with detailed GrantedAccess rights

Prerequisites

  • Elastic Agent with EDR enabled
  • Sysmon configured with Event ID 10 (Process Access)
  • Process memory scanning enabled

Detection Objectives

  • Detect processes created in suspended state
  • Identify memory region modifications
  • Correlate with parent process anomalies

Step-by-Step Creation Guide

  1. In Kibana, go to Security β†’ Detection Rules
  2. Create a new Query rule
  3. Set index pattern to logs-endpoint.*
  4. Paste the EQL query below
  5. Set severity to Critical

Detection Logic

Elastic Detection Rule (Process Hollowing)YAML
id: process-hollowing-detection
name: "Suspicious Process Hollowing Detected"
description: "Detects process hollowing via suspended process creation + memory modification"
severity: "critical"
risk_score: 90
type: "query"
language: "eql"
index: ["logs-endpoint.*"]
query: |
  sequence by process.entity_id
    [process where event.type == "start" and process.Ext.state == "SUSPENDED"] 
    [process where event.type == "change" and 
     process.Ext.memory_region.operation == "WRITE" and 
     process.Ext.memory_region.protection == "EXECUTABLE_READWRITE"]
threshold:
  value: 1
  timeframe: "1m"
tags: ["MITRE T1055", "Defense Evasion", "Malware"]
references:
  - "https://www.elastic.co/guide/en/security/current/process-hollowing.html"
false_positives:
  - description: "Legitimate debugging tools"
    items: ["windbg.exe", "procmon.exe"]
actions:
  - group_by: ["host.name", "process.name"]
    throttle: "2h"
    slack:
      message: "Critical: Possible process hollowing on %{host.name}"
enabled: true
exceptions_list:
  - id: "debug-tools"
    namespace_type: "single"
EQL sequence rule detecting suspended process β†’ executable memory write within 1 minute.
EQL Query (Advanced Analysis)EQL
sequence by process.entity_id
  [process where 
    event.type == "start" and 
    process.name == "svchost.exe" and 
    process.Ext.state == "SUSPENDED" and
    process.parent.name != "services.exe"]
  [process where 
    event.type == "change" and 
    process.Ext.memory_region.size > 500000]
Targeted version focusing on svchost.exe with large memory writes.
Sysmon Config (Critical Events)XML
<Sysmon schemaversion="4.90">
  <EventFiltering>
    <RuleGroup name="Process Hollowing" groupRelation="or">
      <ProcessAccess onmatch="include">
        <TargetImage condition="contains">svchost.exe</TargetImage>
        <GrantedAccess condition="contains">0x1FFFFF</GrantedAccess>
      </ProcessAccess>
    </RuleGroup>
  </EventFiltering>
</Sysmon>
Sysmon rule to log detailed process access events.
Simulate Attack (Test Validation)POWERSHELL
# Mimic process hollowing (requires admin)
$bytes = [System.IO.File]::ReadAllBytes("C:\malware.bin")
$si = New-Object System.Diagnostics.ProcessStartInfo
$si.FileName = "C:\Windows\System32\svchost.exe"
$si.CreateNoWindow = $true
$si.Suspended = $true
$p = [System.Diagnostics.Process]::Start($si)

# Write malicious code to memory
[System.Runtime.InteropServices.Marshal]::Copy(
  $bytes, 0, 
  $p.MainModule.BaseAddress, 
  $bytes.Length
)

# Resume execution
$p.Resume()
PowerShell script simulating real process hollowing.

Key Field Analysis

process.Ext.state

Process creation state (SUSPENDED/RUNNING)

process.Ext.memory_region.protection

Memory protection flags (EXECUTABLE_READWRITE = highly suspicious)

Threshold & Tuning Guidance

Optimization Tips:

  • Exclude development/staging environments
  • Adjust memory region size threshold based on baseline
  • Combine with parent process anomalies for higher fidelity

MITRE ATT&CK Mapping

Defense Evasion (TA0005)

Process Injection (T1055)

Example:

Emotet injecting into svchost.exe

Detection Tips:

Look for mismatches between process name and memory characteristics.

False Positives

  • Legitimate debuggers (WinDbg, OllyDbg)
  • Anti-cheat software in gaming environments

Attack Simulation & Testing

Real-World Simulation:

1. C# Process Hollowing

Incident Investigation Steps

SOC Playbook:

  1. Verify the process:
  2. Check memory regions:

Protection & Mitigation

  • Enable ASLR:
  • Restrict debug privileges:

DNS Tunneling Data Exfiltration Detection – Elastic Network

HighRisk Score: 80ExfiltrationDNSC2T1048

Overview

Identifies suspicious DNS queries indicative of tunneling malware likeDNSCat2 or IODINE that bypass traditional security controls.

Why it matters: 32% of advanced attackers use DNS tunneling for C2 (Mandiant M-Trends 2023).

Use Cases

  • Data exfiltration attempts
  • Command-and-control (C2) channels
  • Covert malware communication

Data Sources

Packetbeat DNS Logs

DNS query/response data with full transaction details

Elastic Network Integration

Flow data for correlation with source processes

Prerequisites

  • Packetbeat configured with DNS module
  • Elastic Common Schema (ECS) DNS fields populated
  • Network traffic visibility to DNS servers

Detection Objectives

  • Detect unusually long DNS hostnames (&ls;50 chars)
  • Identify base64/hex encoded subdomains
  • Alert on high entropy DNS queries

Step-by-Step Creation Guide

  1. Navigate to Security β†’ Detection Rules in Kibana
  2. Create new Query rule with packetbeat-* index
  3. Paste the KQL query below
  4. Set severity to High and risk score to 80

Detection Logic

dns_tunneling_detection.yamlYAML
id: dns-tunneling-detection
name: "DNS Tunneling Exfiltration Attempt"
description: "Detects suspicious DNS queries indicative of data tunneling"
severity: "high"
risk_score: 80
type: "query"
index: ["packetbeat-*"]
query: |
  event.dataset: "dns" and 
  (dns.question.name.length > 50 or 
   dns.question.name: (/[A-Za-z0-9+\/=]{20,}/ or /[0-9a-f]{20,}/) or
   dns.question.registered_domain: ("dyndns.org", "no-ip.com"))
tags: ["Exfiltration", "C2", "MITRE T1048"]
references:
  - "https://www.elastic.co/guide/en/security/current/dns-tunneling-detection.html"
false_positives:
  - "Legitimate CDN subdomains"
  - "DNS-based load balancing"
actions:
  - slack:
      message: "Suspicious DNS tunneling attempt from %{source.ip}"
enabled: true
YAML rule detecting long/encoded DNS queries to known tunneling domains.
Kibana Investigation QueryKQL
event.dataset:dns and dns.question.size > 128
| stats 
    count() as query_count,
    dc(dns.question.name) as unique_domains,
    avg(dns.question.size) as avg_query_size
    by source.ip, dns.question.type
| where query_count > 20 or avg_query_size > 200
Identifies hosts making abnormally large/long DNS queries.
Packetbeat Config SnippetBASH
packetbeat.protocols:
- type: dns
  ports: [53]
  include_authorities: true
  include_additionals: true
processors:
- decode_hex_fields:
    fields: ["dns.question.name"]
    ignore_missing: true
Enhanced DNS monitoring configuration for tunneling detection.

Key Field Analysis

dns.question.name.length

Hostname length (malicious often <50 chars)

dns.question.registered_domain

Known tunneling domains (e.g., no-ip.com)

Threshold & Tuning Guidance

Environment-Specific Tuning:

  • Adjust length threshold based on your DNS baseline
  • Whitelist internal domains/CDNs in exceptions
  • Combine with threat intel feeds for known C2 domains

MITRE ATT&CK Mapping

Exfiltration (TA0010)

Exfiltration Over Alternative Protocol (T1048)

Example:

DNSCat2 exfiltrating data via TXT records

Detection Tips:

Look for sequential subdomains like data1.domain.com, data2.domain.com

False Positives

  • Dynamic DNS services for legitimate remote access
  • Cloudflare-encoded hostnames
  • Internal DNS load balancing

Attack Simulation & Testing

Simulation Commands:

1. Basic DNS Tunneling

2. DNSCat2 Simulation

Incident Investigation Steps

SOC Playbook:

  1. Verify the alert:
  2. Analyze query patterns:

Protection & Mitigation

  • DNS Filtering:
  • Enable DNS Logging:

Suspicious WMI Event Subscription Persistence – Elastic EDR

HighRisk Score: 80PersistenceWMIT1546.003

Overview

Detects malicious WMI Event Subscriptions used for persistence, commonly employed by attackers to maintain access to compromised systems.

Why it matters: WMI persistence is used in 42% of advanced intrusions (FireEye Mandiant 2023) due to its stealthiness.

Use Cases

  • Persistence mechanism detection
  • Lateral movement preparation
  • APT activity identification

Data Sources

Windows Event Log

Event ID 5861 (WMI Activity) and Event ID 20 (WMI Consumer)

Elastic EDR

Process creation events from WMI providers

Sysmon Event ID 19-22

WMI event subscription monitoring

Prerequisites

  • Windows Event Forwarding configured for WMI events
  • Sysmon installed with WMI event monitoring
  • Elastic Agent collecting WMI-related events

Detection Objectives

  • Identify malicious WMI event filters
  • Detect suspicious WMI consumer bindings
  • Alert on WMI-triggered process execution

Step-by-Step Creation Guide

  1. Navigate to Security β†’ Detection Rules in Kibana
  2. Create new Query rule with logs-windows.* index
  3. Paste the EQL query below
  4. Set severity to High and risk score to 80

Detection Logic

wmi_persistence_detection.yamlYAML
id: wmi-persistence-detection
name: "Suspicious WMI Event Subscription"
description: "Detects malicious WMI event subscriptions used for persistence"
severity: "high"
risk_score: 80
type: "eql"
index: ["logs-windows.*"]
query: |
  sequence by host.id
    [process where 
      process.name : "wmiprvse.exe" and 
      event.code : "5861" and 
      winlog.event_data.Operation : "Created"
    ]
    [process where 
      process.parent.name : "wmiprvse.exe" and
      not process.name : ("msiexec.exe", "legit_tool.exe")
    ]
tags: ["Persistence", "MITRE T1546.003"]
references:
  - "https://attack.mitre.org/techniques/T1546/003/"
false_positives:
  - "Legitimate management tools using WMI"
  - "Scheduled software deployments"
actions:
  - slack:
      message: "Suspicious WMI persistence activity on %{host.name}"
enabled: true
exceptions_list:
  - id: "approved-wmi-consumers"
    namespace_type: "single"
EQL sequence detecting WMI event creation followed by suspicious child process.
WMI Event AnalysisKQL
event.code:20 and 
winlog.event_data.ConsumerType:"ActiveScript" and
not winlog.event_data.ScriptingEngine:"VBscript"
Identifies suspicious script-based WMI consumers.
WMI Event Subscription CheckPOWERSHELL
# List all WMI event subscriptions
Get-WmiObject -Namespace rootsubscription -Class __EventFilter
Get-WmiObject -Namespace rootsubscription -Class __EventConsumer
Get-WmiObject -Namespace rootsubscription -Class __FilterToConsumerBinding
PowerShell commands to audit existing WMI subscriptions.

Key Field Analysis

winlog.event_data.Operation

WMI operation type (Created/Deleted/Modified)

winlog.event_data.ConsumerType

WMI consumer type (ActiveScript/CommandLine/etc)

Threshold & Tuning Guidance

Tuning Recommendations:

  • Whitelist known management tool WMI consumers
  • Adjust process name exclusions based on your environment
  • Combine with process ancestry analysis

MITRE ATT&CK Mapping

Persistence (TA0003)

Event Triggered Execution: WMI Event Subscription (T1546.003)

Example:

Creating WMI filter to execute payload on system startup

Detection Tips:

Monitor for WMI event subscriptions with script/command line consumers

False Positives

  • Legitimate system management tools
  • Enterprise software deployment systems
  • Monitoring solutions using WMI

Attack Simulation & Testing

Simulation Commands:

1. Basic WMI Persistence

Incident Investigation Steps

SOC Playbook:

  1. Verify WMI subscriptions:
  2. Analyze WMI events:

Protection & Mitigation

  • Restrict WMI permissions:
  • Enable WMI auditing:

Unauthorized Service Creation Detection – Elastic EDR

HighRisk Score: 75PersistenceT1543.003Windows Services

Overview

Identifies unauthorized Windows service creation, a common persistence and privilege escalation technique used by attackers and malware.

Why it matters: 58% of ransomware attacks use service creation for persistence (Sophos State of Ransomware 2023).

Use Cases

  • Malware persistence detection
  • Privilege escalation monitoring
  • Lateral movement preparation

Data Sources

Windows Security Logs

Event ID 4697 (Service Installed) and Event ID 7045 (Service Creation)

Sysmon Event ID 1

Process creation with service-related command lines

Elastic EDR

Service creation events and process lineage

Prerequisites

  • Windows auditing enabled for service changes
  • Sysmon configured with service creation monitoring
  • Elastic Agent collecting system/service events

Detection Objectives

  • Detect service installations from unusual processes
  • Identify services with suspicious binaries
  • Alert on services created in temporary directories

Step-by-Step Creation Guide

  1. Navigate to Security β†’ Detection Rules in Kibana
  2. Create new Query rule with logs-windows.* index
  3. Paste the EQL query below
  4. Set severity to High and risk score to 75

Detection Logic

service_creation_detection.yamlYAML
id: suspicious-service-creation
name: "Unauthorized Windows Service Creation"
description: "Detects suspicious service installations indicative of attacker activity"
severity: "high"
risk_score: 75
type: "eql"
index: ["logs-windows.*"]
query: |
  process where 
    (event.code : "4697" or winlog.event_id : "7045") and
    (process.name : ("sc.exe", "powershell.exe") or
     winlog.event_data.ImagePath : 
       ("*\Temp\*", "*\AppData\*", "*\Downloads\*")) and
    not winlog.event_data.ServiceName : ("TrustedInstaller", "WinDefend")
tags: ["Persistence", "Privilege Escalation", "MITRE T1543.003"]
references:
  - "https://attack.mitre.org/techniques/T1543/003/"
false_positives:
  - "Legitimate software installers"
  - "Enterprise deployment tools"
actions:
  - slack:
      message: "Suspicious service created on %{host.name}: %{winlog.event_data.ServiceName}"
enabled: true
exceptions_list:
  - id: "approved-installers"
    namespace_type: "single"
Detects service creation from suspicious locations or processes.
Service Creation AnalysisKQL
event.code:7045 and 
(winlog.event_data.ImagePath.keyword:/.*\Temp\.*/ OR 
 winlog.event_data.ImagePath.keyword:/.*\AppData\.*/)
| stats count() by host.name, user.name, winlog.event_data.ServiceName, winlog.event_data.ImagePath
Identifies services installed from temporary/user directories.
Service Audit CommandsPOWERSHELL
# List all services with their binaries
Get-WmiObject Win32_Service | Select-Object Name,DisplayName,PathName,StartMode,State

# Check service creation events
Get-WinEvent -FilterHashtable @{LogName='System';ID=7045} -MaxEvents 50 | Format-List
Commands to audit existing services and creation events.

Key Field Analysis

winlog.event_data.ImagePath

Service binary path (look for temp/user locations)

winlog.event_data.ServiceName

Service name (watch for masquerading as legit services)

Threshold & Tuning Guidance

Tuning Recommendations:

  • Whitelist paths used by approved software installers
  • Exclude known management/deployment tools
  • Combine with process ancestry analysis

MITRE ATT&CK Mapping

Persistence (TA0003)

Create or Modify System Process: Windows Service (T1543.003)

Example:

Creating new service pointing to malicious DLL

Detection Tips:

Monitor for services created from temporary directories or by unusual parent processes

False Positives

  • Legitimate software installers
  • Enterprise deployment systems
  • Patch management tools

Attack Simulation & Testing

Simulation Commands:

1. Basic Service Creation

2. Service DLL Hijacking

Incident Investigation Steps

SOC Playbook:

  1. Verify the service:
  2. Analyze service binary:

Protection & Mitigation

  • Service whitelisting:
  • Service auditing:

Malicious Scheduled Task Creation – Elastic EDR

HighRisk Score: 80PersistenceT1053.005Scheduled Tasks

Overview

Detects suspicious scheduled task creation used by attackers for persistence, privilege escalation, and lateral movement across Windows environments.

Why it matters: Scheduled tasks are abused in 61% of enterprise intrusions (IBM X-Force 2023) due to their stealth and reliability.

Use Cases

  • Persistence mechanism detection
  • Privilege escalation monitoring
  • Lateral movement tracking

Data Sources

Windows Event Log

Event ID 4698 (Scheduled Task Created) and Event ID 106 (Task Registered)

Sysmon Event ID 1

Process creation with schtasks.exe or Task Scheduler API calls

Elastic EDR

Task creation events and process lineage

Prerequisites

  • Windows Task Scheduler operational logging enabled
  • Sysmon configured with process creation monitoring
  • Elastic Agent collecting scheduled task events

Detection Objectives

  • Detect tasks created from unusual processes
  • Identify tasks with suspicious actions/triggers
  • Alert on tasks executing from temporary locations

Step-by-Step Creation Guide

  1. Navigate to Security β†’ Detection Rules in Kibana
  2. Create new Query rule with logs-windows.* index
  3. Paste the EQL query below
  4. Set severity to High and risk score to 80

Detection Logic

scheduled_task_detection.yamlYAML
id: suspicious-scheduled-task
name: "Malicious Scheduled Task Creation"
description: "Detects suspicious scheduled task creation indicative of attacker activity"
severity: "high"
risk_score: 80
type: "eql"
index: ["logs-windows.*"]
query: |
  sequence by host.id
    [process where 
      (process.name : "schtasks.exe" or 
       process.pe.original_file_name : "taskschd.dll") and
      process.args : ("/create", "/run", "/tn") and
      not process.parent.name : ("msiexec.exe", "trustedinstaller.exe")
    ]
    [process where 
      event.code : "4698" and
      (winlog.event_data.TaskName : "*\Microsoft\*" or
       winlog.event_data.Actions : ("*powershell*", "*cmd*", "*rundll32*"))
    ]
tags: ["Persistence", "Execution", "MITRE T1053.005"]
references:
  - "https://attack.mitre.org/techniques/T1053/005/"
false_positives:
  - "Legitimate software installers"
  - "Enterprise management tools"
actions:
  - slack:
      message: "Suspicious scheduled task created on %{host.name}: %{winlog.event_data.TaskName}"
enabled: true
exceptions_list:
  - id: "approved-automation"
    namespace_type: "single"
EQL sequence detecting task creation followed by suspicious task properties.
Task Creation AnalysisKQL
event.code:4698 and 
(winlog.event_data.Actions.keyword:/.*\.(exe|dll|ps1|vbs)/ OR 
 winlog.event_data.Trigger.keyword:/.*Logon.*/)
| stats count() by host.name, user.name, winlog.event_data.TaskName, winlog.event_data.Actions
Identifies tasks with executable actions or logon triggers.
Task Audit CommandsPOWERSHELL
# List all scheduled tasks
Get-ScheduledTask | Select-Object TaskName,State,Actions,Triggers

# Check task creation events
Get-WinEvent -FilterHashtable @{LogName='Security';ID=4698} -MaxEvents 20 | 
  Select-Object TimeCreated,Message
Commands to audit existing tasks and creation events.

Key Field Analysis

winlog.event_data.Actions

Task actions (watch for scripts/executables)

winlog.event_data.Trigger

Task triggers (logon/startup are suspicious)

Threshold & Tuning Guidance

Tuning Recommendations:

  • Whitelist paths used by approved automation tools
  • Exclude tasks created by management systems (SCCM, etc.)
  • Monitor tasks with SYSTEM-level privileges

MITRE ATT&CK Mapping

Execution (TA0002)

Scheduled Task/Job: Scheduled Task (T1053.005)

Example:

Creating task to execute payload on user logon

Detection Tips:

Monitor for tasks created from temporary directories or with unusual triggers

False Positives

  • Legitimate system maintenance tasks
  • Enterprise software deployment
  • Automated backup scripts

Attack Simulation & Testing

Simulation Commands:

1. Basic Task Creation

2. Hidden Task Creation

Incident Investigation Steps

SOC Playbook:

  1. Verify the task:
  2. Analyze task history:

Protection & Mitigation

  • Task whitelisting:
  • Enhanced auditing:

LSASS Memory Dumping Detection – Elastic EDR

CriticalRisk Score: 95T1003.001Credential AccessLSASS

Overview

Detects attempts to dump LSASS process memory, a primary technique for credential theft in enterprise environments.

Why it matters: 78% of ransomware attacks involve LSASS dumping to harvest credentials (CrowdStrike 2024 Threat Report).

Use Cases

  • Credential theft prevention
  • Post-exploitation activity detection
  • Privilege escalation monitoring

Data Sources

Windows Security Events

Event ID 10 (Process Access) and Event ID 4656 (Handle Request)

Sysmon Event ID 10

Detailed process access events with GrantedAccess rights

Elastic EDR

Process creation and memory access events

Prerequisites

  • Sysmon configured with LSASS access monitoring
  • Windows auditing enabled for process access events
  • LSASS protection enabled (RunAsPPL)

Detection Objectives

  • Detect process handle requests to LSASS
  • Identify memory dumping tools (Mimikatz, ProcDump)
  • Alert on suspicious access rights (PROCESS_VM_READ)

Step-by-Step Creation Guide

  1. Navigate to Security β†’ Detection Rules in Kibana
  2. Create new Query rule with logs-endpoint.* index
  3. Paste the EQL query below
  4. Set severity to Critical and risk score to 95

Detection Logic

lsass_dump_detection.yamlYAML
id: lsass-dumping-detection
name: "LSASS Memory Dumping Attempt"
description: "Detects attempts to access LSASS memory for credential theft"
severity: "critical"
risk_score: 95
type: "eql"
index: ["logs-endpoint.*","logs-windows.security-*"]
query: |
  any where 
    (event.code : "10" and 
     target.process.name : "lsass.exe" and 
     process.granted_access : ("0x1FFFFF", "0x1010", "0x1438")) or
    (process.name : ("procdump.exe", "mimikatz.exe") and 
     process.args : "lsass")
tags: ["Credential Access", "T1003.001", "LSASS"]
references:
  - "https://attack.mitre.org/techniques/T1003/001/"
false_positives:
  - "Legitimate debugging tools"
  - "Security products scanning memory"
actions:
  - slack:
      message: "Critical: LSASS access attempt by %{process.name} on %{host.name}"
enabled: true
exceptions_list:
  - id: "approved-debuggers"
    namespace_type: "single"
Detects both direct LSASS access and known dumping tools.
LSASS Access AnalysisKQL
event.code:10 and target.process.name:lsass.exe
| stats 
    count() as access_attempts,
    values(process.granted_access) as access_rights,
    values(user.name) as users
    by process.name, host.name
| where access_attempts > 3
Identifies processes repeatedly accessing LSASS.
Sysmon LSASS ProtectionXML
<Sysmon schemaversion="4.90">
  <EventFiltering>
    <RuleGroup name="LSASS Protection" groupRelation="or">
      <ProcessAccess onmatch="include">
        <TargetImage condition="contains">lsass.exe</TargetImage>
        <GrantedAccess condition="contains">0x1FFFFF</GrantedAccess>
      </ProcessAccess>
    </RuleGroup>
  </EventFiltering>
</Sysmon>
Enhanced Sysmon config for LSASS access monitoring.

Key Field Analysis

process.granted_access

Hex values indicating access rights (0x1FFFFF = full access)

target.process.name

Target process (should only be lsass.exe for this detection)

Threshold & Tuning Guidance

Tuning Recommendations:

  • Exclude approved security tools that scan memory
  • Adjust threshold based on baseline activity
  • Combine with process ancestry analysis

MITRE ATT&CK Mapping

Credential Access (TA0006)

OS Credential Dumping: LSASS Memory (T1003.001)

Example:

Mimikatz sekurlsa::logonpasswords module

Detection Tips:

Monitor for processes opening handles to LSASS with PROCESS_VM_READ rights

False Positives

  • Legitimate debuggers (WinDbg, Process Explorer)
  • EDR products performing memory scans
  • Backup software with process access

Attack Simulation & Testing

Simulation Commands:

1. Direct LSASS Dumping

2. LOLBin Technique

Incident Investigation Steps

SOC Playbook:

  1. Verify LSASS access:
  2. Analyze dumping process:

Protection & Mitigation

  • Enable LSASS Protection:
  • Restrict Debug Privileges:

Malicious PowerShell Execution Patterns – Elastic EDR & SIEM

HighRisk Score: 85T1059.001PowerShellObfuscation

Overview

Detects suspicious PowerShell activity including obfuscation, remote code execution, and credential theft techniques commonly used in cyberattacks.

Why it matters: PowerShell is abused in 73% of fileless malware attacks (CrowdStrike 2024) and 68% of ransomware deployments (Sophos 2024).

Use Cases

  • Fileless malware detection
  • Lateral movement monitoring
  • Credential theft prevention
  • Obfuscated command detection

Data Sources

Windows Event Logs

Event ID 4688 (Process Creation) and PowerShell Operational logs

Sysmon Event ID 1

Process creation with command line logging

Elastic EDR

Process execution and script block logging

Prerequisites

  • PowerShell Script Block Logging enabled (Group Policy)
  • Sysmon configured with command line logging
  • Elastic Agent collecting process creation events

Detection Objectives

  • Detect obfuscated PowerShell commands (-enc, -e)
  • Identify suspicious execution patterns (IEX, DownloadString)
  • Alert on Office macro-initiated PowerShell
  • Flag hidden execution attempts (-WindowStyle Hidden)

Step-by-Step Creation Guide

  1. Navigate to Security β†’ Detection Rules in Kibana
  2. Create new Query rule with logs-windows.* index
  3. Paste the KQL query below
  4. Set severity to High and risk score to 85
  5. Add exceptions for approved automation scripts

Detection Logic

powershell_detection.yamlYAML
id: suspicious-powershell-execution
name: "Malicious PowerShell Execution Patterns"
description: "Detects obfuscated, hidden, and malicious PowerShell activity"
severity: "high"
risk_score: 85
type: "query"
index: ["logs-windows.*", "logs-endpoint.*"]
query: |
  event.category: "process" and 
  (process.name: "powershell.exe" or process.pe.original_file_name: "powershell.exe") and
  (
    process.args: ("-nop", "-w hidden", "-enc", "-e", "Invoke-Expression") or
    process.args: ("IEX", "DownloadString", "WebClient") or
    process.args: ("-Command", "Start-Process", "bypass") or
    process.args: ("-ExecutionPolicy", "Unrestricted", "Hidden") or
    process.args: ("New-Object", "Net.WebClient") or
    process.args: ("-NonInteractive", "-NoLogo", "-NoProfile") or
    process.parent.name: ("winword.exe", "excel.exe", "outlook.exe") or
    process.args: ("FromBase64String", "Compress", "Expand") or
    process.args: ("-WindowStyle", "Hidden") or
    process.args: ("-EncodedCommand", "JABzAD0A")
  )
tags: ["Execution", "Obfuscation", "MITRE T1059.001"]
references:
  - "https://attack.mitre.org/techniques/T1059/001/"
false_positives:
  - "Legitimate automation scripts"
  - "System administration tools"
actions:
  - slack:
      message: "Suspicious PowerShell execution detected on %{host.name}: %{process.args}"
enabled: true
exceptions_list:
  - id: "approved-scripts"
    namespace_type: "single"
Comprehensive detection for malicious PowerShell patterns including obfuscation, remote code execution, and Office macro attacks.
PowerShell Investigation QueryKQL
event.dataset: "windows.powershell" and 
(event.code: "4104" or event.code: "4103") and
(message: "*Invoke-Expression*" or message: "*DownloadString*" or message: "*WebClient*")
| stats count() by host.name, user.name, process.args, message
| sort -count
Analyzes PowerShell Script Block logs for suspicious commands.
Enable PowerShell LoggingPOWERSHELL
# Enable PowerShell Script Block Logging (Group Policy)
New-Item -Path "HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -Force
Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -Name "EnableScriptBlockLogging" -Value 1

# Enable Module Logging
New-Item -Path "HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ModuleLogging" -Force
Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ModuleLogging" -Name "EnableModuleLogging" -Value 1
Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ModuleLogging" -Name "ModuleNames" -Value "*"
Configuration script to enable enhanced PowerShell logging.

Key Field Analysis

process.args

PowerShell command-line arguments (look for obfuscation flags)

process.parent.name

Parent process (Office apps indicate macro-based attacks)

Threshold & Tuning Guidance

Tuning Recommendations:

  • Whitelist paths used by approved automation tools
  • Adjust based on your organization's PowerShell usage
  • Combine with process ancestry analysis for higher fidelity

MITRE ATT&CK Mapping

Execution (TA0002)

Command and Scripting Interpreter: PowerShell (T1059.001)

Example:

Obfuscated PowerShell download cradle

Detection Tips:

Look for base64 encoded commands and suspicious parameter combinations

False Positives

  • Legitimate system administration scripts
  • DevOps automation tools
  • Security scanning utilities

Attack Simulation & Testing

Simulation Commands:

1. Obfuscated Download Cradle

2. Office Macro Payload

Incident Investigation Steps

SOC Playbook:

  1. Verify the activity:
  2. Analyze process tree:

Protection & Mitigation

  • PowerShell Constrained Language Mode:
  • Block Office Macros:

Ransomware Activity Detection – Elastic EDR & SIEM

CriticalRisk Score: 97T1486RansomwareData Encrypted for Impact

Overview

Detects ransomware behavior patterns including mass file encryption, suspicious process activity, and ransom note creation across Windows environments.

Why it matters: Ransomware attacks occur every 11 seconds (Cybersecurity Ventures 2024), with average damages exceeding $4.5 million per incident (IBM Cost of Data Breach Report 2024).

Use Cases

  • Early ransomware attack detection
  • Mass file modification monitoring
  • Ransom note creation alerts
  • Stopping encryption before critical damage

Data Sources

Windows File Audit Logs

Event ID 4663 (File access) and 4656 (Handle request)

Sysmon Event ID 11

File create operations with content modification

Elastic Endpoint Security

Real-time process/file monitoring and behavior analytics

Prerequisites

  • Windows File Server auditing enabled
  • Sysmon configured with file event monitoring
  • Elastic Agent deployed with filesystem integration
  • Process execution monitoring enabled

Detection Objectives

  • Detect rapid file modifications with specific extensions
  • Identify ransom note creation patterns
  • Alert on suspicious process-file interactions
  • Correlate encryption activity with network events

Step-by-Step Creation Guide

  1. Navigate to Security β†’ Detection Rules in Kibana
  2. Create new Threshold rule with logs-endpoint.* index
  3. Paste the EQL query below
  4. Set threshold to 100 files per 5 minutes
  5. Configure auto-containment actions for critical alerts

Detection Logic

ransomware_detection.yamlYAML
id: ransomware-activity-detection
name: "Ransomware Encryption Pattern Detected"
description: "Detects mass file modifications with ransomware patterns"
severity: "critical"
risk_score: 97
type: "threshold"
index: ["logs-endpoint.*", "logs-windows.file-*"]
query: |
  sequence by host.id, process.entity_id with maxspan=5m
    [file where 
      event.action: ("creation", "modification") and 
      file.extension: ("encrypted", "locked", "crypt", "locky", "zepto") and
      not file.path: ("*\Windows\*", "*\Program Files\*")]
    [process where 
      process.name: ("vssadmin.exe", "wbadmin.exe", "cmd.exe") and
      process.args: ("delete shadows", "resize shadowstorage")]
    [file where 
      file.name: ("README.txt", "HOW_TO_DECRYPT.html", "RESTORE_FILES.txt") and
      file.size < 10000]
threshold:
  field: "file.path"
  value: 100
  timeframe: "5m"
tags: ["Impact", "Ransomware", "MITRE T1486"]
references:
  - "https://attack.mitre.org/techniques/T1486/"
false_positives:
  - "Backup software operations"
  - "Legitimate encryption tools"
actions:
  - endpoint:
      operation: "isolate"
      comment: "Automatic containment for ransomware activity"
enabled: true
exceptions_list:
  - id: "approved-backup-software"
    namespace_type: "single"
Multi-stage detection combining file modifications, shadow copy deletion, and ransom note creation.
Ransomware Behavior SequenceEQL
sequence by host.id with maxspan=10m
  [process where 
    process.name: "powershell.exe" and 
    process.args: ("-enc", "Expand-Archive", "Compress-Archive")]
  [file where 
    event.action: "modification" and 
    file.extension: ("docx", "xlsx", "pdf", "jpg") and
    file.size > 0 and file.size < 100000]
  [network where 
    destination.ip: ("185.143.223.*", "45.9.148.*") and 
    destination.port: (443, 8080)]
Detects PowerShell-initiated encryption followed by C2 communication.
Ransom Note HuntingKQL
event.dataset: "windows.file" and 
(file.name: ("*DECRYPT*", "*READ_ME*", "*RESTORE*") or 
 file.contents: ("bitcoin", "payment", "decrypt", "key")) and
file.size < 15000
| stats count() by host.name, file.path, file.owner
Finds potential ransom notes based on naming patterns and content.
Enable File AuditingPOWERSHELL
# Enable detailed file auditing (Admin required)
$paths = "C:\Users", "C:\Shares", "D:\Data"
foreach ($path in $paths) {
    $acl = Get-Acl $path
    $rule = New-Object System.Security.AccessControl.FileSystemAuditRule(
        "Everyone", "Write,Delete", "ContainerInherit,ObjectInherit", "None", "Success,Failure"
    )
    $acl.AddAuditRule($rule)
    Set-Acl -Path $path -AclObject $acl
}

# Enable SACL for critical shares
auditpol /set /subcategory:"File System" /success:enable /failure:enable
Configuration script to enable detailed file auditing for detection.

Key Field Analysis

file.extension

Modified file extensions (watch for encryption patterns)

process.args

Command-line arguments (look for shadow copy deletion)

Threshold & Tuning Guidance

Environment-Specific Tuning:

EnvironmentFile ThresholdTime Window
File Servers50 files2 minutes
Workstations100 files5 minutes

MITRE ATT&CK Mapping

Impact (TA0040)

Data Encrypted for Impact (T1486)

Example:

Conti ransomware encrypting network shares

Detection Tips:

Monitor for rapid file extensions changes combined with shadow copy deletion

False Positives

  • Legitimate backup operations
  • File archiving utilities
  • Disk encryption software

Attack Simulation & Testing

Simulation Commands:

1. Basic Ransomware Simulation

2. Advanced Attack Chain

Incident Investigation Steps

SOC Playbook:

  1. Verify file modifications:
  2. Identify malicious process:

Protection & Mitigation

  • Implement FSRM Protection:
  • Enable Controlled Folder Access:

AI-Generated Phishing Campaign Detection – Elastic Mail Analytics

HighRisk Score: 88AIPhishingT1566.002Innovative

Overview

Detects AI-generated phishing emails by analyzing linguistic patterns, header anomalies, and behavioral signals in enterprise mail flows.

Why it matters: AI-powered phishing attacks have increased 1350% since ChatGPT's launch (Darktrace 2024), with 82% of successful breaches starting with AI-generated emails (Proofpoint 2024).

Use Cases

  • Next-gen phishing detection
  • AI-written content identification
  • Brand impersonation prevention
  • Emerging threat detection

Data Sources

Email Gateway Logs

SMTP headers and metadata from Exchange/O365

Elastic Mail Analytics

Natural language processing of email content

Threat Intelligence Feeds

Known AI phishing infrastructure indicators

Prerequisites

  • Mail server logs ingested into Elastic
  • ML NLP model deployed for text analysis
  • Email headers being parsed into ECS format

Detection Objectives

  • Detect linguistic patterns of LLM-generated text
  • Identify header inconsistencies in "From" fields
  • Flag suspicious temporal clustering of similar emails
  • Correlate with newly registered domains

Step-by-Step Creation Guide

  1. Navigate to Machine Learning β†’ Anomaly Detection
  2. Create new Population Analysis job
  3. Configure the ML features below
  4. Set alert threshold to 0.99 anomaly score
  5. Connect to pre-processing pipeline

Detection Logic

ai_phishing_detection.yamlYAML
id: ai-phishing-detection
name: "AI-Generated Phishing Campaign"
description: "Detects LLM-created phishing emails through linguistic and metadata analysis"
severity: "high"
risk_score: 88
type: "machine_learning"
index: ["logs-email-*"]
ml_config:
  job_id: "ai_phishing_detector_v3"
  features:
    - field: "email.subject"
      analysis: "linguistic_anomaly"
    - field: "email.headers.from"
      analysis: "domain_age"
    - field: "email.headers.received"
      analysis: "time_cluster"
    - field: "email.body.content"
      analysis: "llm_probability"
threshold:
  anomaly_score: 0.99
tags: ["Phishing", "AI", "MITRE T1566.002"]
references:
  - "https://attack.mitre.org/techniques/T1566/002/"
false_positives:
  - "Marketing automation tools"
  - "Legitimate AI-assisted support responses"
actions:
  - email:
      to: "soc@company.com"
      subject: "AI Phishing Campaign Detected"
      body: "Suspected AI-generated phishing campaign from %{email.headers.from}"
enabled: true
ML-powered detection combining linguistic analysis with header forensics.
Email Cluster AnalysisKQL
event.dataset: "email" and 
email.headers.from.domain: ("*.click", "*.xyz", "*.top") and
email.language.detected: "en" and
email.body.entropy > 6.5
| stats 
    count() as email_count,
    dc(email.headers.from) as unique_senders,
    avg(email.body.similarity) as avg_similarity
    by email.subject
| where email_count > 5 and avg_similarity > 0.85
Finds clusters of similar emails from suspicious domains.
LLM Detection Script (Custom Processor)PYTHON
from transformers import pipeline
import numpy as np

class LLMDetector:
    def __init__(self):
        self.classifier = pipeline("text-classification", 
                                model="roberta-base-openai-detector")
    
    def process_email(self, text):
        result = self.classifier(text[:1000])  # First 1000 chars
        return {
            "llm_score": result[0]['score'],
            "predicted_class": result[0]['label']
        }
Custom processor using HuggingFace's OpenAI detector model.
Sample Anomalous EmailJSON
{
  "email": {
    "headers": {
      "from": "support@microsoft-support.click",
      "received": ["2024-05-15T09:02:18Z", "2024-05-15T09:02:20Z"],
      "return-path": "bounce@mailer-0283.xyz"
    },
    "subject": "Urgent: Your Microsoft Account Requires Verification",
    "body": {
      "content": "Dear valued Microsoft customer,

Our systems have detected unusual activity...",
      "entropy": 7.2,
      "llm_score": 0.97
    },
    "attachments": [
      {"name": "Secure_Verification.html", "type": "text/html"}
    ]
  }
}
Example of an AI-generated phishing email with telltale signs.

Key Field Analysis

email.body.llm_score

Probability score (0-1) of AI generation

email.headers.received

Timing anomalies in email routing

Threshold & Tuning Guidance

Threshold Guidelines:

  • 0.85-0.90 for high-volume environments (catch more with higher FP rate)
  • 0.95+ for regulated industries (lower FP rate)
  • Adjust based on your legitimate AI email usage

MITRE ATT&CK Mapping

Initial Access (TA0001)

Phishing: Spearphishing Link (T1566.002)

Example:

AI-generated urgent account verification emails

Detection Tips:

Look for perfect grammar combined with newly registered domains

False Positives

  • Legitimate marketing automation
  • AI-powered customer support
  • Corporate communications tools

Attack Simulation & Testing

Simulation Example:

1. AI-Generated Phishing Email

Detection Signs:Perfect grammar + high entropy (7.1) + new domain (registered 3 days ago) + temporal clustering (52 similar emails in 5 minutes)

Incident Investigation Steps

SOC Playbook:

  1. Verify email artifacts:
  2. Analyze domain reputation:

Protection & Mitigation

  • Implement AI-Powered Email Filtering:
  • DMARC Enforcement:

Work with me

I would love to hear more about your project