Skip to content

hooks: add Thread Name-Calling and TP_DIRECT.Callback hijack coverage - #255

Open
doomedraven wants to merge 1 commit into
kevoreilly:capemonfrom
doomedraven:feat/tnc-and-tp-direct-injection
Open

doomedraven wants to merge 1 commit into
kevoreilly:capemonfrom
doomedraven:feat/tnc-and-tp-direct-injection

Conversation

@doomedraven

@doomedraven doomedraven commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Adds API hook, handle-tracking, and payload-extraction coverage for cross-process Thread Name-Calling (TNC) delivery and TP_DIRECT.Callback thread-pool I/O completion hijacking (as used by loaders such as Maldev-Academy/WhisperLoader and PoolParty Variant 8):

  1. Thread Name-Calling (ThreadNameInformation = 0x26) (ntapi.h, hook_thread.c):

    • Extends THREADINFOCLASS up to ThreadNameInformation (0x26), pinned by C_ASSERT(ThreadNameInformation == 0x26).
    • New_NtSetInformationThread (injector side): snapshots UNICODE_STRING thread-name buffers (IsReadableLocalBuffer via VirtualQuery, preserving lasterror_t and disable_count), invokes ProcessMessage(pid, 0) on cross-process targets, logs a single LOQ_ntstatus record (ThreadName raw 'b' buffer preserving embedded 0x00 bytes and odd lengths) when cross-process, suspicious (IsSuspiciousThreadNameBuffer: odd byte length, >= 256 bytes, embedded 0x0000 WCHAR, invalid UTF-16 surrogates, 0xFFFE/0xFFFF, or C0 control units), or full_logs, and dumps raw payloads (INJECTION_SHELLCODE / UNPACKED_SHELLCODE, FNV-1a deduplicated and capped at 16 dumps).
    • New_NtQueryInformationThread (target side): inspects returned ThreadNameInformation UNICODE_STRING buffers on NT_SUCCESS(ret) and dumps binary/suspicious buffers via DumpThreadNameBuffer. When an unmonitored injector queues kernelbase!GetThreadDescription(NtCurrentThread(), ...) as a remote APC inside a monitored target, GetThreadDescription invokes ntdll!NtQueryInformationThread(ThreadNameInformation) through the target's hooked ntdll.dll, capturing the raw stashed TNC payload on the target side.
  2. Cross-process TP_DIRECT.Callback & IoCompletion hijack (hook_misc.c, hook_sync.c, CAPE/Injection.{h,c}, hooks.{h,c}):

    • New_NtDuplicateObject / New_NtClose: tracks handles duplicated from foreign processes into the current process (remote_handle_set / remote_handle_clear / remote_handle_get_pid in a spinlock-guarded lookup_t, overwritten/cleared on NtClose to handle kernel handle reuse safely) and registers foreign processes via OpenProcessHandler.
    • New_NtSetIoCompletion / New_NtSetIoCompletionEx:
      • Cross-process: when IoCompletionHandle maps to a foreign remote_pid, notifies ProcessMessage(remote_pid, 0), reads remote [KeyContext + TP_DIRECT_CALLBACK_OFFSET] (+0x38 on x64, +0x28 on x86) via ReadProcessMemory, and dumps non-MEM_IMAGE committed executable regions (DumpRemoteExecutableRegion, skipping legitimate ntdll MEM_IMAGE callbacks).
      • Same-process: safely probes [KeyContext + TP_DIRECT_CALLBACK_OFFSET] via VirtualQuery in addition to KeyContext/ApcContext and forwards LocalCallback to NewThreadHandler (&TP_DIRECT sits on the heap, so NewThreadHandler(KeyContext) alone previously missed in-process TP_DIRECT.Callback shellcode).
    • Hooks TpAllocAlpcCompletion and TpAllocJobNotification alongside TpAllocIoCompletion.
  3. APC argument visibility, NtAlertThread, remote NtProtectVirtualMemory, and standalone pipe ThreadId=0 (hook_thread.c, hook_process.c, loader/loader/Loader.c):

    • Appends ApcArgument1 (ApcRoutineContext), ApcArgument2 (ApcStatusBlock), and ApcArgument3 (ApcReserved) to New_NtQueueApcThread and New_NtQueueApcThreadEx while preserving existing field order, and guards ProcessMessage(pid, 0) on pid != 0 && !g_config.single_process.
    • Hooks NtAlertThread across full_hooks, native_hooks, and office_hooks.
    • Extends New_NtProtectVirtualMemory to invoke ProcessMessage(pid, 0) and DumpRemoteExecutableRegion when a remote process's memory is flipped to EXECUTABLE_FLAGS.
    • Fixes standalone CreateMonitorPipe (Loader.c) to accept PROCESS:<pid>,0 (ThreadId == 0) notifications, matching CAPEv2's guest pipe server.

Hard User-Mode Limits

Pure user-mode capemon remains subject to two OS-enforced boundaries when loaders combine these primitives with indirect syscalls and process mitigations:

  1. No monitor injection into CIG-enforced intermediate relay children (BLOCK_NON_MICROSOFT_BINARIES_ALWAYS_ON):
    • When a loader (such as WhisperLoader's Grandparent -> Writer -> Flipper split) invokes NtCreateUserProcess via an indirect syscall with PROCESS_CREATION_MITIGATION_POLICY_BLOCK_NON_MICROSOFT_BINARIES_ALWAYS_ON, inline New_NtCreateUserProcess mitigation stripping is bypassed, and ProcessInstrumentationCallback (Nirvana) executes after the kernel latches EPROCESS.MitigationFlags2 on the child. Injecting unsigned capemon DLLs into Writer or Flipper via LoadLibraryA / IAT (SEC_IMAGE) is rejected by the kernel (STATUS_INVALID_IMAGE_HASH).
    • Companion PR InstrCallback: follow indirect/direct NtCreateUserProcess children and inherited targets #256 (feat/instr-callback-process-follow) mitigates CIG relay stages from user mode by inspecting PS_ATTRIBUTE_HANDLE_LIST on NtCreateUserProcess syscall return and following the inherited foreign target handle (target_pid) directly; once capemon is attached to target_pid, New_NtQueryInformationThread(ThreadNameInformation) in this PR captures the TNC-stashed payload inside target_pid even though Writer and Flipper themselves run unmonitored.
  2. CIG- or ACG-enforced final target host process:
    • If the final TP_POOL host process selected by the injector itself enforces BLOCK_NON_MICROSOFT_BINARIES_ALWAYS_ON (or PROHIBIT_DYNAMIC_CODE / ACG), user-mode LoadLibraryA / SEC_IMAGE injection cannot load an unsigned monitor DLL into target_pid either without a kernel driver, Microsoft-signed monitor binary, or a SEC_IMAGE-free manual PE mapper.

Are these related?

Yes — unlike the coupled NDEBUG case where build flags change macro semantics across unrelated modules, all changes here form the user-mode API hook and payload-capture path for Thread Name-Calling + TP_DIRECT.Callback completion hijacking (both injector-side and target-side).

Verification

  • Note on MSVC compilation: No MSVC toolchain is available on this Linux host, so full Visual Studio solution builds (Win32 / x64) are unverified beyond source inspection.
  • POSIX C ASan/UBSan + TSan harness: Extracted the live C slices from ntapi.h, lookup.c, hook_misc.c, CAPE/Injection.c, hook_thread.c, hook_sync.c, hook_process.c, and loader/loader/Loader.c and compiled under gcc -O1 -g -Wall -Wextra -Werror -fshort-wchar:
    • 64-bit ASan+UBSan (-D_WIN64 -fsanitize=address,undefined): passed all 5 suites (0 warnings, 0 leaks/UB).
    • 32-bit ASan+UBSan (-m32 -U_WIN64 -fsanitize=address,undefined): passed all 5 suites (0 warnings, 0 leaks/UB).
    • 64-bit TSan (-D_WIN64 -fsanitize=thread): passed 8-thread concurrent handle duplication/close/reuse stress (0 warnings on new locks/tables).

Series

Builds cleanly on latest upstream/capemon (616de99) with zero file overlap against companion PR #256 (feat/instr-callback-process-follow) and zero merge conflicts on touched files against open PRs (#207, #209, #210, #213, #215, #243, #251, #253, #254).

- ntapi.h: complete THREADINFOCLASS up to ThreadNameInformation (0x26)
  pinned by C_ASSERT.
- hook_thread.c: inspect ThreadNameInformation in NtSetInformationThread
  and NtQueryInformationThread, following cross-process target PIDs via
  ProcessMessage and dumping non-UTF16 / embedded-NUL / oversized binary
  thread-name buffers (deduplicated and capped). Append ApcArgument1..3
  to NtQueueApcThread / NtQueueApcThreadEx logs and hook NtAlertThread.
- hook_misc.c: track cross-process handles duplicated into the current
  process in NtDuplicateObject (cleared on NtClose) and register remote
  processes with OpenProcessHandler.
- hook_sync.c, CAPE/Injection.c: resolve same-process and cross-process
  TP_DIRECT.Callback (+0x38 x64 / +0x28 x86) in NtSetIoCompletion and
  NtSetIoCompletionEx, dumping non-MEM_IMAGE remote executable regions
  and hooking TpAllocAlpcCompletion and TpAllocJobNotification.
- hook_process.c, loader/loader/Loader.c: follow and dump remote regions
  flipped to executable in NtProtectVirtualMemory, and accept ThreadId=0
  in standalone CreateMonitorPipe PROCESS: notifications.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant