---
name: EDR Evasion
slug: edr-evasion
category: Quality
description: EDR Evasion provides an offensive checklist for hook unhooking, direct syscalls, PPID spoofing, process injection, AMSI bypass, ETW patching, and memory encryption. Use it when planning EDR bypass during red team engagements or researching AV/EDR evasion techniques.
github: "https://github.com/SnailSploit/Claude-Red/tree/main/Skills/infrastructure/offensive-edr-evasion"
language: Python
stars: 2930
forks: 479
install: "npx degit https://github.com/SnailSploit/Claude-Red/tree/main/Skills/infrastructure/offensive-edr-evasion ~/.claude/skills/offensive-edr-evasion"
installs_to: ~/.claude/skills/offensive-edr-evasion
source_path: Skills/infrastructure/offensive-edr-evasion/SKILL.md
collection_size: 25
category_size: 1354
collection_url: "https://dirskills.com/collections/SnailSploit/Claude-Red"
added: 2026-08-17T07:09:57.066Z
last_synced: 2026-08-17T07:09:57.066Z
canonical_url: "https://dirskills.com/skills/edr-evasion"
---

# EDR Evasion

EDR Evasion provides an offensive checklist for hook unhooking, direct syscalls, PPID spoofing, process injection, AMSI bypass, ETW patching, and memory encryption. Use it when planning EDR bypass during red team engagements or researching AV/EDR evasion techniques.

**Install:**

```bash
npx degit https://github.com/SnailSploit/Claude-Red/tree/main/Skills/infrastructure/offensive-edr-evasion ~/.claude/skills/offensive-edr-evasion
```

## README

# SKILL: Endpoint Detection and Response

## Metadata
- **Skill Name**: edr-evasion
- **Folder**: offensive-edr-evasion
- **Source**: https://github.com/SnailSploit/offensive-checklist/blob/main/edr.md

## Description
EDR evasion offensive checklist: hook unhooking (user/kernel), direct syscalls, PPID spoofing, process injection variants, AMSI bypass, ETW patching, memory encryption, and behavior-based evasion. Use when planning EDR bypass during red team engagements or researching AV/EDR evasion techniques.

## Trigger Phrases
Use this skill when the conversation involves any of:
`EDR evasion, EDR bypass, hook unhooking, direct syscalls, PPID spoofing, process injection, AMSI bypass, ETW patch, memory encryption, AV evasion, behavioral evasion, red team evasion`

## Instructions for Claude

When this skill is active:
1. Load and apply the full methodology below as your operational checklist
2. Follow steps in order unless the user specifies otherwise
3. For each technique, consider applicability to the current target/context
4. Track which checklist items have been completed
5. Suggest next steps based on findings

---

## Full Methodology

# Endpoint Detection and Response

## Fundamentals

### AV vs EDR

**Antivirus (preventive approach)**:

- Static Analysis: Matching known signatures in files
- Dynamic Analysis: Limited behavioral monitoring/sandboxing
- Effective against known threats, weaker against advanced attacks

**EDR (proactive & investigative approach)**:

- Continuous endpoint monitoring
- Behavioral analysis at kernel level
- Anomaly detection and post-compromise visibility
- Prioritizes incident response and investigation

### Windows Execution Flow

Windows program execution follows a hierarchical flow:

1. **Applications** - User programs like firefox.exe
2. **DLLs** - Libraries providing Windows functionality without direct low-level access
3. **Kernel32.dll** - Core DLL for memory management, process/thread creation
4. **Ntdll.dll** - Lowest user-mode DLL that exposes the NT API interface to the kernel
5. **Kernel** - Core OS component with unrestricted hardware access

Example operation flow (creating a file):

1. Application invokes `CreateFile` function
2. CreateFile forwards to `NtCreateFile`
3. Ntdll.dll triggers `NtCreateFile` syscall
4. Kernel creates the file and returns a handle

## EDR Visibility

### EDR Architecture & Components

EDR solutions consist of multiple components creating a complex attack surface:

**Client-Side Components:**

- **User-space Applications** - Main agent processes and UI components
- **Kernel-space Drivers** - Filter drivers, network drivers, software drivers
- **Communication Interfaces** - IOCTLs, FilterConnectionPorts, ALPC, Named Pipes

**Component Communication Methods:**

- **Kernel-to-Kernel**: Exported functions, IOCTLs
- **User-to-Kernel**: IOCTLs, FilterConnectionPorts (minifilter-specific), ALPC
- **User-to-User**: ALPC, Named Pipes, Files, Registry

**Server-Side Components:**

- Cloud services and management consoles
- On-premise servers (some vendors)
- Custom protocols for agent-to-cloud communication

### EDR Visibility Methods

EDR solutions require extended visibility into system activities:

- Filesystem monitoring via mini-filter drivers
- Process/module loading via image load kernel callbacks
- Process/.NET modules/Registry/kernel object events via ETW Ti
- Network monitoring via NDIS and network filtering drivers

### Static Analysis

- Extract information from binary
  - Known malicious strings
  - Threat actor IP or domains
  - Malware binary hashes

### Dynamic Analysis

- Execute binary in a sandbox environment and observe it
  - Network connections
  - Registry changes
  - Memory access
  - File creation/deletion
- AntiMalware Scan Interface

### Behavioral Analysis

- Observe the binary as its executing, Hook into functions/syscalls
  - User actions
  - System calls
  - Kernel callbacks
  - Commands executed in the command line
  - Which process is executing the code
  - Event Tracing for Windows

## Detection Methods

### AV Signature Scanning

- Scans files using known signatures (YARA rules)
- Typically targets loaders and droppers
- Primarily static analysis of files on disk

### AV Emulation

- Runs suspicious programs in a simulated environment
- Triggers on behaviors without executing real code
- Used to detect obfuscated malware

### Usermode Hooks

- EDR hooks critical API calls in userspace (ntdll.dll)
- Monitors process creation, memory allocations, and network operations
- Allows for inspection before execution continues

### Kernel Telemetry

- Monitors events directly from the kernel
- Captures file, registry, process, and network operations
- Difficult to bypass as it operates at a lower level

### Memory Scanning

- Scans process memory for known signatures
- Triggers based on suspicious behavior
- Looks for shellcode, encryption, malicious strings
- **Modern Context:**
  - Attackers also scan process memory for sensitive artifacts like authentication tokens. Co‑pilot/IDE integrations, chat assistants, and browser extensions frequently cache Bearer/JWT tokens in memory.
  - Practical triage: search for `"Authorization: Bearer"`, `"eyJ"` (base64 JWT prefix), or provider‑specific headers; dump minimal pages to avoid tripping anti‑exfil rules.

## OpSec Quickstart (lab)

- Pre‑run
  - Network: block or sinkhole vendor EDR/XDR endpoints; disable cloud sample submission; tag lab hosts.
  - Mitigations snapshot: `Get-ProcessMitigation -System`; `Get-CimInstance Win32_DeviceGuard` (VBS/HVCI/KDP); `Get-MpPreference` (ASR/Cloud).
  - Events baseline: enable and tail `Microsoft-Windows-CodeIntegrity/Operational`, `Security (4688/4689)`, `Microsoft-Windows-Sense/Operational`, Sysmon (if present).
- Injection hygiene
  - Favor `MEM_IMAGE` mappings (ghosting/herpaderping/overwriting) over `MEM_PRIVATE` RWX to avoid 24H2 hotpatch loader checks.
  - Satisfy XFG/CET: jump via import thunks; ensure IBT `ENDBR64` at indirect targets; maintain plausible stacks for syscalls (replicate `ntdll` frames).
  - Avoid noisy APIs: split `alloc/write/exec` over time; prefer APC+`NtContinue` pivots; keep thread contexts consistent.
- Telemetry minimization
  - Jitter long‑lived channels; prefer named‑pipe/HTTP3 over noisy HTTP1; throttle upload intervals.
  - Use COM/runspace over PowerShell console to reduce script‑block logs; avoid AMSI‑flagged prologues.
- Cleanup
  - Remove services, tasks, drivers; restore SDDL; revert registry policy flips (WDAC/CI/Defender) and re‑enable protections.
  - Purge user caches (Recent Files, Jump Lists) and ETW providers enabled during tests.

### Memory Regions

- Monitors suspicious memory allocation patterns
- Flags RWX (read-write-execute) regions
- Tracks regions that change from RW to RX

### Callstack Analysis

- Examines the call stack of suspicious functions
- Verifies legitimate origin of critical operations
- Detects unusual function call chains

### Hook Implementation

EDRs can't directly hook kernel memory due to PatchGuard, so they:

1. Inject their DLL into newly spawned processes
2. Position before malware can block/unmap it
3. Adjust `_PEB`, hook process's module `IAT`/Imports, and loaded libraries `EAT`/Exports
4. Implement trampolines, hooks, and detours

### ETW Monitoring

- EDR maintains ring-buffer with per-process activities produced by ETW Ti:
  - Processes, command lines, parent-child relationships
  - File/Registry/Process open/write operations
  - Created threads, their call stacks, starting addresses
  - Native functions called
  - Created .NET AppDomains, loaded .NET assemblies, static class names, methods

#### Event Correlation

- High fidelity alert (such as LSASS open) triggers correlation of collected activities
- High memory/resources cost limits preservation of events to a time window
- ML/AI may compute risk scores and isolate TTP (Tactics, Techniques, and Procedures)

#### Shellcode Loaders

Shellcode loaders typically follow this pattern:

```c
char *shellcode = "\xAA\xBB...";
char *dest = VirtualAlloc(NULL, 0x1234, 0x3000, PAGE_READWRITE);
memcpy(dest, shellcode, 0x1234)
VirtualProtect(dest, 0x1234, PAGE_EXECUTE_READ, &result)
(*(void(*)())(dest))();  // jump to dest: execute shellcode
```

## Attacking EDR Infrastructure Directly

### Driver Attack Surface Analysis

A systematic approach to analyzing EDR drivers from a low-privileged user perspective:

#### 1. Driver Discovery

**Static Analysis:**

```powershell
# List loaded drivers
driverquery /v
Get-WindowsDriver -Online -All

# Using WMI
Get-WmiObject Win32_PnPSignedDriver | Select-String "EDR_Vendor"
```

**Dynamic Analysis:**

```powershell
# Using sc command
sc query type= driver state= all

# Process Monitor filtering
# Filter: Process and Thread Activity -> Show Image/DLL
```

#### 2. Interface Enumeration

**Device Driver Interfaces:**

- Listed in WinObj under "GLOBAL??" as Symbolic Links
- Accessible via `\\.\DEVICE_NAME` format
- Tools: WinObj (Sysinternals), DeviceTree (OSR - discontinued)

**Mini-Filter Driver Interfaces:**

- Listed in WinObj as "FilterConnectionPort" objects
- Communication via `FltCreateCommunicationPort` API
- Example paths: `\CyvrFsfd`, `\SophosPortName`

#### 3. Access Permission Analysis

**Device Driver ACL Checking:**

```cpp
// Using DeviceTree (preferred) or kernel debugger
// WinDbg example:
!object \Device\DeviceName
!sd <SecurityDescriptor_Address> 1
```

**FilterConnectionPort ACL Checking:**

```powershell
# Using NtObjectManager (James Forshaw)
Get-FilterConnectionPort -Path "\FilterPortName"
# Error indicates access denied

# In WinDbg:
!object \FilterPortName
dx (((nt!_OBJECT_HEADER*)0xAddress)->SecurityDescriptor & ~0xa)
!sd <SecurityDescriptor_Address> 1
```

#### 4. Interface Functionality Analysis

**Device Driver Communication:**

- Primary method: DeviceIoControl() → IRP_MJ_DEVICE_CONTROL
- IOCTL codes differentiate between functions
- May include process ID verification for authorization

**FilterConnectionPort Communication:**

- Uses callback functions: ConnectNotifyCallback, DisconnectNotifyCallback, MessageNotifyCallback
- Similar to IOCTL dispatch with different message types

#### 5. Common EDR Driver Interfaces

**Examples of accessible interfaces found in research:**

**Palo Alto Cortex XDR:**

- **Device Interfaces**:
  - `\\.\PaloEdrControlDevice` (tedrdrv.sys) - ~20 IOCTL handlers with various functionality
  - `\\.\CyvrMit` (cyvrmtgn.sys) - Legacy Cyvera interface
  - `\\.\PANWEdrPersistentDevice11343` (tedrpers-<version>.sys) - Persistent device interface
- **FilterConnectionPort**: Various ports with different ACLs
- **Research Findings**:
  - IOCTL 0x2260D8 returns 3088 bytes of statistics data (accessible to low-privileged users)
  - IOCTL 0x2260D0 provides initialization status information
  - Some interfaces accessible due to injected DLL architecture requiring broad permissions

**Sophos Intercept X:**

- **FilterConnectionPort**: `\SophosPortName`
- **Analysis Results**: Accessible interfaces for legitimate process communication but limited attack surface

#### 6. Why EDRs Have Open ACLs

EDRs often use an architecture where:

- Agent injects DLLs into processes (including low-privileged ones like `word.exe`)
- Injected DLLs communicate directly with drivers via IOCTLs
- Drivers cannot restrict based solely on process privilege level
- Results in more permissive ACLs to accommodate legitimate injected processes

## Evasion Techniques

### Memory-Based Evasion

#### EDR-Freeze

A novel technique exploiting Windows Error Reporting (WER) to temporarily disable EDR/AV processes:

##### Mechanism

- Leverages `WerFault.exe` and Windows Error Reporting infrastructure
- Suspends all threads in target EDR/AV processes indefinitely
- No kernel-mode access or driver exploitation required
- Operates entirely from user-mode context

##### Technical Implementation

- Trigger WER fault injection on target security process
- WER suspends all threads for crash dump generation
- Attacker maintains suspended state without completing crash handling
- Target process remains alive but non-functional

##### Advantages

- No elevation required in default WER configurations
- Avoids detection heuristics for process termination
- Temporary disabling without unloading kernel drivers
- Minimal forensic footprint compared to driver killing

##### Limitations

- Effectiveness varies by Windows version and WER configuration
- Some EDRs implement anti-suspension protections
- Temporary nature requires continuous re-application
- May generate WER event logs exposing the technique

> [!TIP]
> Blue team detection: Alert on `PssSuspendProcess` / `PssSuspendThread` API calls combined with `OpenProcess` targeting EDR process IDs, or monitor Event ID 1001 (Windows Error Reporting) with unusual source processes.

#### Memory Encryption

- Encrypts shellcode in memory when not in use
- Popular techniques:
  - SWAPPALA / SLE(A)PING
  - Thread Pool / Pool Party
  - Gargoyle
  - Ekko
  - Cronos
  - Foliage

#### Sleep Obfuscation

- ROP-Styles sleep obfuscations
  - [Ekko](https://github.com/Cracked5pider/Ekko)
  - [FOLIAGE](https://github.com/y11en/FOLIAGE)
  - these setup `_CONTEXT` in advance so that `EIP/RIP` points to native API
  - and then schedule APC with `NtContinue` to jump to that requested API

#### Secure Enclaves (VBS)

- Virtualization-Based Security (VBS) enclaves provide an isolated user-mode TEE that even kernel-mode sensors cannot inspect under normal conditions.
- Deprecation/support scope (Microsoft):
  - Windows 11 ≤ 23H2: VBS enclaves are deprecated; existing enclaves signed with the legacy EKU (OID `1.3.6.1.4.1.311.76.57.1.15`) continue to run until re-signed. New enclave signing requires updated EKUs and is not supported on these versions.
  - Windows 11 24H2+ and Windows Server 2025: VBS enclaves are supported with new EKUs.
- Security fix: CVE-2024-49076 (VBS Enclave EoP) — ensure December 2024+ updates are applied.
- Signing constraints: Only Microsoft-signed enclave DLLs or DLLs signed via Azure Trusted Signing load; test- or self-signed DLLs are rejected.
- Architecture summary:
  - Enclave host app (VTL0) invokes enclave APIs; enclave DLL executes in isolated user mode (VTL1) with restricted API surface; Secure Kernel validates integrity.
- Offensive considerations (lab): viable for secure storage of secrets/implants during sleep and for hiding sensitive code paths; limited by restricted API surface and signing requirements.
- Practical notes:
  - On unsupported SKUs/versions, enclave APIs may appear and return `STATUS_FEATURE_DEPRECATED`.
  - Prefer testing on Windows 11 24H2+/Server 2025 with proper signing.

#### Malware Virtualization

- Malware virtualization provides advanced evasion against modern EDR:
  - Embeds a custom virtual machine to execute bytecode instead of native code
  - Makes static and dynamic analysis difficult through instruction obfuscation
  - Prevents detection of instruction patterns and behavior prediction

- Implementation advantages:
  - Conceals malicious instructions from EDR monitoring
  - Protects against code patching attempts
  - Hinders behavioral analysis through custom execution model

- Multi-VM approach further evades detection:
  - Multiple VMs running concurrently disrupts heuristic pattern detection
  - Each VM creates distinct event patterns, confusing EDR correlation
  - "ETW noise" technique to blend with legitimate activity

- Deployment strategies:
  - Bytecode polling - periodically fetching new instructions from C2
  - Using transpilers to convert compiled binaries to custom bytecode
  - Applying polymorphic engine to mutate VM code itself

- Successfully evaded detection for:
  - Initial shellcode/bytecode execution (subsequent actions still monitored)
  - Specific AV/EDR patching routines (may require updates per product)
  - Initial C2 communication (ongoing traffic patterns may be detected)
  - Specific AD queries (patterns of queries can still be flagged)

### QEMU-Based Virtualization Evasion

- **Concept**: Deploy portable QEMU VMs to execute malicious code within guest OS, avoiding host-based EDR detection
- **Technical Implementation**:
  - Portable QEMU deployment via ZIP archives containing VM binaries and configurations
  - Tiny Core Linux as lightweight guest OS (minimal footprint ~50MB)
  - VBS scripts for automated VM deployment and execution
  - Custom hostname generation for VM identification and tracking

- **Configuration Examples**:

  ```vbs
  # VBS deployment script
  Set shell = CreateObject("WScript.Shell")
  shell.Run "tc.exe -m 512 -hda tc.qcow2 -netdev user,id=net0 -device e1000,netdev=net0"
  ```

  ```conf
  # QEMU configuration file (upd.conf)
  -m 512
  -hda tc.qcow2
  -netdev user,id=net0
  -device e1000,netdev=net0
  ```

- **Persistence Mechanisms**:
  - `bootlocal.sh` modifications for startup execution
  - `filetool.lst` configuration for file persistence across reboots
  - SSH service installation and configuration within guest VM
  - Reverse SSH tunnels over port 443 for C2 communication

- **Advanced Techniques**:
  - Anti-forensic SSH configuration (`StrictHostKeyChecking=no`, known hosts to `/dev/null`)
  - SSL/NoSSL tool deployment for encrypted communications
  - Randomized hostname generation to mask VM tracking
  - Port 443 tunneling to blend with HTTPS traffic

- **Detection Evasion Benefits**:
  - Guest VM operations invisible to host-based EDR sensors
  - VM network traffic appears as legitimate application activity
  - File operations contained within guest filesystem
  - Process execution isolated from host monitoring

- **Limitations & Considerations**:
  - Requires administrative privileges for some QEMU operations
  - VM resource consumption may be detectable
  - Network traffic patterns might still trigger detection
  - Initial VM deployment artifacts remain on host filesystem

### Hook Evasion

#### Unhooking

- malware overwrites EDR hooks before executing payload
- you can obtain original `ntdll.dll` from disk and overwrite it inside your own process
- or you can start the malware process in suspended state and copy the clean `ntdll.dll` from you own memory before executing
  - **Modern Context:** While historically effective, relying solely on replacing `ntdll.dll` or its hooked sections is less reliable. Modern EDRs often use kernel callbacks, ETW, and other telemetry sources that are not bypassed by user-mode unhooking alone. This technique is often used in conjunction with others.
    > [!CAUTION]
    > accessing `ntdll.dll` file can be flagged, API call to overwrite it also might be hooked by EDR

##### API Unhooking for AV Bypass

- Most EDR/AVs like BitDefender hook Windows APIs by replacing first bytes with `JMP` instructions (opcode `0xE9`)
- **Modern Context:** Similar to general unhooking, patching specific API prologues can bypass simple user-mode hooks, but comprehensive EDR solutions have additional detection layers (kernel events, behavioral analysis) that may still detect the malicious activity following the unhook.
- How to identify hooked APIs:
  - Create a test program that calls potentially hooked APIs
  - Examine first byte of API function using a debugger (like x64dbg)
  - If first byte is `0xE9`, the function is hooked
- Common hooked APIs:
  - `CreateRemoteThread`/`CreateRemoteThreadEx`
  - `VirtualAllocEx`
  - `WriteProcessMemory`
  - `OpenProcess`
  - `RtlCreateUserThread`
- Unhooking approach:
  1. Store original bytes of target APIs from clean system
  2. Identify hooked functions in memory
  3. Restore original bytes using `WriteProcessMemory` on the current process
  4. Execute malicious code using now-unhooked APIs
- Sample implementation:

  ```c
  // Find address of target API function
  HANDLE kernelbase_handle = GetModuleHandle("kernel32");
  LPVOID CreateRemoteThread_address = GetProcAddress(kernelbase_ha
