Back to Blog
Vulnerability Research

How to Bypass User-Mode Hooks in Modern EDRs

OffSec Research Team
10 June 2026 • 09:00 AM18 min
How to Bypass User-Mode Hooks in Modern EDRs
TL;DR — Endpoint Detection and Response (EDR) products see what your malware does largely by hooking user-mode API functions — patching the first bytes of NtAllocateVirtualMemory, NtProtectVirtualMemory, and friends inside ntdll.dll so every call detours through the EDR before reaching the kernel. The bypass logic is therefore: don't call the hooked functions, or restore them first. This article (for authorized red-team and detection-engineering use) covers how user-mode hooking works, the four mainstream bypass families — direct syscalls, unhooking/fresh-ntdll, hardware breakpoints, and call-indirection — and, just as importantly, how defenders catch each one through kernel telemetry the hooks were never the whole story.

Context and Authorization

This article is written for authorized red teamers, malware analysts, and detection engineers. Understanding how user-mode hooks are bypassed is essential for both emulating real adversaries during sanctioned engagements and for building detections that don't rely on the hooks themselves. Every technique below is publicly documented and implemented in open-source offensive tooling; the defensive half of each section is the operationally important part for blue teams. Use only against systems you are authorized to test.

Why EDRs Hook User Mode in the First Place

diagram — rendering…
flowchart TD
    A["Malware calls e.g.<br/>VirtualAlloc → NtAllocateVirtualMemory"] --> B["ntdll.dll stub<br/>(normally: setup + syscall)"]
    B --> C{"EDR hook installed?<br/>(JMP patched at stub start)"}
    C -->|Yes| D["Detour to EDR DLL:<br/>inspect args, log, score, maybe block"]
    D --> E["EDR returns to original stub"]
    C -->|No| E
    E --> F["syscall instruction → kernel"]
    style D fill:#0c2a22,stroke:#21d48e,color:#d1fae5

To execute almost anything interesting, malware must eventually ask the kernel — allocate executable memory, change page protections, create threads, write to other processes. On Windows, every such request funnels through native API stubs in `ntdll.dll` (Nt*/Zw*), which set up a syscall number and execute the syscall instruction to enter the kernel.

EDRs want visibility into those requests with full context (arguments, call stack) before they hit the kernel. The cheapest way to get it from user mode is inline hooking: at process start, the EDR's injected DLL overwrites the first few bytes of sensitive ntdll functions with a JMP to its own handler. Now every NtAllocateVirtualMemory call detours through the EDR, which inspects, logs, scores, and optionally blocks — then jumps back to the real stub.

This works well but has an inherent weakness the entire bypass field exploits: the hook lives in the malware's own process memory, which the malware also controls. Anything in your address space you can read, write, and route around.

Bypass Family 1 — Direct Syscalls

If the hook sits at the start of the `ntdll` stub, you can skip the stub entirely: replicate what it does — load the syscall number into EAX and execute syscall yourself — without ever calling the hooked function.

asm
; What ntdll's NtAllocateVirtualMemory stub does (and what you replicate):mov r10, rcxmov eax, 0x18        ; syscall service number (SSN) for the functionsyscallret
text
TOOLING LINEAGESysWhispers / SysWhispers2/3   Generate syscall stubs + resolve SSNsHell's Gate                    Read the SSN dynamically from the (clean) stubHalo's Gate                    If the target stub is hooked, read a NEIGHBOUR                                 stub's SSN and compute the target's (stubs are                                 sequential) — defeats the hook entirelyTartarus' Gate / FreshyCalls   Further SSN-resolution refinements

The catch is that syscall numbers (SSNs) change between Windows versions, so hard-coding them is fragile. The "Gate" techniques solve this by reading SSNs dynamically at runtime: Hell's Gate reads the number from the clean stub; Halo's Gate handles the case where the stub is hooked by reading an adjacent, unhooked stub and computing the offset (since SSNs are assigned in memory order). Direct syscalls were the dominant bypass circa 2020–2022.

How defenders catch it: the giveaway is where the `syscall` instruction executes from. Legitimate syscalls originate from inside ntdll.dll's memory range; a direct syscall executes from your malware's own (non-ntdll) memory. EDRs added call-stack inspection and checks that the return address above a syscall lies within ntdll — so a syscall whose stack doesn't pass through ntdll is flagged. This is what motivated the next family.

Bypass Family 2 — Indirect Syscalls

To defeat the "syscall must come from ntdll" detection, indirect syscalls set up the SSN in your code but execute the actual syscall instruction by jumping to the real `syscall; ret` bytes inside `ntdll`. The stack now shows the syscall originating from ntdll, satisfying the EDR's origin check, while still bypassing the hook at the stub's entry.

asm
; Indirect: prepare SSN ourselves, but borrow ntdll's syscall;ret gadgetmov r10, rcxmov eax, <SSN>jmp [addr_of_syscall_ret_inside_ntdll]   ; the syscall executes "from ntdll"

This is the modern refinement of Family 1 (RecycledGate, SysWhispers3 -jumper mode, many C2 loaders). It re-establishes a plausible call origin and is currently common in mature offensive tooling.

Bypass Family 3 — Unhooking (Restore a Clean ntdll)

Instead of avoiding the hooked functions, remove the hooks and then call the APIs normally.

diagram — rendering…
flowchart TD
    A["EDR has patched ntdll .text in memory"] --> B["Obtain a CLEAN copy of ntdll"]
    B --> C["Map fresh ntdll from disk<br/>(\\KnownDlls, raw file read,<br/>or a suspended process)"]
    C --> D["Overwrite the hooked .text section<br/>with the clean bytes"]
    D --> E["Hooks gone → call APIs normally"]
    style E fill:#2a0c14,stroke:#ef233c,color:#fee2e2

Sources of a clean ntdll:

  • Read it from disk (C:\Windows\System32\ntdll.dll) — the on-disk copy is unhooked — and copy its .text over the in-memory, hooked .text.
  • `\KnownDlls\ntdll.dll` — map the cached section object, which is pristine.
  • Spawn a sandboxed/suspended process and read its fresh ntdll before the EDR injects (or from a process where injection is incomplete).
  • Perun's Fart / similar — read clean stubs from a freshly created suspended child before the EDR's DLL has hooked it.

After overwriting, the stubs are clean and ordinary API calls go straight to the kernel.

How defenders catch it: unhooking writes to `ntdll`'s `.text`. EDRs and the OS provide signals here — page-protection change events on a module's executable section, and integrity checks comparing in-memory .text against the on-disk image. The act of VirtualProtect-ing ntdll to writable, or a .text section that no longer matches disk, is itself highly suspicious. Some EDRs also re-hook periodically or detect the restore.

Bypass Family 4 — Hardware Breakpoints and Other Indirection

A stealthier approach avoids modifying any memory at all. Hardware breakpoint hooking uses the CPU's debug registers (DR0–DR7) to trap execution at a function and redirect it via a vectored exception handler — achieving hook-like control without patching bytes, and conversely letting malware detect and neutralise EDR's behaviour. The broader family also includes:

  • Call-stack spoofing — forge a benign-looking call stack (see the companion call-stack-spoofing article) so even if the EDR inspects the stack at a syscall, it sees a legitimate-looking chain.
  • Vectored Exception Handlers (VEH) to reroute control around hooks via deliberate exceptions.
  • Module stomping / proxying — execute from within a legitimate, signed module's memory so the origin checks pass.

These exist precisely because Families 1–3 each created a detection signal; the frontier is achieving the bypass while also defeating the meta-detections (origin checks, memory-write events).

The Defensive Reality: Hooks Were Never the Whole Story

text
USER-MODE HOOKS         vs        KERNEL / EXTERNAL TELEMETRYin malware's memory               outside malware's controlpatchable, readable               ETW (Threat Intelligence), kernel callbacksbypassable by all the above       Microsoft-Vista+ kernel notify routines:                                    PsSetCreateProcessNotifyRoutine,                                    ObRegisterCallbacks (handle ops),                                    image-load & thread-create callbacks                                  Hard for user-mode malware to evade

The single most important point for blue teams: mature EDRs do not rely on user-mode hooks alone. Hooks are convenient but live in attacker-controlled memory, so they are best treated as a first sensor, not the only one. The durable telemetry comes from places malware in user mode cannot patch:

  • Kernel callbacks — PsSetCreateProcessNotifyRoutineEx, PsSetCreateThreadNotifyRoutine, PsSetLoadImageNotifyRoutine, and ObRegisterCallbacks give the EDR kernel-side notification of process/thread creation, image loads, and handle operations regardless of any user-mode trickery.
  • ETW (Event Tracing for Windows), especially the Threat Intelligence provider, surfaces sensitive operations (memory allocation/protection changes, certain syscalls) from the kernel. (Attackers respond by patching ETW in their own process — EtwEventWrite — which is itself a detectable, suspicious act.)
  • Kernel-mode syscall and behavioural monitoring — the syscall arrives at the kernel no matter how you launched it; EDRs increasingly correlate the kernel-observed action with the (absent or anomalous) user-mode context.

So every user-mode bypass above succeeds at the user layer but tends to generate a different anomaly the EDR can detect from outside the process: a syscall with no ntdll on the stack, a .text write to ntdll, an allocation of RWX memory, ETW gaps, or a mismatch between user-mode and kernel-observed behaviour.

Detection Guidance for Blue Teams

diagram — rendering…
flowchart TD
    A["Don't trust user-mode hooks alone"] --> B["Kernel callbacks for process/thread/image/handle events"]
    A --> C["ETW Threat-Intel provider for memory ops"]
    A --> D["Flag syscalls whose return addr ∉ ntdll<br/>(direct-syscall tell)"]
    A --> E["Flag writes / protection changes to ntdll .text<br/>(unhooking tell)"]
    A --> F["Flag RWX allocations + thread creation patterns"]
    A --> G["Detect ETW/AMSI self-patching in a process"]
    style A fill:#0c2a22,stroke:#21d48e,color:#d1fae5
  • Inspect call stacks at syscall/sensitive events — a syscall originating outside ntdll, or a stack that skips ntdll, indicates direct/indirect syscall abuse or stack spoofing.
  • Monitor `ntdll` `.text` integrity — protection changes to or writes into a system DLL's code section are a strong unhooking signal; compare in-memory code to the on-disk image.
  • Lean on kernel telemetry — register the kernel callbacks and consume the ETW Threat-Intelligence provider so detection doesn't depend on patchable hooks.
  • Detect tampering with the sensors themselves — ETW patching (EtwEventWrite/NtTraceEvent patched in-process) and AMSI patching are themselves high-fidelity indicators of evasion.
  • Correlate behaviours, not single calls — RWX allocation → write → remote thread/APC is a sequence that survives any single-API bypass.
  • Assume bypass and hunt the anomaly — treat the absence of expected user-mode events (a process doing kernel-visible things with no corresponding hook telemetry) as suspicious in itself.

Perun's Fart: NtCreateSection + NtMapViewOfSection Fresh Copy

The canonical "Perun's Fart" technique does not read ntdll.dll from disk at all — a file-read would generate IRP_MJ_CREATE telemetry visible to the EDR's kernel-mode driver. Instead, it obtains a clean copy by opening the `\KnownDlls\ntdll.dll` section object that the Windows Object Manager pre-populates at boot. This section is a shared memory-mapped copy of the unhooked ntdll, available to any process via NtOpenSection. The full sequence uses only two native calls: NtCreateSection (or NtOpenSection for KnownDlls) and NtMapViewOfSection.

One of the stealthiest unhooking approaches avoids reading ntdll.dll from disk (which generates file-access telemetry) by mapping a clean view from the KnownDlls section object instead. This technique, popularized as "Perun's Fart," uses the Object Manager namespace directly:

c
/* * Perun's Fart: map ntdll from KnownDlls section object * instead of reading from disk — no file-read telemetry */NTSTATUS UnhookViaKnownDlls(void) {    UNICODE_STRING sectionName;    RtlInitUnicodeString(&sectionName, L"\\KnownDlls\\ntdll.dll");     OBJECT_ATTRIBUTES oa;    InitializeObjectAttributes(&oa, &sectionName,                                OBJ_CASE_INSENSITIVE, NULL, NULL);     HANDLE hSection = NULL;    NTSTATUS st = NtOpenSection(&hSection, SECTION_MAP_READ, &oa);    if (!NT_SUCCESS(st)) return st;     // Map a read-only view of the clean ntdll    PVOID pCleanNtdll = NULL;    SIZE_T viewSize   = 0;    st = NtMapViewOfSection(hSection, GetCurrentProcess(),                             &pCleanNtdll, 0, 0, NULL, &viewSize,                             ViewUnmap, 0, PAGE_READONLY);    NtClose(hSection);    if (!NT_SUCCESS(st)) return st;     // Get .text section of clean copy    PIMAGE_DOS_HEADER pDos   = (PIMAGE_DOS_HEADER)pCleanNtdll;    PIMAGE_NT_HEADERS pNt    = (PIMAGE_NT_HEADERS)((BYTE*)pCleanNtdll + pDos->e_lfanew);    PIMAGE_SECTION_HEADER pSec = IMAGE_FIRST_SECTION(pNt);    for (WORD i = 0; i < pNt->FileHeader.NumberOfSections; i++, pSec++) {        if (memcmp(pSec->Name, ".text", 5) == 0) {            PVOID pHookedText  = (BYTE*)GetModuleHandleW(L"ntdll.dll") + pSec->VirtualAddress;            PVOID pCleanText   = (BYTE*)pCleanNtdll + pSec->VirtualAddress;            DWORD oldProt;            VirtualProtect(pHookedText, pSec->Misc.VirtualSize, PAGE_EXECUTE_WRITECOPY, &oldProt);            memcpy(pHookedText, pCleanText, pSec->Misc.VirtualSize);            VirtualProtect(pHookedText, pSec->Misc.VirtualSize, oldProt, &oldProt);            break;        }    }    NtUnmapViewOfSection(GetCurrentProcess(), pCleanNtdll);    return STATUS_SUCCESS;}

Why it's stealthier: opening a section object via NtOpenSection on \KnownDlls\ntdll.dll does not generate an IRP_MJ_CREATE (file-open) event — there is no disk read. The clean copy comes from shared memory mapped at system boot.

The remaining detectable event is the VirtualProtect call that flips .text from PAGE_EXECUTE_READ to PAGE_EXECUTE_WRITECOPY before overwriting. An EDR monitoring page-protection change callbacks (MmProtectMdlSystemAddress or via its kernel hook on NtProtectVirtualMemory) will see a protection change on a system DLL's code section — a high-fidelity signal even without observing the file access that would accompany a disk-based unhook.

Hardware Breakpoint-Based Hook Detection

Hardware breakpoints use the CPU's debug registers (DR0–DR3 for addresses, DR7 for control) to trap execution at specific addresses without modifying any code. This capability is normally used by debuggers, but it can be repurposed by both attackers and defenders.

Setting Hardware Breakpoints via SetThreadContext

An attacker or analyst can place a hardware breakpoint on a function (e.g. NtAllocateVirtualMemory) by writing its address into a debug register through SetThreadContext / NtSetContextThread. When the CPU reaches that address, it fires a single-step debug exception which is caught by a registered Vectored Exception Handler (VEH):

c
// Place a hardware breakpoint on NtAllocateVirtualMemory// without modifying any bytes in ntdll's .text section#include <windows.h> LONG WINAPI HWBPHandler(PEXCEPTION_POINTERS ep) {    if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_SINGLE_STEP) {        PCONTEXT ctx = ep->ContextRecord;        // Check which DR fired (DR6 status register)        if (ctx->Dr6 & 0x1) {            // DR0 fired → NtAllocateVirtualMemory was called            // Inspect ctx->Rcx (first arg: process handle), etc.            // Optionally redirect or log, then clear the status            ctx->Dr6 = 0;            return EXCEPTION_CONTINUE_EXECUTION;        }    }    return EXCEPTION_CONTINUE_SEARCH;} void SetHWBreakpointOnNtAlloc(void) {    AddVectoredExceptionHandler(1, HWBPHandler);     CONTEXT ctx = {0};    ctx.ContextFlags = CONTEXT_DEBUG_REGISTERS;    GetThreadContext(GetCurrentThread(), &ctx);     // DR0 = address of NtAllocateVirtualMemory in ntdll    ctx.Dr0 = (DWORD64)GetProcAddress(GetModuleHandleW(L"ntdll.dll"),                                       "NtAllocateVirtualMemory");    ctx.Dr7 = 0x1;          // enable DR0 as a local execute breakpoint    ctx.ContextFlags = CONTEXT_DEBUG_REGISTERS;    SetThreadContext(GetCurrentThread(), &ctx);}

Detecting Inline Hooks at Specific Addresses

The same mechanism lets malware detect whether the EDR has placed an inline hook at a target function: instead of inspecting the bytes of the stub directly (which an EDR might detect), the malware sets a hardware breakpoint just past the expected stub prologue and checks whether the single-step fires or whether it is instead redirected to the EDR handler (indicating a hook redirect consumed the execution before the breakpoint address was reached).

Hardware breakpoint usage by non-debugger processes is itself suspicious — NtSetContextThread calls that set DR0–DR3 from a non-debug process, or GetThreadContext polling of debug registers, are detectable via kernel callbacks on thread context modification.

Kernel Callbacks: The True Detection Surface

Even after successfully removing every user-mode hook, the EDR's kernel-mode driver retains detection capability through kernel callback registration — a set of APIs that the OS provides to kernel drivers to receive synchronous or asynchronous notifications of system events. These fire regardless of any user-mode manipulation.

The Four Critical Callback Types

c
// Kernel driver registration — happens once when the EDR driver loads// (simplified; real registration includes proper error handling) // 1. Process creation/terminationPsSetCreateProcessNotifyRoutineEx(OnProcessCreateEx, FALSE); // 2. Thread creation/termination  PsSetCreateThreadNotifyRoutine(OnThreadCreate); // 3. Image (DLL/EXE) load notificationPsSetLoadImageNotifyRoutine(OnImageLoad); // 4. Object (handle) operation callbacks — watch for OpenProcess/OpenThreadOB_CALLBACK_REGISTRATION reg = { ... };ObRegisterCallbacks(&reg, &hRegistration);

Each of these is a kernel-mode callback — user-mode malware cannot suppress or redirect them. They fire even if the entire ntdll hook layer is removed, even if ETW is patched in the user-mode process, and even if call stacks are spoofed.

What Each Callback Exposes

CallbackAPIWhat EDR Sees
Process creationPsSetCreateProcessNotifyRoutineExNew process PID, parent PID, image path, command line — fires synchronously before the process runs
Thread creationPsSetCreateThreadNotifyRoutineThread created in ANY process (including remote thread injection) — CreateRemoteThread is always visible
Image loadPsSetLoadImageNotifyRoutineEvery DLL loaded into any process, with the image's full path and base address — shellcode that reflectively loads a DLL triggers this
Handle operationsObRegisterCallbacks (pre/post)OpenProcess(PROCESS_VM_WRITE, ...) — the most common injection precursor — fires this callback before the handle is returned

The ObRegisterCallbacks for handle operations is particularly powerful: an EDR can modify the access rights on a handle before it reaches the caller. If malware calls OpenProcess with PROCESS_ALL_ACCESS, the EDR's callback can strip sensitive rights like PROCESS_VM_WRITE and PROCESS_CREATE_THREAD before returning the handle — making the injection impossible without the malware ever knowing a callback fired.

Why Unhooking Does Not Defeat Kernel Callbacks

A common misconception: "if I restore ntdll and bypass the EDR's user-mode hooks, I'm invisible." This is false. The kernel callbacks listed above are registered by the EDR's kernel-mode driver — a component that runs in Ring 0 and is entirely outside the malware's process address space. The malware cannot reach it, cannot patch it, and cannot disable it without a separate kernel vulnerability. Even Perun's Fart, indirect syscalls, and hardware-breakpoint hook detection are all user-mode techniques that leave kernel-visible footprints:

  • Indirect syscall → the syscall instruction reaches the kernel; NtAllocateVirtualMemory executes and is visible to ETW Threat Intelligence.
  • Unhooking → the NtProtectVirtualMemory call (to make .text writable) is itself a syscall the kernel sees, and the image-load callback fires on any subsequently loaded DLL.
  • Thread injection → PsSetCreateThreadNotifyRoutine fires for every NtCreateThreadEx, regardless of how it was invoked.

The arms race therefore asymptotically favours the kernel: each user-mode bypass technique creates a different kernel-observable anomaly — an anomaly that only grows more detectable as EDRs invest in correlating user-mode absence with kernel-observed presence.

Bypass Technique Comparison

TechniqueHooks Bypassed?EDR Telemetry LeftDifficultyDetectable?
Direct syscalls (Hell's Gate)Yes (user-mode only)Syscall without ntdll on call stackMediumYes — call stack check
Indirect syscallsYesSyscall originates from ntdll gadgetMediumHarder — stack looks legitimate
Overwrite ntdll from diskYesFile read of ntdll.dll + .text writeLowYes — file access + section write
KnownDlls section map (Perun)YesSection object open, .text writeMediumYes — .text integrity check
Hardware breakpointsPartialSetThreadContext DR register useHighDifficult — no code patched
ETW/AMSI patchPartial (logging blind)Self-patching in process memoryLowYes — function byte modification

MITRE ATT&CK Mapping

TechniqueATT&CK IDDescription
Process InjectionT1055Injecting code into other processes after bypassing hooks
Defense Evasion: Unhook System DLLT1562.001Restoring hooked ntdll exports to remove EDR visibility
Defense Evasion: Direct SyscallsT1106Issuing system calls without going through ntdll
Impair Defenses: Disable or Modify ToolsT1562Bypassing EDR hook layer and ETW instrumentation
Reflective Code LoadingT1620Loading shellcode in memory after bypassing user-mode detection

Conclusion and Takeaways

User-mode hooking is how EDRs cheaply gain rich, contextual visibility into the native API calls malware must make — but it carries an inherent flaw: the hooks live inside the monitored process's own memory, which the malware can read, write, and route around. The proliferation of bypass techniques — from Hell's Gate and Halo's Gate for dynamic syscall number resolution, to KnownDlls-based ntdll restoration that avoids file telemetry, to hardware-breakpoint indirection that requires no memory patching at all — reflects an arms race that fundamentally cannot be won at the user-mode layer alone. That flaw spawned a well-developed bypass field with four mainstream families: direct syscalls (replicate the ntdll stub and execute syscall yourself, with the Gate techniques resolving syscall numbers dynamically), indirect syscalls (borrow ntdll's own syscall gadget so the call origin looks legitimate), unhooking (overwrite the patched ntdll .text with a clean copy from disk/KnownDlls and call normally), and hardware-breakpoint/indirection methods (control flow without patching any bytes). Each evades the hooks at the user layer.

The decisive insight, and the one that should shape any defensive program, is that the hooks were never meant to stand alone. Every bypass above leaves a different footprint visible from outside the process — a syscall with no ntdll on the call stack, a write or protection change to a system DLL's code, an RWX allocation feeding a remote-thread injection, an ETW gap, or self-patching of the sensors themselves. Mature EDRs therefore anchor detection in kernel callbacks and ETW telemetry that user-mode malware cannot patch, and treat user-mode hooks as one early sensor among many. For red teamers, the lesson is that bypassing the hook is the easy part and avoiding the meta-detection is the real challenge; for defenders, it is to never trust the hooks alone, instrument the kernel, watch for the anomalies each bypass creates, and correlate behaviour rather than chase individual API calls. A mature detection program treats hook telemetry as one data source among many — valuable for context and first-pass triage, but never the last word on whether a process is malicious. The kernel always sees the truth; invest in reading it.