SKILL: Endpoint Detection and Response
Metadata
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:
- Load and apply the full methodology below as your operational checklist
- Follow steps in order unless the user specifies otherwise
- For each technique, consider applicability to the current target/context
- Track which checklist items have been completed
- 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:
- 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
CreateFile function
- CreateFile forwards to
NtCreateFile
- Ntdll.dll triggers
NtCreateFile syscall
- 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:
- Inject their DLL into newly spawned processes
- Position before malware can block/unmap it
- Adjust
_PEB, hook process's module IAT/Imports, and loaded libraries EAT/Exports
- 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:
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:
# List loaded drivers
driverquery /v
Get-WindowsDriver -Online -All
# Using WMI
Get-WmiObject Win32_PnPSignedDriver | Select-String "EDR_Vendor"
Dynamic Analysis:
# 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:
// Using DeviceTree (preferred) or kernel debugger
// WinDbg example:
!object \Device\DeviceName
!sd <SecurityDescriptor_Address> 1
FilterConnectionPort ACL Checking:
# 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-.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
- 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 deployment script
Set shell = CreateObject("WScript.Shell")
shell.Run "tc.exe -m 512 -hda tc.qcow2 -netdev user,id=net0 -device e1000,netdev=net0"
# 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:
- Store original bytes of target APIs from clean system
- Identify hooked functions in memory
- Restore original bytes using
WriteProcessMemory on the current process
- Execute malicious code using now-unhooked APIs
Sample implementation:
// Find address of target API function
HANDLE kernelbase_handle = GetModuleHandle("kernel32");
LPVOID CreateRemoteThread_address = GetProcAddress(kernelbase_handle, "CreateRemoteThread");
// Check if function is hooked (first byte is 0xE9)
byte first_byte = (byte)*(char*)CreateRemoteThread_address;
if (first_byte == 0xe9) {
// Replace with original bytes
char original_bytes[] = "\x4C\x8B\xDC\x48\x83"; // Original prologue bytes
WriteProcessMemory(GetCurrentProcess(), CreateRemoteThread_address, original_bytes, 5, NULL);
}
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.dll hooks
- or obtain
SSN(System Service Number) dynamically and call them(can be done via SysWhispers2)
- Direct syscalls bypass user-mode hooks in
ntdll.dll but 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
ntdll frame 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:
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.dll and jump to that location
- Modern Context: Similar to direct syscalls, this bypasses user-mode hooks but not necessarily kernel-level monitoring. Finding and jumping to existing
syscall instructions 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
d8 debug shell with --allow-natives-syntax for %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 creation
- Executing 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
NtContinue or use delayed initialization
- Avoids 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
LdrInitializeThunk function executes, providing a window of opportunity for code execution before security measures initialize
- watch for early
NtCreateThreadEx inside LdrInitializeThunk
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::sam without detection during early startup
- EDR 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/ResumeThread and SetThreadContext that trigger most alerts
- Required handle access:
- For target process:
PROCESS_VM_OPERATION, PROCESS_VM_READ, PROCESS_VM_WRITE
- For target thread:
THREAD_GET_CONTEXT
- Uses less monitored APIs:
NtQuerySystemInformation (with SystemProcessInformation)
GetThreadContext
ReadProcessMemory
VirtualAllocEx
WriteProcessMemory
VirtualProtectEx
- 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
irql = RaiseIRQL();
dpcPtr = AcquireLock();
do_stuff();
ReleaseLock(dpcPtr);
LowerIRQL(irql);
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 the Intel\ShaderCache directory (%LOCALAPPDATA%\LocalLow\Intel\ShaderCache) combined with the behavior of auto-elevated processes (like taskmgr.exe) writing to this location.
- Mechanism:
- Clear Directory: Requires aggressively terminating processes holding handles (
explorer.exe, sihost.exe, etc.) and deleting files within the ShaderCache directory. Permissions might need adjustment (icacls) to allow deletion. Launching taskmgr.exe briefly (with a timeout) helps identify recently written filenames and can trigger writes needed for the exploit.
- Junction Creation: Create a directory junction from
ShaderCache to \??\GLOBALROOT\RPC CONTROL.
- Symbolic Link: Determine a recently used filename within
ShaderCache (before clearing). Create an object directory symbolic link (CreateDosDevice) from Global\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 to ShaderCache. 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:
# Create alternative service that launches cyserver.exe without PPL protection
sc create "fake_cyserver" binPath="C:\Program Files\Palo Alto Networks\Traps\cyserver.exe" start=auto
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 via RtlCreateProcessParametersEx), PS_CREATE_INFO, and PS_ATTRIBUTE_LIST.
RTL_USER_PROCESS_PARAMETERS: Defines process startup information, including image path, command line, environment variables, etc. The ImagePathName must be in NT path format (e.g., \??\C:\Windows\System32\executable.exe).
PS_ATTRIBUTE_LIST: Can specify attributes like the image name.
- Flags:
ProcessFlags and ThreadFlags allow 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 be NULL.
- Implementation Details: Involves initializing several structures and using functions from
ntdll.dll such as RtlInitUnicodeString, RtlCreateProcessParametersEx, and RtlAllocateHeap. The article also mentions that the ProcessParameters argument for NtCreateUserProcess was found to be mandatory, and RtlCreateProcessParametersEx is used with the RTL_USER_PROCESS_PARAMETERS_NORMALIZED flag. The PS_CREATE_INFO structure needs its Size and State (e.g., PsCreateInitialState) members initialized. The PS_ATTRIBUTE_LIST is populated to include the image name.
Example High-Level Steps:
- Define the path to the executable using
UNICODE_STRING and initialize it with RtlInitUnicodeString (e.g., L"\??\C:\Windows\System32\calc.exe").
- Create and populate
RTL_USER_PROCESS_PARAMETERS using RtlCreateProcessParametersEx, providing the image path and normalizing parameters.
- Initialize a
PS_CREATE_INFO structure.
- Allocate and initialize a
PS_ATTRIBUTE_LIST, setting the PS_ATTRIBUTE_IMAGE_NAME attribute with the image path.
- Call
NtCreateUserProcess with the prepared handles, access masks, and structures.
- Perform cleanup, for instance, by calling
RtlFreeHeap and RtlDestroyProcessParameters.
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.exe window handle using EnumWindows
- Convert to process handle with
GetProcessHandleFromHwnd
- Leverage
PROCESS_DUP_HANDLE to 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!StackWalk64 fails
- implement custom API resolver similar to
GetProcAddress
- before calling out to suspicious functions, overwrite
RetAddr :=0
- when 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
- AceL
…(truncated)
1---2name: skill-endpoint-detection-and-response3description: Skill Endpoint Detection And Response4---5# SKILL: Endpoint Detection and Response
6
7## Metadata
8- **Skill Name**: edr-evasion
9- **Folder**: offensive-edr-evasion
10- **Source**: https://github.com/SnailSploit/offensive-checklist/blob/main/edr.md
11
12## Description
13EDR 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.
14
15## Trigger Phrases
16Use this skill when the conversation involves any of:
17`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`
18
19## Instructions for Claude
20
21When this skill is active:
221. Load and apply the full methodology below as your operational checklist
232. Follow steps in order unless the user specifies otherwise
243. For each technique, consider applicability to the current target/context
254. Track which checklist items have been completed
265. Suggest next steps based on findings
27
28---
29
30## Full Methodology
31
32# Endpoint Detection and Response
33
34## Fundamentals
35
36### AV vs EDR
37
38**Antivirus (preventive approach)**:
39
40- Static Analysis: Matching known signatures in files
41- Dynamic Analysis: Limited behavioral monitoring/sandboxing
42- Effective against known threats, weaker against advanced attacks
43
44**EDR (proactive & investigative approach)**:
45
46- Continuous endpoint monitoring
47- Behavioral analysis at kernel level
48- Anomaly detection and post-compromise visibility
49- Prioritizes incident response and investigation
50
51### Windows Execution Flow
52
53Windows program execution follows a hierarchical flow:
54
551. **Applications** - User programs like firefox.exe
562. **DLLs** - Libraries providing Windows functionality without direct low-level access
573. **Kernel32.dll** - Core DLL for memory management, process/thread creation
584. **Ntdll.dll** - Lowest user-mode DLL that exposes the NT API interface to the kernel
595. **Kernel** - Core OS component with unrestricted hardware access
60
61Example operation flow (creating a file):
62
631. Application invokes `CreateFile` function
642. CreateFile forwards to `NtCreateFile`
653. Ntdll.dll triggers `NtCreateFile` syscall
664. Kernel creates the file and returns a handle
67
68## EDR Visibility
69
70### EDR Architecture & Components
71
72EDR solutions consist of multiple components creating a complex attack surface:
73
74**Client-Side Components:**
75
76- **User-space Applications** - Main agent processes and UI components
77- **Kernel-space Drivers** - Filter drivers, network drivers, software drivers
78- **Communication Interfaces** - IOCTLs, FilterConnectionPorts, ALPC, Named Pipes
79
80**Component Communication Methods:**
81
82- **Kernel-to-Kernel**: Exported functions, IOCTLs
83- **User-to-Kernel**: IOCTLs, FilterConnectionPorts (minifilter-specific), ALPC
84- **User-to-User**: ALPC, Named Pipes, Files, Registry
85
86**Server-Side Components:**
87
88- Cloud services and management consoles
89- On-premise servers (some vendors)
90- Custom protocols for agent-to-cloud communication
91
92### EDR Visibility Methods
93
94EDR solutions require extended visibility into system activities:
95
96- Filesystem monitoring via mini-filter drivers
97- Process/module loading via image load kernel callbacks
98- Process/.NET modules/Registry/kernel object events via ETW Ti
99- Network monitoring via NDIS and network filtering drivers
100
101### Static Analysis
102
103- Extract information from binary
104 - Known malicious strings
105 - Threat actor IP or domains
106 - Malware binary hashes
107
108### Dynamic Analysis
109
110- Execute binary in a sandbox environment and observe it
111 - Network connections
112 - Registry changes
113 - Memory access
114 - File creation/deletion
115- AntiMalware Scan Interface
116
117### Behavioral Analysis
118
119- Observe the binary as its executing, Hook into functions/syscalls
120 - User actions
121 - System calls
122 - Kernel callbacks
123 - Commands executed in the command line
124 - Which process is executing the code
125 - Event Tracing for Windows
126
127## Detection Methods
128
129### AV Signature Scanning
130
131- Scans files using known signatures (YARA rules)
132- Typically targets loaders and droppers
133- Primarily static analysis of files on disk
134
135### AV Emulation
136
137- Runs suspicious programs in a simulated environment
138- Triggers on behaviors without executing real code
139- Used to detect obfuscated malware
140
141### Usermode Hooks
142
143- EDR hooks critical API calls in userspace (ntdll.dll)
144- Monitors process creation, memory allocations, and network operations
145- Allows for inspection before execution continues
146
147### Kernel Telemetry
148
149- Monitors events directly from the kernel
150- Captures file, registry, process, and network operations
151- Difficult to bypass as it operates at a lower level
152
153### Memory Scanning
154
155- Scans process memory for known signatures
156- Triggers based on suspicious behavior
157- Looks for shellcode, encryption, malicious strings
158- **Modern Context:**
159 - 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.
160 - Practical triage: search for `"Authorization: Bearer"`, `"eyJ"` (base64 JWT prefix), or provider‑specific headers; dump minimal pages to avoid tripping anti‑exfil rules.
161
162## OpSec Quickstart (lab)
163
164- Pre‑run
165 - Network: block or sinkhole vendor EDR/XDR endpoints; disable cloud sample submission; tag lab hosts.
166 - Mitigations snapshot: `Get-ProcessMitigation -System`; `Get-CimInstance Win32_DeviceGuard` (VBS/HVCI/KDP); `Get-MpPreference` (ASR/Cloud).
167 - Events baseline: enable and tail `Microsoft-Windows-CodeIntegrity/Operational`, `Security (4688/4689)`, `Microsoft-Windows-Sense/Operational`, Sysmon (if present).
168- Injection hygiene
169 - Favor `MEM_IMAGE` mappings (ghosting/herpaderping/overwriting) over `MEM_PRIVATE` RWX to avoid 24H2 hotpatch loader checks.
170 - Satisfy XFG/CET: jump via import thunks; ensure IBT `ENDBR64` at indirect targets; maintain plausible stacks for syscalls (replicate `ntdll` frames).
171 - Avoid noisy APIs: split `alloc/write/exec` over time; prefer APC+`NtContinue` pivots; keep thread contexts consistent.
172- Telemetry minimization
173 - Jitter long‑lived channels; prefer named‑pipe/HTTP3 over noisy HTTP1; throttle upload intervals.
174 - Use COM/runspace over PowerShell console to reduce script‑block logs; avoid AMSI‑flagged prologues.
175- Cleanup
176 - Remove services, tasks, drivers; restore SDDL; revert registry policy flips (WDAC/CI/Defender) and re‑enable protections.
177 - Purge user caches (Recent Files, Jump Lists) and ETW providers enabled during tests.
178
179### Memory Regions
180
181- Monitors suspicious memory allocation patterns
182- Flags RWX (read-write-execute) regions
183- Tracks regions that change from RW to RX
184
185### Callstack Analysis
186
187- Examines the call stack of suspicious functions
188- Verifies legitimate origin of critical operations
189- Detects unusual function call chains
190
191### Hook Implementation
192
193EDRs can't directly hook kernel memory due to PatchGuard, so they:
194
1951. Inject their DLL into newly spawned processes
1962. Position before malware can block/unmap it
1973. Adjust `_PEB`, hook process's module `IAT`/Imports, and loaded libraries `EAT`/Exports
1984. Implement trampolines, hooks, and detours
199
200### ETW Monitoring
201
202- EDR maintains ring-buffer with per-process activities produced by ETW Ti:
203 - Processes, command lines, parent-child relationships
204 - File/Registry/Process open/write operations
205 - Created threads, their call stacks, starting addresses
206 - Native functions called
207 - Created .NET AppDomains, loaded .NET assemblies, static class names, methods
208
209#### Event Correlation
210
211- High fidelity alert (such as LSASS open) triggers correlation of collected activities
212- High memory/resources cost limits preservation of events to a time window
213- ML/AI may compute risk scores and isolate TTP (Tactics, Techniques, and Procedures)
214
215#### Shellcode Loaders
216
217Shellcode loaders typically follow this pattern:
218
219```c
220char *shellcode = "\xAA\xBB...";
221char *dest = VirtualAlloc(NULL, 0x1234, 0x3000, PAGE_READWRITE);
222memcpy(dest, shellcode, 0x1234)
223VirtualProtect(dest, 0x1234, PAGE_EXECUTE_READ, &result)
224(*(void(*)())(dest))(); // jump to dest: execute shellcode
225```
226
227## Attacking EDR Infrastructure Directly
228
229### Driver Attack Surface Analysis
230
231A systematic approach to analyzing EDR drivers from a low-privileged user perspective:
232
233#### 1. Driver Discovery
234
235**Static Analysis:**
236
237```powershell
238# List loaded drivers
239driverquery /v
240Get-WindowsDriver -Online -All
241
242# Using WMI
243Get-WmiObject Win32_PnPSignedDriver | Select-String "EDR_Vendor"
244```
245
246**Dynamic Analysis:**
247
248```powershell
249# Using sc command
250sc query type= driver state= all
251
252# Process Monitor filtering
253# Filter: Process and Thread Activity -> Show Image/DLL
254```
255
256#### 2. Interface Enumeration
257
258**Device Driver Interfaces:**
259
260- Listed in WinObj under "GLOBAL??" as Symbolic Links
261- Accessible via `\\.\DEVICE_NAME` format
262- Tools: WinObj (Sysinternals), DeviceTree (OSR - discontinued)
263
264**Mini-Filter Driver Interfaces:**
265
266- Listed in WinObj as "FilterConnectionPort" objects
267- Communication via `FltCreateCommunicationPort` API
268- Example paths: `\CyvrFsfd`, `\SophosPortName`
269
270#### 3. Access Permission Analysis
271
272**Device Driver ACL Checking:**
273
274```cpp
275// Using DeviceTree (preferred) or kernel debugger
276// WinDbg example:
277!object \Device\DeviceName
278!sd <SecurityDescriptor_Address> 1
279```
280
281**FilterConnectionPort ACL Checking:**
282
283```powershell
284# Using NtObjectManager (James Forshaw)
285Get-FilterConnectionPort -Path "\FilterPortName"
286# Error indicates access denied
287
288# In WinDbg:
289!object \FilterPortName
290dx (((nt!_OBJECT_HEADER*)0xAddress)->SecurityDescriptor & ~0xa)
291!sd <SecurityDescriptor_Address> 1
292```
293
294#### 4. Interface Functionality Analysis
295
296**Device Driver Communication:**
297
298- Primary method: DeviceIoControl() → IRP_MJ_DEVICE_CONTROL
299- IOCTL codes differentiate between functions
300- May include process ID verification for authorization
301
302**FilterConnectionPort Communication:**
303
304- Uses callback functions: ConnectNotifyCallback, DisconnectNotifyCallback, MessageNotifyCallback
305- Similar to IOCTL dispatch with different message types
306
307#### 5. Common EDR Driver Interfaces
308
309**Examples of accessible interfaces found in research:**
310
311**Palo Alto Cortex XDR:**
312
313- **Device Interfaces**:
314 - `\\.\PaloEdrControlDevice` (tedrdrv.sys) - ~20 IOCTL handlers with various functionality
315 - `\\.\CyvrMit` (cyvrmtgn.sys) - Legacy Cyvera interface
316 - `\\.\PANWEdrPersistentDevice11343` (tedrpers-<version>.sys) - Persistent device interface
317- **FilterConnectionPort**: Various ports with different ACLs
318- **Research Findings**:
319 - IOCTL 0x2260D8 returns 3088 bytes of statistics data (accessible to low-privileged users)
320 - IOCTL 0x2260D0 provides initialization status information
321 - Some interfaces accessible due to injected DLL architecture requiring broad permissions
322
323**Sophos Intercept X:**
324
325- **FilterConnectionPort**: `\SophosPortName`
326- **Analysis Results**: Accessible interfaces for legitimate process communication but limited attack surface
327
328#### 6. Why EDRs Have Open ACLs
329
330EDRs often use an architecture where:
331
332- Agent injects DLLs into processes (including low-privileged ones like `word.exe`)
333- Injected DLLs communicate directly with drivers via IOCTLs
334- Drivers cannot restrict based solely on process privilege level
335- Results in more permissive ACLs to accommodate legitimate injected processes
336
337## Evasion Techniques
338
339### Memory-Based Evasion
340
341#### EDR-Freeze
342
343A novel technique exploiting Windows Error Reporting (WER) to temporarily disable EDR/AV processes:
344
345##### Mechanism
346
347- Leverages `WerFault.exe` and Windows Error Reporting infrastructure
348- Suspends all threads in target EDR/AV processes indefinitely
349- No kernel-mode access or driver exploitation required
350- Operates entirely from user-mode context
351
352##### Technical Implementation
353
354- Trigger WER fault injection on target security process
355- WER suspends all threads for crash dump generation
356- Attacker maintains suspended state without completing crash handling
357- Target process remains alive but non-functional
358
359##### Advantages
360
361- No elevation required in default WER configurations
362- Avoids detection heuristics for process termination
363- Temporary disabling without unloading kernel drivers
364- Minimal forensic footprint compared to driver killing
365
366##### Limitations
367
368- Effectiveness varies by Windows version and WER configuration
369- Some EDRs implement anti-suspension protections
370- Temporary nature requires continuous re-application
371- May generate WER event logs exposing the technique
372
373> [!TIP]
374> 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.
375
376#### Memory Encryption
377
378- Encrypts shellcode in memory when not in use
379- Popular techniques:
380 - SWAPPALA / SLE(A)PING
381 - Thread Pool / Pool Party
382 - Gargoyle
383 - Ekko
384 - Cronos
385 - Foliage
386
387#### Sleep Obfuscation
388
389- ROP-Styles sleep obfuscations
390 - [Ekko](https://github.com/Cracked5pider/Ekko)
391 - [FOLIAGE](https://github.com/y11en/FOLIAGE)
392 - these setup `_CONTEXT` in advance so that `EIP/RIP` points to native API
393 - and then schedule APC with `NtContinue` to jump to that requested API
394
395#### Secure Enclaves (VBS)
396
397- Virtualization-Based Security (VBS) enclaves provide an isolated user-mode TEE that even kernel-mode sensors cannot inspect under normal conditions.
398- Deprecation/support scope (Microsoft):
399 - 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.
400 - Windows 11 24H2+ and Windows Server 2025: VBS enclaves are supported with new EKUs.
401- Security fix: CVE-2024-49076 (VBS Enclave EoP) — ensure December 2024+ updates are applied.
402- Signing constraints: Only Microsoft-signed enclave DLLs or DLLs signed via Azure Trusted Signing load; test- or self-signed DLLs are rejected.
403- Architecture summary:
404 - Enclave host app (VTL0) invokes enclave APIs; enclave DLL executes in isolated user mode (VTL1) with restricted API surface; Secure Kernel validates integrity.
405- 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.
406- Practical notes:
407 - On unsupported SKUs/versions, enclave APIs may appear and return `STATUS_FEATURE_DEPRECATED`.
408 - Prefer testing on Windows 11 24H2+/Server 2025 with proper signing.
409
410#### Malware Virtualization
411
412- Malware virtualization provides advanced evasion against modern EDR:
413 - Embeds a custom virtual machine to execute bytecode instead of native code
414 - Makes static and dynamic analysis difficult through instruction obfuscation
415 - Prevents detection of instruction patterns and behavior prediction
416
417- Implementation advantages:
418 - Conceals malicious instructions from EDR monitoring
419 - Protects against code patching attempts
420 - Hinders behavioral analysis through custom execution model
421
422- Multi-VM approach further evades detection:
423 - Multiple VMs running concurrently disrupts heuristic pattern detection
424 - Each VM creates distinct event patterns, confusing EDR correlation
425 - "ETW noise" technique to blend with legitimate activity
426
427- Deployment strategies:
428 - Bytecode polling - periodically fetching new instructions from C2
429 - Using transpilers to convert compiled binaries to custom bytecode
430 - Applying polymorphic engine to mutate VM code itself
431
432- Successfully evaded detection for:
433 - Initial shellcode/bytecode execution (subsequent actions still monitored)
434 - Specific AV/EDR patching routines (may require updates per product)
435 - Initial C2 communication (ongoing traffic patterns may be detected)
436 - Specific AD queries (patterns of queries can still be flagged)
437
438### QEMU-Based Virtualization Evasion
439
440- **Concept**: Deploy portable QEMU VMs to execute malicious code within guest OS, avoiding host-based EDR detection
441- **Technical Implementation**:
442 - Portable QEMU deployment via ZIP archives containing VM binaries and configurations
443 - Tiny Core Linux as lightweight guest OS (minimal footprint ~50MB)
444 - VBS scripts for automated VM deployment and execution
445 - Custom hostname generation for VM identification and tracking
446
447- **Configuration Examples**:
448
449 ```vbs
450 # VBS deployment script
451 Set shell = CreateObject("WScript.Shell")
452 shell.Run "tc.exe -m 512 -hda tc.qcow2 -netdev user,id=net0 -device e1000,netdev=net0"
453 ```
454
455 ```conf
456 # QEMU configuration file (upd.conf)
457 -m 512
458 -hda tc.qcow2
459 -netdev user,id=net0
460 -device e1000,netdev=net0
461 ```
462
463- **Persistence Mechanisms**:
464 - `bootlocal.sh` modifications for startup execution
465 - `filetool.lst` configuration for file persistence across reboots
466 - SSH service installation and configuration within guest VM
467 - Reverse SSH tunnels over port 443 for C2 communication
468
469- **Advanced Techniques**:
470 - Anti-forensic SSH configuration (`StrictHostKeyChecking=no`, known hosts to `/dev/null`)
471 - SSL/NoSSL tool deployment for encrypted communications
472 - Randomized hostname generation to mask VM tracking
473 - Port 443 tunneling to blend with HTTPS traffic
474
475- **Detection Evasion Benefits**:
476 - Guest VM operations invisible to host-based EDR sensors
477 - VM network traffic appears as legitimate application activity
478 - File operations contained within guest filesystem
479 - Process execution isolated from host monitoring
480
481- **Limitations & Considerations**:
482 - Requires administrative privileges for some QEMU operations
483 - VM resource consumption may be detectable
484 - Network traffic patterns might still trigger detection
485 - Initial VM deployment artifacts remain on host filesystem
486
487### Hook Evasion
488
489#### Unhooking
490
491- malware overwrites EDR hooks before executing payload
492- you can obtain original `ntdll.dll` from disk and overwrite it inside your own process
493- or you can start the malware process in suspended state and copy the clean `ntdll.dll` from you own memory before executing
494 - **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.
495 > [!CAUTION]
496 > accessing `ntdll.dll` file can be flagged, API call to overwrite it also might be hooked by EDR
497
498##### API Unhooking for AV Bypass
499
500- Most EDR/AVs like BitDefender hook Windows APIs by replacing first bytes with `JMP` instructions (opcode `0xE9`)
501- **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.
502- How to identify hooked APIs:
503 - Create a test program that calls potentially hooked APIs
504 - Examine first byte of API function using a debugger (like x64dbg)
505 - If first byte is `0xE9`, the function is hooked
506- Common hooked APIs:
507 - `CreateRemoteThread`/`CreateRemoteThreadEx`
508 - `VirtualAllocEx`
509 - `WriteProcessMemory`
510 - `OpenProcess`
511 - `RtlCreateUserThread`
512- Unhooking approach:
513 1. Store original bytes of target APIs from clean system
514 2. Identify hooked functions in memory
515 3. Restore original bytes using `WriteProcessMemory` on the current process
516 4. Execute malicious code using now-unhooked APIs
517- Sample implementation:
518
519 ```c
520 // Find address of target API function
521 HANDLE kernelbase_handle = GetModuleHandle("kernel32");
522 LPVOID CreateRemoteThread_address = GetProcAddress(kernelbase_handle, "CreateRemoteThread");
523
524 // Check if function is hooked (first byte is 0xE9)
525 byte first_byte = (byte)*(char*)CreateRemoteThread_address;
526 if (first_byte == 0xe9) {
527 // Replace with original bytes
528 char original_bytes[] = "\x4C\x8B\xDC\x48\x83"; // Original prologue bytes
529 WriteProcessMemory(GetCurrentProcess(), CreateRemoteThread_address, original_bytes, 5, NULL);
530 }
531 ```
532
533- 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.**
534
535#### Unhooking Tools
536
537- [unhook BOF](https://github.com/rsmudge/unhook-bof) - module refreshing (less reliable now **due to alternative EDR telemetry sources**)
538- [Unhookme](https://github.com/mgeeky/UnhookMe) - dynamic unhooking
539
540#### Direct System Calls
541
542- malware circumvents hook in system DLL by directly system calling into kernel
543- you can implement own syscall in assembly and bypass `ntdll.dll` hooks
544- or obtain `SSN`(System Service Number) dynamically and call them(can be done via [SysWhispers2](https://github.com/jthuraisamy/SysWhispers2))
545 - Direct syscalls bypass user-mode hooks in `ntdll.dll` but 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).
546 > [!CAUTION]
547 > having syscall assembly instructions can be flagged, also this only helps the loader to evade the EDR not the malware itself
548 - Major EDR vendorsnow flag **non‑ntdll syscall sites**; consider **return‑address replication gadgets** to re‑insert a plausible `ntdll` frame before the transition.
549
550> [!CAUTION]
551> Some EDRs flag syscalls originating outside `ntdll.dll`. Maintaining plausible stacks/return frames may be required to avoid heuristics.
552
553##### Direct Syscall Tools
554
555Bypasses user-mode hooks but not kernel monitoring. Requires System Service Dispatch Table (SSDT) index:
556
557- [FreshyCalls](https://github.com/crummie5/FreshyCalls) - sorting system call addresses
558- [SysWhispers2](https://github.com/jthuraisamy/SysWhispers2) - modernized syscall resolution
559- [SysWhispers3](https://github.com/klezVirus/SysWhispers3) - adds x86/Wow64 support
560- [Runtime Function Table](https://www.mdsec.co.uk/2022/04/resolving-system-service-numbers-using-the-exception-directory/) - reliable SSN computation
561
562#### Indirect System Calls
563
564- malware uses code fragments in kernel DLL without calling the hooked functions in those DLL
565- prepare the system call in assembly then find a syscall instruction in `ntdll.dll` and jump to that location
566 - **Modern Context:** Similar to direct syscalls, this bypasses user-mode hooks but not necessarily kernel-level monitoring. Finding and jumping to existing `syscall` instructions can be less suspicious than embedding raw syscall stubs, but the subsequent kernel activity is still visible.
567 > [!TIP]
568 > this is preferred,you can also boost evasion techniques by hiding inside a `.dll`
569
570#### Kernel‑Mode EDR Killers (BYOVD)
571
572- **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.
573- Typical payload actions
574 - Patch or unregister kernel‑mode notify callbacks (`PsSetCreateProcessNotifyRoutine`, `ObRegisterCallbacks`) to blind user‑mode EDR components.
575 - Overwrite or unload _WdFilter.sys_ and other sensor drivers, fully disabling Defender or third‑party agents.
576- Public toolchains such as **Terminator**, **kdmapper**, and **EDRSensorDisabler** automate these steps.
577- 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.
578
579> [!TIP]
580> 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.
581
582> [!NOTE]
583> 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.
584
585### User-Mode Application Whitelisting Bypass
586
587#### Exploiting Vulnerable Trusted Applications
588
589Windows 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.
590
591- **Concept (Bring Your Own Vulnerable Application - BYOVA)**:
592 - A trusted, signed Electron application (e.g., an older version of VSCode) with a known V8 vulnerability is used as a carrier.
593 - The application's `main.js` (or equivalent) is replaced with a V8 exploit that executes a native shellcode payload.
594 - If the application is whitelisted, WDAC allows it to run, inadvertently executing the malicious shellcode.
595- **Advantages**:
596 - Achieves native shellcode execution, overcoming limitations of pure JavaScript execution in some backdoored Electron app scenarios.
597 - 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.
598- **Exploit Development & Operationalization Challenges**:
599 - **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.
600 - **Debugging**: Building the specific V8 version (e.g., using `d8` debug shell with `--allow-natives-syntax` for `%DebugPrint()`) is crucial for understanding memory layouts and adapting exploits.
601 - **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.
602 - _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).
603 - **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.
604 - **JIT Compiler Interference (e.g., V8 TurboFan)**:
605 - Optimizations can consolidate repeated instruction sequences (e.g., multiple floating-point values), affecting shellcode smuggling. Workarounds include compact shellcode or varying instruction positions.
606 - Copying large shellcode payloads can be problematic. Workaround: multiple smaller copy loops or using a stager payload that fetches the main payload.
607 - **Payload Obfuscation**: Obfuscate the JavaScript exploit (e.g., in `main.js`) to hinder analysis. Re-obfuscating per deployment can help avoid signature-based detection.
608- **Defense & Future Considerations**:
609 - 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.
610 - Older application versions without this fuse remain vulnerable.
611
612### Process Manipulation
613
614#### Early Cascade Injection
615
616- Novel process injection technique targeting user-mode process creation
617- Combines elements of Early Bird APC with EDR-Preloading
618- Avoids queuing cross-process APCs while maintaining minimal remote process interaction
619- Works by:
620 - Targeting processes during the transition from kernel-mode to user-mode (`LdrInitializeThunk`)
621 - Leveraging callback pointers (like `g_pfnSE_DllLoaded`) during Windows process creation
622 - Executing malicious code before EDR detection measures can initialize
623- Advantages:
624 - Operates before EDRs can initialize their hooks and detection measures
625 - Particularly effective against EDRs that hook `NtContinue` or use delayed initialization
626 - Avoids ETW telemetry that traditional injection techniques trigger
627 - Minimal remote process interaction reduces detection footprint
628 - More stealthy than traditional techniques like DLL hijacking or direct syscalls
629- Key insight: EDRs typically load their detection measures after the `LdrInitializeThunk` function executes, providing a window of opportunity for code execution before security measures initialize
630- watch for early `NtCreateThreadEx` inside `LdrInitializeThunk`
631
632#### Early Startup Bypass
633
634**Concept**: Execute malware before the EDR's user-mode component fully initializes, creating a window of opportunity for undetected execution.
635
636**Implementation**:
637
638- Target the gap between kernel driver loading and user-mode agent initialization
639- Execute payload during system startup before EDR hooks are established
640- Leverage services that start before EDR components
641
642**Research Findings (Cortex XDR)**:
643
644- Successfully executed Mimikatz with `lsadump::sam` without detection during early startup
645- EDR kernel drivers may be loaded but user-mode hooks not yet established
646- Timing window varies depending on system performance and EDR implementation
647
648**Detection Evasion**:
649
650- Creates process activity before EDR monitoring is fully operational
651- Avoids user-mode hooks that haven't been established yet
652- Kernel-level monitoring may still detect activity depending on driver initialization order
653
654**Limitations**:
655
656- Requires precise timing and understanding of EDR startup sequence
657- May not work against EDRs with early kernel-level monitoring
658- Window of opportunity may be brief on fast systems
659
660#### Waiting Thread Hijacking (WTH)
661
662- A stealthier version of classic Thread Execution Hijacking
663- Intercepts the flow of a waiting thread and misuses it for executing malicious code
664- Avoids suspicious APIs like `SuspendThread`/`ResumeThread` and `SetThreadContext` that trigger most alerts
665- Required handle access:
666 - For target process: `PROCESS_VM_OPERATION`, `PROCESS_VM_READ`, `PROCESS_VM_WRITE`
667 - For target thread: `THREAD_GET_CONTEXT`
668- Uses less monitored APIs:
669 - `NtQuerySystemInformation` (with `SystemProcessInformation`)
670 - `GetThreadContext`
671 - `ReadProcessMemory`
672 - `VirtualAllocEx`
673 - `WriteProcessMemory`
674 - `VirtualProtectEx`
675- Implementation can be further obfuscated by splitting steps across multiple functions to evade behavioral signatures
676- Primarily bypasses EDRs that focus on detecting specific API calls rather than behavioral patterns
677- Effective against EDRs that are restrictive about remote execution methods but more lenient with allocations and writes
678- Suitable for hiding the point at which implanted code was executed
679
680#### PPID Spoofing
681
682- Creates process with fake parent process ID
683- Hides true process creation chain
684- Makes process tree analysis misleading
685
686#### Process Hiding
687
688A technique to hide processes from EDR monitoring by manipulating the Interrupt Request Level (IRQL):
689
690- Raise the IRQL of current CPU core
691- Create and queue Deferred Procedure Calls (DPCs) to raise the IRQL of other cores
692- Perform sensitive task (for example, hiding process)
693- Signal DPCs in other cores to stop spinning and exit
694- Lower IRQL of current core back to original
695
696```c
697irql = RaiseIRQL();
698dpcPtr = AcquireLock();
699do_stuff();
700ReleaseLock(dpcPtr);
701LowerIRQL(irql);
702```
703
704This approach temporarily prevents EDR from monitoring the process during the critical operations by operating at an elevated privilege level.
705
706> [!NOTE]
707> HVCI-enabled 23H2 kernels may crash when raising IRQL this way. Safer alternative: kernel-driver patching of `PsLookupProcessByProcessId`.
708
709#### UAC Bypass via Intel ShaderCache Directory
710
711- Concept: Exploits weak permissions (`Authenticated Users: Full Control`) on the `Intel\ShaderCache` directory (`%LOCALAPPDATA%\LocalLow\Intel\ShaderCache`) combined with the behavior of auto-elevated processes (like `taskmgr.exe`) writing to this location.
712- Mechanism:
713 1. Clear Directory: Requires aggressively terminating processes holding handles (`explorer.exe`, `sihost.exe`, etc.) and deleting files within the `ShaderCache` directory. Permissions might need adjustment (`icacls`) to allow deletion. Launching `taskmgr.exe` briefly (with a timeout) helps identify recently written filenames and can trigger writes needed for the exploit.
714 2. Junction Creation: Create a directory junction from `ShaderCache` to `\??\GLOBALROOT\RPC CONTROL`.
715 3. Symbolic Link: Determine a recently used filename within `ShaderCache` (before clearing). Create an object directory symbolic link (`CreateDosDevice`) from `Global\GLOBALROOT\RPC CONTROL\<recent_filename>` to a target DLL path (e.g., `\??\C:\Windows\System32\oci.dll`).
716 4. Trigger Write: Launch an auto-elevated process (e.g., `taskmgr.exe`) that writes to `ShaderCache`. 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`).
717 5. 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.
718- EDR Relevance:
719 - Bypasses User Account Control (UAC), a primary defense layer.
720 - Relies on manipulating file system objects (junctions, symlinks) and process interactions that EDRs monitor.
721 - Involves potentially noisy actions like mass process termination and permission changes.
722 - The final payload execution often relies on DLL hijacking techniques.
723
724> [!TIP]
725> Symlink/junction UAC races are build‑dependent and brittle. Validate on the specific target build; many have partial or complete mitigations.
726
727#### PPL (Protected Process Light) Bypass
728
729**Concept**: Bypass Protected Process Light security by creating alternative service configurations that avoid PPL protections.
730
731**Palo Alto Cortex XDR PPL Bypass Technique**:
732
733```powershell
734# Create alternative service that launches cyserver.exe without PPL protection
735sc create "fake_cyserver" binPath="C:\Program Files\Palo Alto Networks\Traps\cyserver.exe" start=auto
736```
737
738**How it works**:
739
740- Creates a second service that launches the EDR's main process (cyserver.exe)
741- Original PPL-protected service fails to start due to startup dependencies
742- New service configuration is not protected by EDR drivers
743- EDR process runs without PPL protection, expanding attack surface
744
745**Limitations**:
746
747- Service names beginning with "cyserver\*" are blocked by some EDR implementations
748- EDR functionality may remain intact despite PPL bypass
749- Self-protection mechanisms may still be active at process level
750- Vendor response varies - may not be considered a security vulnerability
751
752**Detection & Response**:
753
754- EDR thinks original service is stopped but agent continues running
755- Attack surface increases as process no longer has PPL protections
756- Reported to Palo Alto on 12.09.2023 with limited vendor response
757
758**Broader Implications**:
759
760- Demonstrates service configuration vulnerabilities in EDR implementations
761- Shows potential for bypassing Windows security features through alternative execution paths
762- Relevant for other EDRs that rely on PPL for self-protection
763
764#### Using `NtCreateUserProcess` for Stealthy Process Creation
765
766The 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.
767
768**Key Concepts:**
769
770- **Bypass Mechanism**: Avoids user-land hooks on more commonly monitored APIs like `CreateProcessW`.
771- **Process Parameters**: Requires careful setup of structures like `RTL_USER_PROCESS_PARAMETERS` (often via `RtlCreateProcessParametersEx`), `PS_CREATE_INFO`, and `PS_ATTRIBUTE_LIST`.
772 - `RTL_USER_PROCESS_PARAMETERS`: Defines process startup information, including image path, command line, environment variables, etc. The `ImagePathName` must be in NT path format (e.g., `\??\C:\Windows\System32\executable.exe`).
773 - `PS_ATTRIBUTE_LIST`: Can specify attributes like the image name.
774- **Flags**: `ProcessFlags` and `ThreadFlags` allow 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 be `NULL`.
775- **Implementation Details**: Involves initializing several structures and using functions from `ntdll.dll` such as `RtlInitUnicodeString`, `RtlCreateProcessParametersEx`, and `RtlAllocateHeap`. The article also mentions that the `ProcessParameters` argument for `NtCreateUserProcess` was found to be mandatory, and `RtlCreateProcessParametersEx` is used with the `RTL_USER_PROCESS_PARAMETERS_NORMALIZED` flag. The `PS_CREATE_INFO` structure needs its `Size` and `State` (e.g., `PsCreateInitialState`) members initialized. The `PS_ATTRIBUTE_LIST` is populated to include the image name.
776
777**Example High-Level Steps:**
778
7791. Define the path to the executable using `UNICODE_STRING` and initialize it with `RtlInitUnicodeString` (e.g., `L"\??\C:\Windows\System32\calc.exe"`).
7802. Create and populate `RTL_USER_PROCESS_PARAMETERS` using `RtlCreateProcessParametersEx`, providing the image path and normalizing parameters.
7813. Initialize a `PS_CREATE_INFO` structure.
7824. Allocate and initialize a `PS_ATTRIBUTE_LIST`, setting the `PS_ATTRIBUTE_IMAGE_NAME` attribute with the image path.
7835. Call `NtCreateUserProcess` with the prepared handles, access masks, and structures.
7846. Perform cleanup, for instance, by calling `RtlFreeHeap` and `RtlDestroyProcessParameters`.
785
786This 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.
787
788#### Advanced Process Execution Alternatives
789
790- [TangledWinExec](https://github.com/daem0nc0re/TangledWinExec) - alternative process execution techniques
791- [rad9800](https://github.com/rad9800/misc/blob/main/bypasses/WorkItemLoadLibrary.c) - indirectly loading DLL through a work item
792
793#### Acquiring Process Handles
794
795- Without using suspicious `OpenProcess`:
796 - Find `explorer.exe` window handle using `EnumWindows`
797 - Convert to process handle with `GetProcessHandleFromHwnd`
798 - Leverage `PROCESS_DUP_HANDLE` to duplicate into a pseudo handle for [Full Access](https://jsecurity101.medium.com/bypassing-access-mask-auditing-strategies-480fb641c158)
799
800### Callstack Manipulation
801
802#### Return Address Overwrite
803
804- overwrite function's return address with 0
805 - that terminates call stack's unwinding algorithm
806 - examination based on `DbgHelp!StackWalk64` fails
807- implement custom API resolver similar to `GetProcAddress`
808 - before calling out to suspicious functions, overwrite `RetAddr :=0`
809 - when system API returns, restore own `RetAddr`
810
811#### Callstack Spoofing
812
813- Manipulates the call stack to appear legitimate
814- Makes it harder to detect malicious code execution
815- Tools and techniques:
816 - ThreadStackSpoofer
817 - CallStackSpoofer
818 - AceL
819
820…(truncated)