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:
Applications - User programs like firefox.exe
DLLs - Libraries providing Windows functionality without direct low-level access
Kernel32.dll - Core DLL for memory management, process/thread creation
Ntdll.dll - Lowest user-mode DLL that exposes the NT API interface to the kernel
Kernel - Core OS component with unrestricted hardware access
Example operation flow (creating a file):
Application invokes
CreateFilefunctionCreateFile forwards to
NtCreateFileNtdll.dll triggers
NtCreateFilesyscallKernel 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_IMAGEmappings (ghosting/herpaderping/overwriting) overMEM_PRIVATERWX to avoid 24H2 hotpatch loader checks.Satisfy XFG/CET: jump via import thunks; ensure IBT
ENDBR64at indirect targets; maintain plausible stacks for syscalls (replicatentdllframes).Avoid noisy APIs: split
alloc/write/execover time; prefer APC+NtContinuepivots; 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:
Inject their DLL into newly spawned processes
Position before malware can block/unmap it
Adjust
_PEB, hook process's moduleIAT/Imports, and loaded librariesEAT/ExportsImplement 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:
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:
Dynamic Analysis:
2. Interface Enumeration
Device Driver Interfaces:
Listed in WinObj under "GLOBAL??" as Symbolic Links
Accessible via
\\.\DEVICE_NAMEformatTools: WinObj (Sysinternals), DeviceTree (OSR - discontinued)
Mini-Filter Driver Interfaces:
Listed in WinObj as "FilterConnectionPort" objects
Communication via
FltCreateCommunicationPortAPIExample paths:
\CyvrFsfd,\SophosPortName
3. Access Permission Analysis
Device Driver ACL Checking:
FilterConnectionPort ACL Checking:
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-.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:
\SophosPortNameAnalysis 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.exeand Windows Error Reporting infrastructureSuspends 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/PssSuspendThreadAPI calls combined withOpenProcesstargeting 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
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:
Persistence Mechanisms:
bootlocal.shmodifications for startup executionfiletool.lstconfiguration for file persistence across rebootsSSH 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.dllfrom disk and overwrite it inside your own processor you can start the malware process in suspended state and copy the clean
ntdll.dllfrom you own memory before executingModern Context: While historically effective, relying solely on replacing
ntdll.dllor 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.dllfile 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
JMPinstructions (opcode0xE9)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/CreateRemoteThreadExVirtualAllocExWriteProcessMemoryOpenProcessRtlCreateUserThread
Unhooking approach:
Store original bytes of target APIs from clean system
Identify hooked functions in memory
Restore original bytes using
WriteProcessMemoryon the current processExecute malicious code using now-unhooked APIs
Sample implementation:
This technique is effective but may require separate execution for the final payload since some AVs block executing immediately after unhooking. Modern EDRs might still correlate the unhooking activity with subsequent suspicious actions.
Unhooking Tools
unhook BOF - module refreshing (less reliable now due to alternative EDR telemetry sources)
Unhookme - dynamic unhooking
Direct System Calls
malware circumvents hook in system DLL by directly system calling into kernel
you can implement own syscall in assembly and bypass
ntdll.dllhooksor obtain
SSN(System Service Number) dynamically and call them(can be done via SysWhispers2)Direct syscalls bypass user-mode hooks in
ntdll.dllbut do not inherently bypass kernel-level monitoring (e.g., via kernel callbacks or ETW). EDRs are increasingly monitoring for patterns indicative of direct syscall usage itself (e.g., unusual call stack origins for syscalls).[!CAUTION] having syscall assembly instructions can be flagged, also this only helps the loader to evade the EDR not the malware itself
Major EDR vendorsnow flag non?ntdll syscall sites; consider return?address replication gadgets to re?insert a plausible
ntdllframe before the transition.
[!CAUTION] Some EDRs flag syscalls originating outside
ntdll.dll. Maintaining plausible stacks/return frames may be required to avoid heuristics.
Direct Syscall Tools
Bypasses user-mode hooks but not kernel monitoring. Requires System Service Dispatch Table (SSDT) index:
FreshyCalls - sorting system call addresses
SysWhispers2 - modernized syscall resolution
SysWhispers3 - adds x86/Wow64 support
Runtime Function Table - reliable SSN computation
Indirect System Calls
malware uses code fragments in kernel DLL without calling the hooked functions in those DLL
prepare the system call in assembly then find a syscall instruction in
ntdll.dlland jump to that locationModern Context: Similar to direct syscalls, this bypasses user-mode hooks but not necessarily kernel-level monitoring. Finding and jumping to existing
syscallinstructions can be less suspicious than embedding raw syscall stubs, but the subsequent kernel activity is still visible.[!TIP] this is preferred,you can also boost evasion techniques by hiding inside a
.dll
Kernel?Mode EDR Killers (BYOVD)
Bring?Your?Own?Vulnerable?Driver (BYOVD) attacks load legitimately signed but exploitable drivers�examples include rtcore64.sys, iqvw64e.sys, and terminator.sys�to execute privileged code inside the kernel.
Typical payload actions
Patch or unregister kernel?mode notify callbacks (
PsSetCreateProcessNotifyRoutine,ObRegisterCallbacks) to blind user?mode EDR components.Overwrite or unload WdFilter.sys and other sensor drivers, fully disabling Defender or third?party agents.
Public toolchains such as Terminator, kdmapper, and EDRSensorDisabler automate these steps.
Case study: Lenovo
LnvMSRIO.sys(CVE?2025?8061). Exposes physical memory/MSR read?write primitives to low?privileged users; can overwrite MSR_LSTAR and pivot to Ring?0 payload, then patch/unregister callbacks to blind EDR.
[!TIP] The vulnerable?driver blocklist (
DriverSiPolicy.p7b) is enabled by default on Windows?11?22H2+ and refreshed every Patch Tuesday. Keep HVCI/KDP enabled so attacker drivers cannot patch protected code pages, and enable Hardware?Enforced Stack Protection (CET/Shadow?Stack) on Windows?11?24H2 to break call?stack spoofing.
[!NOTE] Because the blocklist is on by default and updated frequently, a BYOVD chain now often needs two vulnerable drivers: one to disable Secure?Boot or flip
CiOptions, and a second to perform the EDR?killer actions before the next blocklist refresh.
User-Mode Application Whitelisting Bypass
Exploiting Vulnerable Trusted Applications
Windows Defender Application Control (WDAC) and similar application whitelisting solutions can be bypassed by leveraging vulnerabilities in trusted, signed applications. A notable technique involves exploiting N-day vulnerabilities in the V8 JavaScript engine within Electron-based applications.
Concept (Bring Your Own Vulnerable Application - BYOVA):
A trusted, signed Electron application (e.g., an older version of VSCode) with a known V8 vulnerability is used as a carrier.
The application's
main.js(or equivalent) is replaced with a V8 exploit that executes a native shellcode payload.If the application is whitelisted, WDAC allows it to run, inadvertently executing the malicious shellcode.
Advantages:
Achieves native shellcode execution, overcoming limitations of pure JavaScript execution in some backdoored Electron app scenarios.
Shellcode runs in a browser-like process context, where behaviors like Read-Write-Execute (RWX) memory regions (due to JIT compilers) are common and may appear less suspicious to EDRs.
Exploit Development & Operationalization Challenges:
V8 Version Targeting: Electron's V8 often lags behind Chrome's and includes backported security patches. Vulnerabilities must be chosen that were patched after the target application's Electron version was frozen. Electron's cherry-picked patches should be reviewed.
Debugging: Building the specific V8 version (e.g., using
d8debug shell with--allow-natives-syntaxfor%DebugPrint()) is crucial for understanding memory layouts and adapting exploits.Offset Inconsistencies: Hardcoded offsets in public exploits (often Linux-based) need adjustment for the target V8 version and OS (Windows). Function pointer offsets for overwriting can even vary between Windows versions.
Solution for offset variation: Launch the exploit multiple times in child processes, each trying a different potential offset. The parent process monitors for success (e.g., mutex creation by payload).
Sandbox Escape: Public V8 exploits might use sandbox escape techniques already patched (cherry-picked) in the target Electron V8 version, requiring new or modified escapes.
JIT Compiler Interference (e.g., V8 TurboFan):
Optimizations can consolidate repeated instruction sequences (e.g., multiple floating-point values), affecting shellcode smuggling. Workarounds include compact shellcode or varying instruction positions.
Copying large shellcode payloads can be problematic. Workaround: multiple smaller copy loops or using a stager payload that fetches the main payload.
Payload Obfuscation: Obfuscate the JavaScript exploit (e.g., in
main.js) to hinder analysis. Re-obfuscating per deployment can help avoid signature-based detection.
Defense & Future Considerations:
Electron's experimental integrity fuse feature, if enabled by developers, can verify the integrity of application files (including
main.js) at runtime, potentially thwarting this technique by exiting if tampering is detected.Older application versions without this fuse remain vulnerable.
Process Manipulation
Early Cascade Injection
Novel process injection technique targeting user-mode process creation
Combines elements of Early Bird APC with EDR-Preloading
Avoids queuing cross-process APCs while maintaining minimal remote process interaction
Works by:
Targeting processes during the transition from kernel-mode to user-mode (
LdrInitializeThunk)Leveraging callback pointers (like
g_pfnSE_DllLoaded) during Windows process creationExecuting malicious code before EDR detection measures can initialize
Advantages:
Operates before EDRs can initialize their hooks and detection measures
Particularly effective against EDRs that hook
NtContinueor use delayed initializationAvoids ETW telemetry that traditional injection techniques trigger
Minimal remote process interaction reduces detection footprint
More stealthy than traditional techniques like DLL hijacking or direct syscalls
Key insight: EDRs typically load their detection measures after the
LdrInitializeThunkfunction executes, providing a window of opportunity for code execution before security measures initializewatch for early
NtCreateThreadExinsideLdrInitializeThunk
Early Startup Bypass
Concept: Execute malware before the EDR's user-mode component fully initializes, creating a window of opportunity for undetected execution.
Implementation:
Target the gap between kernel driver loading and user-mode agent initialization
Execute payload during system startup before EDR hooks are established
Leverage services that start before EDR components
Research Findings (Cortex XDR):
Successfully executed Mimikatz with
lsadump::samwithout detection during early startupEDR kernel drivers may be loaded but user-mode hooks not yet established
Timing window varies depending on system performance and EDR implementation
Detection Evasion:
Creates process activity before EDR monitoring is fully operational
Avoids user-mode hooks that haven't been established yet
Kernel-level monitoring may still detect activity depending on driver initialization order
Limitations:
Requires precise timing and understanding of EDR startup sequence
May not work against EDRs with early kernel-level monitoring
Window of opportunity may be brief on fast systems
Waiting Thread Hijacking (WTH)
A stealthier version of classic Thread Execution Hijacking
Intercepts the flow of a waiting thread and misuses it for executing malicious code
Avoids suspicious APIs like
SuspendThread/ResumeThreadandSetThreadContextthat trigger most alertsRequired handle access:
For target process:
PROCESS_VM_OPERATION,PROCESS_VM_READ,PROCESS_VM_WRITEFor target thread:
THREAD_GET_CONTEXT
Uses less monitored APIs:
NtQuerySystemInformation(withSystemProcessInformation)GetThreadContextReadProcessMemoryVirtualAllocExWriteProcessMemoryVirtualProtectEx
Implementation can be further obfuscated by splitting steps across multiple functions to evade behavioral signatures
Primarily bypasses EDRs that focus on detecting specific API calls rather than behavioral patterns
Effective against EDRs that are restrictive about remote execution methods but more lenient with allocations and writes
Suitable for hiding the point at which implanted code was executed
PPID Spoofing
Creates process with fake parent process ID
Hides true process creation chain
Makes process tree analysis misleading
Process Hiding
A technique to hide processes from EDR monitoring by manipulating the Interrupt Request Level (IRQL):
Raise the IRQL of current CPU core
Create and queue Deferred Procedure Calls (DPCs) to raise the IRQL of other cores
Perform sensitive task (for example, hiding process)
Signal DPCs in other cores to stop spinning and exit
Lower IRQL of current core back to original
This approach temporarily prevents EDR from monitoring the process during the critical operations by operating at an elevated privilege level.
[!NOTE] HVCI-enabled 23H2 kernels may crash when raising IRQL this way. Safer alternative: kernel-driver patching of
PsLookupProcessByProcessId.
UAC Bypass via Intel ShaderCache Directory
Concept: Exploits weak permissions (
Authenticated Users: Full Control) on theIntel\ShaderCachedirectory (%LOCALAPPDATA%\LocalLow\Intel\ShaderCache) combined with the behavior of auto-elevated processes (liketaskmgr.exe) writing to this location.Mechanism:
Clear Directory: Requires aggressively terminating processes holding handles (
explorer.exe,sihost.exe, etc.) and deleting files within theShaderCachedirectory. Permissions might need adjustment (icacls) to allow deletion. Launchingtaskmgr.exebriefly (with a timeout) helps identify recently written filenames and can trigger writes needed for the exploit.Junction Creation: Create a directory junction from
ShaderCacheto\??\GLOBALROOT\RPC CONTROL.Symbolic Link: Determine a recently used filename within
ShaderCache(before clearing). Create an object directory symbolic link (CreateDosDevice) fromGlobal\GLOBALROOT\RPC CONTROL\<recent_filename>to a target DLL path (e.g.,\??\C:\Windows\System32\oci.dll).Trigger Write: Launch an auto-elevated process (e.g.,
taskmgr.exe) that writes toShaderCache. The write operation follows the junction and then the symbolic link, resulting in the creation of a (dummy) target file (e.g.,oci.dll) in a privileged location (System32).Overwrite & Execute: Overwrite the created dummy file with the actual malicious DLL. Launch a process (like
comexp.msc) that attempts to load the target DLL, thereby executing the malicious code with elevated privileges.
EDR Relevance:
Bypasses User Account Control (UAC), a primary defense layer.
Relies on manipulating file system objects (junctions, symlinks) and process interactions that EDRs monitor.
Involves potentially noisy actions like mass process termination and permission changes.
The final payload execution often relies on DLL hijacking techniques.
[!TIP] Symlink/junction UAC races are build?dependent and brittle. Validate on the specific target build; many have partial or complete mitigations.
PPL (Protected Process Light) Bypass
Concept: Bypass Protected Process Light security by creating alternative service configurations that avoid PPL protections.
Palo Alto Cortex XDR PPL Bypass Technique:
How it works:
Creates a second service that launches the EDR's main process (cyserver.exe)
Original PPL-protected service fails to start due to startup dependencies
New service configuration is not protected by EDR drivers
EDR process runs without PPL protection, expanding attack surface
Limitations:
Service names beginning with "cyserver*" are blocked by some EDR implementations
EDR functionality may remain intact despite PPL bypass
Self-protection mechanisms may still be active at process level
Vendor response varies - may not be considered a security vulnerability
Detection & Response:
EDR thinks original service is stopped but agent continues running
Attack surface increases as process no longer has PPL protections
Reported to Palo Alto on 12.09.2023 with limited vendor response
Broader Implications:
Demonstrates service configuration vulnerabilities in EDR implementations
Shows potential for bypassing Windows security features through alternative execution paths
Relevant for other EDRs that rely on PPL for self-protection
Using NtCreateUserProcess for Stealthy Process Creation
The native API NtCreateUserProcess(), located in ntdll.dll, is the lowest-level user-mode function for creating processes. Calling it directly can bypass EDR hooks placed on higher-level functions like CreateProcessW in kernel32.dll. This makes it a valuable technique for stealthier process creation.
Key Concepts:
Bypass Mechanism: Avoids user-land hooks on more commonly monitored APIs like
CreateProcessW.Process Parameters: Requires careful setup of structures like
RTL_USER_PROCESS_PARAMETERS(often viaRtlCreateProcessParametersEx),PS_CREATE_INFO, andPS_ATTRIBUTE_LIST.RTL_USER_PROCESS_PARAMETERS: Defines process startup information, including image path, command line, environment variables, etc. TheImagePathNamemust be in NT path format (e.g.,\??\C:\Windows\System32\executable.exe).PS_ATTRIBUTE_LIST: Can specify attributes like the image name.
Flags:
ProcessFlagsandThreadFlagsallow fine-grained control over process and thread creation (e.g., creating suspended). Sources like Process Hacker's headers (ntpsapi.h) can provide valid flag definitions. For minimal use, these can sometimes beNULL.Implementation Details: Involves initializing several structures and using functions from
ntdll.dllsuch asRtlInitUnicodeString,RtlCreateProcessParametersEx, andRtlAllocateHeap. The article also mentions that theProcessParametersargument forNtCreateUserProcesswas found to be mandatory, andRtlCreateProcessParametersExis used with theRTL_USER_PROCESS_PARAMETERS_NORMALIZEDflag. ThePS_CREATE_INFOstructure needs itsSizeandState(e.g.,PsCreateInitialState) members initialized. ThePS_ATTRIBUTE_LISTis populated to include the image name.
Example High-Level Steps:
Define the path to the executable using
UNICODE_STRINGand initialize it withRtlInitUnicodeString(e.g.,L"\??\C:\Windows\System32\calc.exe").Create and populate
RTL_USER_PROCESS_PARAMETERSusingRtlCreateProcessParametersEx, providing the image path and normalizing parameters.Initialize a
PS_CREATE_INFOstructure.Allocate and initialize a
PS_ATTRIBUTE_LIST, setting thePS_ATTRIBUTE_IMAGE_NAMEattribute with the image path.Call
NtCreateUserProcesswith the prepared handles, access masks, and structures.Perform cleanup, for instance, by calling
RtlFreeHeapandRtlDestroyProcessParameters.
This technique allows for creating a new process with more direct control, potentially evading EDRs that primarily hook kernel32.dll API calls. However, EDRs with kernel telemetry or hooks deeper within ntdll.dll (or monitoring syscalls directly) might still detect the NtCreateUserProcess call or the subsequent behavior of the spawned process.
Advanced Process Execution Alternatives
TangledWinExec - alternative process execution techniques
rad9800 - indirectly loading DLL through a work item
Acquiring Process Handles
Without using suspicious
OpenProcess:Find
explorer.exewindow handle usingEnumWindowsConvert to process handle with
GetProcessHandleFromHwndLeverage
PROCESS_DUP_HANDLEto duplicate into a pseudo handle for Full Access
Callstack Manipulation
Return Address Overwrite
overwrite function's return address with 0
that terminates call stack's unwinding algorithm
examination based on
DbgHelp!StackWalk64fails
implement custom API resolver similar to
GetProcAddressbefore calling out to suspicious functions, overwrite
RetAddr :=0when system API returns, restore own
RetAddr
Callstack Spoofing
Manipulates the call stack to appear legitimate
Makes it harder to detect malicious code execution
Tools and techniques:
ThreadStackSpoofer
CallStackSpoofer
AceLdr
CallStackMasker
Unwinder
TitanLdr
uwd - Rust library for call stack spoofing with
#[no_std]supportOffers both
Synthetic(thread-like stack emulation) andDesync(JOP gadget-based stack misalignment) methodsProvides inline macros for spoofing functions and syscalls
Compatible with both MSVC and GNU toolchains on x86_64
Control Flow Manipulation
Control Flow Hijacking via Data Pointers
Concept: Overwrite function pointers located in readable/writable memory sections (e.g.,
.data) to hijack control flow when that pointer is called. A key benefit is potentially avoiding noisy API calls likeVirtualProtectExif the target pointer already resides in a writable section.Target: Often targets pointers within
KnownDlls(e.g.,ntdll.dll,combase.dll) as they load at predictable base addresses across processes, simplifying remote process injection and pointer discovery.Mechanism:
Identify a function pointer stored in a writable section (
.data). This can be done manually via disassembly or automatically by scripting searches for code patterns (e.g., findingtailcall(rax)instructions whereraxis loaded from.data).In a target process, allocate memory for shellcode (or a stub).
Write the shellcode/stub to the allocated memory.
Overwrite the original function pointer in the writable section to point to the shellcode/stub. This typically requires
PROCESS_VM_WRITEpermissions.Execution is diverted when the legitimate code path calls the hijacked function pointer.
Example: The blog post details hijacking
combase.dll!__guard_check_icall_fptr.Advantages:
Can avoid direct calls to commonly monitored APIs used in other injection techniques (like
CreateRemoteThread,QueueUserAPC).If the target pointer resides in memory that is already writable, it may avoid the need for
VirtualProtectEx, reducing noise.
Detection/Context: While this bypasses direct hooks on APIs like
VirtualProtectorCreateRemoteThread, EDRs may still detect the initialWriteProcessMemoryto the.datasection or correlate the unusual execution flow originating from a data segment via kernel callbacks or ETW.
Hookchain
Resolve System Service Number
Map critical functions
NtAllocateReserveObjectNtAllocateVirtualMemoryNtQueryInformationProcessNtProtectVirtualMemoryNtReadVritualMemoryNtWriteVirtualMemory
Create a relationship table with SSN + Custom stub function of critical
ntdll.dlland hooked functionsImplant IAT hook at all DLL subsystems that points to
ntdll.dllcritical and hooked functions(DLL pre-loading)Use Indirect system call + mapped critical functions and modification of IAT of key DLL functions before call to
ntdll.dllto bypass EDR
ETW and AMSI Evasion
ETW Patching
Patch Event Tracing for Windows functionality
Prevents telemetry from being sent to the EDR
Targets ETW provider registration or logging mechanisms
[!CAUTION] Defender engine?1.417? re?hooks common byte patches within ~50 ms. Prefer callback filtering (e.g., wrapping
EtwEventWriteFull) or the patch?less SharpBlock fork.
ETW Evasion Techniques
Significant delays among risky events:
alloc,write,exec- "Driploader" stylentdll!EtwEventWritepatchingDisabling tracing via
ntdll!EtwEventUnregister
AMSI Bypass/Patching
Bypasses Anti-Malware Scan Interface
Patches AMSI functionality in memory
Prevents script scanning before execution
Defender now ships dynamic signature VirTool:Win64/HBPAmsibyp.A that fires on known NOP?sled?prologues. A stealthier option is to swap to a COM?visible PowerShell runspace instead of patching
AmsiScanBuffer.
AMSI and ETW Evasion Implementation
AMSI (
amsi.dll!AmsiScanBuffer):Patch the function prologue
Alternatively, increment AMSI magic value deeper in code
ETW (
ntdll.dll!NtTraceEventandntdll.NtTraceControl):Use patchless strategy for evasion
Consider tools like SharpBlock
Modern AMSI Bypass Techniques
Classic AmsiScanBuffer patching (e.g., overwriting with ret or NOP sled) is now detected by Defender's VirTool:Win64/HBPAmsibyp.A signature and engine 1.425.x uses CFG/XFG checks to validate function integrity.
Patchless AMSI bypass (VEH / vtable)
VEH-based bypass: Register vectored exception handlers to set hardware breakpoints on
amsi.dll!AmsiScanBufferand re-route execution to a benign stub without byte-patching (a.k.a. VEH�). This avoids obvious prologue modifications.COM/vtable approach: Overwrite IAmsiStream vtable entries or CLSID pointers used during
AmsiInitializeso the provider cannot be created and AMSI calls short-circuit � again without alteringAmsiScanBufferbytes.Defender considerations: 2024�2025 engines re-hook common byte patches rapidly; patchless flows reduce simple signature hits but still leave behavioral traces.
Blue detections:
Monitor
AddVectoredExceptionHandlerusage paired with debug register changes (CONTEXT.Dr0�Dr7) shortly before AMSI invocations.Hunt for unusual call stacks entering
AmsiScanBufferthat immediately return, and COM activation failures around AMSI provider creation.ETW/PowerShell: alert on script engines loading
amsi.dllfollowed by VEH registration and memory permission flips.
1. COM VTable Hooking Method
Instead of patching AmsiScanBuffer, hook the IAmsiStream COM interface:
2. ETW Provider Registration Manipulation
Modify ETW provider registration to disable telemetry without patching:
3. AMSI Context Manipulation
Forge the AMSI context session to bypass scanning:
4. PowerShell Runspace Alternative (Patchless)
Use a COM-visible PowerShell runspace that bypasses AMSI entirely:
5. Memory-Only AMSI Bypass (No Disk)
Load a minimal AMSI bypass directly in memory without patching:
Detection Evasion Notes:
COM VTable Method: Bypasses signature-based detection; harder to detect than direct patching
ETW Provider Manipulation: Requires admin privileges but cleaner than hooking
Context Corruption: Minimal memory writes; low detection surface
Runspace Method: No patching required; entirely legitimate PowerShell usage
Reflection Method: PowerShell-only; works in constrained language mode bypass scenarios
Blue Team Detection:
Monitor for:
Unusual COM interface access patterns to
amsi.dllETW provider manipulation via
ControlTraceAPIPowerShell runspace creation with
FullLanguagemode in restricted environmentsReflection access to
System.Management.Automationinternal structures
Platform Realities & Defender Hunts
Windows 11
24H2+ Security Baseline
Hardware?Enforced Stack Protection (CET/Shadow Stack) breaks na�ve call?stack spoofing; evasions must maintain valid shadow stacks.
LSASS protection (RunAsPPL) is on by default on recent fresh installs; expect minidump blockers. Favor live?off?land telemetry for detection/response.
HVCI/KDP/Secure Launch raise the bar on BYOVD and protected pages. Hunt for policy flips and failed driver loads.
Quarterly Vulnerable Driver Blocklist
DriverSiPolicy.p7benabled by default on Windows 11 22H2+Automatic updates every Patch Tuesday via Windows Update
Blocks known vulnerable drivers before they can load
BYOVD attacks now often require two-stage driver chains
Monitor for policy tampering:
HKLM\SYSTEM\CurrentControlSet\Control\CI\Policy
Kernel Data Protection (KDP)
Protects critical kernel structures and EDR code pages
Makes them read-only even to kernel-mode drivers
Requires HVCI to be enabled
Significantly raises bar for kernel-mode EDR killers
Verify status:
Get-ComputerInfo | Select CsDeviceGuardSecurityServicesRunning
Confidential Computing Support
Intel TDX (Trust Domain Extensions) for VM-level isolation
AMD SEV-SNP (Secure Encrypted Virtualization) support
Protects guest VMs from hypervisor inspection
EDR visibility limited in confidential VMs
Requires specialized attestation and monitoring approaches
macOS
Use EndpointSecurity (ES) events with unified logs; monitor
syspolicydGatekeeper verdicts and TCC changes.macOS Sequoia (15) enhances XProtect and Background Task Management
Notarization requirements increasingly strict for all distributed software
Linux/Kubernetes
Hunt eBPF program/map churn and sensor detaches; sidecars outside node?agent PID filters; attempts to access runtime sockets.
eBPF-based EDR becoming standard (Falco, Tetragon, Cilium)
Container runtime security monitoring essential
Service mesh observability integration (Istio, Linkerd)
Network-Based EDR Silencing
These techniques focus on disrupting the EDR agent's communication with its management servers, effectively blinding it without directly tampering with the agent process itself.
Sinkholing by Secondary IP Addresses
Concept: Assign secondary IP addresses to local network interfaces that match the IP addresses of the EDR's communication endpoints (C2 servers, telemetry collectors).
Mechanism: When the EDR agent attempts to connect to its server IP, the network stack routes the traffic to the local interface instead, effectively dropping the connection.
Implementation:
Identify EDR communication IPs (e.g., using network monitoring).
Manually assign IPs via Network Adapter Properties > IPv4 > Advanced > IP Settings (requires static IP configuration, not DHCP).
Use PowerShell:
New-NetIPAddress -InterfaceAlias "Ethernet" -IPAddress <EDR_IP> -PrefixLength 32Use
netsh:netsh interface ipv4 add address "Ethernet" <EDR_IP> 255.255.255.255Scripting: Tools like
IPMutecan monitor process network connections and dynamically add remote IPs as secondary local IPs.
Persistence/Detection:
Static IP settings are stored in
HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\{GUID}\IPAddress.Changes made via PowerShell/GUI/netsh modify the registry via
wmiprvse.exe/DllHost.exe/netsh.exerespectively.A device configuration profile that sets
VpnTrafficFilterListwill override any locally created IPsec rules.Direct registry edits require an interface disable/enable cycle to take effect.
[!CAUTION] Some EDR/XDR products flag sudden
/32self?IP assignments (host routes) created withNew?NetIPAddressas potential IP spoofing. Expect alerts on repeated adds/removes or tight timing around agent network failures. Prefer/31pairs or upstream firewall/DNAT approaches where possible.
IPSec Filter Rules
Concept: Leverage Windows IPsec policies to create rules that block traffic to specific EDR IPs, IP ranges, or even domains, even without a full IPsec deployment.
Mechanism: IPsec rules operate at a low level and can filter traffic based on source/destination addresses and protocols. Rules can block specific connections required by the EDR.
Implementation (using
netsh):Persistence/Detection:
IPsec policy configuration is stored in the registry under
HKLM\Software\Policies\Microsoft\Windows\IPSec\Policy\Local\.Rule creation via
netshwrites registry values vianetsh.exe. GUI edits usemmc.exe.These registry keys can be monitored or potentially protected.
Cleanup:
DNS Sinkholing
Hosts File Modification
Concept: Add entries to the system's
hostsfile (C:\Windows\System32\drivers\etc\hosts) mapping EDR domain names to127.0.0.1or0.0.0.0.Mechanism: When the EDR agent performs a DNS lookup for its server, the
hostsfile takes precedence, resolving the domain to localhost and preventing the actual connection.Limitations:
Does not affect existing established connections.
DNS resolutions might be cached within the EDR process itself.
Requires clearing DNS cache (
ipconfig /flushdns) and potentially waiting or restarting the EDR process/system.Ineffective if the EDR uses hardcoded IP addresses.
Changing DNS Servers
Concept: Modify the system's DNS server settings to point to an attacker-controlled DNS server or a public DNS filtering service (like OpenDNS) configured to block EDR domains.
Mechanism: All DNS lookups from the system (including the EDR) are routed through the malicious/filtering DNS server, which returns incorrect or blocked responses for EDR domains.
Limitations:
Same caching issues as hosts file modification apply.
Requires administrative privileges to change system-wide DNS settings.
Easily detectable if network settings are monitored.
Agent Tampering & Tamper?Protection Bypasses
Microsoft?Defender's Tamper Protection (and similar vendor self?protection) can be disabled by
Launching a TrustedInstaller?child process and modifying service registry keys (e.g.,
sc config Sense start= disabled).Changing ACLs on
WdFilterorSenseIRregistry values, then rebooting so the filter driver never loads.
Many commercial EDRs expose self?protection flags via WMI namespaces; clearing the flag allows the agent service to be stopped or deleted.
Detection guidance: alert on writes to antivirus/EDR service parameters or attempted driver unloads while the service is running.
Cloud?Side XDR Telemetry Throttling & Poisoning
Local evasion is incomplete: vendors replay queued events when connectivity returns.
Attackers therefore:
Throttle upload intervals (e.g.,
SenseUploadFrequency) to several hours.Inject thousands of benign events (mass process creations) to drown anomaly?detection models (�telemetry poisoning�).
Blue teams should monitor for sudden policy flips or extreme event?volume spikes with low entropy.
Scanning Engine DoS Attacks
A technique to disable EDRs by exploiting memory corruption vulnerabilities in their file scanning engines, particularly effective against Microsoft Defender.
Concept:
Trigger memory corruption bugs in EDR scanning engines
Crashes the main EDR process when malicious files are scanned
Can be deployed alongside initial access payloads or before credential dumping
Microsoft Defender Targeting (mpengine.dll):
File-based DoS Vectors:
Delivery Methods:
Email attachment delivery:
Attack Sequence for Initial Access:
Deliver crash file alongside main payload
Crash file triggers when Defender scans downloads folder
Main EDR process (MsMpEng.exe) crashes and restarts
Execute main payload during restart window
Subsequent malicious activity may go undetected
Attack Sequence for Internal Movement:
Upload crash file to network share before credential dumping
Wait for Defender to scan and crash
Execute credential dumping tools (Mimikatz, etc.)
EDR restart may not catch the dumping activity
Limitations:
Requires specific file format knowledge
Some crashes only occur with PageHeap enabled
Microsoft may quietly patch vulnerabilities
Defender restarts automatically, limiting window
Other EDR vendors may have different scanning engines
Defensive Considerations:
Monitor for unexpected MsMpEng.exe crashes
Implement scanning engine crash alerting
Consider sandboxing file scanning processes
Deploy additional EDR solutions for redundancy
EDR-Specific Driver Interface Abuse
ALPC Communication Attacks
Advanced Local Procedure Call (ALPC) is commonly used for EDR inter-process communication and presents a significant attack surface:
Windows ALPC Technical Background
ALPC Overview:
Windows Advanced (or Asynchronous) Local Procedure Call is an IPC mechanism for same-host communication
Undocumented by Microsoft - developers intended to use official libraries like RPCRT4.dll
Fast and efficient mechanism heavily used within Windows OS
Commonly implemented as Windows RPC "ncalrpc" transport
ALPC Port Registration:
Key ALPC Characteristics:
Port Naming: If port name is NULL, random name like
LRPC-71dcaff45b0f633aadis assignedAccess Control: Ports can be restricted using Security Descriptors
Endpoint Mapper: Most EDR ports are NOT registered at RPC Endpoint Mapper
Visibility: ProcessHacker/SystemInformer displays all ports in Handles tab; WinObj shows them under
\RPC Control\Client Connection: Clients connect using port name or interface UUID (if registered)
ALPC Vulnerability Categories:
Weak Access Control: Missing restrictions leading to unauthorized access
Memory Corruption: Bugs in function parameter handling
Impersonation Issues: Though usefulness in realistic scenarios unclear
DoS via Blocking: The vulnerability class discovered in this research (previously undiscussed publicly)
Namespace Object Exploitation
Object Manager Namespace Attacks:
Exploit how EDRs handle preexisting objects in the Object Manager's namespace
Can cause permanent agent crashes/stops for low-privileged users
Part of the broader ALPC blocking vulnerability class affecting multiple EDR vendors
Technical Background:
Windows Object Manager maintains a hierarchical namespace for kernel objects
Objects include mutexes, events, semaphores, ALPC ports, and named pipes
EDRs often use predictable object names for inter-process communication
Poor error handling when objects already exist leads to initialization failures
Exploitation Techniques:
ALPC Port Pre-registration:
Mutex/Event Object Blocking:
Named Pipe Blocking:
Persistence via Scheduled Tasks:
Additional Evasion Techniques
Telemetry Complexity Attacks (TCAs)
A novel evasion technique that exploits mismatches between EDR data collection and processing capabilities:
Attack Mechanism
Generates deeply nested and oversized telemetry data structures
Exploits bounded processing capabilities vs unbounded data collection
Stresses serialization and storage boundaries in EDR pipelines
Causes denial-of-analysis without requiring privileges or sensor tampering
Impact
Truncated or missing behavioral reports in EDR consoles
Rejected database inserts due to size/complexity limits
Unresponsive dashboards from query timeouts
Silent failures in telemetry correlation engines
Technical Details
Targets JSON/XML serialization depth limits
Overflows event buffer ring structures
Exploits database column size constraints
Triggers timeout conditions in real-time analysis
Azure/Entra Device Attribute Manipulation
Concept: Modify device attributes via dsreg.dll to potentially impact device identification or monitoring
Mechanism: Uses Windows
dsregcmd /updateDeviceinternally or direct API calls to modify device propertiesLogging implications:
displayNamechanges generate Azure audit logs (initiator: "Device Registration Service")hostnameschanges do not generate Azure audit logs at allBoth operations update local registry at
HKLM\SYSTEM\CurrentControlSet\Control\CloudDomainJoin\JoinInfo\{ID}\
Implementation via API requires device certificate authentication
Limited attack surface but demonstrates interesting logging blind spots for cloud-managed devices
Conditional Access Evasion
Conditional?Access policies hinge on properties like
trustType,deviceComplianceState, and risk level.Attackers possessing the device certificate can invoke
DsregSetDeviceProperty()to flip these flags, then rundsregcmd /refreshprereqsto push altered attributes to Entra?ID.Impact: stolen or cached tokens appear compliant, bypassing MFA or device?based restrictions until the next compliance refresh.
Note: "No detection" of the initial execution or implant drop doesn't guarantee that no alerts are generated for the blue team based on telemetry or subsequent actions.
String Obfuscation
Use strings obfuscation libraries to make static analysis more difficult:
Golang - Garble
Rust - obfstr
Nim - NimProtect
PE Attribute Cloning & Code Signing for Evasion
Cloning: Modifying an implant's PE attributes (icon, version info, name, etc.) to match a legitimate, commonly found binary on the target system can aid evasion.
Cloning an unsigned legitimate binary (like
at.exe) and leaving the implant unsigned might bypass checks more effectively than cloning a signed binary (likeRuntimeBroker.exe) and signing the implant with a spoofed certificate, especially if the defender verifies signatures for known system files.
Code Signing (Spoofed): Signing an implant, even with an invalid or spoofed certificate (e.g., mimicking a legitimate entity), can sometimes reduce detection rates. Some AV/EDR solutions may not rigorously validate the certificate chain.
Timestamping Server: The specific Time Stamp Authority (TSA) server used during the signing process can unexpectedly influence detection outcomes by different AV/EDR products.
Testing: Effectiveness heavily depends on the specific EDR/AV and target environment configuration. Always test locally.
Entropy, File Pumping, Bloating
Entropy measures how random data appears:
Lower entropy indicates less randomness
Higher entropy might flag as packed/compressed/anomalous
Techniques to manipulate entropy:
Add long strings of random English words
Keep implant small but insert many English words (file bloating)
Bloat the file significantly so AV/EDR won't bother scanning
Time-Delayed Execution
Allows execution to time-out emulation sweeps
Slow down each step of malware execution:
alloc => chunk1 write ... chunkN write => executeGeneral Suggestions
use
SORTED-RVAstrategyFreshyCallsRuntime Function Table
don't rely on fresh
NTDLL.DLLparsing, don't load one from process/memorydon't used direct syscalls that extract syscall
Emulator Evasion
Environmental keying - check username, domain, specific UNC/SMB path, registry value
IP geolocation - call out to services like
http://ip-api.com/jsonto verify locationVerify expected process/filename - sandboxes often rename samples to
<HASH>.exeVerify expected parent process - useful for DLL side-loading scenarios where sandboxes run DLLs via
rundll32Check for physical display devices
Controlled Decryption
Carefully inspect environment before decompressing and decrypting shellcode
For zero knowledge about environment, pull decryption keys from internet/DNS
Fooling Import Hash (ImpHash)
Create unreachable code paths in native loader
In that unreachable code, call Windows APIs with dummy parameters
Compile the code
Locate those APIs in the executable's import address table
Overwrite imported function names in PE headers with random other names from the same DLL
Command Line Spoofing
Modifies command line arguments in process memory
Hides actual parameters from EDR telemetry
Makes detection based on command line difficult
Killing Bit Technique
Detection Signatures are being implemented on
Syscall Hashes
Assembly stub bytes
Hashing routines/functions
Evasion
Implement your own or modify existing direct syscalls harness
After hashing algorithm change
KEY/BitShift/ROL/arithmaticis enough to refresh hashesInsert junk instructions into assembly stubs so naive static signatures won't match any longer
use Indirect Syscalls, find
SYSCALLinstruction somewhere inntdll.dlland jump there
General Suggestions
use
SORTED-RVAstrategyFreshyCallsRuntime Function Table
don't rely on fresh
NTDLL.DLLparsing, don't load one from process/memorydon't used direct syscalls that extract syscall
DripLoader Technique
Implementation available at github.com/xuanxuan0/DripLoader
Technique details:
Reserve 64KB chunks with
NO_ACCESSprotectionAllocate chunks with
Read+Writepermissions in that reserved pool (4KB each)Write shellcode in chunks using randomized order
Change protection to
Read+ExecOverwrite prologue of
ntdll!RtlpWow64CtxFromAmd64withJMPtrampoline to shellcodeUse direct syscalls for memory operations and thread creation
Reminder on Post-Exploitation: Successful initial execution (e.g., implant download/run) doesn't guarantee stealth for subsequent actions. EDR can still detect malicious behavior later (e.g., Meterpreter activity). In-memory evasion techniques remain critical.
General Evasion Strategy
using a less known C&C tool with indirect system calls and the help of
.dllis recommendedyou should avoid the built-in
execute assemblyoption of C&C tools, use community extensions instead (beacon object file or inline execute assembly)for example Certify and SharpHound
sample EDR bypass
user downloads a zip that contains
.lnkfile(modern browsers refuse to download a link file directly).lnkexecutesmshta.exewith the malware location as argument(to bypass AppLocker)mshta.exedownloads and executes a.htamalicious file from our serverdue to
.dllhijacking, our payload executes every time Microsoft Teams is openedEDR doesn't detect infection
EDR Evasion Strategy for Persistence
Complete EDR evasion is challenging. Consider these strategies:
Instead of evading detection entirely, focus on persistence
Aim for delayed & extended execution (dechain file write & exec events)
Use VBA/WSH to drop DLL/XLL:
COM hijacking
DLL side-loading/hijacking
XLL, XLAM, WLL persistence
Drop
VbaProject.OTM*to backdoor Outlook (particularly effective against CrowdStrike)Drop CPL (
%APPDATA%\Microsoft\Outlook\VbaProject.OTM)
Hide Services:
Use Security Descriptor Definition Language (SDDL) strings to modify service permissions, making them harder to detect or query by standard tools. You can use
sc sdsetfor this.See SID Strings for documentation.
Additional reading:
AV-Specific Evasion
Example: McAfee exclusions can be found in logs:
c:\ProgramData\McAfee\Endpoint Security\Logs\AdaptiveThreatProtection_Activity.logDiscovering excluded processes (like
conhost.exe) enables targeted injection
Practical Implementation
Setting Up a Testing Lab
Kali (Attacker) Setup:
Generate shellcode using msfvenom:
Launch Meterpreter listener:
Windows (Victim) Setup:
Ensure VMs can communicate
Keep Windows and Defender updated
Create antivirus exclusion on test directory
Disable "Automatic sample submission" during testing (re-enable outside testing)
Windows Defender Bypass Tools
Available at github.com/hackmosphere/DefenderBypass:
myEncoder3.py - Transforms binary files to hex and applies XOR encryption
InjectBasic.cpp - Basic shellcode injector in C++
InjectCryptXOR.cpp - Adds XOR decryption for encrypted shellcode
InjectSyscall-LocalProcess.cpp - Uses direct syscalls to bypass userland hooks, removes suspicious functions from IAT
InjectSyscall-RemoteProcess.cpp - Injects shellcode into remote processes
Progressive techniques:
Begin with basic shellcode execution
Add encryption/obfuscation
Implement direct syscalls to bypass monitoring
Move to remote process injection when needed
WSC API Abuse (defendnot)
A sophisticated technique that abuses the Windows Security Center (WSC) service to disable Windows Defender by registering a fake antivirus:
Concept: WSC is used by legitimate antiviruses to notify Windows that another AV is present, causing Windows to automatically disable Defender
Implementation: defendnot directly interacts with the undocumented WSC API to register itself as an antivirus
Advantages:
Completely disables Windows Defender rather than just evading detection
Uses legitimate Windows functionality (WSC service)
More reliable than traditional bypass methods
Successor to older techniques like "no-defender"
Installation Methods:
Command Line Options:
--name- Custom antivirus display name--disable- Disable defendnot--verbose- Verbose logging--silent- No console allocation--autorun-as-user- Create autorun task as current user--disable-autorun- Disable autorun task creation
Technical Details:
WSC API is undocumented and typically requires Microsoft NDA for documentation
Registers the fake AV directly with WSC rather than using third-party code
Requires persistence via autorun to maintain registration after reboot
Binaries must remain on disk for continued operation
Limitations:
Requires autorun persistence (detectability concern)
May be flagged by other security solutions monitoring WSC changes
Effectiveness depends on target system configuration and other security layers
Legitimate Use Cases:
Development environment resource optimization
Performance testing under different security configurations
Educational research on Windows security mechanisms
Home lab experimentation
Enhance Protection
Prevent LSASS dumping by running it as a protected process light (
RunAsPPL)Deeper analysis on EDR telemetry
Heavy monitoring on common external compromise vectors
Application Allow Listing
LSASS protection (RunAsPPL) defaults
Windows 11 version 22H2 (new installs): Added LSA protection is enabled by default when the device is enterprise joined and supports HVCI; upgrades may not auto-enable.
Windows 11 version 24H2: LSA protection defaults are broader; Microsoft notes it is enabled by default on more device categories (MSA/Entra/hybrid/local) with evaluation behavior on upgrade.
Blue-team quick checks:
Verify registry:
HKLM\SYSTEM\CurrentControlSet\Control\Lsa?RunAsPPL/RunAsPPLBoot(policy may also store a UEFI variable for lock).Confirm status with eventing and
Get-ProcessMitigation -Systemand hardware readiness (Get-CimInstance Win32_DeviceGuard).
Firmware & Boot?level Threats
UEFI Bootkits (e.g., BlackLotus, CosmicStrand?2024) execute during the DXE phase, disable BitLocker and HVCI before Windows loads, and can patch kernel code pages before EDR starts.
Secure?Boot bypass CVE?2024?7344 abuses an un?revoked test?signed shim to load unsigned payloads even with Secure Boot enabled.
Mitigations
Keep DBX revocation list current (August?2024 or later).
Enable Windows Defender System Guard Secure Launch and SVI.
Collect & review TPM PCR[7] and System Guard logs for unexpected changes.
Linux / Container Visibility & Evasion
eBPF Runtime Sensors
Tools like Falco?0.38+ , Cilium?Tetragon (real?time enforcement with
kubectl tetragon observe), and AWS?GuardDuty?eBPF hooksys_entertracepoints and kprobes to emulate EDR telemetry on Kubernetes nodes.Evasion
Detach or overwrite the eBPF program with
bpftool prog detach.Remount
debugfselsewhere to hide BPF maps and programs.Hide processes in sidecar containers that run outside the node?agent's PID namespace filter.
PID?Namespace & Cgroup Tricks
CVE?2025?26324 leaks host PIDs, allowing a container process to open
/proc/<hostpid>/memand bypass namespace?based sensors.Sidecars running in the host network namespace can exfiltrate data without visibility from node?level agents.
Non?Windows Endpoints (macOS, iOS, Android)
macOS
Starting with macOS?Sonoma?(14), every Gatekeeper verdict is logged via the unified log channel
sender=syspolicyd. Blue teams monitor these streams; red teams should clear the quarantine flag before first execution or ship a notarised loader.Direct edits to TCC.db grant screen?recording, camera, or microphone entitlements without user prompts.
Combine with notarised, ad?hoc signed apps to bypass Gatekeeper on macOS 15.
Mobile
Android?13/14: SIM?swap plus deferred
appopsremoves MDM profiles without factory reset.iOS 17 KFD exploit enables sideloading unsigned binaries that most Mobile Threat Defence solutions fail to scan.
Kernel Driver Blocklists & Core Isolation (Windows 11 23H2+)
Windows now ships a quarterly updated vulnerable?driver blocklist; violations surface under Device security ? Core isolation.
Kernel Data Protection (KDP) marks EDR code pages read?only�even for kernel drivers.
Attacker response: use driver?name collision (rename malicious driver to
iqvw64e.sys) or flip CiOptions from a BYOVD payload before loading unsigned code.Defender quick checks:
Get-ProcessMitigation -System,Get-CimInstance -ClassName Win32_DeviceGuard, andGet-WindowsDriver -Online -All | ? Name -match 'wd'.Hardware?Enforced Stack Protection (CET/Shadow Stack) is increasingly enabled (Windows 11 24H2+). Call?stack spoofing must account for CET or will fault.
LSASS protection (RunAsPPL) is enabled by default on recent Windows 11 new installs; credential theft attempts must consider this.
Diagrams
EDR Detection & Prevention Mechanisms
EDR Evasion Techniques
Modern EDR Evasion Workflow
Last updated