TL;DR — When an EDR installs user-mode hooks inntdll.dll, it patches the first bytes of native API stubs withJMPinstructions that detour calls through the vendor's inspection code. Unhooking restores those bytes to their original, unpatched state — after which API calls route cleanly to the kernel with no interception. This article covers the mechanics of inline hook installation, three categories of fresh-ntdllsourcing (disk read,KnownDllssection mapping, andNtCreateSection-from-a-clean-child), the overwrite procedure, common detection artefacts each variant leaves, and the defensive telemetry that observes them.
Executive Summary
Every API call a process makes to the native layer — NtAllocateVirtualMemory, NtCreateThread, NtWriteVirtualMemory — passes through a small stub inside ntdll.dll. At its simplest, that stub loads a syscall service number into EAX and executes the syscall instruction to enter the kernel. Security products gain visibility into those calls by patching the first 5–12 bytes of each stub with a `JMP` to their own handler, diverting every call through inspection logic before it reaches the kernel.
The unhooking idea is elegant: obtain a copy of ntdll.dll that was never tampered with, and overwrite the patched bytes with the original bytes. After the restoration, the stub functions exactly as it did before the EDR touched it — calls flow straight to the kernel with no interception. This is not an exotic trick; it was independently described by numerous researchers and is implemented in most mature C2 frameworks and loaders. Understanding it precisely — including where each variant leaves traces — is what allows detection engineers to build the telemetry that catches it.
What an Inline Hook Looks Like
When a process starts on a Windows host with an EDR, the vendor's injected DLL (edr_hook.dll) locates the target stubs in the process's already-mapped ntdll and patches them:
; CLEAN stub (NtAllocateVirtualMemory, x64)4C 8B D1 mov r10, rcxB8 18 00 00 00 mov eax, 0x18 ; syscall service number0F 05 syscallC3 ret ; HOOKED stub (EDR replaces first 5–12 bytes)FF 25 00 00 00 00 jmp qword ptr [rip+0] ; 6-byte near/far JMP<EDR handler addr> ; the inspection function<remaining original bytes, unused>The JMP lands in the EDR's DLL, which logs arguments, evaluates the call against a behavioural model, optionally blocks, and then calls the original stub (kept in a "trampoline" region) to complete the API call. Every NtAllocateVirtualMemory call now traverses the EDR's inspection logic regardless of what the calling code does.
The hook lives in the process's own address space, in a region (ntdll's .text section) the process has read access to and — crucially — can also write to if it first changes the page protection.
Obtaining a Clean ntdll
To unhook, the operator needs the original, unpatched bytes. Three sourcing strategies exist, each with different properties:
flowchart TD
A["Need: clean ntdll bytes"] --> B["1. Read from disk<br/>C:\\Windows\\System32\\ntdll.dll"]
A --> C["2. Map \\KnownDlls\\ntdll<br/>(cached section object)"]
A --> D["3. Spawn suspended child<br/>read ntdll BEFORE EDR hooks it"]
B --> E["Pros: simple<br/>Cons: may be MONITORED file path;<br/>EDR can hook NtReadFile too"]
C --> F["Pros: object section, no disk read<br/>Cons: EDR may also patch KnownDlls view"]
D --> G["Pros: definitely pre-hook<br/>Cons: process-creation noise;<br/>'Perun's Fart' variant uses NtCreateUserProcess timing"]
style A fill:#2a0c14,stroke:#ef233c,color:#fee2e2Strategy 1 — Read from Disk
Open the real ntdll.dll file as a data file, parse the PE, locate the .text section, and use those bytes to overwrite the in-memory, hooked .text. The disk copy is never patched by the EDR; it reflects the vendor's original .text.
// Pseudocode — simplified for clarityHANDLE hFile = CreateFileW(L"C:\\Windows\\System32\\ntdll.dll", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);// ... parse PE headers, locate .text offset & size ...// VirtualProtect(ntdll_text_in_memory, size, PAGE_EXECUTE_READWRITE, &old)// memcpy(ntdll_text_in_memory, file_text_data, size)// VirtualProtect(ntdll_text_in_memory, size, old, &dummy)Detection artefact: a VirtualProtect call changing a system DLL's .text section to writable is rare in benign code and is directly observable via ETW and EDR kernel callbacks. The CreateFile on ntdll.dll itself is also a logged operation, though common enough to require correlation.
Strategy 2 — Map from \KnownDlls\ntdll
Windows caches a pre-mapped section of ntdll in the \KnownDlls object directory for fast loader use. Opening and mapping this section gives a view of the clean image:
UNICODE_STRING name = RTL_CONSTANT_STRING(L"\\KnownDlls\\ntdll.dll");OBJECT_ATTRIBUTES oa = { sizeof(oa), NULL, &name, OBJ_CASE_INSENSITIVE };HANDLE hSection;NtOpenSection(&hSection, SECTION_MAP_READ | SECTION_QUERY, &oa);PVOID mappedView = NULL; SIZE_T viewSize = 0;NtMapViewOfSection(hSection, GetCurrentProcess(), &mappedView, ...);// parse the mapped view, extract .text, overwrite the live ntdllNtUnmapViewOfSection(GetCurrentProcess(), mappedView);This avoids a CreateFile on the path — but the NtOpenSection / NtMapViewOfSection calls are still visible, and if the EDR also patched the cached section (some do), the bytes may themselves be hooked.
Strategy 3 — Suspended Child (Perun's Fart Pattern)
Create a child process suspended before the EDR's DLL has had a chance to inject and hook. Map the child's ntdll view — which is still clean at that moment — read the .text bytes, and use them to patch the parent's hooked ntdll. Terminate the child.
This is the most "atomic" source of clean bytes, since the child's ntdll provably existed before any hook installation. The cost is the process-creation event, which is logged regardless.
The Overwrite Procedure
Regardless of the source, the overwrite follows the same structure:
sequenceDiagram
participant L as Loader (malware)
participant N as ntdll.dll (in-memory, hooked)
participant S as Source (disk / KnownDlls / child)
L->>S: Read/map clean .text bytes
L->>N: VirtualProtect(.text → RWX or RW) ← detection signal
L->>N: memcpy(hooked .text ← clean bytes) ← detection signal
L->>N: VirtualProtect(.text → RX, restored)
Note over N: hooks removed; API calls flow straight to kernelThe two mandatory syscalls — protecting and then writing to .text — are the structural tells. A page-protection change on any system DLL's code section is highly anomalous; a subsequent write to that section confirms the act.
Perils and Partial Unhooking
A naive full-.text overwrite restores every hooked stub, which is thorough but noisy. Targeted approaches only restore the specific stubs the operator needs:
// Targeted: overwrite only the first 8 bytes of NtAllocateVirtualMemory// rather than the entire .text section — fewer bytes written, same effect// for that one function.PVOID stubAddr = GetProcAddress(GetModuleHandleA("ntdll.dll"), "NtAllocateVirtualMemory");VirtualProtect(stubAddr, 8, PAGE_EXECUTE_READWRITE, &old);memcpy(stubAddr, cleanBytes, 8);VirtualProtect(stubAddr, 8, old, &dummy);Targeted overwriting limits the blast radius of the protection-change event and is harder to detect than overwriting megabytes of .text — though the detection signal (RW on system DLL code, bytes changed) is identical in nature.
What Doesn't Get Unhooked
User-mode hooks in ntdll are only part of the detection stack. Unhooking removes the user-mode interception layer, but it cannot touch:
NOT REACHABLE BY UNHOOKINGKernel-mode syscall handlers → kernel callbacks fire regardless of hook stateETW Threat-Intelligence provider → fires from the kernel, not ntdllPsSetCreateProcessNotifyRoutine → kernel callback, per-process, hook-independentObRegisterCallbacks (handles) → sameImage-load notifications → sameMemory-scanning / call-stack checks done out-of-process by the EDR serviceAn unhooking operator who then does something behaviorally anomalous — allocates RWX memory, creates a remote thread, spawns an unexpected child — still generates kernel-visible events. Unhooking buys silence on the first sensor layer; the deeper layers remain.
Detection Guidance
flowchart TD
A["Detecting ntdll unhooking"] --> B["Flag VirtualProtect on any<br/>system DLL .text (PAGE_EXECUTE_READWRITE<br/>or PAGE_EXECUTE_WRITECOPY)"]
A --> C["Compare in-memory .text of ntdll<br/>to disk image: byte diff = tampered"]
A --> D["ETW: page-protection change + write<br/>sequence on a loaded module region"]
A --> E["Detect NtOpenSection(\\KnownDlls\\ntdll)<br/>followed by NtMapViewOfSection in<br/>a process that's not the loader"]
style A fill:#0c2a22,stroke:#21d48e,color:#d1fae5- Alert on protection changes to system DLL code sections.
VirtualProtect(or the underlyingNtProtectVirtualMemory) targeting the.textofntdll.dll,kernel32.dll, or any signed system module with aPAGE_EXECUTE_WRITE*flag is an excellent high-fidelity signal; legitimate software almost never does this. - Continuously compare in-memory `.text` to on-disk or known-good bytes. Tools like PE-sieve, Hollows Hunter, and EDR memory inspection engines detect the byte-level discrepancy. The absence of hooks (all stubs look like clean
mov eax; syscall) is itself a signal if the EDR inserted hooks at startup and they later disappeared. - ETW + kernel callbacks provide hook-independent visibility. Because the purpose of unhooking is to evade the hooks, detection must not depend on the hooks. Instrument through ETW and kernel callbacks so that a successful unhook generates anomalous absence of user-mode telemetry alongside continued kernel-level observations — the mismatch is the tell.
- Watch the precursor reads.
NtOpenSection/NtMapViewOfSectionon\KnownDlls\ntdll.dllby a non-loader process, orCreateFile/ReadFileonSystem32\ntdll.dllfrom a process that has no business reading system DLLs, are useful precursor signals.
Alternative Approaches: Hardware Breakpoints and Kernel Patching
Unhooking via .text overwrite is the most common approach but is not the only one. Researchers have developed alternative strategies that achieve the same "bypass the hook" goal while avoiding the high-signal memory-write event.
Hardware Breakpoint Hooks
Modern x86 CPUs include four debug registers (DR0–DR3) that each record a memory address and a condition type (execute, read/write). When execution reaches a DR-configured address, the CPU raises a #DB (debug) exception rather than running that instruction. A process can install a Vectored Exception Handler (VEH) to catch that exception and redirect execution — effectively building a software-invisible hook.
// Install a hardware breakpoint on a hooked stub via a VEH// Step 1: set DR0 to the address of the hooked functionCONTEXT ctx = {0};ctx.ContextFlags = CONTEXT_DEBUG_REGISTERS;GetThreadContext(GetCurrentThread(), &ctx);ctx.Dr0 = (DWORD64)GetProcAddress(GetModuleHandleA("ntdll"), "NtAllocateVirtualMemory");ctx.Dr7 = 0x1; // enable DR0 for local exec breakpointSetThreadContext(GetCurrentThread(), &ctx); // Step 2: VEH catches EXCEPTION_SINGLE_STEP, checks if eip == DR0 addr,// redirects to a trampoline that executes the original syscallAddVectoredExceptionHandler(1, MyVehHandler);flowchart TD
A["Code calls NtAllocateVirtualMemory"] --> B["CPU reaches DR0 address<br/>(hooked stub start)"]
B --> C["EXCEPTION_SINGLE_STEP fires<br/>before the JMP executes"]
C --> D["VEH handler intercepts"]
D --> E["Handler: emits syscall directly<br/>or jumps to clean trampoline"]
E --> F["EDR hook JMP never executes"]
style C fill:#1a230c,stroke:#fca311,color:#fef3c7
style F fill:#2a0c14,stroke:#ef233c,color:#fee2e2The critical property: no bytes in `ntdll` are modified. The hook is still there; it is simply never reached because the CPU exception fires first. This means none of the page-protection-change or .text write signals fire — the artefact that detectors look for is absent. The cost is complexity: VEH-based redirection requires careful handling of multi-threaded environments (DR registers are per-thread in 32-bit, and DR7 scope is local), and exception-heavy code paths can trigger AV/EDR heuristics that monitor for unusual vectored exception activity.
Detection engineering against this variant focuses on:
- Processes registering a VEH shortly after startup (rare in benign software).
- Debug-register state being set on a thread that is not being debugged (
DR7 != 0with no debugger attached). - The
SetThreadContext/NtSetContextThreadcall with aCONTEXT_DEBUG_REGISTERSmask — a low-frequency event that EDR kernel callbacks surface even with no memory writes.
Kernel-Level Patching (Shadow SSDT / Filter Drivers)
At the extreme end, sophisticated implants move the bypass to kernel mode — beyond the reach of user-mode EDR hooks entirely. A kernel driver can:
- Replace SSDT entries (Shadow SSDT patching, applicable to 32-bit Windows; kernel PatchGuard blocks direct SSDT replacement on x64 but drivers can use other intercept points).
- Install a filter driver that intercepts I/O requests or kernel calls before the EDR's kernel driver sees them.
- Hook SSDT via a KPP-aware technique — bypassing Kernel Patch Protection through timing windows, hypervisor exploitation, or signed driver abuse.
These approaches are the province of advanced, signed-driver-level malware and state-level tooling. They are noted here because the escalation path exists: when user-mode unhooking is detected, a well-resourced actor moves down the stack. Detection at this level requires Hypervisor-based Introspection (HVI) — running an EDR component below the OS level (e.g. in a Type-1 hypervisor) so that kernel-level tampering is itself observed from a privileged vantage point the malware cannot reach.
Detecting Unhooking Attempts: Sysmon and ETW Queries
Operationalising unhooking detection in a real SOC requires concrete queries and event mappings. Below are detection approaches across common telemetry sources.
Sysmon Event ID 10 — VirtualProtect on System Modules
Sysmon does not directly log VirtualProtect calls, but Process Access events (Event ID 10) with OpenProcess targeting a process that subsequently writes to system module memory can be correlated. More directly, Microsoft-Windows-Threat-Intelligence ETW provider (Microsoft-Windows-Threat-Intelligence) surfaces VirtualProtect calls with full module/address context.
<!-- Sysmon config: catch self-injection patterns near ntdll --><RuleGroup name="Unhooking - VirtualProtect on system DLL" groupRelation="or"> <ProcessAccess onmatch="include"> <!-- Catch a process reading ntdll.dll from disk (precursor read) --> <TargetImage condition="is">C:\Windows\System32\ntdll.dll</TargetImage> </ProcessAccess></RuleGroup>ETW Threat-Intelligence Provider Queries (KQL / Sentinel)
// Azure Sentinel / Microsoft Defender for Endpoint KQL// Flag VirtualProtect on ntdll .text from a non-system processDeviceEvents| where ActionType == "MemoryProtectionChanged"| where InitiatingProcessFolderPath !startswith "C:\\Windows\\"| where AdditionalFields.TargetModule contains "ntdll"| where AdditionalFields.NewProtection in ("PAGE_EXECUTE_READWRITE", "PAGE_EXECUTE_WRITECOPY")| project Timestamp, DeviceName, InitiatingProcessFileName, InitiatingProcessCommandLine, AdditionalFields| order by Timestamp desc// Detect KnownDlls section mapping by non-loader processesDeviceEvents| where ActionType == "OpenSection"| where AdditionalFields.ObjectName == "\\KnownDlls\\ntdll.dll"| where InitiatingProcessFolderPath !startswith "C:\\Windows\\System32\\"| project Timestamp, DeviceName, InitiatingProcessFileName, InitiatingProcessCommandLineCompound Indicator: Absence of Hook Telemetry
The most powerful long-term signal is not a single event but a pattern mismatch: a process that continues to make kernel-visible allocations, thread creations, and memory writes — yet the user-mode telemetry stream from that process has gone quiet. This requires baselining expected hook-derived event rates per process type and alerting on:
COMPOUND INDICATORProcess X has: - Made N user-mode-hook-logged API calls in the last 5 minutes - Then: zero hook-logged calls for 30 seconds - But: kernel callbacks still recording process/thread activity - And: an ETW memory-protection event fired on ntdll 30 seconds ago→ HIGH-CONFIDENCE unhooking followed by continued operationImplementing this requires correlating two streams: hook-derived (user-mode) events and kernel-callback events, looking for the moment the hook stream drops while kernel activity continues.
| Detection Method | Signal Quality | Requires |
|---|---|---|
| VirtualProtect on system DLL .text | Very High | ETW TI / EDR kernel callback |
| Byte diff: in-memory vs on-disk ntdll | Very High | Periodic memory scanning (PE-sieve) |
| KnownDlls section open by non-loader | High | Object access auditing |
| CreateFile on ntdll.dll by user process | Medium | File auditing |
| VEH registration at process start | Medium | SetThreadContext / NtSetContextThread monitoring |
| Absence of hook telemetry + kernel activity | Very High (compound) | Dual-stream correlation |
Conclusion and Takeaways
Unhooking ntdll.dll is the direct counter to EDR user-mode hooks: obtain the original, unpatched bytes — from disk, from the \KnownDlls object, or from a suspended child's not-yet-hooked view — change the page protection on the live ntdll's .text section, overwrite the patched stubs with clean bytes, restore protection, and call APIs normally. The technique is straightforward because the hooks live in the attacker's own address space; the attacker has the same memory-manipulation rights as the EDR that installed the hooks.
Alternative approaches — hardware breakpoints that intercept before the hook JMP fires, kernel-level filter drivers, or SSDT manipulation — escalate the bypass into territory that .text overwrite detection cannot reach, but they carry their own detection surfaces (debug-register manipulation, kernel driver signatures, Hypervisor-based Introspection).
What keeps every unhooking variant visible is the detection architecture below the user-mode layer. The protection change on a system DLL's code section is an anomalous, observable event; the byte-level discrepancy between in-memory and on-disk .text is a persistent artefact; and the kernel-level telemetry — ETW, process/handle/image callbacks — fires regardless of what happens to ntdll's stubs. For the detection engineer, the practical takeaway is to treat unhooking not as a worst-case failure of visibility but as its own detection opportunity: the act of restoring ntdll is noisier than the API calls the attacker is trying to hide, and the absence of expected hook telemetry alongside continued kernel-level behaviour is a reliable compound indicator. Build the telemetry at every layer, and unhooking transitions from an evasion into a beacon.